Debian Codegraph @

mojoshader_assembler.c

raw symbols SCIP
1 /**
2 * MojoShader; generate shader programs from bytecode of compiled
3 * Direct3D shaders.
4 *
5 * Please see the file LICENSE.txt in the source's root directory.
6 *
7 * This file written by Ryan C. Gordon.
8 */
9
10 // !!! FIXME: this should probably use a formal grammar and not a hand-written
11 // !!! FIXME: pile of C code.
12
13 #define __MOJOSHADER_INTERNAL__ 1
14 #include "mojoshader_internal.h"
15
16 #if !SUPPORT_PROFILE_BYTECODE
17 #error Shader assembler needs bytecode profile. Fix your build.
18 #endif
19
20 #if DEBUG_ASSEMBLER_PARSER
21 #define print_debug_token(token, len, val) \
22 MOJOSHADER_print_debug_token("ASSEMBLER", token, len, val)
23 #else
24 #define print_debug_token(token, len, val)
25 #endif
26
27
28 typedef struct SourcePos
29 {
30 const char *filename;
31 uint32 line;
32 } SourcePos;
33
34
35 // Context...this is state that changes as we assemble a shader...
36 typedef struct Context
37 {
38 int isfail;
39 int out_of_memory;
40 MOJOSHADER_malloc malloc;
41 MOJOSHADER_free free;
42 void *malloc_data;
43 const char *current_file;
44 int current_position;
45 ErrorList *errors;
46 Preprocessor *preprocessor;
47 MOJOSHADER_shaderType shader_type;
48 uint8 major_ver;
49 uint8 minor_ver;
50 int pushedback;
51 const char *token; // assembler token!
52 unsigned int tokenlen; // assembler token!
53 Token tokenval; // assembler token!
54 uint32 version_token; // bytecode token!
55 uint32 tokenbuf[16]; // bytecode tokens!
56 int tokenbufpos; // bytecode tokens!
57 DestArgInfo dest_arg;
58 uint8 default_writemask;
59 uint8 default_swizzle;
60 Buffer *output;
61 Buffer *token_to_source;
62 Buffer *ctab;
63 } Context;
64
65
66 // !!! FIXME: cut and paste between every damned source file follows...
67 // !!! FIXME: We need to make some sort of ContextBase that applies to all
68 // !!! FIXME: files and move this stuff to mojoshader_common.c ...
69
70 // Convenience functions for allocators...
71
72 static inline void out_of_memory(Context *ctx)
73 {
74 ctx->isfail = ctx->out_of_memory = 1;
75 } // out_of_memory
76
77 static inline void *Malloc(Context *ctx, const size_t len)
78 {
79 void *retval = ctx->malloc((int) len, ctx->malloc_data);
80 if (retval == NULL)
81 out_of_memory(ctx);
82 return retval;
83 } // Malloc
84
85 static inline char *StrDup(Context *ctx, const char *str)
86 {
87 char *retval = (char *) Malloc(ctx, strlen(str) + 1);
88 if (retval != NULL)
89 strcpy(retval, str);
90 return retval;
91 } // StrDup
92
93 static inline void Free(Context *ctx, void *ptr)
94 {
95 ctx->free(ptr, ctx->malloc_data);
96 } // Free
97
98 static void *MallocBridge(int bytes, void *data)
99 {
100 return Malloc((Context *) data, (size_t) bytes);
101 } // MallocBridge
102
103 static void FreeBridge(void *ptr, void *data)
104 {
105 Free((Context *) data, ptr);
106 } // FreeBridge
107
108
109 static void failf(Context *ctx, const char *fmt, ...) ISPRINTF(2,3);
110 static void failf(Context *ctx, const char *fmt, ...)
111 {
112 ctx->isfail = 1;
113 if (ctx->out_of_memory)
114 return;
115
116 va_list ap;
117 va_start(ap, fmt);
118 errorlist_add_va(ctx->errors, ctx->current_file, ctx->current_position, fmt, ap);
119 va_end(ap);
120 } // failf
121
122 static inline void fail(Context *ctx, const char *reason)
123 {
124 failf(ctx, "%s", reason);
125 } // fail
126
127 static inline int isfail(const Context *ctx)
128 {
129 return ctx->isfail;
130 } // isfail
131
132 static int vecsize_from_writemask(const uint8 m)
133 {
134 return (m & 1) + ((m >> 1) & 1) + ((m >> 2) & 1) + ((m >> 3) & 1);
135 } // vecsize_from_writemask
136
137 static void set_dstarg_writemask(DestArgInfo *dst, const uint8 mask)
138 {
139 dst->writemask = mask;
140 dst->writemask0 = ((mask >> 0) & 1);
141 dst->writemask1 = ((mask >> 1) & 1);
142 dst->writemask2 = ((mask >> 2) & 1);
143 dst->writemask3 = ((mask >> 3) & 1);
144 } // set_dstarg_writemask
145
146 // Shader model version magic...
147
148 static inline uint32 ver_ui32(const uint8 major, const uint8 minor)
149 {
150 return ( (((uint32) major) << 16) | (((minor) == 0xFF) ? 0 : (minor)) );
151 } // version_ui32
152
153 static inline int shader_version_atleast(const Context *ctx, const uint8 maj,
154 const uint8 min)
155 {
156 return (ver_ui32(ctx->major_ver, ctx->minor_ver) >= ver_ui32(maj, min));
157 } // shader_version_atleast
158
159 static inline int shader_is_pixel(const Context *ctx)
160 {
161 return (ctx->shader_type == MOJOSHADER_TYPE_PIXEL);
162 } // shader_is_pixel
163
164 static inline int shader_is_vertex(const Context *ctx)
165 {
166 return (ctx->shader_type == MOJOSHADER_TYPE_VERTEX);
167 } // shader_is_vertex
168
169 static inline void pushback(Context *ctx)
170 {
171 #if DEBUG_ASSEMBLER_PARSER
172 printf("ASSEMBLER PUSHBACK\n");
173 #endif
174 assert(!ctx->pushedback);
175 ctx->pushedback = 1;
176 } // pushback
177
178
179 static Token nexttoken(Context *ctx)
180 {
181 if (ctx->pushedback)
182 ctx->pushedback = 0;
183 else
184 {
185 while (1)
186 {
187 ctx->token = preprocessor_nexttoken(ctx->preprocessor,
188 &ctx->tokenlen,
189 &ctx->tokenval);
190
191 if (preprocessor_outofmemory(ctx->preprocessor))
192 {
193 ctx->tokenval = TOKEN_EOI;
194 ctx->token = NULL;
195 ctx->tokenlen = 0;
196 break;
197 } // if
198
199 unsigned int line;
200 ctx->current_file = preprocessor_sourcepos(ctx->preprocessor,&line);
201 ctx->current_position = (int) line;
202
203 if (ctx->tokenval == TOKEN_BAD_CHARS)
204 {
205 fail(ctx, "Bad characters in source file");
206 continue;
207 } // else if
208
209 else if (ctx->tokenval == TOKEN_PREPROCESSING_ERROR)
210 {
211 fail(ctx, ctx->token);
212 continue;
213 } // else if
214
215 break;
216 } // while
217 } // else
218
219 print_debug_token(ctx->token, ctx->tokenlen, ctx->tokenval);
220 return ctx->tokenval;
221 } // nexttoken
222
223
224 static void output_token_noswap(Context *ctx, const uint32 token)
225 {
226 if (!isfail(ctx))
227 {
228 buffer_append(ctx->output, &token, sizeof (token));
229
230 // We only need a list of these that grows throughout processing, and
231 // is flattened for reference at the end of the run, so we use a
232 // Buffer. It's sneaky!
233 unsigned int pos = 0;
234 const char *fname = preprocessor_sourcepos(ctx->preprocessor, &pos);
235 SourcePos srcpos;
236 memset(&srcpos, '\0', sizeof (SourcePos));
237 srcpos.line = pos;
238 srcpos.filename = fname; // cached in preprocessor!
239 buffer_append(ctx->token_to_source, &srcpos, sizeof (SourcePos));
240 } // if
241 } // output_token_noswap
242
243
244 static inline void output_token(Context *ctx, const uint32 token)
245 {
246 output_token_noswap(ctx, SWAP32(token));
247 } // output_token
248
249
250 static void output_comment_bytes(Context *ctx, const uint8 *buf, size_t len)
251 {
252 if (len > (0xFFFF * 4)) // length is stored as token count, in 16 bits.
253 fail(ctx, "Comment field is too big");
254 else if (!isfail(ctx))
255 {
256 const uint32 tokencount = (len / 4) + ((len % 4) ? 1 : 0);
257 output_token(ctx, 0xFFFE | (tokencount << 16));
258 while (len >= 4)
259 {
260 output_token_noswap(ctx, *((const uint32 *) buf));
261 len -= 4;
262 buf += 4;
263 } // while
264
265 if (len > 0) // handle spillover...
266 {
267 union { uint8 ui8[4]; uint32 ui32; } overflow;
268 overflow.ui32 = 0;
269 memcpy(overflow.ui8, buf, len);
270 output_token_noswap(ctx, overflow.ui32);
271 } // if
272 } // else if
273 } // output_comment_bytes
274
275
276 static inline void output_comment_string(Context *ctx, const char *str)
277 {
278 output_comment_bytes(ctx, (const uint8 *) str, strlen(str));
279 } // output_comment_string
280
281
282 static int require_comma(Context *ctx)
283 {
284 const Token token = nexttoken(ctx);
285 if (token != ((Token) ','))
286 {
287 fail(ctx, "Comma expected");
288 return 0;
289 } // if
290 return 1;
291 } // require_comma
292
293
294 static int check_token_segment(Context *ctx, const char *str)
295 {
296 // !!! FIXME: these are case-insensitive, right?
297 const size_t len = strlen(str);
298 if ( (ctx->tokenlen < len) || (strncasecmp(ctx->token, str, len) != 0) )
299 return 0;
300 ctx->token += len;
301 ctx->tokenlen -= len;
302 return 1;
303 } // check_token_segment
304
305
306 static int check_token(Context *ctx, const char *str)
307 {
308 const size_t len = strlen(str);
309 if ( (ctx->tokenlen != len) || (strncasecmp(ctx->token, str, len) != 0) )
310 return 0;
311 ctx->token += len;
312 ctx->tokenlen = 0;
313 return 1;
314 } // check_token
315
316
317 static int ui32fromtoken(Context *ctx, uint32 *_val)
318 {
319 unsigned int i;
320 for (i = 0; i < ctx->tokenlen; i++)
321 {
322 if ((ctx->token[i] < '0') || (ctx->token[i] > '9'))
323 break;
324 } // for
325
326 if (i == 0)
327 {
328 *_val = 0;
329 return 0;
330 } // if
331
332 const unsigned int len = i;
333 uint32 val = 0;
334 uint32 mult = 1;
335 while (i--)
336 {
337 val += ((uint32) (ctx->token[i] - '0')) * mult;
338 mult *= 10;
339 } // while
340
341 ctx->token += len;
342 ctx->tokenlen -= len;
343
344 *_val = val;
345 return 1;
346 } // ui32fromtoken
347
348
349 static int parse_register_name(Context *ctx, RegisterType *rtype, int *rnum)
350 {
351 if (nexttoken(ctx) != TOKEN_IDENTIFIER)
352 {
353 fail(ctx, "Expected register");
354 return 0;
355 } // if
356
357 int neednum = 1;
358 int regnum = 0;
359 RegisterType regtype = REG_TYPE_TEMP;
360
361 // Watch out for substrings! oDepth must be checked before oD, since
362 // the latter will match either case.
363 if (check_token_segment(ctx, "oDepth"))
364 {
365 regtype = REG_TYPE_DEPTHOUT;
366 neednum = 0;
367 } // else if
368 else if (check_token_segment(ctx, "vFace"))
369 {
370 regtype = REG_TYPE_MISCTYPE;
371 regnum = (int) MISCTYPE_TYPE_FACE;
372 neednum = 0;
373 } // else if
374 else if (check_token_segment(ctx, "vPos"))
375 {
376 regtype = REG_TYPE_MISCTYPE;
377 regnum = (int) MISCTYPE_TYPE_POSITION;
378 neednum = 0;
379 } // else if
380 else if (check_token_segment(ctx, "oPos"))
381 {
382 regtype = REG_TYPE_RASTOUT;
383 regnum = (int) RASTOUT_TYPE_POSITION;
384 neednum = 0;
385 } // else if
386 else if (check_token_segment(ctx, "oFog"))
387 {
388 regtype = REG_TYPE_RASTOUT;
389 regnum = (int) RASTOUT_TYPE_FOG;
390 neednum = 0;
391 } // else if
392 else if (check_token_segment(ctx, "oPts"))
393 {
394 regtype = REG_TYPE_RASTOUT;
395 regnum = (int) RASTOUT_TYPE_POINT_SIZE;
396 neednum = 0;
397 } // else if
398 else if (check_token_segment(ctx, "aL"))
399 {
400 regtype = REG_TYPE_LOOP;
401 neednum = 0;
402 } // else if
403 else if (check_token_segment(ctx, "oC"))
404 regtype = REG_TYPE_COLOROUT;
405 else if (check_token_segment(ctx, "oT"))
406 regtype = REG_TYPE_OUTPUT;
407 else if (check_token_segment(ctx, "oD"))
408 regtype = REG_TYPE_ATTROUT;
409 else if (check_token_segment(ctx, "r"))
410 regtype = REG_TYPE_TEMP;
411 else if (check_token_segment(ctx, "v"))
412 regtype = REG_TYPE_INPUT;
413 else if (check_token_segment(ctx, "c"))
414 regtype = REG_TYPE_CONST;
415 else if (check_token_segment(ctx, "i"))
416 regtype = REG_TYPE_CONSTINT;
417 else if (check_token_segment(ctx, "b"))
418 regtype = REG_TYPE_CONSTBOOL;
419 else if (check_token_segment(ctx, "s"))
420 regtype = REG_TYPE_SAMPLER;
421 else if (check_token_segment(ctx, "l"))
422 regtype = REG_TYPE_LABEL;
423 else if (check_token_segment(ctx, "p"))
424 regtype = REG_TYPE_PREDICATE;
425 else if (check_token_segment(ctx, "o"))
426 regtype = REG_TYPE_OUTPUT;
427 else if (check_token_segment(ctx, "a"))
428 regtype = REG_TYPE_ADDRESS;
429 else if (check_token_segment(ctx, "t"))
430 regtype = REG_TYPE_ADDRESS;
431
432 //case REG_TYPE_TEMPFLOAT16: // !!! FIXME: don't know this asm string
433
434 else
435 {
436 fail(ctx, "expected register type");
437 regtype = REG_TYPE_CONST;
438 regnum = 0;
439 neednum = 0;
440 } // else
441
442 // "c[5]" is the same as "c5", so if the token is done, see if next is '['.
443 if ((neednum) && (ctx->tokenlen == 0))
444 {
445 const int tlen = ctx->tokenlen; // we need to protect this for later.
446 if (nexttoken(ctx) == ((Token) '['))
447 neednum = 0; // don't need a number on register name itself.
448 pushback(ctx);
449 ctx->tokenlen = tlen;
450 } // if
451
452 if (neednum)
453 {
454 uint32 ui32 = 0;
455 if (!ui32fromtoken(ctx, &ui32))
456 fail(ctx, "Invalid register index");
457 regnum = (int) ui32;
458 } // if
459
460 // split up REG_TYPE_CONST
461 if (regtype == REG_TYPE_CONST)
462 {
463 if (regnum < 2048)
464 {
465 regtype = REG_TYPE_CONST;
466 regnum -= 0;
467 } // if
468 else if (regnum < 4096)
469 {
470 regtype = REG_TYPE_CONST2;
471 regnum -= 2048;
472 } // if
473 else if (regnum < 6144)
474 {
475 regtype = REG_TYPE_CONST3;
476 regnum -= 4096;
477 } // if
478 else if (regnum < 8192)
479 {
480 regtype = REG_TYPE_CONST4;
481 regnum -= 6144;
482 } // if
483 else
484 {
485 fail(ctx, "Invalid const register index");
486 } // else
487 } // if
488
489 *rtype = regtype;
490 *rnum = regnum;
491
492 return 1;
493 } // parse_register_name
494
495
496 static void set_result_shift(Context *ctx, DestArgInfo *info, const int val)
497 {
498 if (info->result_shift != 0)
499 fail(ctx, "Multiple result shift modifiers");
500 info->result_shift = val;
501 } // set_result_shift
502
503
504 static inline int tokenbuf_overflow(Context *ctx)
505 {
506 if ( ctx->tokenbufpos >= ((int) (STATICARRAYLEN(ctx->tokenbuf))) )
507 {
508 fail(ctx, "Too many tokens");
509 return 1;
510 } // if
511
512 return 0;
513 } // tokenbuf_overflow
514
515
516 static int parse_destination_token(Context *ctx)
517 {
518 DestArgInfo *info = &ctx->dest_arg;
519 memset(info, '\0', sizeof (DestArgInfo));
520
521 // parse_instruction_token() sets ctx->token to the end of the instruction
522 // so we can see if there are destination modifiers on the instruction
523 // itself...
524
525 int invalid_modifier = 0;
526
527 while ((ctx->tokenlen > 0) && (!invalid_modifier))
528 {
529 if (check_token_segment(ctx, "_x2"))
530 set_result_shift(ctx, info, 0x1);
531 else if (check_token_segment(ctx, "_x4"))
532 set_result_shift(ctx, info, 0x2);
533 else if (check_token_segment(ctx, "_x8"))
534 set_result_shift(ctx, info, 0x3);
535 else if (check_token_segment(ctx, "_d8"))
536 set_result_shift(ctx, info, 0xD);
537 else if (check_token_segment(ctx, "_d4"))
538 set_result_shift(ctx, info, 0xE);
539 else if (check_token_segment(ctx, "_d2"))
540 set_result_shift(ctx, info, 0xF);
541 else if (check_token_segment(ctx, "_sat"))
542 info->result_mod |= MOD_SATURATE;
543 else if (check_token_segment(ctx, "_pp"))
544 info->result_mod |= MOD_PP;
545 else if (check_token_segment(ctx, "_centroid"))
546 info->result_mod |= MOD_CENTROID;
547 else
548 invalid_modifier = 1;
549 } // while
550
551 if (invalid_modifier)
552 fail(ctx, "Invalid destination modifier");
553
554 // !!! FIXME: predicates.
555 if (nexttoken(ctx) == ((Token) '('))
556 fail(ctx, "Predicates unsupported at this time"); // !!! FIXME: ...
557
558 pushback(ctx); // parse_register_name calls nexttoken().
559
560 parse_register_name(ctx, &info->regtype, &info->regnum);
561 // parse_register_name() can't check this: dest regs might have modifiers.
562 if (ctx->tokenlen > 0)
563 fail(ctx, "invalid register name");
564
565 // !!! FIXME: can dest registers do relative addressing?
566
567 int invalid_writemask = 0;
568 if (nexttoken(ctx) != ((Token) '.'))
569 {
570 set_dstarg_writemask(info, ctx->default_writemask);
571 pushback(ctx); // no explicit writemask; do default mask.
572 } // if
573 else if (nexttoken(ctx) != TOKEN_IDENTIFIER)
574 {
575 invalid_writemask = 1;
576 } // else if
577 else
578 {
579 char tokenbytes[5] = { '\0', '\0', '\0', '\0', '\0' };
580 const unsigned int tokenlen = ctx->tokenlen;
581 memcpy(tokenbytes, ctx->token, ((tokenlen < 4) ? tokenlen : 4));
582 char *ptr = tokenbytes;
583 uint8 writemask = 0;
584 if ((*ptr == 'r') || (*ptr == 'x')) { writemask |= (1<<0); ptr++; }
585 if ((*ptr == 'g') || (*ptr == 'y')) { writemask |= (1<<1); ptr++; }
586 if ((*ptr == 'b') || (*ptr == 'z')) { writemask |= (1<<2); ptr++; }
587 if ((*ptr == 'a') || (*ptr == 'w')) { writemask |= (1<<3); ptr++; }
588
589 if (*ptr != '\0')
590 invalid_writemask = 1;
591
592 // Cg generates code with oDepth.z, and Microsoft's tools accept
593 // oFog.x and probably others. For safety's sake, we'll allow
594 // any single channel to be specified and will just wipe out the
595 // writemask as if it wasn't specified at all. More than one
596 // channel will be a fail, though.
597 if (!invalid_writemask && scalar_register(ctx->shader_type, info->regtype, info->regnum))
598 {
599 const int numchans = vecsize_from_writemask(writemask);
600 if (numchans != 1)
601 fail(ctx, "Non-scalar writemask specified for scalar register");
602 writemask = 0xF;
603 } // if
604
605 set_dstarg_writemask(info, writemask);
606 } // else
607
608 if (invalid_writemask)
609 fail(ctx, "Invalid writemask");
610
611 info->orig_writemask = info->writemask;
612
613 if (tokenbuf_overflow(ctx))
614 return 1;
615
616 ctx->tokenbuf[ctx->tokenbufpos++] =
617 ( ((((uint32) 1)) << 31) |
618 ((((uint32) info->regnum) & 0x7ff) << 0) |
619 ((((uint32) info->relative) & 0x1) << 13) |
620 ((((uint32) info->result_mod) & 0xF) << 20) |
621 ((((uint32) info->result_shift) & 0xF) << 24) |
622 ((((uint32) info->writemask) & 0xF) << 16) |
623 ((((uint32) info->regtype) & 0x7) << 28) |
624 ((((uint32) info->regtype) & 0x18) << 8) );
625
626 return 1;
627 } // parse_destination_token
628
629
630 static void set_source_mod(Context *ctx, const int negate,
631 const SourceMod norm, const SourceMod negated,
632 SourceMod *srcmod)
633 {
634 if ( (*srcmod != SRCMOD_NONE) || (negate && (negated == SRCMOD_NONE)) )
635 fail(ctx, "Incompatible source modifiers");
636 else
637 *srcmod = ((negate) ? negated : norm);
638 } // set_source_mod
639
640
641 static int parse_source_token_maybe_relative(Context *ctx, const int relok)
642 {
643 int retval = 1;
644
645 // If we've set a weird default swizzle, save it off and then go back to
646 // the default, so it won't reuse the setting for relative addressing
647 // processing. We only need a weird default for a handful of instructions.
648 const uint8 default_swizzle = ctx->default_swizzle;
649 ctx->default_swizzle = 0xE4; // 0xE4 == 11100100 ... 0 1 2 3. No swizzle.
650
651 if (tokenbuf_overflow(ctx))
652 return 0;
653
654 // mark this now, so optional relative addressing token is placed second.
655 uint32 *outtoken = &ctx->tokenbuf[ctx->tokenbufpos++];
656 *outtoken = 0;
657
658 SourceMod srcmod = SRCMOD_NONE;
659 int negate = 0;
660 Token token = nexttoken(ctx);
661
662 if (token == ((Token) '!'))
663 srcmod = SRCMOD_NOT;
664 else if (token == ((Token) '-'))
665 negate = 1;
666 else if ( (token == TOKEN_INT_LITERAL) && (check_token(ctx, "1")) )
667 {
668 if (nexttoken(ctx) != ((Token) '-'))
669 fail(ctx, "Unexpected token");
670 else
671 srcmod = SRCMOD_COMPLEMENT;
672 } // else
673 else
674 {
675 pushback(ctx);
676 } // else
677
678 RegisterType regtype;
679 int regnum;
680 parse_register_name(ctx, &regtype, &regnum);
681
682 if (ctx->tokenlen == 0)
683 {
684 if (negate)
685 set_source_mod(ctx, negate, SRCMOD_NONE, SRCMOD_NEGATE, &srcmod);
686 } // if
687 else
688 {
689 assert(ctx->tokenlen > 0);
690 if (check_token_segment(ctx, "_bias"))
691 set_source_mod(ctx, negate, SRCMOD_BIAS, SRCMOD_BIASNEGATE, &srcmod);
692 else if (check_token_segment(ctx, "_bx2"))
693 set_source_mod(ctx, negate, SRCMOD_SIGN, SRCMOD_SIGNNEGATE, &srcmod);
694 else if (check_token_segment(ctx, "_x2"))
695 set_source_mod(ctx, negate, SRCMOD_X2, SRCMOD_X2NEGATE, &srcmod);
696 else if (check_token_segment(ctx, "_dz"))
697 set_source_mod(ctx, negate, SRCMOD_DZ, SRCMOD_NONE, &srcmod);
698 else if (check_token_segment(ctx, "_db"))
699 set_source_mod(ctx, negate, SRCMOD_DZ, SRCMOD_NONE, &srcmod);
700 else if (check_token_segment(ctx, "_dw"))
701 set_source_mod(ctx, negate, SRCMOD_DW, SRCMOD_NONE, &srcmod);
702 else if (check_token_segment(ctx, "_da"))
703 set_source_mod(ctx, negate, SRCMOD_DW, SRCMOD_NONE, &srcmod);
704 else if (check_token_segment(ctx, "_abs"))
705 set_source_mod(ctx, negate, SRCMOD_ABS, SRCMOD_ABSNEGATE, &srcmod);
706 else
707 fail(ctx, "Invalid source modifier");
708 } // else
709
710 uint32 relative = 0;
711 if (nexttoken(ctx) != ((Token) '['))
712 pushback(ctx); // not relative addressing?
713 else
714 {
715 // quick hack here to make "c[5]" convert to "c5". This will also
716 // work with "c0[5]" but that's possibly illegal...?
717 int skip_relative_parsing = 0;
718 if ((regtype == REG_TYPE_CONST) && (regnum == 0))
719 {
720 uint32 ui32 = 0;
721 if (nexttoken(ctx) != TOKEN_INT_LITERAL)
722 pushback(ctx);
723 else if (!ui32fromtoken(ctx, &ui32))
724 pushback(ctx);
725 else
726 {
727 regnum = ui32;
728 skip_relative_parsing = 1;
729 } // else
730 } // if
731
732 if (!skip_relative_parsing)
733 {
734 if (!relok)
735 fail(ctx, "Relative addressing not permitted here.");
736 else
737 retval++;
738
739 parse_source_token_maybe_relative(ctx, 0);
740 relative = 1;
741
742 if (nexttoken(ctx) != ((Token) '+'))
743 pushback(ctx);
744 else
745 {
746 // !!! FIXME: maybe c3[a0.x + 5] is legal and becomes c[a0.x + 8] ?
747 if (regnum != 0)
748 fail(ctx, "Relative addressing with explicit register number.");
749
750 uint32 ui32 = 0;
751 if ( (nexttoken(ctx) != TOKEN_INT_LITERAL) ||
752 (!ui32fromtoken(ctx, &ui32)) ||
753 (ctx->tokenlen != 0) )
754 {
755 fail(ctx, "Invalid relative addressing offset");
756 } // if
757 regnum += (int) ui32;
758 } // else
759 } // if
760
761 if (nexttoken(ctx) != ((Token) ']'))
762 fail(ctx, "Expected ']'");
763 } // else
764
765 int invalid_swizzle = 0;
766 uint32 swizzle = 0;
767 if (nexttoken(ctx) != ((Token) '.'))
768 {
769 swizzle = default_swizzle;
770 pushback(ctx); // no explicit swizzle; use the default.
771 } // if
772 else if (scalar_register(ctx->shader_type, regtype, regnum))
773 fail(ctx, "Swizzle specified for scalar register");
774 else if (nexttoken(ctx) != TOKEN_IDENTIFIER)
775 invalid_swizzle = 1;
776 else
777 {
778 char tokenbytes[5] = { '\0', '\0', '\0', '\0', '\0' };
779 const unsigned int tokenlen = ctx->tokenlen;
780 memcpy(tokenbytes, ctx->token, ((tokenlen < 4) ? tokenlen : 4));
781
782 // deal with shortened form (.x = .xxxx, etc).
783 if (tokenlen == 1)
784 tokenbytes[1] = tokenbytes[2] = tokenbytes[3] = tokenbytes[0];
785 else if (tokenlen == 2)
786 tokenbytes[2] = tokenbytes[3] = tokenbytes[1];
787 else if (tokenlen == 3)
788 tokenbytes[3] = tokenbytes[2];
789 else if (tokenlen != 4)
790 invalid_swizzle = 1;
791 tokenbytes[4] = '\0';
792
793 uint32 val = 0;
794 int i;
795 for (i = 0; i < 4; i++)
796 {
797 const int component = (int) tokenbytes[i];
798 switch (component)
799 {
800 case 'r': case 'x': val = 0; break;
801 case 'g': case 'y': val = 1; break;
802 case 'b': case 'z': val = 2; break;
803 case 'a': case 'w': val = 3; break;
804 default: invalid_swizzle = 1; break;
805 } // switch
806 swizzle |= (val << (i * 2));
807 } // for
808 } // else
809
810 if (invalid_swizzle)
811 fail(ctx, "Invalid swizzle");
812
813 *outtoken = ( ((((uint32) 1)) << 31) |
814 ((((uint32) regnum) & 0x7ff) << 0) |
815 ((((uint32) relative) & 0x1) << 13) |
816 ((((uint32) swizzle) & 0xFF) << 16) |
817 ((((uint32) srcmod) & 0xF) << 24) |
818 ((((uint32) regtype) & 0x7) << 28) |
819 ((((uint32) regtype) & 0x18) << 8) );
820
821 return retval;
822 } // parse_source_token_maybe_relative
823
824
825 static inline int parse_source_token(Context *ctx)
826 {
827 return parse_source_token_maybe_relative(ctx, 1);
828 } // parse_source_token
829
830
831 static int parse_args_NULL(Context *ctx)
832 {
833 return 1;
834 } // parse_args_NULL
835
836
837 static int parse_num(Context *ctx, const int floatok, uint32 *value)
838 {
839 union { float f; int32 si32; uint32 ui32; } cvt;
840 int negative = 0;
841 Token token = nexttoken(ctx);
842
843 if (token == ((Token) '-'))
844 {
845 negative = 1;
846 token = nexttoken(ctx);
847 } // if
848
849 if (token == TOKEN_INT_LITERAL)
850 {
851 int d = 0;
852 sscanf(ctx->token, "%d", &d);
853 if (floatok)
854 cvt.f = (float) ((negative) ? -d : d);
855 else
856 cvt.si32 = (int32) ((negative) ? -d : d);
857 } // if
858 else if (token == TOKEN_FLOAT_LITERAL)
859 {
860 if (!floatok)
861 {
862 fail(ctx, "Expected whole number");
863 *value = 0;
864 return 0;
865 } // if
866 sscanf(ctx->token, "%f", &cvt.f);
867 if (negative)
868 cvt.f = -cvt.f;
869 } // if
870 else
871 {
872 fail(ctx, "Expected number");
873 *value = 0;
874 return 0;
875 } // else
876
877 *value = cvt.ui32;
878 return 1;
879 } // parse_num
880
881
882 static int parse_args_DEFx(Context *ctx, const int isflt)
883 {
884 parse_destination_token(ctx);
885 require_comma(ctx);
886 parse_num(ctx, isflt, &ctx->tokenbuf[ctx->tokenbufpos++]);
887 require_comma(ctx);
888 parse_num(ctx, isflt, &ctx->tokenbuf[ctx->tokenbufpos++]);
889 require_comma(ctx);
890 parse_num(ctx, isflt, &ctx->tokenbuf[ctx->tokenbufpos++]);
891 require_comma(ctx);
892 parse_num(ctx, isflt, &ctx->tokenbuf[ctx->tokenbufpos++]);
893 return 6;
894 } // parse_args_DEFx
895
896
897 static int parse_args_DEF(Context *ctx)
898 {
899 return parse_args_DEFx(ctx, 1);
900 } // parse_args_DEF
901
902
903 static int parse_args_DEFI(Context *ctx)
904 {
905 return parse_args_DEFx(ctx, 0);
906 } // parse_args_DEFI
907
908
909 static int parse_args_DEFB(Context *ctx)
910 {
911 parse_destination_token(ctx);
912 require_comma(ctx);
913
914 // !!! FIXME: do a TOKEN_TRUE and TOKEN_FALSE? Is this case-sensitive?
915 const Token token = nexttoken(ctx);
916
917 int bad = 0;
918 if (token != TOKEN_IDENTIFIER)
919 bad = 1;
920 else if (check_token_segment(ctx, "true"))
921 ctx->tokenbuf[ctx->tokenbufpos++] = 1;
922 else if (check_token_segment(ctx, "false"))
923 ctx->tokenbuf[ctx->tokenbufpos++] = 0;
924 else
925 bad = 1;
926
927 if (ctx->tokenlen != 0)
928 bad = 1;
929
930 if (bad)
931 fail(ctx, "Expected 'true' or 'false'");
932
933 return 3;
934 } // parse_args_DEFB
935
936
937 static int parse_dcl_usage(Context *ctx, uint32 *val, int *issampler)
938 {
939 size_t i;
940 static const char *samplerusagestrs[] = { "_2d", "_cube", "_volume" };
941 static const char *usagestrs[] = {
942 "_position", "_blendweight", "_blendindices", "_normal", "_psize",
943 "_texcoord", "_tangent", "_binormal", "_tessfactor", "_positiont",
944 "_color", "_fog", "_depth", "_sample"
945 };
946
947 for (i = 0; i < STATICARRAYLEN(usagestrs); i++)
948 {
949 if (check_token_segment(ctx, usagestrs[i]))
950 {
951 *issampler = 0;
952 *val = i;
953 return 1;
954 } // if
955 } // for
956
957 for (i = 0; i < STATICARRAYLEN(samplerusagestrs); i++)
958 {
959 if (check_token_segment(ctx, samplerusagestrs[i]))
960 {
961 *issampler = 1;
962 *val = i + 2;
963 return 1;
964 } // if
965 } // for
966
967 *issampler = 0;
968 *val = 0;
969 return 0;
970 } // parse_dcl_usage
971
972
973 static int parse_args_DCL(Context *ctx)
974 {
975 int issampler = 0;
976 uint32 usage = 0;
977 uint32 index = 0;
978
979 ctx->tokenbufpos++; // save a spot for the usage/index token.
980 ctx->tokenbuf[0] = 0;
981
982 // parse_instruction_token() sets ctx->token to the end of the instruction
983 // so we can see if there are destination modifiers on the instruction
984 // itself...
985
986 if (parse_dcl_usage(ctx, &usage, &issampler))
987 {
988 if ((ctx->tokenlen > 0) && (*ctx->token != '_'))
989 {
990 if (!ui32fromtoken(ctx, &index))
991 fail(ctx, "Expected usage index");
992 } // if
993 } // if
994
995 parse_destination_token(ctx);
996
997 const int samplerreg = (ctx->dest_arg.regtype == REG_TYPE_SAMPLER);
998 if (issampler != samplerreg)
999 fail(ctx, "Invalid usage");
1000 else if (samplerreg)
1001 ctx->tokenbuf[0] = (usage << 27) | 0x80000000;
1002 else if (shader_is_pixel(ctx)) // all other pixel shader types are zero'd.
1003 ctx->tokenbuf[0] = 0x80000000;
1004 else
1005 ctx->tokenbuf[0] = usage | (index << 16) | 0x80000000;
1006
1007 return 3;
1008 } // parse_args_DCL
1009
1010
1011 static int parse_args_D(Context *ctx)
1012 {
1013 int retval = 1;
1014 retval += parse_destination_token(ctx);
1015 return retval;
1016 } // parse_args_D
1017
1018
1019 static int parse_args_S(Context *ctx)
1020 {
1021 int retval = 1;
1022 retval += parse_source_token(ctx);
1023 return retval;
1024 } // parse_args_S
1025
1026
1027 static int parse_args_SS(Context *ctx)
1028 {
1029 int retval = 1;
1030 retval += parse_source_token(ctx);
1031 require_comma(ctx);
1032 retval += parse_source_token(ctx);
1033 return retval;
1034 } // parse_args_SS
1035
1036
1037 static int parse_args_DS(Context *ctx)
1038 {
1039 int retval = 1;
1040 retval += parse_destination_token(ctx);
1041 require_comma(ctx);
1042 retval += parse_source_token(ctx);
1043 return retval;
1044 } // parse_args_DS
1045
1046
1047 static int parse_args_DSS(Context *ctx)
1048 {
1049 int retval = 1;
1050 retval += parse_destination_token(ctx);
1051 require_comma(ctx);
1052 retval += parse_source_token(ctx);
1053 require_comma(ctx);
1054 retval += parse_source_token(ctx);
1055 return retval;
1056 } // parse_args_DSS
1057
1058
1059 static int parse_args_DSSS(Context *ctx)
1060 {
1061 int retval = 1;
1062 retval += parse_destination_token(ctx);
1063 require_comma(ctx);
1064 retval += parse_source_token(ctx);
1065 require_comma(ctx);
1066 retval += parse_source_token(ctx);
1067 require_comma(ctx);
1068 retval += parse_source_token(ctx);
1069 return retval;
1070 } // parse_args_DSSS
1071
1072
1073 static int parse_args_DSSSS(Context *ctx)
1074 {
1075 int retval = 1;
1076 retval += parse_destination_token(ctx);
1077 require_comma(ctx);
1078 retval += parse_source_token(ctx);
1079 require_comma(ctx);
1080 retval += parse_source_token(ctx);
1081 require_comma(ctx);
1082 retval += parse_source_token(ctx);
1083 require_comma(ctx);
1084 retval += parse_source_token(ctx);
1085 return retval;
1086 } // parse_args_DSSSS
1087
1088
1089 static int parse_args_SINCOS(Context *ctx)
1090 {
1091 // this opcode needs extra registers for sm2 and lower.
1092 if (!shader_version_atleast(ctx, 3, 0))
1093 return parse_args_DSSS(ctx);
1094 return parse_args_DS(ctx);
1095 } // parse_args_SINCOS
1096
1097
1098 static int parse_args_TEXCRD(Context *ctx)
1099 {
1100 // added extra register in ps_1_4.
1101 if (shader_version_atleast(ctx, 1, 4))
1102 return parse_args_DS(ctx);
1103 return parse_args_D(ctx);
1104 } // parse_args_TEXCRD
1105
1106
1107 static int parse_args_TEXLD(Context *ctx)
1108 {
1109 // different registers in px_1_3, ps_1_4, and ps_2_0!
1110 if (shader_version_atleast(ctx, 2, 0))
1111 return parse_args_DSS(ctx);
1112 else if (shader_version_atleast(ctx, 1, 4))
1113 return parse_args_DS(ctx);
1114 return parse_args_D(ctx);
1115 } // parse_args_TEXLD
1116
1117
1118
1119 // one args function for each possible sequence of opcode arguments.
1120 typedef int (*args_function)(Context *ctx);
1121
1122 // Lookup table for instruction opcodes...
1123 typedef struct
1124 {
1125 const char *opcode_string;
1126 const uint8 default_writemask;
1127 args_function parse_args;
1128 } Instruction;
1129
1130
1131 static const Instruction instructions[] =
1132 {
1133 #define INSTRUCTION_STATE(op, opstr, s, a, t, w) { opstr, w, parse_args_##a },
1134 #define INSTRUCTION(op, opstr, slots, a, t, w) { opstr, w, parse_args_##a },
1135 #define MOJOSHADER_DO_INSTRUCTION_TABLE 1
1136 #include "mojoshader_internal.h"
1137 };
1138
1139
1140 static int parse_condition(Context *ctx, uint32 *controls)
1141 {
1142 static const char *comps[] = { "_gt", "_eq", "_ge", "_lt", "_ne", "_le" };
1143 size_t i;
1144
1145 if (ctx->tokenlen >= 3)
1146 {
1147 for (i = 0; i < STATICARRAYLEN(comps); i++)
1148 {
1149 if (check_token_segment(ctx, comps[i]))
1150 {
1151 *controls = (uint32) (i + 1);
1152 return 1;
1153 } // if
1154 } // for
1155 } // if
1156
1157 return 0;
1158 } // parse_condition
1159
1160
1161 static int parse_instruction_token(Context *ctx, Token token)
1162 {
1163 int coissue = 0;
1164 int predicated = 0;
1165
1166 if (token == ((Token) '+'))
1167 {
1168 coissue = 1;
1169 token = nexttoken(ctx);
1170 } // if
1171
1172 if (token != TOKEN_IDENTIFIER)
1173 {
1174 fail(ctx, "Expected instruction");
1175 return 0;
1176 } // if
1177
1178 uint32 controls = 0;
1179 uint32 opcode = OPCODE_TEXLD;
1180 const char *origtoken = ctx->token;
1181 const unsigned int origtokenlen = ctx->tokenlen;
1182
1183 // "TEX" is only meaningful in ps_1_1.
1184 if ((!shader_version_atleast(ctx, 1, 4)) && (ctx->tokenlen == 3) && (check_token_segment(ctx, "TEX")))
1185 controls = 0;
1186
1187 // This might need to be TEXLD instead of TEXLDP.
1188 else if (check_token_segment(ctx, "TEXLDP"))
1189 controls = CONTROL_TEXLDP;
1190
1191 // This might need to be TEXLD instead of TEXLDB.
1192 else if (check_token_segment(ctx, "TEXLDB"))
1193 controls = CONTROL_TEXLDB;
1194
1195 else // find the instruction.
1196 {
1197 size_t i;
1198 for (i = 0; i < STATICARRAYLEN(instructions); i++)
1199 {
1200 const char *opcode_string = instructions[i].opcode_string;
1201 if (opcode_string == NULL)
1202 continue; // skip this.
1203 else if (!check_token_segment(ctx, opcode_string))
1204 continue; // not us.
1205 else if ((ctx->tokenlen > 0) && (*ctx->token != '_'))
1206 {
1207 ctx->token = origtoken;
1208 ctx->tokenlen = origtokenlen;
1209 continue; // not the match: TEXLD when we wanted TEXLDL, etc.
1210 } // if
1211
1212 break; // found it!
1213 } // for
1214
1215 opcode = (uint32) i;
1216
1217 // This might need to be IFC instead of IF.
1218 if (opcode == OPCODE_IF)
1219 {
1220 if (parse_condition(ctx, &controls))
1221 opcode = OPCODE_IFC;
1222 } // if
1223
1224 // This might need to be BREAKC instead of BREAK.
1225 else if (opcode == OPCODE_BREAK)
1226 {
1227 if (parse_condition(ctx, &controls))
1228 opcode = OPCODE_BREAKC;
1229 } // else if
1230
1231 // SETP has a conditional code, always.
1232 else if (opcode == OPCODE_SETP)
1233 {
1234 if (!parse_condition(ctx, &controls))
1235 fail(ctx, "SETP requires a condition");
1236 } // else if
1237 } // else
1238
1239 if ( (opcode == STATICARRAYLEN(instructions)) ||
1240 ((ctx->tokenlen > 0) && (ctx->token[0] != '_')) )
1241 {
1242 char opstr[32];
1243 const int len = Min(sizeof (opstr) - 1, origtokenlen);
1244 memcpy(opstr, origtoken, len);
1245 opstr[len] = '\0';
1246 failf(ctx, "Unknown instruction '%s'", opstr);
1247 return 0;
1248 } // if
1249
1250 const Instruction *instruction = &instructions[opcode];
1251
1252 // !!! FIXME: predicated instructions
1253
1254 ctx->tokenbufpos = 0;
1255 ctx->default_writemask = instruction->default_writemask;
1256
1257 // RCP and RSQ have an implicit swizzle of .xxxx if not specified.
1258 if ((opcode == OPCODE_RCP) || (opcode == OPCODE_RSQ))
1259 ctx->default_swizzle = 0; // .xxxx replicate swizzle.
1260
1261 const int tokcount = instruction->parse_args(ctx);
1262
1263 // insttoks bits are reserved and should be zero if < SM2.
1264 const uint32 insttoks = shader_version_atleast(ctx, 2, 0) ? tokcount-1 : 0;
1265
1266 // write out the instruction token.
1267 output_token(ctx, ((opcode & 0xFFFF) << 0) |
1268 ((controls & 0xFF) << 16) |
1269 ((insttoks & 0xF) << 24) |
1270 ((coissue) ? 0x40000000 : 0x00000000) |
1271 ((predicated) ? 0x10000000 : 0x00000000) );
1272
1273 // write out the argument tokens.
1274 int i;
1275 for (i = 0; i < (tokcount-1); i++)
1276 output_token(ctx, ctx->tokenbuf[i]);
1277
1278 return 1;
1279 } // parse_instruction_token
1280
1281
1282 static void parse_version_token(Context *ctx)
1283 {
1284 int bad = 0;
1285 int dot_form = 0;
1286 uint32 shader_type = 0;
1287
1288 if (nexttoken(ctx) != TOKEN_IDENTIFIER)
1289 bad = 1;
1290 else if (check_token_segment(ctx, "vs"))
1291 {
1292 ctx->shader_type = MOJOSHADER_TYPE_VERTEX;
1293 shader_type = 0xFFFE;
1294 } // if
1295 else if (check_token_segment(ctx, "ps"))
1296 {
1297 ctx->shader_type = MOJOSHADER_TYPE_PIXEL;
1298 shader_type = 0xFFFF;
1299 } // if
1300 else
1301 {
1302 // !!! FIXME: geometry shaders?
1303 bad = 1;
1304 } // else
1305
1306 dot_form = ((!bad) && (ctx->tokenlen == 0)); // it's in xs.x.x form?
1307
1308 uint32 major = 0;
1309 uint32 minor = 0;
1310
1311 if (dot_form)
1312 {
1313 Token t = TOKEN_UNKNOWN;
1314
1315 if (!bad)
1316 {
1317 t = nexttoken(ctx);
1318 // stupid lexer sees "vs.2.0" and makes the ".2" into a float.
1319 if (t == ((Token) '.'))
1320 t = nexttoken(ctx);
1321 else
1322 {
1323 if ((t != TOKEN_FLOAT_LITERAL) || (ctx->token[0] != '.'))
1324 bad = 1;
1325 else
1326 {
1327 ctx->tokenval = t = TOKEN_INT_LITERAL;
1328 ctx->token++;
1329 ctx->tokenlen--;
1330 } // else
1331 } // else
1332 } // if
1333
1334 if (!bad)
1335 {
1336 if (t != TOKEN_INT_LITERAL)
1337 bad = 1;
1338 else if (!ui32fromtoken(ctx, &major))
1339 bad = 1;
1340 } // if
1341
1342 if (!bad)
1343 {
1344 t = nexttoken(ctx);
1345 // stupid lexer sees "vs.2.0" and makes the ".2" into a float.
1346 if (t == ((Token) '.'))
1347 t = nexttoken(ctx);
1348 else
1349 {
1350 if ((t != TOKEN_FLOAT_LITERAL) || (ctx->token[0] != '.'))
1351 bad = 1;
1352 else
1353 {
1354 ctx->tokenval = t = TOKEN_INT_LITERAL;
1355 ctx->token++;
1356 ctx->tokenlen--;
1357 } // else
1358 } // else
1359 } // if
1360
1361 if (!bad)
1362 {
1363 if ((t == TOKEN_INT_LITERAL) && (ui32fromtoken(ctx, &minor)))
1364 ; // good to go.
1365 else if ((t == TOKEN_IDENTIFIER) && (check_token_segment(ctx, "x")))
1366 minor = 1;
1367 else if ((t == TOKEN_IDENTIFIER) && (check_token_segment(ctx, "sw")))
1368 minor = 255;
1369 else
1370 bad = 1;
1371 } // if
1372 } // if
1373 else
1374 {
1375 if (!check_token_segment(ctx, "_"))
1376 bad = 1;
1377 else if (!ui32fromtoken(ctx, &major))
1378 bad = 1;
1379 else if (!check_token_segment(ctx, "_"))
1380 bad = 1;
1381 else if (check_token_segment(ctx, "x"))
1382 minor = 1;
1383 else if (check_token_segment(ctx, "sw"))
1384 minor = 255;
1385 else if (!ui32fromtoken(ctx, &minor))
1386 bad = 1;
1387 } // else
1388
1389 if ((!bad) && (ctx->tokenlen != 0))
1390 bad = 1;
1391
1392 if (bad)
1393 fail(ctx, "Expected valid version string");
1394
1395 ctx->major_ver = major;
1396 ctx->minor_ver = minor;
1397
1398 ctx->version_token = (shader_type << 16) | (major << 8) | (minor << 0);
1399 output_token(ctx, ctx->version_token);
1400 } // parse_version_token
1401
1402
1403 static void parse_phase_token(Context *ctx)
1404 {
1405 output_token(ctx, 0x0000FFFD); // phase token always 0x0000FFFD.
1406 } // parse_phase_token
1407
1408
1409 static void parse_end_token(Context *ctx)
1410 {
1411 // We don't emit the end token bits here, since it's valid for a shader
1412 // to not specify an "end" string at all; it's implicit, in that case.
1413 // Instead, we make sure if we see "end" that it's the last thing we see.
1414 if (nexttoken(ctx) != TOKEN_EOI)
1415 fail(ctx, "Content after END");
1416 } // parse_end_token
1417
1418
1419 static void parse_token(Context *ctx, const Token token)
1420 {
1421 if (token != TOKEN_IDENTIFIER)
1422 parse_instruction_token(ctx, token); // might be a coissue '+', etc.
1423 else
1424 {
1425 if (check_token(ctx, "end"))
1426 parse_end_token(ctx);
1427 else if (check_token(ctx, "phase"))
1428 parse_phase_token(ctx);
1429 else
1430 parse_instruction_token(ctx, token);
1431 } // if
1432 } // parse_token
1433
1434
1435 static void destroy_context(Context *ctx)
1436 {
1437 if (ctx != NULL)
1438 {
1439 MOJOSHADER_free f = ((ctx->free != NULL) ? ctx->free : MOJOSHADER_internal_free);
1440 void *d = ctx->malloc_data;
1441 preprocessor_end(ctx->preprocessor);
1442 errorlist_destroy(ctx->errors);
1443 buffer_destroy(ctx->ctab);
1444 buffer_destroy(ctx->token_to_source);
1445 buffer_destroy(ctx->output);
1446 f(ctx, d);
1447 } // if
1448 } // destroy_context
1449
1450
1451 static Context *build_context(const char *filename,
1452 const char *source, unsigned int sourcelen,
1453 const MOJOSHADER_preprocessorDefine *defines,
1454 unsigned int define_count,
1455 MOJOSHADER_includeOpen include_open,
1456 MOJOSHADER_includeClose include_close,
1457 MOJOSHADER_malloc m, MOJOSHADER_free f, void *d)
1458 {
1459 if (!m) m = MOJOSHADER_internal_malloc;
1460 if (!f) f = MOJOSHADER_internal_free;
1461 if (!include_open) include_open = MOJOSHADER_internal_include_open;
1462 if (!include_close) include_close = MOJOSHADER_internal_include_close;
1463
1464 Context *ctx = (Context *) m(sizeof (Context), d);
1465 if (ctx == NULL)
1466 return NULL;
1467
1468 memset(ctx, '\0', sizeof (Context));
1469 ctx->malloc = m;
1470 ctx->free = f;
1471 ctx->malloc_data = d;
1472 ctx->current_position = MOJOSHADER_POSITION_BEFORE;
1473 ctx->default_writemask = 0xF;
1474 ctx->default_swizzle = 0xE4; // 0xE4 == 11100100 ... 0 1 2 3. No swizzle.
1475
1476 const size_t outblk = sizeof (uint32) * 4 * 64; // 64 4-token instrs.
1477 ctx->output = buffer_create(outblk, MallocBridge, FreeBridge, ctx);
1478 if (ctx->output == NULL)
1479 goto build_context_failed;
1480
1481 const size_t mapblk = sizeof (SourcePos) * 4 * 64; // 64 * 4-tokens.
1482 ctx->token_to_source = buffer_create(mapblk, MallocBridge, FreeBridge, ctx);
1483 if (ctx->token_to_source == NULL)
1484 goto build_context_failed;
1485
1486 ctx->errors = errorlist_create(MallocBridge, FreeBridge, ctx);
1487 if (ctx->errors == NULL)
1488 goto build_context_failed;
1489
1490 ctx->preprocessor = preprocessor_start(filename, source, sourcelen,
1491 include_open, include_close,
1492 defines, define_count, 1,
1493 MallocBridge, FreeBridge, ctx);
1494
1495 if (ctx->preprocessor == NULL)
1496 goto build_context_failed;
1497
1498 return ctx;
1499
1500 build_context_failed: // ctx is allocated and zeroed before this is called.
1501 destroy_context(ctx);
1502 return NULL;
1503 } // build_context
1504
1505
1506 static const MOJOSHADER_parseData *build_failed_assembly(Context *ctx)
1507 {
1508 assert(isfail(ctx));
1509
1510 if (ctx->out_of_memory)
1511 return &MOJOSHADER_out_of_mem_data;
1512
1513 MOJOSHADER_parseData *retval = NULL;
1514 retval = (MOJOSHADER_parseData*) Malloc(ctx, sizeof(MOJOSHADER_parseData));
1515 if (retval == NULL)
1516 return &MOJOSHADER_out_of_mem_data;
1517
1518 memset(retval, '\0', sizeof (MOJOSHADER_parseData));
1519 retval->malloc = (ctx->malloc == MOJOSHADER_internal_malloc) ? NULL : ctx->malloc;
1520 retval->free = (ctx->free == MOJOSHADER_internal_free) ? NULL : ctx->free;
1521 retval->malloc_data = ctx->malloc_data;
1522
1523 retval->error_count = errorlist_count(ctx->errors);
1524 retval->errors = errorlist_flatten(ctx->errors);
1525
1526 if (ctx->out_of_memory)
1527 {
1528 Free(ctx, retval->errors);
1529 Free(ctx, retval);
1530 return &MOJOSHADER_out_of_mem_data;
1531 } // if
1532
1533 return retval;
1534 } // build_failed_assembly
1535
1536
1537 static int blockscmp(BufferBlock *item, const uint8 *data, size_t len)
1538 {
1539 if (len == 0)
1540 return 1; // "match"
1541
1542 while (item != NULL)
1543 {
1544 const size_t itemremain = item->bytes;
1545 const size_t avail = len < itemremain ? len : itemremain;
1546 if (memcmp(item->data, data, avail) != 0)
1547 return 0; // not a match.
1548
1549 if (len == avail)
1550 return 1; // complete match!
1551
1552 len -= avail;
1553 data += avail;
1554 item = item->next;
1555 } // while
1556
1557 return 0; // not a complete match.
1558 } // blockscmp
1559
1560
1561 ssize_t buffer_find(Buffer *buffer, const size_t start,
1562 const void *_data, const size_t len)
1563 {
1564 if (len == 0)
1565 return 0; // I guess that's right.
1566
1567 if (start >= buffer->total_bytes)
1568 return -1; // definitely can't match.
1569
1570 if (len > (buffer->total_bytes - start))
1571 return -1; // definitely can't match.
1572
1573 // Find the start point somewhere in the center of a buffer.
1574 BufferBlock *item = buffer->head;
1575 const uint8 *ptr = item->data;
1576 size_t pos = 0;
1577 if (start > 0)
1578 {
1579 while (1)
1580 {
1581 assert(item != NULL);
1582 if ((pos + item->bytes) > start) // start is in this block.
1583 {
1584 ptr = item->data + (start - pos);
1585 break;
1586 } // if
1587
1588 pos += item->bytes;
1589 item = item->next;
1590 } // while
1591 } // if
1592
1593 // okay, we're at the origin of the search.
1594 assert(item != NULL);
1595 assert(ptr != NULL);
1596
1597 const uint8 *data = (const uint8 *) _data;
1598 const uint8 first = *data;
1599 while (item != NULL)
1600 {
1601 const size_t itemremain = item->bytes - ((size_t)(ptr-item->data));
1602 ptr = (uint8 *) memchr(ptr, first, itemremain);
1603 while (ptr != NULL)
1604 {
1605 const size_t retval = pos + ((size_t) (ptr - item->data));
1606 if (len == 1)
1607 return retval; // we're done, here it is!
1608
1609 const size_t itemremain = item->bytes - ((size_t)(ptr-item->data));
1610 const size_t avail = len < itemremain ? len : itemremain;
1611 if ((avail == 0) || (memcmp(ptr, data, avail) == 0))
1612 {
1613 // okay, we've got a (sub)string match! Move to the next block.
1614 // check all blocks until we get a complete match or a failure.
1615 if (blockscmp(item->next, data+avail, len-avail))
1616 return (ssize_t) retval;
1617 } // if
1618
1619 // try again, further in this block.
1620 ptr = (uint8 *) memchr(ptr + 1, first, itemremain - 1);
1621 } // while
1622
1623 pos += item->bytes;
1624 item = item->next;
1625 if (item != NULL)
1626 ptr = item->data;
1627 } // while
1628
1629 return -1; // no match found.
1630 } // buffer_find
1631
1632
1633 static uint32 add_ctab_bytes(Context *ctx, const uint8 *bytes, const size_t len)
1634 {
1635 if (isfail(ctx))
1636 return 0;
1637
1638 const size_t extra = CTAB_SIZE + sizeof (uint32);
1639 const ssize_t pos = buffer_find(ctx->ctab, extra, bytes, len);
1640 if (pos >= 0) // blob is already in here.
1641 return ((uint32) pos) - sizeof (uint32);
1642
1643 // add it to the byte pile...
1644 const uint32 retval = ((uint32) buffer_size(ctx->ctab)) - sizeof (uint32);
1645 buffer_append(ctx->ctab, bytes, len);
1646 return retval;
1647 } // add_ctab_bytes
1648
1649
1650 static inline uint32 add_ctab_string(Context *ctx, const char *str)
1651 {
1652 return add_ctab_bytes(ctx, (const uint8 *) str, strlen(str) + 1);
1653 } // add_ctab_string
1654
1655
1656 static uint32 add_ctab_typeinfo(Context *ctx, const MOJOSHADER_symbolTypeInfo *info);
1657
1658 static uint32 add_ctab_members(Context *ctx, const MOJOSHADER_symbolTypeInfo *info)
1659 {
1660 unsigned int i;
1661 const size_t len = info->member_count * CMEMBERINFO_SIZE;
1662 uint8 *bytes = (uint8 *) Malloc(ctx, len);
1663 if (bytes == NULL)
1664 return 0;
1665
1666 union { uint8 *ui8; uint16 *ui16; uint32 *ui32; } ptr;
1667 ptr.ui8 = bytes;
1668 for (i = 0; i < info->member_count; i++)
1669 {
1670 const MOJOSHADER_symbolStructMember *member = &info->members[i];
1671 *(ptr.ui32++) = SWAP32(add_ctab_string(ctx, member->name));
1672 *(ptr.ui32++) = SWAP32(add_ctab_typeinfo(ctx, &member->info));
1673 } // for
1674
1675 const uint32 retval = add_ctab_bytes(ctx, bytes, len);
1676 Free(ctx, bytes);
1677 return retval;
1678 } // add_ctab_members
1679
1680
1681 static uint32 add_ctab_typeinfo(Context *ctx, const MOJOSHADER_symbolTypeInfo *info)
1682 {
1683 uint8 bytes[CTYPEINFO_SIZE];
1684 union { uint8 *ui8; uint16 *ui16; uint32 *ui32; } ptr;
1685 ptr.ui8 = bytes;
1686
1687 *(ptr.ui16++) = SWAP16((uint16) info->parameter_class);
1688 *(ptr.ui16++) = SWAP16((uint16) info->parameter_type);
1689 *(ptr.ui16++) = SWAP16((uint16) info->rows);
1690 *(ptr.ui16++) = SWAP16((uint16) info->columns);
1691 *(ptr.ui16++) = SWAP16((uint16) info->elements);
1692 *(ptr.ui16++) = SWAP16((uint16) info->member_count);
1693 *(ptr.ui32++) = SWAP32(add_ctab_members(ctx, info));
1694
1695 return add_ctab_bytes(ctx, bytes, sizeof (bytes));
1696 } // add_ctab_typeinfo
1697
1698
1699 static uint32 add_ctab_info(Context *ctx, const MOJOSHADER_symbol *symbols,
1700 const unsigned int symbol_count)
1701 {
1702 unsigned int i;
1703 const size_t len = symbol_count * CINFO_SIZE;
1704 uint8 *bytes = (uint8 *) Malloc(ctx, len);
1705 if (bytes == NULL)
1706 return 0;
1707
1708 union { uint8 *ui8; uint16 *ui16; uint32 *ui32; } ptr;
1709 ptr.ui8 = bytes;
1710 for (i = 0; i < symbol_count; i++)
1711 {
1712 const MOJOSHADER_symbol *sym = &symbols[i];
1713 *(ptr.ui32++) = SWAP32(add_ctab_string(ctx, sym->name));
1714 *(ptr.ui16++) = SWAP16((uint16) sym->register_set);
1715 *(ptr.ui16++) = SWAP16((uint16) sym->register_index);
1716 *(ptr.ui16++) = SWAP16((uint16) sym->register_count);
1717 *(ptr.ui16++) = SWAP16(0); // reserved
1718 *(ptr.ui32++) = SWAP32(add_ctab_typeinfo(ctx, &sym->info));
1719 *(ptr.ui32++) = SWAP32(0); // !!! FIXME: default value.
1720 } // for
1721
1722 const uint32 retval = add_ctab_bytes(ctx, bytes, len);
1723 Free(ctx, bytes);
1724 return retval;
1725 } // add_ctab_info
1726
1727
1728 static void output_ctab(Context *ctx, const MOJOSHADER_symbol *symbols,
1729 unsigned int symbol_count, const char *creator)
1730 {
1731 const size_t tablelen = CTAB_SIZE + sizeof (uint32);
1732
1733 ctx->ctab = buffer_create(256, MallocBridge, FreeBridge, ctx);
1734 if (ctx->ctab == NULL)
1735 return; // out of memory.
1736
1737 uint32 *table = (uint32 *) buffer_reserve(ctx->ctab, tablelen);
1738 if (table == NULL)
1739 {
1740 buffer_destroy(ctx->ctab);
1741 ctx->ctab = NULL;
1742 return; // out of memory.
1743 } // if
1744
1745 *(table++) = SWAP32(CTAB_ID);
1746 *(table++) = SWAP32(CTAB_SIZE);
1747 *(table++) = SWAP32(add_ctab_string(ctx, creator));
1748 *(table++) = SWAP32(ctx->version_token);
1749 *(table++) = SWAP32(((uint32) symbol_count));
1750 *(table++) = SWAP32(add_ctab_info(ctx, symbols, symbol_count));
1751 *(table++) = SWAP32(0); // build flags.
1752 *(table++) = SWAP32(add_ctab_string(ctx, "")); // !!! FIXME: target?
1753
1754 const size_t ctablen = buffer_size(ctx->ctab);
1755 uint8 *buf = (uint8 *) buffer_flatten(ctx->ctab);
1756 if (buf != NULL)
1757 {
1758 output_comment_bytes(ctx, buf, ctablen);
1759 Free(ctx, buf);
1760 } // if
1761
1762 buffer_destroy(ctx->ctab);
1763 ctx->ctab = NULL;
1764 } // output_ctab
1765
1766
1767 static void output_comments(Context *ctx, const char **comments,
1768 unsigned int comment_count,
1769 const MOJOSHADER_symbol *symbols,
1770 unsigned int symbol_count)
1771 {
1772 if (isfail(ctx))
1773 return;
1774
1775 // make error messages sane if CTAB fails, etc.
1776 const char *prev_fname = ctx->current_file;
1777 const int prev_position = ctx->current_position;
1778 ctx->current_file = NULL;
1779 ctx->current_position = MOJOSHADER_POSITION_BEFORE;
1780
1781 const char *creator = "MojoShader revision " MOJOSHADER_CHANGESET;
1782 if (symbol_count > 0)
1783 output_ctab(ctx, symbols, symbol_count, creator);
1784 else
1785 output_comment_string(ctx, creator);
1786
1787 unsigned int i;
1788 for (i = 0; i < comment_count; i++)
1789 output_comment_string(ctx, comments[i]);
1790
1791 ctx->current_file = prev_fname;
1792 ctx->current_position = prev_position;
1793 } // output_comments
1794
1795
1796 static const MOJOSHADER_parseData *build_final_assembly(Context *ctx)
1797 {
1798 if (isfail(ctx))
1799 return build_failed_assembly(ctx);
1800
1801 // get the final bytecode!
1802 const unsigned int output_len = (unsigned int) buffer_size(ctx->output);
1803 unsigned char *bytecode = (unsigned char *) buffer_flatten(ctx->output);
1804 buffer_destroy(ctx->output);
1805 ctx->output = NULL;
1806
1807 if (bytecode == NULL)
1808 return build_failed_assembly(ctx);
1809
1810 // This validates the shader; there are lots of things that are
1811 // invalid, but will successfully parse in the assembler,
1812 // generating bad bytecode; this will catch them without us
1813 // having to duplicate most of the validation here.
1814 // It also saves us the trouble of duplicating all the other work,
1815 // like setting up the uniforms list, etc.
1816 MOJOSHADER_parseData *retval = (MOJOSHADER_parseData *)
1817 MOJOSHADER_parse(MOJOSHADER_PROFILE_BYTECODE, NULL,
1818 bytecode, output_len, NULL, 0, NULL, 0,
1819 ctx->malloc, ctx->free, ctx->malloc_data);
1820 Free(ctx, bytecode);
1821
1822 SourcePos *token_to_src = NULL;
1823 if (retval->error_count > 0)
1824 token_to_src = (SourcePos *) buffer_flatten(ctx->token_to_source);
1825 buffer_destroy(ctx->token_to_source);
1826 ctx->token_to_source = NULL;
1827
1828 if (retval->error_count > 0)
1829 {
1830 if (token_to_src == NULL)
1831 {
1832 assert(ctx->out_of_memory);
1833 MOJOSHADER_freeParseData(retval);
1834 return build_failed_assembly(ctx);
1835 } // if
1836
1837 // on error, map the bytecode back to a line number.
1838 int i;
1839 for (i = 0; i < retval->error_count; i++)
1840 {
1841 MOJOSHADER_error *error = &retval->errors[i];
1842 if (error->error_position >= 0)
1843 {
1844 assert(retval != &MOJOSHADER_out_of_mem_data);
1845 assert((error->error_position % sizeof (uint32)) == 0);
1846
1847 const size_t pos = error->error_position / sizeof(uint32);
1848 if (pos >= output_len)
1849 error->error_position = -1; // oh well.
1850 else
1851 {
1852 const SourcePos *srcpos = &token_to_src[pos];
1853 Free(ctx, (void *) error->filename);
1854 char *fname = NULL;
1855 if (srcpos->filename != NULL)
1856 fname = StrDup(ctx, srcpos->filename);
1857 error->error_position = srcpos->line;
1858 error->filename = fname; // may be NULL, that's okay.
1859 } // else
1860 } // if
1861 } // for
1862
1863 Free(ctx, token_to_src);
1864 } // if
1865
1866 return retval;
1867 } // build_final_assembly
1868
1869
1870 // API entry point...
1871
1872 const MOJOSHADER_parseData *MOJOSHADER_assemble(const char *filename,
1873 const char *source, unsigned int sourcelen,
1874 const char **comments, unsigned int comment_count,
1875 const MOJOSHADER_symbol *symbols,
1876 unsigned int symbol_count,
1877 const MOJOSHADER_preprocessorDefine *defines,
1878 unsigned int define_count,
1879 MOJOSHADER_includeOpen include_open,
1880 MOJOSHADER_includeClose include_close,
1881 MOJOSHADER_malloc m, MOJOSHADER_free f, void *d)
1882 {
1883 const MOJOSHADER_parseData *retval = NULL;
1884 Context *ctx = NULL;
1885
1886 if ( ((m == NULL) && (f != NULL)) || ((m != NULL) && (f == NULL)) )
1887 return &MOJOSHADER_out_of_mem_data; // supply both or neither.
1888
1889 ctx = build_context(filename, source, sourcelen, defines, define_count,
1890 include_open, include_close, m, f, d);
1891 if (ctx == NULL)
1892 return &MOJOSHADER_out_of_mem_data;
1893
1894 // Version token always comes first.
1895 parse_version_token(ctx);
1896 output_comments(ctx, comments, comment_count, symbols, symbol_count);
1897
1898 // parse out the rest of the tokens after the version token...
1899 Token token;
1900 while ((token = nexttoken(ctx)) != TOKEN_EOI)
1901 parse_token(ctx, token);
1902
1903 ctx->current_file = NULL;
1904 ctx->current_position = MOJOSHADER_POSITION_AFTER;
1905
1906 output_token(ctx, 0x0000FFFF); // end token always 0x0000FFFF.
1907
1908 retval = build_final_assembly(ctx);
1909 destroy_context(ctx);
1910 return retval;
1911 } // MOJOSHADER_assemble
1912
1913 // end of mojoshader_assembler.c ...
1914