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