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