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