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