blob: 519b61328606791f80bf9057ba0ed8b767516566 [file] [log] [blame]
Nicolas Capens0bac2852016-05-07 06:09:58 -04001// Copyright 2016 The SwiftShader Authors. All Rights Reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#include "OutputASM.h"
16#include "Common/Math.hpp"
17
18#include "common/debug.h"
19#include "InfoSink.h"
20
21#include "libGLESv2/Shader.h"
22
23#include <GLES2/gl2.h>
24#include <GLES2/gl2ext.h>
25#include <GLES3/gl3.h>
26
27namespace glsl
28{
29 // Integer to TString conversion
30 TString str(int i)
31 {
32 char buffer[20];
33 sprintf(buffer, "%d", i);
34 return buffer;
35 }
36
37 class Temporary : public TIntermSymbol
38 {
39 public:
40 Temporary(OutputASM *assembler) : TIntermSymbol(TSymbolTableLevel::nextUniqueId(), "tmp", TType(EbtFloat, EbpHigh, EvqTemporary, 4, 1, false)), assembler(assembler)
41 {
42 }
43
44 ~Temporary()
45 {
46 assembler->freeTemporary(this);
47 }
48
49 private:
50 OutputASM *const assembler;
51 };
52
53 class Constant : public TIntermConstantUnion
54 {
55 public:
56 Constant(float x, float y, float z, float w) : TIntermConstantUnion(constants, TType(EbtFloat, EbpHigh, EvqConstExpr, 4, 1, false))
57 {
58 constants[0].setFConst(x);
59 constants[1].setFConst(y);
60 constants[2].setFConst(z);
61 constants[3].setFConst(w);
62 }
63
64 Constant(bool b) : TIntermConstantUnion(constants, TType(EbtBool, EbpHigh, EvqConstExpr, 1, 1, false))
65 {
66 constants[0].setBConst(b);
67 }
68
69 Constant(int i) : TIntermConstantUnion(constants, TType(EbtInt, EbpHigh, EvqConstExpr, 1, 1, false))
70 {
71 constants[0].setIConst(i);
72 }
73
74 ~Constant()
75 {
76 }
77
78 private:
79 ConstantUnion constants[4];
80 };
81
82 Uniform::Uniform(GLenum type, GLenum precision, const std::string &name, int arraySize, int registerIndex, int blockId, const BlockMemberInfo& blockMemberInfo) :
83 type(type), precision(precision), name(name), arraySize(arraySize), registerIndex(registerIndex), blockId(blockId), blockInfo(blockMemberInfo)
84 {
85 }
86
87 UniformBlock::UniformBlock(const std::string& name, unsigned int dataSize, unsigned int arraySize,
88 TLayoutBlockStorage layout, bool isRowMajorLayout, int registerIndex, int blockId) :
89 name(name), dataSize(dataSize), arraySize(arraySize), layout(layout),
90 isRowMajorLayout(isRowMajorLayout), registerIndex(registerIndex), blockId(blockId)
91 {
92 }
93
94 BlockLayoutEncoder::BlockLayoutEncoder(bool rowMajor)
95 : mCurrentOffset(0), isRowMajor(rowMajor)
96 {
97 }
98
99 BlockMemberInfo BlockLayoutEncoder::encodeType(const TType &type)
100 {
101 int arrayStride;
102 int matrixStride;
103
104 getBlockLayoutInfo(type, type.getArraySize(), isRowMajor, &arrayStride, &matrixStride);
105
106 const BlockMemberInfo memberInfo(static_cast<int>(mCurrentOffset * BytesPerComponent),
107 static_cast<int>(arrayStride * BytesPerComponent),
108 static_cast<int>(matrixStride * BytesPerComponent),
109 (matrixStride > 0) && isRowMajor);
110
111 advanceOffset(type, type.getArraySize(), isRowMajor, arrayStride, matrixStride);
112
113 return memberInfo;
114 }
115
116 // static
117 size_t BlockLayoutEncoder::getBlockRegister(const BlockMemberInfo &info)
118 {
119 return (info.offset / BytesPerComponent) / ComponentsPerRegister;
120 }
121
122 // static
123 size_t BlockLayoutEncoder::getBlockRegisterElement(const BlockMemberInfo &info)
124 {
125 return (info.offset / BytesPerComponent) % ComponentsPerRegister;
126 }
127
128 void BlockLayoutEncoder::nextRegister()
129 {
130 mCurrentOffset = sw::align(mCurrentOffset, ComponentsPerRegister);
131 }
132
133 Std140BlockEncoder::Std140BlockEncoder(bool rowMajor) : BlockLayoutEncoder(rowMajor)
134 {
135 }
136
137 void Std140BlockEncoder::enterAggregateType()
138 {
139 nextRegister();
140 }
141
142 void Std140BlockEncoder::exitAggregateType()
143 {
144 nextRegister();
145 }
146
147 void Std140BlockEncoder::getBlockLayoutInfo(const TType &type, unsigned int arraySize, bool isRowMajorMatrix, int *arrayStrideOut, int *matrixStrideOut)
148 {
149 size_t baseAlignment = 0;
150 int matrixStride = 0;
151 int arrayStride = 0;
152
153 if(type.isMatrix())
154 {
155 baseAlignment = ComponentsPerRegister;
156 matrixStride = ComponentsPerRegister;
157
158 if(arraySize > 0)
159 {
160 const int numRegisters = isRowMajorMatrix ? type.getSecondarySize() : type.getNominalSize();
161 arrayStride = ComponentsPerRegister * numRegisters;
162 }
163 }
164 else if(arraySize > 0)
165 {
166 baseAlignment = ComponentsPerRegister;
167 arrayStride = ComponentsPerRegister;
168 }
169 else
170 {
171 const size_t numComponents = type.getElementSize();
172 baseAlignment = (numComponents == 3 ? 4u : numComponents);
173 }
174
175 mCurrentOffset = sw::align(mCurrentOffset, baseAlignment);
176
177 *matrixStrideOut = matrixStride;
178 *arrayStrideOut = arrayStride;
179 }
180
181 void Std140BlockEncoder::advanceOffset(const TType &type, unsigned int arraySize, bool isRowMajorMatrix, int arrayStride, int matrixStride)
182 {
183 if(arraySize > 0)
184 {
185 mCurrentOffset += arrayStride * arraySize;
186 }
187 else if(type.isMatrix())
188 {
189 ASSERT(matrixStride == ComponentsPerRegister);
190 const int numRegisters = isRowMajorMatrix ? type.getSecondarySize() : type.getNominalSize();
191 mCurrentOffset += ComponentsPerRegister * numRegisters;
192 }
193 else
194 {
195 mCurrentOffset += type.getElementSize();
196 }
197 }
198
199 Attribute::Attribute()
200 {
201 type = GL_NONE;
202 arraySize = 0;
203 registerIndex = 0;
204 }
205
206 Attribute::Attribute(GLenum type, const std::string &name, int arraySize, int location, int registerIndex)
207 {
208 this->type = type;
209 this->name = name;
210 this->arraySize = arraySize;
211 this->location = location;
212 this->registerIndex = registerIndex;
213 }
214
215 sw::PixelShader *Shader::getPixelShader() const
216 {
217 return 0;
218 }
219
220 sw::VertexShader *Shader::getVertexShader() const
221 {
222 return 0;
223 }
224
225 OutputASM::TextureFunction::TextureFunction(const TString& nodeName) : method(IMPLICIT), proj(false), offset(false)
226 {
227 TString name = TFunction::unmangleName(nodeName);
228
229 if(name == "texture2D" || name == "textureCube" || name == "texture" || name == "texture3D")
230 {
231 method = IMPLICIT;
232 }
233 else if(name == "texture2DProj" || name == "textureProj")
234 {
235 method = IMPLICIT;
236 proj = true;
237 }
238 else if(name == "texture2DLod" || name == "textureCubeLod" || name == "textureLod")
239 {
240 method = LOD;
241 }
242 else if(name == "texture2DProjLod" || name == "textureProjLod")
243 {
244 method = LOD;
245 proj = true;
246 }
247 else if(name == "textureSize")
248 {
249 method = SIZE;
250 }
251 else if(name == "textureOffset")
252 {
253 method = IMPLICIT;
254 offset = true;
255 }
256 else if(name == "textureProjOffset")
257 {
258 method = IMPLICIT;
259 offset = true;
260 proj = true;
261 }
262 else if(name == "textureLodOffset")
263 {
264 method = LOD;
265 offset = true;
266 }
267 else if(name == "textureProjLodOffset")
268 {
269 method = LOD;
270 proj = true;
271 offset = true;
272 }
273 else if(name == "texelFetch")
274 {
275 method = FETCH;
276 }
277 else if(name == "texelFetchOffset")
278 {
279 method = FETCH;
280 offset = true;
281 }
282 else if(name == "textureGrad")
283 {
284 method = GRAD;
285 }
286 else if(name == "textureGradOffset")
287 {
288 method = GRAD;
289 offset = true;
290 }
291 else if(name == "textureProjGrad")
292 {
293 method = GRAD;
294 proj = true;
295 }
296 else if(name == "textureProjGradOffset")
297 {
298 method = GRAD;
299 proj = true;
300 offset = true;
301 }
302 else UNREACHABLE(0);
303 }
304
305 OutputASM::OutputASM(TParseContext &context, Shader *shaderObject) : TIntermTraverser(true, true, true), shaderObject(shaderObject), mContext(context)
306 {
307 shader = 0;
308 pixelShader = 0;
309 vertexShader = 0;
310
311 if(shaderObject)
312 {
313 shader = shaderObject->getShader();
314 pixelShader = shaderObject->getPixelShader();
315 vertexShader = shaderObject->getVertexShader();
316 }
317
318 functionArray.push_back(Function(0, "main(", 0, 0));
319 currentFunction = 0;
320 outputQualifier = EvqOutput; // Set outputQualifier to any value other than EvqFragColor or EvqFragData
321 }
322
323 OutputASM::~OutputASM()
324 {
325 }
326
327 void OutputASM::output()
328 {
329 if(shader)
330 {
331 emitShader(GLOBAL);
332
333 if(functionArray.size() > 1) // Only call main() when there are other functions
334 {
335 Instruction *callMain = emit(sw::Shader::OPCODE_CALL);
336 callMain->dst.type = sw::Shader::PARAMETER_LABEL;
337 callMain->dst.index = 0; // main()
338
339 emit(sw::Shader::OPCODE_RET);
340 }
341
342 emitShader(FUNCTION);
343 }
344 }
345
346 void OutputASM::emitShader(Scope scope)
347 {
348 emitScope = scope;
349 currentScope = GLOBAL;
350 mContext.getTreeRoot()->traverse(this);
351 }
352
353 void OutputASM::freeTemporary(Temporary *temporary)
354 {
355 free(temporaries, temporary);
356 }
357
358 sw::Shader::Opcode OutputASM::getOpcode(sw::Shader::Opcode op, TIntermTyped *in) const
359 {
360 TBasicType baseType = in->getType().getBasicType();
361
362 switch(op)
363 {
364 case sw::Shader::OPCODE_NEG:
365 switch(baseType)
366 {
367 case EbtInt:
368 case EbtUInt:
369 return sw::Shader::OPCODE_INEG;
370 case EbtFloat:
371 default:
372 return op;
373 }
374 case sw::Shader::OPCODE_ABS:
375 switch(baseType)
376 {
377 case EbtInt:
378 return sw::Shader::OPCODE_IABS;
379 case EbtFloat:
380 default:
381 return op;
382 }
383 case sw::Shader::OPCODE_SGN:
384 switch(baseType)
385 {
386 case EbtInt:
387 return sw::Shader::OPCODE_ISGN;
388 case EbtFloat:
389 default:
390 return op;
391 }
392 case sw::Shader::OPCODE_ADD:
393 switch(baseType)
394 {
395 case EbtInt:
396 case EbtUInt:
397 return sw::Shader::OPCODE_IADD;
398 case EbtFloat:
399 default:
400 return op;
401 }
402 case sw::Shader::OPCODE_SUB:
403 switch(baseType)
404 {
405 case EbtInt:
406 case EbtUInt:
407 return sw::Shader::OPCODE_ISUB;
408 case EbtFloat:
409 default:
410 return op;
411 }
412 case sw::Shader::OPCODE_MUL:
413 switch(baseType)
414 {
415 case EbtInt:
416 case EbtUInt:
417 return sw::Shader::OPCODE_IMUL;
418 case EbtFloat:
419 default:
420 return op;
421 }
422 case sw::Shader::OPCODE_DIV:
423 switch(baseType)
424 {
425 case EbtInt:
426 return sw::Shader::OPCODE_IDIV;
427 case EbtUInt:
428 return sw::Shader::OPCODE_UDIV;
429 case EbtFloat:
430 default:
431 return op;
432 }
433 case sw::Shader::OPCODE_IMOD:
434 return baseType == EbtUInt ? sw::Shader::OPCODE_UMOD : op;
435 case sw::Shader::OPCODE_ISHR:
436 return baseType == EbtUInt ? sw::Shader::OPCODE_USHR : op;
437 case sw::Shader::OPCODE_MIN:
438 switch(baseType)
439 {
440 case EbtInt:
441 return sw::Shader::OPCODE_IMIN;
442 case EbtUInt:
443 return sw::Shader::OPCODE_UMIN;
444 case EbtFloat:
445 default:
446 return op;
447 }
448 case sw::Shader::OPCODE_MAX:
449 switch(baseType)
450 {
451 case EbtInt:
452 return sw::Shader::OPCODE_IMAX;
453 case EbtUInt:
454 return sw::Shader::OPCODE_UMAX;
455 case EbtFloat:
456 default:
457 return op;
458 }
459 default:
460 return op;
461 }
462 }
463
464 void OutputASM::visitSymbol(TIntermSymbol *symbol)
465 {
466 // Vertex varyings don't have to be actively used to successfully link
467 // against pixel shaders that use them. So make sure they're declared.
468 if(symbol->getQualifier() == EvqVaryingOut || symbol->getQualifier() == EvqInvariantVaryingOut || symbol->getQualifier() == EvqVertexOut)
469 {
470 if(symbol->getBasicType() != EbtInvariant) // Typeless declarations are not new varyings
471 {
472 declareVarying(symbol, -1);
473 }
474 }
475
476 TInterfaceBlock* block = symbol->getType().getInterfaceBlock();
477 // OpenGL ES 3.0.4 spec, section 2.12.6 Uniform Variables:
478 // "All members of a named uniform block declared with a shared or std140 layout qualifier
479 // are considered active, even if they are not referenced in any shader in the program.
480 // The uniform block itself is also considered active, even if no member of the block is referenced."
481 if(block && ((block->blockStorage() == EbsShared) || (block->blockStorage() == EbsStd140)))
482 {
483 uniformRegister(symbol);
484 }
485 }
486
487 bool OutputASM::visitBinary(Visit visit, TIntermBinary *node)
488 {
489 if(currentScope != emitScope)
490 {
491 return false;
492 }
493
494 TIntermTyped *result = node;
495 TIntermTyped *left = node->getLeft();
496 TIntermTyped *right = node->getRight();
497 const TType &leftType = left->getType();
498 const TType &rightType = right->getType();
Nicolas Capens0bac2852016-05-07 06:09:58 -0400499
500 if(isSamplerRegister(result))
501 {
502 return false; // Don't traverse, the register index is determined statically
503 }
504
505 switch(node->getOp())
506 {
507 case EOpAssign:
508 if(visit == PostVisit)
509 {
510 assignLvalue(left, right);
511 copy(result, right);
512 }
513 break;
514 case EOpInitialize:
515 if(visit == PostVisit)
516 {
517 copy(left, right);
518 }
519 break;
520 case EOpMatrixTimesScalarAssign:
521 if(visit == PostVisit)
522 {
523 for(int i = 0; i < leftType.getNominalSize(); i++)
524 {
525 emit(sw::Shader::OPCODE_MUL, result, i, left, i, right);
526 }
527
528 assignLvalue(left, result);
529 }
530 break;
531 case EOpVectorTimesMatrixAssign:
532 if(visit == PostVisit)
533 {
534 int size = leftType.getNominalSize();
535
536 for(int i = 0; i < size; i++)
537 {
538 Instruction *dot = emit(sw::Shader::OPCODE_DP(size), result, 0, left, 0, right, i);
539 dot->dst.mask = 1 << i;
540 }
541
542 assignLvalue(left, result);
543 }
544 break;
545 case EOpMatrixTimesMatrixAssign:
546 if(visit == PostVisit)
547 {
548 int dim = leftType.getNominalSize();
549
550 for(int i = 0; i < dim; i++)
551 {
552 Instruction *mul = emit(sw::Shader::OPCODE_MUL, result, i, left, 0, right, i);
553 mul->src[1].swizzle = 0x00;
554
555 for(int j = 1; j < dim; j++)
556 {
557 Instruction *mad = emit(sw::Shader::OPCODE_MAD, result, i, left, j, right, i, result, i);
558 mad->src[1].swizzle = j * 0x55;
559 }
560 }
561
562 assignLvalue(left, result);
563 }
564 break;
565 case EOpIndexDirect:
566 if(visit == PostVisit)
567 {
568 int index = right->getAsConstantUnion()->getIConst(0);
569
570 if(result->isMatrix() || result->isStruct() || result->isInterfaceBlock())
571 {
572 ASSERT(left->isArray());
573 copy(result, left, index * left->elementRegisterCount());
574 }
575 else if(result->isRegister())
576 {
577 int srcIndex = 0;
578 if(left->isRegister())
579 {
580 srcIndex = 0;
581 }
582 else if(left->isArray())
583 {
584 srcIndex = index * left->elementRegisterCount();
585 }
586 else if(left->isMatrix())
587 {
588 ASSERT(index < left->getNominalSize()); // FIXME: Report semantic error
589 srcIndex = index;
590 }
591 else UNREACHABLE(0);
592
593 Instruction *mov = emit(sw::Shader::OPCODE_MOV, result, 0, left, srcIndex);
594
595 if(left->isRegister())
596 {
597 mov->src[0].swizzle = index;
598 }
599 }
600 else UNREACHABLE(0);
601 }
602 break;
603 case EOpIndexIndirect:
604 if(visit == PostVisit)
605 {
606 if(left->isArray() || left->isMatrix())
607 {
608 for(int index = 0; index < result->totalRegisterCount(); index++)
609 {
610 Instruction *mov = emit(sw::Shader::OPCODE_MOV, result, index, left, index);
611 mov->dst.mask = writeMask(result, index);
612
613 if(left->totalRegisterCount() > 1)
614 {
615 sw::Shader::SourceParameter relativeRegister;
616 argument(relativeRegister, right);
617
618 mov->src[0].rel.type = relativeRegister.type;
619 mov->src[0].rel.index = relativeRegister.index;
620 mov->src[0].rel.scale = result->totalRegisterCount();
621 mov->src[0].rel.deterministic = !(vertexShader && left->getQualifier() == EvqUniform);
622 }
623 }
624 }
625 else if(left->isRegister())
626 {
627 emit(sw::Shader::OPCODE_EXTRACT, result, left, right);
628 }
629 else UNREACHABLE(0);
630 }
631 break;
632 case EOpIndexDirectStruct:
633 case EOpIndexDirectInterfaceBlock:
634 if(visit == PostVisit)
635 {
636 ASSERT(leftType.isStruct() || (leftType.isInterfaceBlock()));
637
638 const TFieldList& fields = (node->getOp() == EOpIndexDirectStruct) ?
639 leftType.getStruct()->fields() :
640 leftType.getInterfaceBlock()->fields();
641 int index = right->getAsConstantUnion()->getIConst(0);
642 int fieldOffset = 0;
643
644 for(int i = 0; i < index; i++)
645 {
646 fieldOffset += fields[i]->type()->totalRegisterCount();
647 }
648
649 copy(result, left, fieldOffset);
650 }
651 break;
652 case EOpVectorSwizzle:
653 if(visit == PostVisit)
654 {
655 int swizzle = 0;
656 TIntermAggregate *components = right->getAsAggregate();
657
658 if(components)
659 {
660 TIntermSequence &sequence = components->getSequence();
661 int component = 0;
662
663 for(TIntermSequence::iterator sit = sequence.begin(); sit != sequence.end(); sit++)
664 {
665 TIntermConstantUnion *element = (*sit)->getAsConstantUnion();
666
667 if(element)
668 {
669 int i = element->getUnionArrayPointer()[0].getIConst();
670 swizzle |= i << (component * 2);
671 component++;
672 }
673 else UNREACHABLE(0);
674 }
675 }
676 else UNREACHABLE(0);
677
678 Instruction *mov = emit(sw::Shader::OPCODE_MOV, result, left);
679 mov->src[0].swizzle = swizzle;
680 }
681 break;
682 case EOpAddAssign: if(visit == PostVisit) emitAssign(getOpcode(sw::Shader::OPCODE_ADD, result), result, left, left, right); break;
683 case EOpAdd: if(visit == PostVisit) emitBinary(getOpcode(sw::Shader::OPCODE_ADD, result), result, left, right); break;
684 case EOpSubAssign: if(visit == PostVisit) emitAssign(getOpcode(sw::Shader::OPCODE_SUB, result), result, left, left, right); break;
685 case EOpSub: if(visit == PostVisit) emitBinary(getOpcode(sw::Shader::OPCODE_SUB, result), result, left, right); break;
686 case EOpMulAssign: if(visit == PostVisit) emitAssign(getOpcode(sw::Shader::OPCODE_MUL, result), result, left, left, right); break;
687 case EOpMul: if(visit == PostVisit) emitBinary(getOpcode(sw::Shader::OPCODE_MUL, result), result, left, right); break;
688 case EOpDivAssign: if(visit == PostVisit) emitAssign(getOpcode(sw::Shader::OPCODE_DIV, result), result, left, left, right); break;
689 case EOpDiv: if(visit == PostVisit) emitBinary(getOpcode(sw::Shader::OPCODE_DIV, result), result, left, right); break;
690 case EOpIModAssign: if(visit == PostVisit) emitAssign(getOpcode(sw::Shader::OPCODE_IMOD, result), result, left, left, right); break;
691 case EOpIMod: if(visit == PostVisit) emitBinary(getOpcode(sw::Shader::OPCODE_IMOD, result), result, left, right); break;
692 case EOpBitShiftLeftAssign: if(visit == PostVisit) emitAssign(sw::Shader::OPCODE_SHL, result, left, left, right); break;
693 case EOpBitShiftLeft: if(visit == PostVisit) emitBinary(sw::Shader::OPCODE_SHL, result, left, right); break;
694 case EOpBitShiftRightAssign: if(visit == PostVisit) emitAssign(getOpcode(sw::Shader::OPCODE_ISHR, result), result, left, left, right); break;
695 case EOpBitShiftRight: if(visit == PostVisit) emitBinary(getOpcode(sw::Shader::OPCODE_ISHR, result), result, left, right); break;
696 case EOpBitwiseAndAssign: if(visit == PostVisit) emitAssign(sw::Shader::OPCODE_AND, result, left, left, right); break;
697 case EOpBitwiseAnd: if(visit == PostVisit) emitBinary(sw::Shader::OPCODE_AND, result, left, right); break;
698 case EOpBitwiseXorAssign: if(visit == PostVisit) emitAssign(sw::Shader::OPCODE_XOR, result, left, left, right); break;
699 case EOpBitwiseXor: if(visit == PostVisit) emitBinary(sw::Shader::OPCODE_XOR, result, left, right); break;
700 case EOpBitwiseOrAssign: if(visit == PostVisit) emitAssign(sw::Shader::OPCODE_OR, result, left, left, right); break;
701 case EOpBitwiseOr: if(visit == PostVisit) emitBinary(sw::Shader::OPCODE_OR, result, left, right); break;
702 case EOpEqual:
703 if(visit == PostVisit)
704 {
705 emitBinary(sw::Shader::OPCODE_EQ, result, left, right);
706
707 for(int index = 1; index < left->totalRegisterCount(); index++)
708 {
709 Temporary equal(this);
710 emit(sw::Shader::OPCODE_EQ, &equal, 0, left, index, right, index);
711 emit(sw::Shader::OPCODE_AND, result, result, &equal);
712 }
713 }
714 break;
715 case EOpNotEqual:
716 if(visit == PostVisit)
717 {
718 emitBinary(sw::Shader::OPCODE_NE, result, left, right);
719
720 for(int index = 1; index < left->totalRegisterCount(); index++)
721 {
722 Temporary notEqual(this);
723 emit(sw::Shader::OPCODE_NE, &notEqual, 0, left, index, right, index);
724 emit(sw::Shader::OPCODE_OR, result, result, &notEqual);
725 }
726 }
727 break;
728 case EOpLessThan: if(visit == PostVisit) emitCmp(sw::Shader::CONTROL_LT, result, left, right); break;
729 case EOpGreaterThan: if(visit == PostVisit) emitCmp(sw::Shader::CONTROL_GT, result, left, right); break;
730 case EOpLessThanEqual: if(visit == PostVisit) emitCmp(sw::Shader::CONTROL_LE, result, left, right); break;
731 case EOpGreaterThanEqual: if(visit == PostVisit) emitCmp(sw::Shader::CONTROL_GE, result, left, right); break;
732 case EOpVectorTimesScalarAssign: if(visit == PostVisit) emitAssign(getOpcode(sw::Shader::OPCODE_MUL, left), result, left, left, right); break;
733 case EOpVectorTimesScalar: if(visit == PostVisit) emit(getOpcode(sw::Shader::OPCODE_MUL, left), result, left, right); break;
734 case EOpMatrixTimesScalar:
735 if(visit == PostVisit)
736 {
737 if(left->isMatrix())
738 {
739 for(int i = 0; i < leftType.getNominalSize(); i++)
740 {
741 emit(sw::Shader::OPCODE_MUL, result, i, left, i, right, 0);
742 }
743 }
744 else if(right->isMatrix())
745 {
746 for(int i = 0; i < rightType.getNominalSize(); i++)
747 {
748 emit(sw::Shader::OPCODE_MUL, result, i, left, 0, right, i);
749 }
750 }
751 else UNREACHABLE(0);
752 }
753 break;
754 case EOpVectorTimesMatrix:
755 if(visit == PostVisit)
756 {
757 sw::Shader::Opcode dpOpcode = sw::Shader::OPCODE_DP(leftType.getNominalSize());
758
759 int size = rightType.getNominalSize();
760 for(int i = 0; i < size; i++)
761 {
762 Instruction *dot = emit(dpOpcode, result, 0, left, 0, right, i);
763 dot->dst.mask = 1 << i;
764 }
765 }
766 break;
767 case EOpMatrixTimesVector:
768 if(visit == PostVisit)
769 {
770 Instruction *mul = emit(sw::Shader::OPCODE_MUL, result, left, right);
771 mul->src[1].swizzle = 0x00;
772
773 int size = rightType.getNominalSize();
774 for(int i = 1; i < size; i++)
775 {
776 Instruction *mad = emit(sw::Shader::OPCODE_MAD, result, 0, left, i, right, 0, result);
777 mad->src[1].swizzle = i * 0x55;
778 }
779 }
780 break;
781 case EOpMatrixTimesMatrix:
782 if(visit == PostVisit)
783 {
784 int dim = leftType.getNominalSize();
785
786 int size = rightType.getNominalSize();
787 for(int i = 0; i < size; i++)
788 {
789 Instruction *mul = emit(sw::Shader::OPCODE_MUL, result, i, left, 0, right, i);
790 mul->src[1].swizzle = 0x00;
791
792 for(int j = 1; j < dim; j++)
793 {
794 Instruction *mad = emit(sw::Shader::OPCODE_MAD, result, i, left, j, right, i, result, i);
795 mad->src[1].swizzle = j * 0x55;
796 }
797 }
798 }
799 break;
800 case EOpLogicalOr:
801 if(trivial(right, 6))
802 {
803 if(visit == PostVisit)
804 {
805 emit(sw::Shader::OPCODE_OR, result, left, right);
806 }
807 }
808 else // Short-circuit evaluation
809 {
810 if(visit == InVisit)
811 {
812 emit(sw::Shader::OPCODE_MOV, result, left);
813 Instruction *ifnot = emit(sw::Shader::OPCODE_IF, 0, result);
814 ifnot->src[0].modifier = sw::Shader::MODIFIER_NOT;
815 }
816 else if(visit == PostVisit)
817 {
818 emit(sw::Shader::OPCODE_MOV, result, right);
819 emit(sw::Shader::OPCODE_ENDIF);
820 }
821 }
822 break;
823 case EOpLogicalXor: if(visit == PostVisit) emit(sw::Shader::OPCODE_XOR, result, left, right); break;
824 case EOpLogicalAnd:
825 if(trivial(right, 6))
826 {
827 if(visit == PostVisit)
828 {
829 emit(sw::Shader::OPCODE_AND, result, left, right);
830 }
831 }
832 else // Short-circuit evaluation
833 {
834 if(visit == InVisit)
835 {
836 emit(sw::Shader::OPCODE_MOV, result, left);
837 emit(sw::Shader::OPCODE_IF, 0, result);
838 }
839 else if(visit == PostVisit)
840 {
841 emit(sw::Shader::OPCODE_MOV, result, right);
842 emit(sw::Shader::OPCODE_ENDIF);
843 }
844 }
845 break;
846 default: UNREACHABLE(node->getOp());
847 }
848
849 return true;
850 }
851
852 void OutputASM::emitDeterminant(TIntermTyped *result, TIntermTyped *arg, int size, int col, int row, int outCol, int outRow)
853 {
854 switch(size)
855 {
856 case 1: // Used for cofactor computation only
857 {
858 // For a 2x2 matrix, the cofactor is simply a transposed move or negate
859 bool isMov = (row == col);
860 sw::Shader::Opcode op = isMov ? sw::Shader::OPCODE_MOV : sw::Shader::OPCODE_NEG;
861 Instruction *mov = emit(op, result, outCol, arg, isMov ? 1 - row : row);
862 mov->src[0].swizzle = 0x55 * (isMov ? 1 - col : col);
863 mov->dst.mask = 1 << outRow;
864 }
865 break;
866 case 2:
867 {
868 static const unsigned int swizzle[3] = { 0x99, 0x88, 0x44 }; // xy?? : yzyz, xzxz, xyxy
869
870 bool isCofactor = (col >= 0) && (row >= 0);
871 int col0 = (isCofactor && (col <= 0)) ? 1 : 0;
872 int col1 = (isCofactor && (col <= 1)) ? 2 : 1;
873 bool negate = isCofactor && ((col & 0x01) ^ (row & 0x01));
874
875 Instruction *det = emit(sw::Shader::OPCODE_DET2, result, outCol, arg, negate ? col1 : col0, arg, negate ? col0 : col1);
876 det->src[0].swizzle = det->src[1].swizzle = swizzle[isCofactor ? row : 2];
877 det->dst.mask = 1 << outRow;
878 }
879 break;
880 case 3:
881 {
882 static const unsigned int swizzle[4] = { 0xF9, 0xF8, 0xF4, 0xE4 }; // xyz? : yzww, xzww, xyww, xyzw
883
884 bool isCofactor = (col >= 0) && (row >= 0);
885 int col0 = (isCofactor && (col <= 0)) ? 1 : 0;
886 int col1 = (isCofactor && (col <= 1)) ? 2 : 1;
887 int col2 = (isCofactor && (col <= 2)) ? 3 : 2;
888 bool negate = isCofactor && ((col & 0x01) ^ (row & 0x01));
889
890 Instruction *det = emit(sw::Shader::OPCODE_DET3, result, outCol, arg, col0, arg, negate ? col2 : col1, arg, negate ? col1 : col2);
891 det->src[0].swizzle = det->src[1].swizzle = det->src[2].swizzle = swizzle[isCofactor ? row : 3];
892 det->dst.mask = 1 << outRow;
893 }
894 break;
895 case 4:
896 {
897 Instruction *det = emit(sw::Shader::OPCODE_DET4, result, outCol, arg, 0, arg, 1, arg, 2, arg, 3);
898 det->dst.mask = 1 << outRow;
899 }
900 break;
901 default:
902 UNREACHABLE(size);
903 break;
904 }
905 }
906
907 bool OutputASM::visitUnary(Visit visit, TIntermUnary *node)
908 {
909 if(currentScope != emitScope)
910 {
911 return false;
912 }
913
914 TIntermTyped *result = node;
915 TIntermTyped *arg = node->getOperand();
916 TBasicType basicType = arg->getType().getBasicType();
917
918 union
919 {
920 float f;
921 int i;
922 } one_value;
923
924 if(basicType == EbtInt || basicType == EbtUInt)
925 {
926 one_value.i = 1;
927 }
928 else
929 {
930 one_value.f = 1.0f;
931 }
932
933 Constant one(one_value.f, one_value.f, one_value.f, one_value.f);
934 Constant rad(1.74532925e-2f, 1.74532925e-2f, 1.74532925e-2f, 1.74532925e-2f);
935 Constant deg(5.72957795e+1f, 5.72957795e+1f, 5.72957795e+1f, 5.72957795e+1f);
936
937 switch(node->getOp())
938 {
939 case EOpNegative:
940 if(visit == PostVisit)
941 {
942 sw::Shader::Opcode negOpcode = getOpcode(sw::Shader::OPCODE_NEG, arg);
943 for(int index = 0; index < arg->totalRegisterCount(); index++)
944 {
945 emit(negOpcode, result, index, arg, index);
946 }
947 }
948 break;
949 case EOpVectorLogicalNot: if(visit == PostVisit) emit(sw::Shader::OPCODE_NOT, result, arg); break;
950 case EOpLogicalNot: if(visit == PostVisit) emit(sw::Shader::OPCODE_NOT, result, arg); break;
951 case EOpPostIncrement:
952 if(visit == PostVisit)
953 {
954 copy(result, arg);
955
956 sw::Shader::Opcode addOpcode = getOpcode(sw::Shader::OPCODE_ADD, arg);
957 for(int index = 0; index < arg->totalRegisterCount(); index++)
958 {
959 emit(addOpcode, arg, index, arg, index, &one);
960 }
961
962 assignLvalue(arg, arg);
963 }
964 break;
965 case EOpPostDecrement:
966 if(visit == PostVisit)
967 {
968 copy(result, arg);
969
970 sw::Shader::Opcode subOpcode = getOpcode(sw::Shader::OPCODE_SUB, arg);
971 for(int index = 0; index < arg->totalRegisterCount(); index++)
972 {
973 emit(subOpcode, arg, index, arg, index, &one);
974 }
975
976 assignLvalue(arg, arg);
977 }
978 break;
979 case EOpPreIncrement:
980 if(visit == PostVisit)
981 {
982 sw::Shader::Opcode addOpcode = getOpcode(sw::Shader::OPCODE_ADD, arg);
983 for(int index = 0; index < arg->totalRegisterCount(); index++)
984 {
985 emit(addOpcode, result, index, arg, index, &one);
986 }
987
988 assignLvalue(arg, result);
989 }
990 break;
991 case EOpPreDecrement:
992 if(visit == PostVisit)
993 {
994 sw::Shader::Opcode subOpcode = getOpcode(sw::Shader::OPCODE_SUB, arg);
995 for(int index = 0; index < arg->totalRegisterCount(); index++)
996 {
997 emit(subOpcode, result, index, arg, index, &one);
998 }
999
1000 assignLvalue(arg, result);
1001 }
1002 break;
1003 case EOpRadians: if(visit == PostVisit) emit(sw::Shader::OPCODE_MUL, result, arg, &rad); break;
1004 case EOpDegrees: if(visit == PostVisit) emit(sw::Shader::OPCODE_MUL, result, arg, &deg); break;
1005 case EOpSin: if(visit == PostVisit) emit(sw::Shader::OPCODE_SIN, result, arg); break;
1006 case EOpCos: if(visit == PostVisit) emit(sw::Shader::OPCODE_COS, result, arg); break;
1007 case EOpTan: if(visit == PostVisit) emit(sw::Shader::OPCODE_TAN, result, arg); break;
1008 case EOpAsin: if(visit == PostVisit) emit(sw::Shader::OPCODE_ASIN, result, arg); break;
1009 case EOpAcos: if(visit == PostVisit) emit(sw::Shader::OPCODE_ACOS, result, arg); break;
1010 case EOpAtan: if(visit == PostVisit) emit(sw::Shader::OPCODE_ATAN, result, arg); break;
1011 case EOpSinh: if(visit == PostVisit) emit(sw::Shader::OPCODE_SINH, result, arg); break;
1012 case EOpCosh: if(visit == PostVisit) emit(sw::Shader::OPCODE_COSH, result, arg); break;
1013 case EOpTanh: if(visit == PostVisit) emit(sw::Shader::OPCODE_TANH, result, arg); break;
1014 case EOpAsinh: if(visit == PostVisit) emit(sw::Shader::OPCODE_ASINH, result, arg); break;
1015 case EOpAcosh: if(visit == PostVisit) emit(sw::Shader::OPCODE_ACOSH, result, arg); break;
1016 case EOpAtanh: if(visit == PostVisit) emit(sw::Shader::OPCODE_ATANH, result, arg); break;
1017 case EOpExp: if(visit == PostVisit) emit(sw::Shader::OPCODE_EXP, result, arg); break;
1018 case EOpLog: if(visit == PostVisit) emit(sw::Shader::OPCODE_LOG, result, arg); break;
1019 case EOpExp2: if(visit == PostVisit) emit(sw::Shader::OPCODE_EXP2, result, arg); break;
1020 case EOpLog2: if(visit == PostVisit) emit(sw::Shader::OPCODE_LOG2, result, arg); break;
1021 case EOpSqrt: if(visit == PostVisit) emit(sw::Shader::OPCODE_SQRT, result, arg); break;
1022 case EOpInverseSqrt: if(visit == PostVisit) emit(sw::Shader::OPCODE_RSQ, result, arg); break;
1023 case EOpAbs: if(visit == PostVisit) emit(getOpcode(sw::Shader::OPCODE_ABS, result), result, arg); break;
1024 case EOpSign: if(visit == PostVisit) emit(getOpcode(sw::Shader::OPCODE_SGN, result), result, arg); break;
1025 case EOpFloor: if(visit == PostVisit) emit(sw::Shader::OPCODE_FLOOR, result, arg); break;
1026 case EOpTrunc: if(visit == PostVisit) emit(sw::Shader::OPCODE_TRUNC, result, arg); break;
1027 case EOpRound: if(visit == PostVisit) emit(sw::Shader::OPCODE_ROUND, result, arg); break;
1028 case EOpRoundEven: if(visit == PostVisit) emit(sw::Shader::OPCODE_ROUNDEVEN, result, arg); break;
1029 case EOpCeil: if(visit == PostVisit) emit(sw::Shader::OPCODE_CEIL, result, arg, result); break;
1030 case EOpFract: if(visit == PostVisit) emit(sw::Shader::OPCODE_FRC, result, arg); break;
1031 case EOpIsNan: if(visit == PostVisit) emit(sw::Shader::OPCODE_ISNAN, result, arg); break;
1032 case EOpIsInf: if(visit == PostVisit) emit(sw::Shader::OPCODE_ISINF, result, arg); break;
1033 case EOpLength: if(visit == PostVisit) emit(sw::Shader::OPCODE_LEN(dim(arg)), result, arg); break;
1034 case EOpNormalize: if(visit == PostVisit) emit(sw::Shader::OPCODE_NRM(dim(arg)), result, arg); break;
1035 case EOpDFdx: if(visit == PostVisit) emit(sw::Shader::OPCODE_DFDX, result, arg); break;
1036 case EOpDFdy: if(visit == PostVisit) emit(sw::Shader::OPCODE_DFDY, result, arg); break;
1037 case EOpFwidth: if(visit == PostVisit) emit(sw::Shader::OPCODE_FWIDTH, result, arg); break;
1038 case EOpAny: if(visit == PostVisit) emit(sw::Shader::OPCODE_ANY, result, arg); break;
1039 case EOpAll: if(visit == PostVisit) emit(sw::Shader::OPCODE_ALL, result, arg); break;
1040 case EOpFloatBitsToInt: if(visit == PostVisit) emit(sw::Shader::OPCODE_FLOATBITSTOINT, result, arg); break;
1041 case EOpFloatBitsToUint: if(visit == PostVisit) emit(sw::Shader::OPCODE_FLOATBITSTOUINT, result, arg); break;
1042 case EOpIntBitsToFloat: if(visit == PostVisit) emit(sw::Shader::OPCODE_INTBITSTOFLOAT, result, arg); break;
1043 case EOpUintBitsToFloat: if(visit == PostVisit) emit(sw::Shader::OPCODE_UINTBITSTOFLOAT, result, arg); break;
1044 case EOpPackSnorm2x16: if(visit == PostVisit) emit(sw::Shader::OPCODE_PACKSNORM2x16, result, arg); break;
1045 case EOpPackUnorm2x16: if(visit == PostVisit) emit(sw::Shader::OPCODE_PACKUNORM2x16, result, arg); break;
1046 case EOpPackHalf2x16: if(visit == PostVisit) emit(sw::Shader::OPCODE_PACKHALF2x16, result, arg); break;
1047 case EOpUnpackSnorm2x16: if(visit == PostVisit) emit(sw::Shader::OPCODE_UNPACKSNORM2x16, result, arg); break;
1048 case EOpUnpackUnorm2x16: if(visit == PostVisit) emit(sw::Shader::OPCODE_UNPACKUNORM2x16, result, arg); break;
1049 case EOpUnpackHalf2x16: if(visit == PostVisit) emit(sw::Shader::OPCODE_UNPACKHALF2x16, result, arg); break;
1050 case EOpTranspose:
1051 if(visit == PostVisit)
1052 {
1053 int numCols = arg->getNominalSize();
1054 int numRows = arg->getSecondarySize();
1055 for(int i = 0; i < numCols; ++i)
1056 {
1057 for(int j = 0; j < numRows; ++j)
1058 {
1059 Instruction *mov = emit(sw::Shader::OPCODE_MOV, result, j, arg, i);
1060 mov->src[0].swizzle = 0x55 * j;
1061 mov->dst.mask = 1 << i;
1062 }
1063 }
1064 }
1065 break;
1066 case EOpDeterminant:
1067 if(visit == PostVisit)
1068 {
1069 int size = arg->getNominalSize();
1070 ASSERT(size == arg->getSecondarySize());
1071
1072 emitDeterminant(result, arg, size);
1073 }
1074 break;
1075 case EOpInverse:
1076 if(visit == PostVisit)
1077 {
1078 int size = arg->getNominalSize();
1079 ASSERT(size == arg->getSecondarySize());
1080
1081 // Compute transposed matrix of cofactors
1082 for(int i = 0; i < size; ++i)
1083 {
1084 for(int j = 0; j < size; ++j)
1085 {
1086 // For a 2x2 matrix, the cofactor is simply a transposed move or negate
1087 // For a 3x3 or 4x4 matrix, the cofactor is a transposed determinant
1088 emitDeterminant(result, arg, size - 1, j, i, i, j);
1089 }
1090 }
1091
1092 // Compute 1 / determinant
1093 Temporary invDet(this);
1094 emitDeterminant(&invDet, arg, size);
1095 Constant one(1.0f, 1.0f, 1.0f, 1.0f);
1096 Instruction *div = emit(sw::Shader::OPCODE_DIV, &invDet, &one, &invDet);
1097 div->src[1].swizzle = 0x00; // xxxx
1098
1099 // Divide transposed matrix of cofactors by determinant
1100 for(int i = 0; i < size; ++i)
1101 {
1102 emit(sw::Shader::OPCODE_MUL, result, i, result, i, &invDet);
1103 }
1104 }
1105 break;
1106 default: UNREACHABLE(node->getOp());
1107 }
1108
1109 return true;
1110 }
1111
1112 bool OutputASM::visitAggregate(Visit visit, TIntermAggregate *node)
1113 {
1114 if(currentScope != emitScope && node->getOp() != EOpFunction && node->getOp() != EOpSequence)
1115 {
1116 return false;
1117 }
1118
1119 Constant zero(0.0f, 0.0f, 0.0f, 0.0f);
1120
1121 TIntermTyped *result = node;
1122 const TType &resultType = node->getType();
1123 TIntermSequence &arg = node->getSequence();
1124 size_t argumentCount = arg.size();
1125
1126 switch(node->getOp())
1127 {
1128 case EOpSequence: break;
1129 case EOpDeclaration: break;
1130 case EOpInvariantDeclaration: break;
1131 case EOpPrototype: break;
1132 case EOpComma:
1133 if(visit == PostVisit)
1134 {
1135 copy(result, arg[1]);
1136 }
1137 break;
1138 case EOpFunction:
1139 if(visit == PreVisit)
1140 {
1141 const TString &name = node->getName();
1142
1143 if(emitScope == FUNCTION)
1144 {
1145 if(functionArray.size() > 1) // No need for a label when there's only main()
1146 {
1147 Instruction *label = emit(sw::Shader::OPCODE_LABEL);
1148 label->dst.type = sw::Shader::PARAMETER_LABEL;
1149
1150 const Function *function = findFunction(name);
1151 ASSERT(function); // Should have been added during global pass
1152 label->dst.index = function->label;
1153 currentFunction = function->label;
1154 }
1155 }
1156 else if(emitScope == GLOBAL)
1157 {
1158 if(name != "main(")
1159 {
1160 TIntermSequence &arguments = node->getSequence()[0]->getAsAggregate()->getSequence();
1161 functionArray.push_back(Function(functionArray.size(), name, &arguments, node));
1162 }
1163 }
1164 else UNREACHABLE(emitScope);
1165
1166 currentScope = FUNCTION;
1167 }
1168 else if(visit == PostVisit)
1169 {
1170 if(emitScope == FUNCTION)
1171 {
1172 if(functionArray.size() > 1) // No need to return when there's only main()
1173 {
1174 emit(sw::Shader::OPCODE_RET);
1175 }
1176 }
1177
1178 currentScope = GLOBAL;
1179 }
1180 break;
1181 case EOpFunctionCall:
1182 if(visit == PostVisit)
1183 {
1184 if(node->isUserDefined())
1185 {
1186 const TString &name = node->getName();
1187 const Function *function = findFunction(name);
1188
1189 if(!function)
1190 {
1191 mContext.error(node->getLine(), "function definition not found", name.c_str());
1192 return false;
1193 }
1194
1195 TIntermSequence &arguments = *function->arg;
1196
1197 for(size_t i = 0; i < argumentCount; i++)
1198 {
1199 TIntermTyped *in = arguments[i]->getAsTyped();
1200
1201 if(in->getQualifier() == EvqIn ||
1202 in->getQualifier() == EvqInOut ||
1203 in->getQualifier() == EvqConstReadOnly)
1204 {
1205 copy(in, arg[i]);
1206 }
1207 }
1208
1209 Instruction *call = emit(sw::Shader::OPCODE_CALL);
1210 call->dst.type = sw::Shader::PARAMETER_LABEL;
1211 call->dst.index = function->label;
1212
1213 if(function->ret && function->ret->getType().getBasicType() != EbtVoid)
1214 {
1215 copy(result, function->ret);
1216 }
1217
1218 for(size_t i = 0; i < argumentCount; i++)
1219 {
1220 TIntermTyped *argument = arguments[i]->getAsTyped();
1221 TIntermTyped *out = arg[i]->getAsTyped();
1222
1223 if(argument->getQualifier() == EvqOut ||
1224 argument->getQualifier() == EvqInOut)
1225 {
Nicolas Capens5da2d3f2016-06-11 00:41:49 -04001226 assignLvalue(out, argument);
Nicolas Capens0bac2852016-05-07 06:09:58 -04001227 }
1228 }
1229 }
1230 else
1231 {
1232 const TextureFunction textureFunction(node->getName());
1233 TIntermTyped *t = arg[1]->getAsTyped();
1234
1235 Temporary coord(this);
1236
1237 if(textureFunction.proj)
1238 {
1239 TIntermConstantUnion* constant = arg[1]->getAsConstantUnion();
1240 if(constant)
1241 {
1242 float projFactor = 1.0f / constant->getFConst(t->getNominalSize() - 1);
1243 Constant projCoord(constant->getFConst(0) * projFactor,
1244 constant->getFConst(1) * projFactor,
1245 constant->getFConst(2) * projFactor,
1246 0.0f);
1247 emit(sw::Shader::OPCODE_MOV, &coord, &projCoord);
1248 }
1249 else
1250 {
1251 Instruction *rcp = emit(sw::Shader::OPCODE_RCPX, &coord, arg[1]);
1252 rcp->src[0].swizzle = 0x55 * (t->getNominalSize() - 1);
1253 rcp->dst.mask = 0x7;
1254
1255 Instruction *mul = emit(sw::Shader::OPCODE_MUL, &coord, arg[1], &coord);
1256 mul->dst.mask = 0x7;
1257 }
1258 }
1259 else
1260 {
1261 emit(sw::Shader::OPCODE_MOV, &coord, arg[1]);
1262 }
1263
1264 switch(textureFunction.method)
1265 {
1266 case TextureFunction::IMPLICIT:
1267 {
1268 TIntermNode* offset = textureFunction.offset ? arg[2] : 0;
1269
1270 if(argumentCount == 2 || (textureFunction.offset && argumentCount == 3))
1271 {
Alexis Hetu7208e932016-06-02 11:19:24 -04001272 emit(textureFunction.offset ? sw::Shader::OPCODE_TEXOFFSET : sw::Shader::OPCODE_TEX,
1273 result, &coord, arg[0], offset);
Nicolas Capens0bac2852016-05-07 06:09:58 -04001274 }
1275 else if(argumentCount == 3 || (textureFunction.offset && argumentCount == 4)) // bias
1276 {
1277 Instruction *bias = emit(sw::Shader::OPCODE_MOV, &coord, arg[textureFunction.offset ? 3 : 2]);
1278 bias->dst.mask = 0x8;
1279
1280 Instruction *tex = emit(textureFunction.offset ? sw::Shader::OPCODE_TEXOFFSET : sw::Shader::OPCODE_TEX,
1281 result, &coord, arg[0], offset); // FIXME: Implement an efficient TEXLDB instruction
1282 tex->bias = true;
1283 }
1284 else UNREACHABLE(argumentCount);
1285 }
1286 break;
1287 case TextureFunction::LOD:
1288 {
1289 Instruction *lod = emit(sw::Shader::OPCODE_MOV, &coord, arg[2]);
1290 lod->dst.mask = 0x8;
1291
1292 emit(textureFunction.offset ? sw::Shader::OPCODE_TEXLDLOFFSET : sw::Shader::OPCODE_TEXLDL,
1293 result, &coord, arg[0], textureFunction.offset ? arg[3] : nullptr);
1294 }
1295 break;
1296 case TextureFunction::FETCH:
1297 {
1298 if(argumentCount == 3 || (textureFunction.offset && argumentCount == 4))
1299 {
Meng-Lin Wu9d62c482016-06-14 11:11:25 -04001300 Instruction *lod = emit(sw::Shader::OPCODE_MOV, &coord, arg[2]);
1301 lod->dst.mask = 0x8;
1302
Nicolas Capens0bac2852016-05-07 06:09:58 -04001303 TIntermNode *offset = textureFunction.offset ? arg[3] : nullptr;
1304
1305 emit(textureFunction.offset ? sw::Shader::OPCODE_TEXELFETCHOFFSET : sw::Shader::OPCODE_TEXELFETCH,
Meng-Lin Wu9d62c482016-06-14 11:11:25 -04001306 result, &coord, arg[0], offset);
Nicolas Capens0bac2852016-05-07 06:09:58 -04001307 }
1308 else UNREACHABLE(argumentCount);
1309 }
1310 break;
1311 case TextureFunction::GRAD:
1312 {
1313 if(argumentCount == 4 || (textureFunction.offset && argumentCount == 5))
1314 {
1315 TIntermNode *offset = textureFunction.offset ? arg[4] : nullptr;
1316
1317 emit(textureFunction.offset ? sw::Shader::OPCODE_TEXGRADOFFSET : sw::Shader::OPCODE_TEXGRAD,
1318 result, &coord, arg[0], arg[2], arg[3], offset);
1319 }
1320 else UNREACHABLE(argumentCount);
1321 }
1322 break;
1323 case TextureFunction::SIZE:
1324 emit(sw::Shader::OPCODE_TEXSIZE, result, arg[1], arg[0]);
1325 break;
1326 default:
1327 UNREACHABLE(textureFunction.method);
1328 }
1329 }
1330 }
1331 break;
1332 case EOpParameters:
1333 break;
1334 case EOpConstructFloat:
1335 case EOpConstructVec2:
1336 case EOpConstructVec3:
1337 case EOpConstructVec4:
1338 case EOpConstructBool:
1339 case EOpConstructBVec2:
1340 case EOpConstructBVec3:
1341 case EOpConstructBVec4:
1342 case EOpConstructInt:
1343 case EOpConstructIVec2:
1344 case EOpConstructIVec3:
1345 case EOpConstructIVec4:
1346 case EOpConstructUInt:
1347 case EOpConstructUVec2:
1348 case EOpConstructUVec3:
1349 case EOpConstructUVec4:
1350 if(visit == PostVisit)
1351 {
1352 int component = 0;
1353
1354 for(size_t i = 0; i < argumentCount; i++)
1355 {
1356 TIntermTyped *argi = arg[i]->getAsTyped();
1357 int size = argi->getNominalSize();
1358
1359 if(!argi->isMatrix())
1360 {
1361 Instruction *mov = emitCast(result, argi);
1362 mov->dst.mask = (0xF << component) & 0xF;
1363 mov->src[0].swizzle = readSwizzle(argi, size) << (component * 2);
1364
1365 component += size;
1366 }
1367 else // Matrix
1368 {
1369 int column = 0;
1370
1371 while(component < resultType.getNominalSize())
1372 {
1373 Instruction *mov = emitCast(result, 0, argi, column);
1374 mov->dst.mask = (0xF << component) & 0xF;
1375 mov->src[0].swizzle = readSwizzle(argi, size) << (component * 2);
1376
1377 column++;
1378 component += size;
1379 }
1380 }
1381 }
1382 }
1383 break;
1384 case EOpConstructMat2:
1385 case EOpConstructMat2x3:
1386 case EOpConstructMat2x4:
1387 case EOpConstructMat3x2:
1388 case EOpConstructMat3:
1389 case EOpConstructMat3x4:
1390 case EOpConstructMat4x2:
1391 case EOpConstructMat4x3:
1392 case EOpConstructMat4:
1393 if(visit == PostVisit)
1394 {
1395 TIntermTyped *arg0 = arg[0]->getAsTyped();
1396 const int outCols = result->getNominalSize();
1397 const int outRows = result->getSecondarySize();
1398
1399 if(arg0->isScalar() && arg.size() == 1) // Construct scale matrix
1400 {
1401 for(int i = 0; i < outCols; i++)
1402 {
Alexis Hetu7208e932016-06-02 11:19:24 -04001403 emit(sw::Shader::OPCODE_MOV, result, i, &zero);
Nicolas Capens0bac2852016-05-07 06:09:58 -04001404 Instruction *mov = emitCast(result, i, arg0, 0);
1405 mov->dst.mask = 1 << i;
1406 ASSERT(mov->src[0].swizzle == 0x00);
1407 }
1408 }
1409 else if(arg0->isMatrix())
1410 {
1411 const int inCols = arg0->getNominalSize();
1412 const int inRows = arg0->getSecondarySize();
1413
1414 for(int i = 0; i < outCols; i++)
1415 {
1416 if(i >= inCols || outRows > inRows)
1417 {
1418 // Initialize to identity matrix
1419 Constant col((i == 0 ? 1.0f : 0.0f), (i == 1 ? 1.0f : 0.0f), (i == 2 ? 1.0f : 0.0f), (i == 3 ? 1.0f : 0.0f));
Alexis Hetu7208e932016-06-02 11:19:24 -04001420 emitCast(result, i, &col, 0);
Nicolas Capens0bac2852016-05-07 06:09:58 -04001421 }
1422
1423 if(i < inCols)
1424 {
1425 Instruction *mov = emitCast(result, i, arg0, i);
1426 mov->dst.mask = 0xF >> (4 - inRows);
1427 }
1428 }
1429 }
1430 else
1431 {
1432 int column = 0;
1433 int row = 0;
1434
1435 for(size_t i = 0; i < argumentCount; i++)
1436 {
1437 TIntermTyped *argi = arg[i]->getAsTyped();
1438 int size = argi->getNominalSize();
1439 int element = 0;
1440
1441 while(element < size)
1442 {
1443 Instruction *mov = emitCast(result, column, argi, 0);
1444 mov->dst.mask = (0xF << row) & 0xF;
1445 mov->src[0].swizzle = (readSwizzle(argi, size) << (row * 2)) + 0x55 * element;
1446
1447 int end = row + size - element;
1448 column = end >= outRows ? column + 1 : column;
1449 element = element + outRows - row;
1450 row = end >= outRows ? 0 : end;
1451 }
1452 }
1453 }
1454 }
1455 break;
1456 case EOpConstructStruct:
1457 if(visit == PostVisit)
1458 {
1459 int offset = 0;
1460 for(size_t i = 0; i < argumentCount; i++)
1461 {
1462 TIntermTyped *argi = arg[i]->getAsTyped();
1463 int size = argi->totalRegisterCount();
1464
1465 for(int index = 0; index < size; index++)
1466 {
1467 Instruction *mov = emit(sw::Shader::OPCODE_MOV, result, index + offset, argi, index);
1468 mov->dst.mask = writeMask(result, offset + index);
1469 }
1470
1471 offset += size;
1472 }
1473 }
1474 break;
1475 case EOpLessThan: if(visit == PostVisit) emitCmp(sw::Shader::CONTROL_LT, result, arg[0], arg[1]); break;
1476 case EOpGreaterThan: if(visit == PostVisit) emitCmp(sw::Shader::CONTROL_GT, result, arg[0], arg[1]); break;
1477 case EOpLessThanEqual: if(visit == PostVisit) emitCmp(sw::Shader::CONTROL_LE, result, arg[0], arg[1]); break;
1478 case EOpGreaterThanEqual: if(visit == PostVisit) emitCmp(sw::Shader::CONTROL_GE, result, arg[0], arg[1]); break;
1479 case EOpVectorEqual: if(visit == PostVisit) emitCmp(sw::Shader::CONTROL_EQ, result, arg[0], arg[1]); break;
1480 case EOpVectorNotEqual: if(visit == PostVisit) emitCmp(sw::Shader::CONTROL_NE, result, arg[0], arg[1]); break;
1481 case EOpMod: if(visit == PostVisit) emit(sw::Shader::OPCODE_MOD, result, arg[0], arg[1]); break;
1482 case EOpModf:
1483 if(visit == PostVisit)
1484 {
1485 TIntermTyped* arg1 = arg[1]->getAsTyped();
1486 emit(sw::Shader::OPCODE_TRUNC, arg1, arg[0]);
1487 assignLvalue(arg1, arg1);
1488 emitBinary(sw::Shader::OPCODE_SUB, result, arg[0], arg1);
1489 }
1490 break;
1491 case EOpPow: if(visit == PostVisit) emit(sw::Shader::OPCODE_POW, result, arg[0], arg[1]); break;
1492 case EOpAtan: if(visit == PostVisit) emit(sw::Shader::OPCODE_ATAN2, result, arg[0], arg[1]); break;
1493 case EOpMin: if(visit == PostVisit) emit(getOpcode(sw::Shader::OPCODE_MIN, result), result, arg[0], arg[1]); break;
1494 case EOpMax: if(visit == PostVisit) emit(getOpcode(sw::Shader::OPCODE_MAX, result), result, arg[0], arg[1]); break;
1495 case EOpClamp:
1496 if(visit == PostVisit)
1497 {
1498 emit(getOpcode(sw::Shader::OPCODE_MAX, result), result, arg[0], arg[1]);
1499 emit(getOpcode(sw::Shader::OPCODE_MIN, result), result, result, arg[2]);
1500 }
1501 break;
1502 case EOpMix: if(visit == PostVisit) emit(sw::Shader::OPCODE_LRP, result, arg[2], arg[1], arg[0]); break;
1503 case EOpStep: if(visit == PostVisit) emit(sw::Shader::OPCODE_STEP, result, arg[0], arg[1]); break;
1504 case EOpSmoothStep: if(visit == PostVisit) emit(sw::Shader::OPCODE_SMOOTH, result, arg[0], arg[1], arg[2]); break;
1505 case EOpDistance: if(visit == PostVisit) emit(sw::Shader::OPCODE_DIST(dim(arg[0])), result, arg[0], arg[1]); break;
1506 case EOpDot: if(visit == PostVisit) emit(sw::Shader::OPCODE_DP(dim(arg[0])), result, arg[0], arg[1]); break;
1507 case EOpCross: if(visit == PostVisit) emit(sw::Shader::OPCODE_CRS, result, arg[0], arg[1]); break;
1508 case EOpFaceForward: if(visit == PostVisit) emit(sw::Shader::OPCODE_FORWARD(dim(arg[0])), result, arg[0], arg[1], arg[2]); break;
1509 case EOpReflect: if(visit == PostVisit) emit(sw::Shader::OPCODE_REFLECT(dim(arg[0])), result, arg[0], arg[1]); break;
1510 case EOpRefract: if(visit == PostVisit) emit(sw::Shader::OPCODE_REFRACT(dim(arg[0])), result, arg[0], arg[1], arg[2]); break;
1511 case EOpMul:
1512 if(visit == PostVisit)
1513 {
1514 TIntermTyped *arg0 = arg[0]->getAsTyped();
1515 TIntermTyped *arg1 = arg[1]->getAsTyped();
1516 ASSERT((arg0->getNominalSize() == arg1->getNominalSize()) && (arg0->getSecondarySize() == arg1->getSecondarySize()));
1517
1518 int size = arg0->getNominalSize();
1519 for(int i = 0; i < size; i++)
1520 {
1521 emit(sw::Shader::OPCODE_MUL, result, i, arg[0], i, arg[1], i);
1522 }
1523 }
1524 break;
1525 case EOpOuterProduct:
1526 if(visit == PostVisit)
1527 {
1528 for(int i = 0; i < dim(arg[1]); i++)
1529 {
1530 Instruction *mul = emit(sw::Shader::OPCODE_MUL, result, i, arg[0], 0, arg[1]);
1531 mul->src[1].swizzle = 0x55 * i;
1532 }
1533 }
1534 break;
1535 default: UNREACHABLE(node->getOp());
1536 }
1537
1538 return true;
1539 }
1540
1541 bool OutputASM::visitSelection(Visit visit, TIntermSelection *node)
1542 {
1543 if(currentScope != emitScope)
1544 {
1545 return false;
1546 }
1547
1548 TIntermTyped *condition = node->getCondition();
1549 TIntermNode *trueBlock = node->getTrueBlock();
1550 TIntermNode *falseBlock = node->getFalseBlock();
1551 TIntermConstantUnion *constantCondition = condition->getAsConstantUnion();
1552
1553 condition->traverse(this);
1554
1555 if(node->usesTernaryOperator())
1556 {
1557 if(constantCondition)
1558 {
1559 bool trueCondition = constantCondition->getUnionArrayPointer()->getBConst();
1560
1561 if(trueCondition)
1562 {
1563 trueBlock->traverse(this);
1564 copy(node, trueBlock);
1565 }
1566 else
1567 {
1568 falseBlock->traverse(this);
1569 copy(node, falseBlock);
1570 }
1571 }
1572 else if(trivial(node, 6)) // Fast to compute both potential results and no side effects
1573 {
1574 trueBlock->traverse(this);
1575 falseBlock->traverse(this);
1576 emit(sw::Shader::OPCODE_SELECT, node, condition, trueBlock, falseBlock);
1577 }
1578 else
1579 {
1580 emit(sw::Shader::OPCODE_IF, 0, condition);
1581
1582 if(trueBlock)
1583 {
1584 trueBlock->traverse(this);
1585 copy(node, trueBlock);
1586 }
1587
1588 if(falseBlock)
1589 {
1590 emit(sw::Shader::OPCODE_ELSE);
1591 falseBlock->traverse(this);
1592 copy(node, falseBlock);
1593 }
1594
1595 emit(sw::Shader::OPCODE_ENDIF);
1596 }
1597 }
1598 else // if/else statement
1599 {
1600 if(constantCondition)
1601 {
1602 bool trueCondition = constantCondition->getUnionArrayPointer()->getBConst();
1603
1604 if(trueCondition)
1605 {
1606 if(trueBlock)
1607 {
1608 trueBlock->traverse(this);
1609 }
1610 }
1611 else
1612 {
1613 if(falseBlock)
1614 {
1615 falseBlock->traverse(this);
1616 }
1617 }
1618 }
1619 else
1620 {
1621 emit(sw::Shader::OPCODE_IF, 0, condition);
1622
1623 if(trueBlock)
1624 {
1625 trueBlock->traverse(this);
1626 }
1627
1628 if(falseBlock)
1629 {
1630 emit(sw::Shader::OPCODE_ELSE);
1631 falseBlock->traverse(this);
1632 }
1633
1634 emit(sw::Shader::OPCODE_ENDIF);
1635 }
1636 }
1637
1638 return false;
1639 }
1640
1641 bool OutputASM::visitLoop(Visit visit, TIntermLoop *node)
1642 {
1643 if(currentScope != emitScope)
1644 {
1645 return false;
1646 }
1647
1648 unsigned int iterations = loopCount(node);
1649
1650 if(iterations == 0)
1651 {
1652 return false;
1653 }
1654
1655 bool unroll = (iterations <= 4);
1656
1657 if(unroll)
1658 {
1659 LoopUnrollable loopUnrollable;
1660 unroll = loopUnrollable.traverse(node);
1661 }
1662
1663 TIntermNode *init = node->getInit();
1664 TIntermTyped *condition = node->getCondition();
1665 TIntermTyped *expression = node->getExpression();
1666 TIntermNode *body = node->getBody();
1667 Constant True(true);
1668
1669 if(node->getType() == ELoopDoWhile)
1670 {
1671 Temporary iterate(this);
1672 emit(sw::Shader::OPCODE_MOV, &iterate, &True);
1673
1674 emit(sw::Shader::OPCODE_WHILE, 0, &iterate); // FIXME: Implement real do-while
1675
1676 if(body)
1677 {
1678 body->traverse(this);
1679 }
1680
1681 emit(sw::Shader::OPCODE_TEST);
1682
1683 condition->traverse(this);
1684 emit(sw::Shader::OPCODE_MOV, &iterate, condition);
1685
1686 emit(sw::Shader::OPCODE_ENDWHILE);
1687 }
1688 else
1689 {
1690 if(init)
1691 {
1692 init->traverse(this);
1693 }
1694
1695 if(unroll)
1696 {
1697 for(unsigned int i = 0; i < iterations; i++)
1698 {
1699 // condition->traverse(this); // Condition could contain statements, but not in an unrollable loop
1700
1701 if(body)
1702 {
1703 body->traverse(this);
1704 }
1705
1706 if(expression)
1707 {
1708 expression->traverse(this);
1709 }
1710 }
1711 }
1712 else
1713 {
1714 if(condition)
1715 {
1716 condition->traverse(this);
1717 }
1718 else
1719 {
1720 condition = &True;
1721 }
1722
1723 emit(sw::Shader::OPCODE_WHILE, 0, condition);
1724
1725 if(body)
1726 {
1727 body->traverse(this);
1728 }
1729
1730 emit(sw::Shader::OPCODE_TEST);
1731
1732 if(expression)
1733 {
1734 expression->traverse(this);
1735 }
1736
1737 if(condition)
1738 {
1739 condition->traverse(this);
1740 }
1741
1742 emit(sw::Shader::OPCODE_ENDWHILE);
1743 }
1744 }
1745
1746 return false;
1747 }
1748
1749 bool OutputASM::visitBranch(Visit visit, TIntermBranch *node)
1750 {
1751 if(currentScope != emitScope)
1752 {
1753 return false;
1754 }
1755
1756 switch(node->getFlowOp())
1757 {
1758 case EOpKill: if(visit == PostVisit) emit(sw::Shader::OPCODE_DISCARD); break;
1759 case EOpBreak: if(visit == PostVisit) emit(sw::Shader::OPCODE_BREAK); break;
1760 case EOpContinue: if(visit == PostVisit) emit(sw::Shader::OPCODE_CONTINUE); break;
1761 case EOpReturn:
1762 if(visit == PostVisit)
1763 {
1764 TIntermTyped *value = node->getExpression();
1765
1766 if(value)
1767 {
1768 copy(functionArray[currentFunction].ret, value);
1769 }
1770
1771 emit(sw::Shader::OPCODE_LEAVE);
1772 }
1773 break;
1774 default: UNREACHABLE(node->getFlowOp());
1775 }
1776
1777 return true;
1778 }
1779
Alexis Hetu9aa83a92016-05-02 17:34:46 -04001780 bool OutputASM::visitSwitch(Visit visit, TIntermSwitch *node)
1781 {
1782 if(currentScope != emitScope)
1783 {
1784 return false;
1785 }
1786
1787 TIntermTyped* switchValue = node->getInit();
1788 TIntermAggregate* opList = node->getStatementList();
1789
1790 if(!switchValue || !opList)
1791 {
1792 return false;
1793 }
1794
1795 switchValue->traverse(this);
1796
1797 emit(sw::Shader::OPCODE_SWITCH);
1798
1799 TIntermSequence& sequence = opList->getSequence();
1800 TIntermSequence::iterator it = sequence.begin();
1801 TIntermSequence::iterator defaultIt = sequence.end();
1802 int nbCases = 0;
1803 for(; it != sequence.end(); ++it)
1804 {
1805 TIntermCase* currentCase = (*it)->getAsCaseNode();
1806 if(currentCase)
1807 {
1808 TIntermSequence::iterator caseIt = it;
1809
1810 TIntermTyped* condition = currentCase->getCondition();
1811 if(condition) // non default case
1812 {
1813 if(nbCases != 0)
1814 {
1815 emit(sw::Shader::OPCODE_ELSE);
1816 }
1817
1818 condition->traverse(this);
1819 Temporary result(this);
1820 emitBinary(sw::Shader::OPCODE_EQ, &result, switchValue, condition);
1821 emit(sw::Shader::OPCODE_IF, 0, &result);
1822 nbCases++;
1823
1824 for(++caseIt; caseIt != sequence.end(); ++caseIt)
1825 {
1826 (*caseIt)->traverse(this);
1827 if((*caseIt)->getAsBranchNode()) // Kill, Break, Continue or Return
1828 {
1829 break;
1830 }
1831 }
1832 }
1833 else
1834 {
1835 defaultIt = it; // The default case might not be the last case, keep it for last
1836 }
1837 }
1838 }
1839
1840 // If there's a default case, traverse it here
1841 if(defaultIt != sequence.end())
1842 {
1843 emit(sw::Shader::OPCODE_ELSE);
1844 for(++defaultIt; defaultIt != sequence.end(); ++defaultIt)
1845 {
1846 (*defaultIt)->traverse(this);
1847 if((*defaultIt)->getAsBranchNode()) // Kill, Break, Continue or Return
1848 {
1849 break;
1850 }
1851 }
1852 }
1853
1854 for(int i = 0; i < nbCases; ++i)
1855 {
1856 emit(sw::Shader::OPCODE_ENDIF);
1857 }
1858
1859 emit(sw::Shader::OPCODE_ENDSWITCH);
1860
1861 return false;
1862 }
1863
Nicolas Capens0bac2852016-05-07 06:09:58 -04001864 Instruction *OutputASM::emit(sw::Shader::Opcode op, TIntermTyped *dst, TIntermNode *src0, TIntermNode *src1, TIntermNode *src2, TIntermNode *src3, TIntermNode *src4)
1865 {
1866 return emit(op, dst, 0, src0, 0, src1, 0, src2, 0, src3, 0, src4, 0);
1867 }
1868
1869 Instruction *OutputASM::emit(sw::Shader::Opcode op, TIntermTyped *dst, int dstIndex, TIntermNode *src0, int index0, TIntermNode *src1, int index1,
1870 TIntermNode *src2, int index2, TIntermNode *src3, int index3, TIntermNode *src4, int index4)
1871 {
1872 Instruction *instruction = new Instruction(op);
1873
1874 if(dst)
1875 {
1876 instruction->dst.type = registerType(dst);
1877 instruction->dst.index = registerIndex(dst) + dstIndex;
1878 instruction->dst.mask = writeMask(dst);
1879 instruction->dst.integer = (dst->getBasicType() == EbtInt);
1880 }
1881
1882 argument(instruction->src[0], src0, index0);
1883 argument(instruction->src[1], src1, index1);
1884 argument(instruction->src[2], src2, index2);
1885 argument(instruction->src[3], src3, index3);
1886 argument(instruction->src[4], src4, index4);
1887
1888 shader->append(instruction);
1889
1890 return instruction;
1891 }
1892
1893 Instruction *OutputASM::emitCast(TIntermTyped *dst, TIntermTyped *src)
1894 {
1895 return emitCast(dst, 0, src, 0);
1896 }
1897
1898 Instruction *OutputASM::emitCast(TIntermTyped *dst, int dstIndex, TIntermTyped *src, int srcIndex)
1899 {
1900 switch(src->getBasicType())
1901 {
1902 case EbtBool:
1903 switch(dst->getBasicType())
1904 {
1905 case EbtInt: return emit(sw::Shader::OPCODE_B2I, dst, dstIndex, src, srcIndex);
1906 case EbtUInt: return emit(sw::Shader::OPCODE_B2I, dst, dstIndex, src, srcIndex);
1907 case EbtFloat: return emit(sw::Shader::OPCODE_B2F, dst, dstIndex, src, srcIndex);
1908 default: break;
1909 }
1910 break;
1911 case EbtInt:
1912 switch(dst->getBasicType())
1913 {
1914 case EbtBool: return emit(sw::Shader::OPCODE_I2B, dst, dstIndex, src, srcIndex);
1915 case EbtFloat: return emit(sw::Shader::OPCODE_I2F, dst, dstIndex, src, srcIndex);
1916 default: break;
1917 }
1918 break;
1919 case EbtUInt:
1920 switch(dst->getBasicType())
1921 {
1922 case EbtBool: return emit(sw::Shader::OPCODE_I2B, dst, dstIndex, src, srcIndex);
1923 case EbtFloat: return emit(sw::Shader::OPCODE_U2F, dst, dstIndex, src, srcIndex);
1924 default: break;
1925 }
1926 break;
1927 case EbtFloat:
1928 switch(dst->getBasicType())
1929 {
1930 case EbtBool: return emit(sw::Shader::OPCODE_F2B, dst, dstIndex, src, srcIndex);
1931 case EbtInt: return emit(sw::Shader::OPCODE_F2I, dst, dstIndex, src, srcIndex);
1932 case EbtUInt: return emit(sw::Shader::OPCODE_F2U, dst, dstIndex, src, srcIndex);
1933 default: break;
1934 }
1935 break;
1936 default:
1937 break;
1938 }
1939
1940 ASSERT((src->getBasicType() == dst->getBasicType()) ||
1941 ((src->getBasicType() == EbtInt) && (dst->getBasicType() == EbtUInt)) ||
1942 ((src->getBasicType() == EbtUInt) && (dst->getBasicType() == EbtInt)));
1943
1944 return emit(sw::Shader::OPCODE_MOV, dst, dstIndex, src, srcIndex);
1945 }
1946
1947 void OutputASM::emitBinary(sw::Shader::Opcode op, TIntermTyped *dst, TIntermNode *src0, TIntermNode *src1, TIntermNode *src2)
1948 {
1949 for(int index = 0; index < dst->elementRegisterCount(); index++)
1950 {
1951 emit(op, dst, index, src0, index, src1, index, src2, index);
1952 }
1953 }
1954
1955 void OutputASM::emitAssign(sw::Shader::Opcode op, TIntermTyped *result, TIntermTyped *lhs, TIntermTyped *src0, TIntermTyped *src1)
1956 {
1957 emitBinary(op, result, src0, src1);
1958 assignLvalue(lhs, result);
1959 }
1960
1961 void OutputASM::emitCmp(sw::Shader::Control cmpOp, TIntermTyped *dst, TIntermNode *left, TIntermNode *right, int index)
1962 {
1963 sw::Shader::Opcode opcode;
1964 switch(left->getAsTyped()->getBasicType())
1965 {
1966 case EbtBool:
1967 case EbtInt:
1968 opcode = sw::Shader::OPCODE_ICMP;
1969 break;
1970 case EbtUInt:
1971 opcode = sw::Shader::OPCODE_UCMP;
1972 break;
1973 default:
1974 opcode = sw::Shader::OPCODE_CMP;
1975 break;
1976 }
1977
1978 Instruction *cmp = emit(opcode, dst, 0, left, index, right, index);
1979 cmp->control = cmpOp;
1980 }
1981
1982 int componentCount(const TType &type, int registers)
1983 {
1984 if(registers == 0)
1985 {
1986 return 0;
1987 }
1988
1989 if(type.isArray() && registers >= type.elementRegisterCount())
1990 {
1991 int index = registers / type.elementRegisterCount();
1992 registers -= index * type.elementRegisterCount();
1993 return index * type.getElementSize() + componentCount(type, registers);
1994 }
1995
1996 if(type.isStruct() || type.isInterfaceBlock())
1997 {
1998 const TFieldList& fields = type.getStruct() ? type.getStruct()->fields() : type.getInterfaceBlock()->fields();
1999 int elements = 0;
2000
2001 for(TFieldList::const_iterator field = fields.begin(); field != fields.end(); field++)
2002 {
2003 const TType &fieldType = *((*field)->type());
2004
2005 if(fieldType.totalRegisterCount() <= registers)
2006 {
2007 registers -= fieldType.totalRegisterCount();
2008 elements += fieldType.getObjectSize();
2009 }
2010 else // Register within this field
2011 {
2012 return elements + componentCount(fieldType, registers);
2013 }
2014 }
2015 }
2016 else if(type.isMatrix())
2017 {
2018 return registers * type.registerSize();
2019 }
2020
2021 UNREACHABLE(0);
2022 return 0;
2023 }
2024
2025 int registerSize(const TType &type, int registers)
2026 {
2027 if(registers == 0)
2028 {
2029 if(type.isStruct())
2030 {
2031 return registerSize(*((*(type.getStruct()->fields().begin()))->type()), 0);
2032 }
2033 else if(type.isInterfaceBlock())
2034 {
2035 return registerSize(*((*(type.getInterfaceBlock()->fields().begin()))->type()), 0);
2036 }
2037
2038 return type.registerSize();
2039 }
2040
2041 if(type.isArray() && registers >= type.elementRegisterCount())
2042 {
2043 int index = registers / type.elementRegisterCount();
2044 registers -= index * type.elementRegisterCount();
2045 return registerSize(type, registers);
2046 }
2047
2048 if(type.isStruct() || type.isInterfaceBlock())
2049 {
2050 const TFieldList& fields = type.getStruct() ? type.getStruct()->fields() : type.getInterfaceBlock()->fields();
2051 int elements = 0;
2052
2053 for(TFieldList::const_iterator field = fields.begin(); field != fields.end(); field++)
2054 {
2055 const TType &fieldType = *((*field)->type());
2056
2057 if(fieldType.totalRegisterCount() <= registers)
2058 {
2059 registers -= fieldType.totalRegisterCount();
2060 elements += fieldType.getObjectSize();
2061 }
2062 else // Register within this field
2063 {
2064 return registerSize(fieldType, registers);
2065 }
2066 }
2067 }
2068 else if(type.isMatrix())
2069 {
2070 return registerSize(type, 0);
2071 }
2072
2073 UNREACHABLE(0);
2074 return 0;
2075 }
2076
2077 int OutputASM::getBlockId(TIntermTyped *arg)
2078 {
2079 if(arg)
2080 {
2081 const TType &type = arg->getType();
2082 TInterfaceBlock* block = type.getInterfaceBlock();
2083 if(block && (type.getQualifier() == EvqUniform))
2084 {
2085 // Make sure the uniform block is declared
2086 uniformRegister(arg);
2087
2088 const char* blockName = block->name().c_str();
2089
2090 // Fetch uniform block index from array of blocks
2091 for(ActiveUniformBlocks::const_iterator it = shaderObject->activeUniformBlocks.begin(); it != shaderObject->activeUniformBlocks.end(); ++it)
2092 {
2093 if(blockName == it->name)
2094 {
2095 return it->blockId;
2096 }
2097 }
2098
2099 ASSERT(false);
2100 }
2101 }
2102
2103 return -1;
2104 }
2105
2106 OutputASM::ArgumentInfo OutputASM::getArgumentInfo(TIntermTyped *arg, int index)
2107 {
2108 const TType &type = arg->getType();
2109 int blockId = getBlockId(arg);
2110 ArgumentInfo argumentInfo(BlockMemberInfo::getDefaultBlockInfo(), type, -1, -1);
2111 if(blockId != -1)
2112 {
2113 argumentInfo.bufferIndex = 0;
2114 for(int i = 0; i < blockId; ++i)
2115 {
2116 int blockArraySize = shaderObject->activeUniformBlocks[i].arraySize;
2117 argumentInfo.bufferIndex += blockArraySize > 0 ? blockArraySize : 1;
2118 }
2119
2120 const BlockDefinitionIndexMap& blockDefinition = blockDefinitions[blockId];
2121
2122 BlockDefinitionIndexMap::const_iterator itEnd = blockDefinition.end();
2123 BlockDefinitionIndexMap::const_iterator it = itEnd;
2124
2125 argumentInfo.clampedIndex = index;
2126 if(type.isInterfaceBlock())
2127 {
2128 // Offset index to the beginning of the selected instance
2129 int blockRegisters = type.elementRegisterCount();
2130 int bufferOffset = argumentInfo.clampedIndex / blockRegisters;
2131 argumentInfo.bufferIndex += bufferOffset;
2132 argumentInfo.clampedIndex -= bufferOffset * blockRegisters;
2133 }
2134
2135 int regIndex = registerIndex(arg);
2136 for(int i = regIndex + argumentInfo.clampedIndex; i >= regIndex; --i)
2137 {
2138 it = blockDefinition.find(i);
2139 if(it != itEnd)
2140 {
2141 argumentInfo.clampedIndex -= (i - regIndex);
2142 break;
2143 }
2144 }
2145 ASSERT(it != itEnd);
2146
2147 argumentInfo.typedMemberInfo = it->second;
2148
2149 int registerCount = argumentInfo.typedMemberInfo.type.totalRegisterCount();
2150 argumentInfo.clampedIndex = (argumentInfo.clampedIndex >= registerCount) ? registerCount - 1 : argumentInfo.clampedIndex;
2151 }
2152 else
2153 {
2154 argumentInfo.clampedIndex = (index >= arg->totalRegisterCount()) ? arg->totalRegisterCount() - 1 : index;
2155 }
2156
2157 return argumentInfo;
2158 }
2159
2160 void OutputASM::argument(sw::Shader::SourceParameter &parameter, TIntermNode *argument, int index)
2161 {
2162 if(argument)
2163 {
2164 TIntermTyped *arg = argument->getAsTyped();
2165 Temporary unpackedUniform(this);
2166
2167 const TType& srcType = arg->getType();
2168 TInterfaceBlock* srcBlock = srcType.getInterfaceBlock();
2169 if(srcBlock && (srcType.getQualifier() == EvqUniform))
2170 {
2171 const ArgumentInfo argumentInfo = getArgumentInfo(arg, index);
2172 const TType &memberType = argumentInfo.typedMemberInfo.type;
2173
2174 if(memberType.getBasicType() == EbtBool)
2175 {
2176 int arraySize = (memberType.isArray() ? memberType.getArraySize() : 1);
2177 ASSERT(argumentInfo.clampedIndex < arraySize);
2178
2179 // Convert the packed bool, which is currently an int, to a true bool
2180 Instruction *instruction = new Instruction(sw::Shader::OPCODE_I2B);
2181 instruction->dst.type = sw::Shader::PARAMETER_TEMP;
2182 instruction->dst.index = registerIndex(&unpackedUniform);
2183 instruction->src[0].type = sw::Shader::PARAMETER_CONST;
2184 instruction->src[0].bufferIndex = argumentInfo.bufferIndex;
2185 instruction->src[0].index = argumentInfo.typedMemberInfo.offset + argumentInfo.clampedIndex * argumentInfo.typedMemberInfo.arrayStride;
2186
2187 shader->append(instruction);
2188
2189 arg = &unpackedUniform;
2190 index = 0;
2191 }
2192 else if((srcBlock->matrixPacking() == EmpRowMajor) && memberType.isMatrix())
2193 {
2194 int numCols = memberType.getNominalSize();
2195 int numRows = memberType.getSecondarySize();
2196 int arraySize = (memberType.isArray() ? memberType.getArraySize() : 1);
2197
2198 ASSERT(argumentInfo.clampedIndex < (numCols * arraySize));
2199
2200 unsigned int dstIndex = registerIndex(&unpackedUniform);
2201 unsigned int srcSwizzle = (argumentInfo.clampedIndex % numCols) * 0x55;
2202 int arrayIndex = argumentInfo.clampedIndex / numCols;
2203 int matrixStartOffset = argumentInfo.typedMemberInfo.offset + arrayIndex * argumentInfo.typedMemberInfo.arrayStride;
2204
2205 for(int j = 0; j < numRows; ++j)
2206 {
2207 // Transpose the row major matrix
2208 Instruction *instruction = new Instruction(sw::Shader::OPCODE_MOV);
2209 instruction->dst.type = sw::Shader::PARAMETER_TEMP;
2210 instruction->dst.index = dstIndex;
2211 instruction->dst.mask = 1 << j;
2212 instruction->src[0].type = sw::Shader::PARAMETER_CONST;
2213 instruction->src[0].bufferIndex = argumentInfo.bufferIndex;
2214 instruction->src[0].index = matrixStartOffset + j * argumentInfo.typedMemberInfo.matrixStride;
2215 instruction->src[0].swizzle = srcSwizzle;
2216
2217 shader->append(instruction);
2218 }
2219
2220 arg = &unpackedUniform;
2221 index = 0;
2222 }
2223 }
2224
2225 const ArgumentInfo argumentInfo = getArgumentInfo(arg, index);
2226 const TType &type = argumentInfo.typedMemberInfo.type;
2227
2228 int size = registerSize(type, argumentInfo.clampedIndex);
2229
2230 parameter.type = registerType(arg);
2231 parameter.bufferIndex = argumentInfo.bufferIndex;
2232
2233 if(arg->getAsConstantUnion() && arg->getAsConstantUnion()->getUnionArrayPointer())
2234 {
2235 int component = componentCount(type, argumentInfo.clampedIndex);
2236 ConstantUnion *constants = arg->getAsConstantUnion()->getUnionArrayPointer();
2237
2238 for(int i = 0; i < 4; i++)
2239 {
2240 if(size == 1) // Replicate
2241 {
2242 parameter.value[i] = constants[component + 0].getAsFloat();
2243 }
2244 else if(i < size)
2245 {
2246 parameter.value[i] = constants[component + i].getAsFloat();
2247 }
2248 else
2249 {
2250 parameter.value[i] = 0.0f;
2251 }
2252 }
2253 }
2254 else
2255 {
2256 parameter.index = registerIndex(arg) + argumentInfo.clampedIndex;
2257
2258 if(parameter.bufferIndex != -1)
2259 {
2260 int stride = (argumentInfo.typedMemberInfo.matrixStride > 0) ? argumentInfo.typedMemberInfo.matrixStride : argumentInfo.typedMemberInfo.arrayStride;
2261 parameter.index = argumentInfo.typedMemberInfo.offset + argumentInfo.clampedIndex * stride;
2262 }
2263 }
2264
2265 if(!IsSampler(arg->getBasicType()))
2266 {
2267 parameter.swizzle = readSwizzle(arg, size);
2268 }
2269 }
2270 }
2271
2272 void OutputASM::copy(TIntermTyped *dst, TIntermNode *src, int offset)
2273 {
2274 for(int index = 0; index < dst->totalRegisterCount(); index++)
2275 {
2276 Instruction *mov = emit(sw::Shader::OPCODE_MOV, dst, index, src, offset + index);
2277 mov->dst.mask = writeMask(dst, index);
2278 }
2279 }
2280
2281 int swizzleElement(int swizzle, int index)
2282 {
2283 return (swizzle >> (index * 2)) & 0x03;
2284 }
2285
2286 int swizzleSwizzle(int leftSwizzle, int rightSwizzle)
2287 {
2288 return (swizzleElement(leftSwizzle, swizzleElement(rightSwizzle, 0)) << 0) |
2289 (swizzleElement(leftSwizzle, swizzleElement(rightSwizzle, 1)) << 2) |
2290 (swizzleElement(leftSwizzle, swizzleElement(rightSwizzle, 2)) << 4) |
2291 (swizzleElement(leftSwizzle, swizzleElement(rightSwizzle, 3)) << 6);
2292 }
2293
2294 void OutputASM::assignLvalue(TIntermTyped *dst, TIntermTyped *src)
2295 {
2296 if(src &&
2297 ((src->isVector() && (!dst->isVector() || (src->getNominalSize() != dst->getNominalSize()))) ||
2298 (src->isMatrix() && (!dst->isMatrix() || (src->getNominalSize() != dst->getNominalSize()) || (src->getSecondarySize() != dst->getSecondarySize())))))
2299 {
2300 return mContext.error(src->getLine(), "Result type should match the l-value type in compound assignment", src->isVector() ? "vector" : "matrix");
2301 }
2302
2303 TIntermBinary *binary = dst->getAsBinaryNode();
2304
2305 if(binary && binary->getOp() == EOpIndexIndirect && binary->getLeft()->isVector() && dst->isScalar())
2306 {
2307 Instruction *insert = new Instruction(sw::Shader::OPCODE_INSERT);
2308
2309 Temporary address(this);
2310 lvalue(insert->dst, address, dst);
2311
2312 insert->src[0].type = insert->dst.type;
2313 insert->src[0].index = insert->dst.index;
2314 insert->src[0].rel = insert->dst.rel;
2315 argument(insert->src[1], src);
2316 argument(insert->src[2], binary->getRight());
2317
2318 shader->append(insert);
2319 }
2320 else
2321 {
2322 for(int offset = 0; offset < dst->totalRegisterCount(); offset++)
2323 {
2324 Instruction *mov = new Instruction(sw::Shader::OPCODE_MOV);
2325
2326 Temporary address(this);
2327 int swizzle = lvalue(mov->dst, address, dst);
2328 mov->dst.index += offset;
2329
2330 if(offset > 0)
2331 {
2332 mov->dst.mask = writeMask(dst, offset);
2333 }
2334
2335 argument(mov->src[0], src, offset);
2336 mov->src[0].swizzle = swizzleSwizzle(mov->src[0].swizzle, swizzle);
2337
2338 shader->append(mov);
2339 }
2340 }
2341 }
2342
2343 int OutputASM::lvalue(sw::Shader::DestinationParameter &dst, Temporary &address, TIntermTyped *node)
2344 {
2345 TIntermTyped *result = node;
2346 TIntermBinary *binary = node->getAsBinaryNode();
2347 TIntermSymbol *symbol = node->getAsSymbolNode();
2348
2349 if(binary)
2350 {
2351 TIntermTyped *left = binary->getLeft();
2352 TIntermTyped *right = binary->getRight();
2353
2354 int leftSwizzle = lvalue(dst, address, left); // Resolve the l-value of the left side
2355
2356 switch(binary->getOp())
2357 {
2358 case EOpIndexDirect:
2359 {
2360 int rightIndex = right->getAsConstantUnion()->getIConst(0);
2361
2362 if(left->isRegister())
2363 {
2364 int leftMask = dst.mask;
2365
2366 dst.mask = 1;
2367 while((leftMask & dst.mask) == 0)
2368 {
2369 dst.mask = dst.mask << 1;
2370 }
2371
2372 int element = swizzleElement(leftSwizzle, rightIndex);
2373 dst.mask = 1 << element;
2374
2375 return element;
2376 }
2377 else if(left->isArray() || left->isMatrix())
2378 {
2379 dst.index += rightIndex * result->totalRegisterCount();
2380 return 0xE4;
2381 }
2382 else UNREACHABLE(0);
2383 }
2384 break;
2385 case EOpIndexIndirect:
2386 {
2387 if(left->isRegister())
2388 {
2389 // Requires INSERT instruction (handled by calling function)
2390 }
2391 else if(left->isArray() || left->isMatrix())
2392 {
2393 int scale = result->totalRegisterCount();
2394
2395 if(dst.rel.type == sw::Shader::PARAMETER_VOID) // Use the index register as the relative address directly
2396 {
2397 if(left->totalRegisterCount() > 1)
2398 {
2399 sw::Shader::SourceParameter relativeRegister;
2400 argument(relativeRegister, right);
2401
2402 dst.rel.index = relativeRegister.index;
2403 dst.rel.type = relativeRegister.type;
2404 dst.rel.scale = scale;
2405 dst.rel.deterministic = !(vertexShader && left->getQualifier() == EvqUniform);
2406 }
2407 }
2408 else if(dst.rel.index != registerIndex(&address)) // Move the previous index register to the address register
2409 {
2410 if(scale == 1)
2411 {
2412 Constant oldScale((int)dst.rel.scale);
2413 Instruction *mad = emit(sw::Shader::OPCODE_IMAD, &address, &address, &oldScale, right);
2414 mad->src[0].index = dst.rel.index;
2415 mad->src[0].type = dst.rel.type;
2416 }
2417 else
2418 {
2419 Constant oldScale((int)dst.rel.scale);
2420 Instruction *mul = emit(sw::Shader::OPCODE_IMUL, &address, &address, &oldScale);
2421 mul->src[0].index = dst.rel.index;
2422 mul->src[0].type = dst.rel.type;
2423
2424 Constant newScale(scale);
2425 emit(sw::Shader::OPCODE_IMAD, &address, right, &newScale, &address);
2426 }
2427
2428 dst.rel.type = sw::Shader::PARAMETER_TEMP;
2429 dst.rel.index = registerIndex(&address);
2430 dst.rel.scale = 1;
2431 }
2432 else // Just add the new index to the address register
2433 {
2434 if(scale == 1)
2435 {
2436 emit(sw::Shader::OPCODE_IADD, &address, &address, right);
2437 }
2438 else
2439 {
2440 Constant newScale(scale);
2441 emit(sw::Shader::OPCODE_IMAD, &address, right, &newScale, &address);
2442 }
2443 }
2444 }
2445 else UNREACHABLE(0);
2446 }
2447 break;
2448 case EOpIndexDirectStruct:
2449 case EOpIndexDirectInterfaceBlock:
2450 {
2451 const TFieldList& fields = (binary->getOp() == EOpIndexDirectStruct) ?
2452 left->getType().getStruct()->fields() :
2453 left->getType().getInterfaceBlock()->fields();
2454 int index = right->getAsConstantUnion()->getIConst(0);
2455 int fieldOffset = 0;
2456
2457 for(int i = 0; i < index; i++)
2458 {
2459 fieldOffset += fields[i]->type()->totalRegisterCount();
2460 }
2461
2462 dst.type = registerType(left);
2463 dst.index += fieldOffset;
2464 dst.mask = writeMask(right);
2465
2466 return 0xE4;
2467 }
2468 break;
2469 case EOpVectorSwizzle:
2470 {
2471 ASSERT(left->isRegister());
2472
2473 int leftMask = dst.mask;
2474
2475 int swizzle = 0;
2476 int rightMask = 0;
2477
2478 TIntermSequence &sequence = right->getAsAggregate()->getSequence();
2479
2480 for(unsigned int i = 0; i < sequence.size(); i++)
2481 {
2482 int index = sequence[i]->getAsConstantUnion()->getIConst(0);
2483
2484 int element = swizzleElement(leftSwizzle, index);
2485 rightMask = rightMask | (1 << element);
2486 swizzle = swizzle | swizzleElement(leftSwizzle, i) << (element * 2);
2487 }
2488
2489 dst.mask = leftMask & rightMask;
2490
2491 return swizzle;
2492 }
2493 break;
2494 default:
2495 UNREACHABLE(binary->getOp()); // Not an l-value operator
2496 break;
2497 }
2498 }
2499 else if(symbol)
2500 {
2501 dst.type = registerType(symbol);
2502 dst.index = registerIndex(symbol);
2503 dst.mask = writeMask(symbol);
2504 return 0xE4;
2505 }
2506
2507 return 0xE4;
2508 }
2509
2510 sw::Shader::ParameterType OutputASM::registerType(TIntermTyped *operand)
2511 {
2512 if(isSamplerRegister(operand))
2513 {
2514 return sw::Shader::PARAMETER_SAMPLER;
2515 }
2516
2517 const TQualifier qualifier = operand->getQualifier();
2518 if((EvqFragColor == qualifier) || (EvqFragData == qualifier))
2519 {
2520 if(((EvqFragData == qualifier) && (EvqFragColor == outputQualifier)) ||
2521 ((EvqFragColor == qualifier) && (EvqFragData == outputQualifier)))
2522 {
2523 mContext.error(operand->getLine(), "static assignment to both gl_FragData and gl_FragColor", "");
2524 }
2525 outputQualifier = qualifier;
2526 }
2527
2528 if(qualifier == EvqConstExpr && (!operand->getAsConstantUnion() || !operand->getAsConstantUnion()->getUnionArrayPointer()))
2529 {
2530 return sw::Shader::PARAMETER_TEMP;
2531 }
2532
2533 switch(qualifier)
2534 {
2535 case EvqTemporary: return sw::Shader::PARAMETER_TEMP;
2536 case EvqGlobal: return sw::Shader::PARAMETER_TEMP;
2537 case EvqConstExpr: return sw::Shader::PARAMETER_FLOAT4LITERAL; // All converted to float
2538 case EvqAttribute: return sw::Shader::PARAMETER_INPUT;
2539 case EvqVaryingIn: return sw::Shader::PARAMETER_INPUT;
2540 case EvqVaryingOut: return sw::Shader::PARAMETER_OUTPUT;
2541 case EvqVertexIn: return sw::Shader::PARAMETER_INPUT;
2542 case EvqFragmentOut: return sw::Shader::PARAMETER_COLOROUT;
2543 case EvqVertexOut: return sw::Shader::PARAMETER_OUTPUT;
2544 case EvqFragmentIn: return sw::Shader::PARAMETER_INPUT;
2545 case EvqInvariantVaryingIn: return sw::Shader::PARAMETER_INPUT; // FIXME: Guarantee invariance at the backend
2546 case EvqInvariantVaryingOut: return sw::Shader::PARAMETER_OUTPUT; // FIXME: Guarantee invariance at the backend
2547 case EvqSmooth: return sw::Shader::PARAMETER_OUTPUT;
2548 case EvqFlat: return sw::Shader::PARAMETER_OUTPUT;
2549 case EvqCentroidOut: return sw::Shader::PARAMETER_OUTPUT;
2550 case EvqSmoothIn: return sw::Shader::PARAMETER_INPUT;
2551 case EvqFlatIn: return sw::Shader::PARAMETER_INPUT;
2552 case EvqCentroidIn: return sw::Shader::PARAMETER_INPUT;
2553 case EvqUniform: return sw::Shader::PARAMETER_CONST;
2554 case EvqIn: return sw::Shader::PARAMETER_TEMP;
2555 case EvqOut: return sw::Shader::PARAMETER_TEMP;
2556 case EvqInOut: return sw::Shader::PARAMETER_TEMP;
2557 case EvqConstReadOnly: return sw::Shader::PARAMETER_TEMP;
2558 case EvqPosition: return sw::Shader::PARAMETER_OUTPUT;
2559 case EvqPointSize: return sw::Shader::PARAMETER_OUTPUT;
2560 case EvqInstanceID: return sw::Shader::PARAMETER_MISCTYPE;
2561 case EvqFragCoord: return sw::Shader::PARAMETER_MISCTYPE;
2562 case EvqFrontFacing: return sw::Shader::PARAMETER_MISCTYPE;
2563 case EvqPointCoord: return sw::Shader::PARAMETER_INPUT;
2564 case EvqFragColor: return sw::Shader::PARAMETER_COLOROUT;
2565 case EvqFragData: return sw::Shader::PARAMETER_COLOROUT;
2566 case EvqFragDepth: return sw::Shader::PARAMETER_DEPTHOUT;
2567 default: UNREACHABLE(qualifier);
2568 }
2569
2570 return sw::Shader::PARAMETER_VOID;
2571 }
2572
Alexis Hetu12b00502016-05-20 13:01:11 -04002573 bool OutputASM::hasFlatQualifier(TIntermTyped *operand)
2574 {
2575 const TQualifier qualifier = operand->getQualifier();
2576 return qualifier == EvqFlat || qualifier == EvqFlatOut || qualifier == EvqFlatIn;
2577 }
2578
Nicolas Capens0bac2852016-05-07 06:09:58 -04002579 unsigned int OutputASM::registerIndex(TIntermTyped *operand)
2580 {
2581 if(isSamplerRegister(operand))
2582 {
2583 return samplerRegister(operand);
2584 }
2585
2586 switch(operand->getQualifier())
2587 {
2588 case EvqTemporary: return temporaryRegister(operand);
2589 case EvqGlobal: return temporaryRegister(operand);
2590 case EvqConstExpr: return temporaryRegister(operand); // Unevaluated constant expression
2591 case EvqAttribute: return attributeRegister(operand);
2592 case EvqVaryingIn: return varyingRegister(operand);
2593 case EvqVaryingOut: return varyingRegister(operand);
2594 case EvqVertexIn: return attributeRegister(operand);
2595 case EvqFragmentOut: return fragmentOutputRegister(operand);
2596 case EvqVertexOut: return varyingRegister(operand);
2597 case EvqFragmentIn: return varyingRegister(operand);
2598 case EvqInvariantVaryingIn: return varyingRegister(operand);
2599 case EvqInvariantVaryingOut: return varyingRegister(operand);
2600 case EvqSmooth: return varyingRegister(operand);
2601 case EvqFlat: return varyingRegister(operand);
2602 case EvqCentroidOut: return varyingRegister(operand);
2603 case EvqSmoothIn: return varyingRegister(operand);
2604 case EvqFlatIn: return varyingRegister(operand);
2605 case EvqCentroidIn: return varyingRegister(operand);
2606 case EvqUniform: return uniformRegister(operand);
2607 case EvqIn: return temporaryRegister(operand);
2608 case EvqOut: return temporaryRegister(operand);
2609 case EvqInOut: return temporaryRegister(operand);
2610 case EvqConstReadOnly: return temporaryRegister(operand);
2611 case EvqPosition: return varyingRegister(operand);
2612 case EvqPointSize: return varyingRegister(operand);
2613 case EvqInstanceID: vertexShader->instanceIdDeclared = true; return 0;
2614 case EvqFragCoord: pixelShader->vPosDeclared = true; return 0;
2615 case EvqFrontFacing: pixelShader->vFaceDeclared = true; return 1;
2616 case EvqPointCoord: return varyingRegister(operand);
2617 case EvqFragColor: return 0;
2618 case EvqFragData: return fragmentOutputRegister(operand);
2619 case EvqFragDepth: return 0;
2620 default: UNREACHABLE(operand->getQualifier());
2621 }
2622
2623 return 0;
2624 }
2625
2626 int OutputASM::writeMask(TIntermTyped *destination, int index)
2627 {
2628 if(destination->getQualifier() == EvqPointSize)
2629 {
2630 return 0x2; // Point size stored in the y component
2631 }
2632
2633 return 0xF >> (4 - registerSize(destination->getType(), index));
2634 }
2635
2636 int OutputASM::readSwizzle(TIntermTyped *argument, int size)
2637 {
2638 if(argument->getQualifier() == EvqPointSize)
2639 {
2640 return 0x55; // Point size stored in the y component
2641 }
2642
2643 static const unsigned char swizzleSize[5] = {0x00, 0x00, 0x54, 0xA4, 0xE4}; // (void), xxxx, xyyy, xyzz, xyzw
2644
2645 return swizzleSize[size];
2646 }
2647
2648 // Conservatively checks whether an expression is fast to compute and has no side effects
2649 bool OutputASM::trivial(TIntermTyped *expression, int budget)
2650 {
2651 if(!expression->isRegister())
2652 {
2653 return false;
2654 }
2655
2656 return cost(expression, budget) >= 0;
2657 }
2658
2659 // Returns the remaining computing budget (if < 0 the expression is too expensive or has side effects)
2660 int OutputASM::cost(TIntermNode *expression, int budget)
2661 {
2662 if(budget < 0)
2663 {
2664 return budget;
2665 }
2666
2667 if(expression->getAsSymbolNode())
2668 {
2669 return budget;
2670 }
2671 else if(expression->getAsConstantUnion())
2672 {
2673 return budget;
2674 }
2675 else if(expression->getAsBinaryNode())
2676 {
2677 TIntermBinary *binary = expression->getAsBinaryNode();
2678
2679 switch(binary->getOp())
2680 {
2681 case EOpVectorSwizzle:
2682 case EOpIndexDirect:
2683 case EOpIndexDirectStruct:
2684 case EOpIndexDirectInterfaceBlock:
2685 return cost(binary->getLeft(), budget - 0);
2686 case EOpAdd:
2687 case EOpSub:
2688 case EOpMul:
2689 return cost(binary->getLeft(), cost(binary->getRight(), budget - 1));
2690 default:
2691 return -1;
2692 }
2693 }
2694 else if(expression->getAsUnaryNode())
2695 {
2696 TIntermUnary *unary = expression->getAsUnaryNode();
2697
2698 switch(unary->getOp())
2699 {
2700 case EOpAbs:
2701 case EOpNegative:
2702 return cost(unary->getOperand(), budget - 1);
2703 default:
2704 return -1;
2705 }
2706 }
2707 else if(expression->getAsSelectionNode())
2708 {
2709 TIntermSelection *selection = expression->getAsSelectionNode();
2710
2711 if(selection->usesTernaryOperator())
2712 {
2713 TIntermTyped *condition = selection->getCondition();
2714 TIntermNode *trueBlock = selection->getTrueBlock();
2715 TIntermNode *falseBlock = selection->getFalseBlock();
2716 TIntermConstantUnion *constantCondition = condition->getAsConstantUnion();
2717
2718 if(constantCondition)
2719 {
2720 bool trueCondition = constantCondition->getUnionArrayPointer()->getBConst();
2721
2722 if(trueCondition)
2723 {
2724 return cost(trueBlock, budget - 0);
2725 }
2726 else
2727 {
2728 return cost(falseBlock, budget - 0);
2729 }
2730 }
2731 else
2732 {
2733 return cost(trueBlock, cost(falseBlock, budget - 2));
2734 }
2735 }
2736 }
2737
2738 return -1;
2739 }
2740
2741 const Function *OutputASM::findFunction(const TString &name)
2742 {
2743 for(unsigned int f = 0; f < functionArray.size(); f++)
2744 {
2745 if(functionArray[f].name == name)
2746 {
2747 return &functionArray[f];
2748 }
2749 }
2750
2751 return 0;
2752 }
2753
2754 int OutputASM::temporaryRegister(TIntermTyped *temporary)
2755 {
2756 return allocate(temporaries, temporary);
2757 }
2758
2759 int OutputASM::varyingRegister(TIntermTyped *varying)
2760 {
2761 int var = lookup(varyings, varying);
2762
2763 if(var == -1)
2764 {
2765 var = allocate(varyings, varying);
2766 int componentCount = varying->registerSize();
2767 int registerCount = varying->totalRegisterCount();
2768
2769 if(pixelShader)
2770 {
Nicolas Capens3b4c93f2016-05-18 12:51:37 -04002771 if((var + registerCount) > sw::MAX_FRAGMENT_INPUTS)
Nicolas Capens0bac2852016-05-07 06:09:58 -04002772 {
2773 mContext.error(varying->getLine(), "Varyings packing failed: Too many varyings", "fragment shader");
2774 return 0;
2775 }
2776
2777 if(varying->getQualifier() == EvqPointCoord)
2778 {
2779 ASSERT(varying->isRegister());
2780 if(componentCount >= 1) pixelShader->semantic[var][0] = sw::Shader::Semantic(sw::Shader::USAGE_TEXCOORD, var);
2781 if(componentCount >= 2) pixelShader->semantic[var][1] = sw::Shader::Semantic(sw::Shader::USAGE_TEXCOORD, var);
2782 if(componentCount >= 3) pixelShader->semantic[var][2] = sw::Shader::Semantic(sw::Shader::USAGE_TEXCOORD, var);
2783 if(componentCount >= 4) pixelShader->semantic[var][3] = sw::Shader::Semantic(sw::Shader::USAGE_TEXCOORD, var);
2784 }
2785 else
2786 {
2787 for(int i = 0; i < varying->totalRegisterCount(); i++)
2788 {
Alexis Hetu12b00502016-05-20 13:01:11 -04002789 bool flat = hasFlatQualifier(varying);
2790
2791 if(componentCount >= 1) pixelShader->semantic[var + i][0] = sw::Shader::Semantic(sw::Shader::USAGE_COLOR, var + i, flat);
2792 if(componentCount >= 2) pixelShader->semantic[var + i][1] = sw::Shader::Semantic(sw::Shader::USAGE_COLOR, var + i, flat);
2793 if(componentCount >= 3) pixelShader->semantic[var + i][2] = sw::Shader::Semantic(sw::Shader::USAGE_COLOR, var + i, flat);
2794 if(componentCount >= 4) pixelShader->semantic[var + i][3] = sw::Shader::Semantic(sw::Shader::USAGE_COLOR, var + i, flat);
Nicolas Capens0bac2852016-05-07 06:09:58 -04002795 }
2796 }
2797 }
2798 else if(vertexShader)
2799 {
Nicolas Capensec0936c2016-05-18 12:32:02 -04002800 if((var + registerCount) > sw::MAX_VERTEX_OUTPUTS)
Nicolas Capens0bac2852016-05-07 06:09:58 -04002801 {
2802 mContext.error(varying->getLine(), "Varyings packing failed: Too many varyings", "vertex shader");
2803 return 0;
2804 }
2805
2806 if(varying->getQualifier() == EvqPosition)
2807 {
2808 ASSERT(varying->isRegister());
2809 vertexShader->output[var][0] = sw::Shader::Semantic(sw::Shader::USAGE_POSITION, 0);
2810 vertexShader->output[var][1] = sw::Shader::Semantic(sw::Shader::USAGE_POSITION, 0);
2811 vertexShader->output[var][2] = sw::Shader::Semantic(sw::Shader::USAGE_POSITION, 0);
2812 vertexShader->output[var][3] = sw::Shader::Semantic(sw::Shader::USAGE_POSITION, 0);
2813 vertexShader->positionRegister = var;
2814 }
2815 else if(varying->getQualifier() == EvqPointSize)
2816 {
2817 ASSERT(varying->isRegister());
2818 vertexShader->output[var][0] = sw::Shader::Semantic(sw::Shader::USAGE_PSIZE, 0);
2819 vertexShader->output[var][1] = sw::Shader::Semantic(sw::Shader::USAGE_PSIZE, 0);
2820 vertexShader->output[var][2] = sw::Shader::Semantic(sw::Shader::USAGE_PSIZE, 0);
2821 vertexShader->output[var][3] = sw::Shader::Semantic(sw::Shader::USAGE_PSIZE, 0);
2822 vertexShader->pointSizeRegister = var;
2823 }
2824 else
2825 {
2826 // Semantic indexes for user varyings will be assigned during program link to match the pixel shader
2827 }
2828 }
2829 else UNREACHABLE(0);
2830
2831 declareVarying(varying, var);
2832 }
2833
2834 return var;
2835 }
2836
2837 void OutputASM::declareVarying(TIntermTyped *varying, int reg)
2838 {
2839 if(varying->getQualifier() != EvqPointCoord) // gl_PointCoord does not need linking
2840 {
2841 const TType &type = varying->getType();
2842 const char *name = varying->getAsSymbolNode()->getSymbol().c_str();
2843 VaryingList &activeVaryings = shaderObject->varyings;
2844
2845 // Check if this varying has been declared before without having a register assigned
2846 for(VaryingList::iterator v = activeVaryings.begin(); v != activeVaryings.end(); v++)
2847 {
2848 if(v->name == name)
2849 {
2850 if(reg >= 0)
2851 {
2852 ASSERT(v->reg < 0 || v->reg == reg);
2853 v->reg = reg;
2854 }
2855
2856 return;
2857 }
2858 }
2859
2860 activeVaryings.push_back(glsl::Varying(glVariableType(type), name, varying->getArraySize(), reg, 0));
2861 }
2862 }
2863
2864 int OutputASM::uniformRegister(TIntermTyped *uniform)
2865 {
2866 const TType &type = uniform->getType();
2867 ASSERT(!IsSampler(type.getBasicType()));
2868 TInterfaceBlock *block = type.getAsInterfaceBlock();
2869 TIntermSymbol *symbol = uniform->getAsSymbolNode();
2870 ASSERT(symbol || block);
2871
2872 if(symbol || block)
2873 {
2874 TInterfaceBlock* parentBlock = type.getInterfaceBlock();
2875 bool isBlockMember = (!block && parentBlock);
2876 int index = isBlockMember ? lookup(uniforms, parentBlock) : lookup(uniforms, uniform);
2877
2878 if(index == -1 || isBlockMember)
2879 {
2880 if(index == -1)
2881 {
2882 index = allocate(uniforms, uniform);
2883 }
2884
2885 // Verify if the current uniform is a member of an already declared block
2886 const TString &name = symbol ? symbol->getSymbol() : block->name();
2887 int blockMemberIndex = blockMemberLookup(type, name, index);
2888 if(blockMemberIndex == -1)
2889 {
2890 declareUniform(type, name, index);
2891 }
2892 else
2893 {
2894 index = blockMemberIndex;
2895 }
2896 }
2897
2898 return index;
2899 }
2900
2901 return 0;
2902 }
2903
2904 int OutputASM::attributeRegister(TIntermTyped *attribute)
2905 {
2906 ASSERT(!attribute->isArray());
2907
2908 int index = lookup(attributes, attribute);
2909
2910 if(index == -1)
2911 {
2912 TIntermSymbol *symbol = attribute->getAsSymbolNode();
2913 ASSERT(symbol);
2914
2915 if(symbol)
2916 {
2917 index = allocate(attributes, attribute);
2918 const TType &type = attribute->getType();
2919 int registerCount = attribute->totalRegisterCount();
2920
Nicolas Capensf0aef1a2016-05-18 14:44:21 -04002921 if(vertexShader && (index + registerCount) <= sw::MAX_VERTEX_INPUTS)
Nicolas Capens0bac2852016-05-07 06:09:58 -04002922 {
2923 for(int i = 0; i < registerCount; i++)
2924 {
2925 vertexShader->input[index + i] = sw::Shader::Semantic(sw::Shader::USAGE_TEXCOORD, index + i);
2926 }
2927 }
2928
2929 ActiveAttributes &activeAttributes = shaderObject->activeAttributes;
2930
2931 const char *name = symbol->getSymbol().c_str();
2932 activeAttributes.push_back(Attribute(glVariableType(type), name, type.getArraySize(), type.getLayoutQualifier().location, index));
2933 }
2934 }
2935
2936 return index;
2937 }
2938
2939 int OutputASM::fragmentOutputRegister(TIntermTyped *fragmentOutput)
2940 {
2941 return allocate(fragmentOutputs, fragmentOutput);
2942 }
2943
2944 int OutputASM::samplerRegister(TIntermTyped *sampler)
2945 {
2946 const TType &type = sampler->getType();
2947 ASSERT(IsSampler(type.getBasicType()) || type.isStruct()); // Structures can contain samplers
2948
2949 TIntermSymbol *symbol = sampler->getAsSymbolNode();
2950 TIntermBinary *binary = sampler->getAsBinaryNode();
2951
2952 if(symbol && type.getQualifier() == EvqUniform)
2953 {
2954 return samplerRegister(symbol);
2955 }
2956 else if(binary)
2957 {
2958 TIntermTyped *left = binary->getLeft();
2959 TIntermTyped *right = binary->getRight();
2960 const TType &leftType = left->getType();
2961 int index = right->getAsConstantUnion() ? right->getAsConstantUnion()->getIConst(0) : 0;
2962 int offset = 0;
2963
2964 switch(binary->getOp())
2965 {
2966 case EOpIndexDirect:
2967 ASSERT(left->isArray());
2968 offset = index * leftType.elementRegisterCount();
2969 break;
2970 case EOpIndexDirectStruct:
2971 ASSERT(leftType.isStruct());
2972 {
2973 const TFieldList &fields = leftType.getStruct()->fields();
2974
2975 for(int i = 0; i < index; i++)
2976 {
2977 offset += fields[i]->type()->totalRegisterCount();
2978 }
2979 }
2980 break;
2981 case EOpIndexIndirect: // Indirect indexing produces a temporary, not a sampler register
2982 return -1;
2983 case EOpIndexDirectInterfaceBlock: // Interface blocks can't contain samplers
2984 default:
2985 UNREACHABLE(binary->getOp());
2986 return -1;
2987 }
2988
2989 int base = samplerRegister(left);
2990
2991 if(base < 0)
2992 {
2993 return -1;
2994 }
2995
2996 return base + offset;
2997 }
2998
2999 UNREACHABLE(0);
3000 return -1; // Not a sampler register
3001 }
3002
3003 int OutputASM::samplerRegister(TIntermSymbol *sampler)
3004 {
3005 const TType &type = sampler->getType();
3006 ASSERT(IsSampler(type.getBasicType()) || type.isStruct()); // Structures can contain samplers
3007
3008 int index = lookup(samplers, sampler);
3009
3010 if(index == -1)
3011 {
3012 index = allocate(samplers, sampler);
3013
3014 if(sampler->getQualifier() == EvqUniform)
3015 {
3016 const char *name = sampler->getSymbol().c_str();
3017 declareUniform(type, name, index);
3018 }
3019 }
3020
3021 return index;
3022 }
3023
3024 bool OutputASM::isSamplerRegister(TIntermTyped *operand)
3025 {
3026 return operand && IsSampler(operand->getBasicType()) && samplerRegister(operand) >= 0;
3027 }
3028
3029 int OutputASM::lookup(VariableArray &list, TIntermTyped *variable)
3030 {
3031 for(unsigned int i = 0; i < list.size(); i++)
3032 {
3033 if(list[i] == variable)
3034 {
3035 return i; // Pointer match
3036 }
3037 }
3038
3039 TIntermSymbol *varSymbol = variable->getAsSymbolNode();
3040 TInterfaceBlock *varBlock = variable->getType().getAsInterfaceBlock();
3041
3042 if(varBlock)
3043 {
3044 for(unsigned int i = 0; i < list.size(); i++)
3045 {
3046 if(list[i])
3047 {
3048 TInterfaceBlock *listBlock = list[i]->getType().getAsInterfaceBlock();
3049
3050 if(listBlock)
3051 {
3052 if(listBlock->name() == varBlock->name())
3053 {
3054 ASSERT(listBlock->arraySize() == varBlock->arraySize());
3055 ASSERT(listBlock->fields() == varBlock->fields());
3056 ASSERT(listBlock->blockStorage() == varBlock->blockStorage());
3057 ASSERT(listBlock->matrixPacking() == varBlock->matrixPacking());
3058
3059 return i;
3060 }
3061 }
3062 }
3063 }
3064 }
3065 else if(varSymbol)
3066 {
3067 for(unsigned int i = 0; i < list.size(); i++)
3068 {
3069 if(list[i])
3070 {
3071 TIntermSymbol *listSymbol = list[i]->getAsSymbolNode();
3072
3073 if(listSymbol)
3074 {
3075 if(listSymbol->getId() == varSymbol->getId())
3076 {
3077 ASSERT(listSymbol->getSymbol() == varSymbol->getSymbol());
3078 ASSERT(listSymbol->getType() == varSymbol->getType());
3079 ASSERT(listSymbol->getQualifier() == varSymbol->getQualifier());
3080
3081 return i;
3082 }
3083 }
3084 }
3085 }
3086 }
3087
3088 return -1;
3089 }
3090
3091 int OutputASM::lookup(VariableArray &list, TInterfaceBlock *block)
3092 {
3093 for(unsigned int i = 0; i < list.size(); i++)
3094 {
3095 if(list[i] && (list[i]->getType().getInterfaceBlock() == block))
3096 {
3097 return i; // Pointer match
3098 }
3099 }
3100 return -1;
3101 }
3102
3103 int OutputASM::allocate(VariableArray &list, TIntermTyped *variable)
3104 {
3105 int index = lookup(list, variable);
3106
3107 if(index == -1)
3108 {
3109 unsigned int registerCount = variable->blockRegisterCount();
3110
3111 for(unsigned int i = 0; i < list.size(); i++)
3112 {
3113 if(list[i] == 0)
3114 {
3115 unsigned int j = 1;
3116 for( ; j < registerCount && (i + j) < list.size(); j++)
3117 {
3118 if(list[i + j] != 0)
3119 {
3120 break;
3121 }
3122 }
3123
3124 if(j == registerCount) // Found free slots
3125 {
3126 for(unsigned int j = 0; j < registerCount; j++)
3127 {
3128 list[i + j] = variable;
3129 }
3130
3131 return i;
3132 }
3133 }
3134 }
3135
3136 index = list.size();
3137
3138 for(unsigned int i = 0; i < registerCount; i++)
3139 {
3140 list.push_back(variable);
3141 }
3142 }
3143
3144 return index;
3145 }
3146
3147 void OutputASM::free(VariableArray &list, TIntermTyped *variable)
3148 {
3149 int index = lookup(list, variable);
3150
3151 if(index >= 0)
3152 {
3153 list[index] = 0;
3154 }
3155 }
3156
3157 int OutputASM::blockMemberLookup(const TType &type, const TString &name, int registerIndex)
3158 {
3159 const TInterfaceBlock *block = type.getInterfaceBlock();
3160
3161 if(block)
3162 {
3163 ActiveUniformBlocks &activeUniformBlocks = shaderObject->activeUniformBlocks;
3164 const TFieldList& fields = block->fields();
3165 const TString &blockName = block->name();
3166 int fieldRegisterIndex = registerIndex;
3167
3168 if(!type.isInterfaceBlock())
3169 {
3170 // This is a uniform that's part of a block, let's see if the block is already defined
3171 for(size_t i = 0; i < activeUniformBlocks.size(); ++i)
3172 {
3173 if(activeUniformBlocks[i].name == blockName.c_str())
3174 {
3175 // The block is already defined, find the register for the current uniform and return it
3176 for(size_t j = 0; j < fields.size(); j++)
3177 {
3178 const TString &fieldName = fields[j]->name();
3179 if(fieldName == name)
3180 {
3181 return fieldRegisterIndex;
3182 }
3183
3184 fieldRegisterIndex += fields[j]->type()->totalRegisterCount();
3185 }
3186
3187 ASSERT(false);
3188 return fieldRegisterIndex;
3189 }
3190 }
3191 }
3192 }
3193
3194 return -1;
3195 }
3196
3197 void OutputASM::declareUniform(const TType &type, const TString &name, int registerIndex, int blockId, BlockLayoutEncoder* encoder)
3198 {
3199 const TStructure *structure = type.getStruct();
3200 const TInterfaceBlock *block = (type.isInterfaceBlock() || (blockId == -1)) ? type.getInterfaceBlock() : nullptr;
3201
3202 if(!structure && !block)
3203 {
3204 ActiveUniforms &activeUniforms = shaderObject->activeUniforms;
3205 const BlockMemberInfo blockInfo = encoder ? encoder->encodeType(type) : BlockMemberInfo::getDefaultBlockInfo();
3206 if(blockId >= 0)
3207 {
3208 blockDefinitions[blockId][registerIndex] = TypedMemberInfo(blockInfo, type);
3209 shaderObject->activeUniformBlocks[blockId].fields.push_back(activeUniforms.size());
3210 }
3211 int fieldRegisterIndex = encoder ? shaderObject->activeUniformBlocks[blockId].registerIndex + BlockLayoutEncoder::getBlockRegister(blockInfo) : registerIndex;
3212 activeUniforms.push_back(Uniform(glVariableType(type), glVariablePrecision(type), name.c_str(), type.getArraySize(),
3213 fieldRegisterIndex, blockId, blockInfo));
3214 if(IsSampler(type.getBasicType()))
3215 {
3216 for(int i = 0; i < type.totalRegisterCount(); i++)
3217 {
3218 shader->declareSampler(fieldRegisterIndex + i);
3219 }
3220 }
3221 }
3222 else if(block)
3223 {
3224 ActiveUniformBlocks &activeUniformBlocks = shaderObject->activeUniformBlocks;
3225 const TFieldList& fields = block->fields();
3226 const TString &blockName = block->name();
3227 int fieldRegisterIndex = registerIndex;
3228 bool isUniformBlockMember = !type.isInterfaceBlock() && (blockId == -1);
3229
3230 blockId = activeUniformBlocks.size();
3231 bool isRowMajor = block->matrixPacking() == EmpRowMajor;
3232 activeUniformBlocks.push_back(UniformBlock(blockName.c_str(), 0, block->arraySize(),
3233 block->blockStorage(), isRowMajor, registerIndex, blockId));
3234 blockDefinitions.push_back(BlockDefinitionIndexMap());
3235
3236 Std140BlockEncoder currentBlockEncoder(isRowMajor);
3237 currentBlockEncoder.enterAggregateType();
3238 for(size_t i = 0; i < fields.size(); i++)
3239 {
3240 const TType &fieldType = *(fields[i]->type());
3241 const TString &fieldName = fields[i]->name();
3242 if(isUniformBlockMember && (fieldName == name))
3243 {
3244 registerIndex = fieldRegisterIndex;
3245 }
3246
3247 const TString uniformName = block->hasInstanceName() ? blockName + "." + fieldName : fieldName;
3248
3249 declareUniform(fieldType, uniformName, fieldRegisterIndex, blockId, &currentBlockEncoder);
3250 fieldRegisterIndex += fieldType.totalRegisterCount();
3251 }
3252 currentBlockEncoder.exitAggregateType();
3253 activeUniformBlocks[blockId].dataSize = currentBlockEncoder.getBlockSize();
3254 }
3255 else
3256 {
3257 int fieldRegisterIndex = registerIndex;
3258
3259 const TFieldList& fields = structure->fields();
3260 if(type.isArray() && (structure || type.isInterfaceBlock()))
3261 {
3262 for(int i = 0; i < type.getArraySize(); i++)
3263 {
3264 if(encoder)
3265 {
3266 encoder->enterAggregateType();
3267 }
3268 for(size_t j = 0; j < fields.size(); j++)
3269 {
3270 const TType &fieldType = *(fields[j]->type());
3271 const TString &fieldName = fields[j]->name();
3272 const TString uniformName = name + "[" + str(i) + "]." + fieldName;
3273
3274 declareUniform(fieldType, uniformName, fieldRegisterIndex, blockId, encoder);
3275 fieldRegisterIndex += fieldType.totalRegisterCount();
3276 }
3277 if(encoder)
3278 {
3279 encoder->exitAggregateType();
3280 }
3281 }
3282 }
3283 else
3284 {
3285 if(encoder)
3286 {
3287 encoder->enterAggregateType();
3288 }
3289 for(size_t i = 0; i < fields.size(); i++)
3290 {
3291 const TType &fieldType = *(fields[i]->type());
3292 const TString &fieldName = fields[i]->name();
3293 const TString uniformName = name + "." + fieldName;
3294
3295 declareUniform(fieldType, uniformName, fieldRegisterIndex, blockId, encoder);
3296 fieldRegisterIndex += fieldType.totalRegisterCount();
3297 }
3298 if(encoder)
3299 {
3300 encoder->exitAggregateType();
3301 }
3302 }
3303 }
3304 }
3305
3306 GLenum OutputASM::glVariableType(const TType &type)
3307 {
3308 switch(type.getBasicType())
3309 {
3310 case EbtFloat:
3311 if(type.isScalar())
3312 {
3313 return GL_FLOAT;
3314 }
3315 else if(type.isVector())
3316 {
3317 switch(type.getNominalSize())
3318 {
3319 case 2: return GL_FLOAT_VEC2;
3320 case 3: return GL_FLOAT_VEC3;
3321 case 4: return GL_FLOAT_VEC4;
3322 default: UNREACHABLE(type.getNominalSize());
3323 }
3324 }
3325 else if(type.isMatrix())
3326 {
3327 switch(type.getNominalSize())
3328 {
3329 case 2:
3330 switch(type.getSecondarySize())
3331 {
3332 case 2: return GL_FLOAT_MAT2;
3333 case 3: return GL_FLOAT_MAT2x3;
3334 case 4: return GL_FLOAT_MAT2x4;
3335 default: UNREACHABLE(type.getSecondarySize());
3336 }
3337 case 3:
3338 switch(type.getSecondarySize())
3339 {
3340 case 2: return GL_FLOAT_MAT3x2;
3341 case 3: return GL_FLOAT_MAT3;
3342 case 4: return GL_FLOAT_MAT3x4;
3343 default: UNREACHABLE(type.getSecondarySize());
3344 }
3345 case 4:
3346 switch(type.getSecondarySize())
3347 {
3348 case 2: return GL_FLOAT_MAT4x2;
3349 case 3: return GL_FLOAT_MAT4x3;
3350 case 4: return GL_FLOAT_MAT4;
3351 default: UNREACHABLE(type.getSecondarySize());
3352 }
3353 default: UNREACHABLE(type.getNominalSize());
3354 }
3355 }
3356 else UNREACHABLE(0);
3357 break;
3358 case EbtInt:
3359 if(type.isScalar())
3360 {
3361 return GL_INT;
3362 }
3363 else if(type.isVector())
3364 {
3365 switch(type.getNominalSize())
3366 {
3367 case 2: return GL_INT_VEC2;
3368 case 3: return GL_INT_VEC3;
3369 case 4: return GL_INT_VEC4;
3370 default: UNREACHABLE(type.getNominalSize());
3371 }
3372 }
3373 else UNREACHABLE(0);
3374 break;
3375 case EbtUInt:
3376 if(type.isScalar())
3377 {
3378 return GL_UNSIGNED_INT;
3379 }
3380 else if(type.isVector())
3381 {
3382 switch(type.getNominalSize())
3383 {
3384 case 2: return GL_UNSIGNED_INT_VEC2;
3385 case 3: return GL_UNSIGNED_INT_VEC3;
3386 case 4: return GL_UNSIGNED_INT_VEC4;
3387 default: UNREACHABLE(type.getNominalSize());
3388 }
3389 }
3390 else UNREACHABLE(0);
3391 break;
3392 case EbtBool:
3393 if(type.isScalar())
3394 {
3395 return GL_BOOL;
3396 }
3397 else if(type.isVector())
3398 {
3399 switch(type.getNominalSize())
3400 {
3401 case 2: return GL_BOOL_VEC2;
3402 case 3: return GL_BOOL_VEC3;
3403 case 4: return GL_BOOL_VEC4;
3404 default: UNREACHABLE(type.getNominalSize());
3405 }
3406 }
3407 else UNREACHABLE(0);
3408 break;
3409 case EbtSampler2D:
3410 return GL_SAMPLER_2D;
3411 case EbtISampler2D:
3412 return GL_INT_SAMPLER_2D;
3413 case EbtUSampler2D:
3414 return GL_UNSIGNED_INT_SAMPLER_2D;
3415 case EbtSamplerCube:
3416 return GL_SAMPLER_CUBE;
3417 case EbtISamplerCube:
3418 return GL_INT_SAMPLER_CUBE;
3419 case EbtUSamplerCube:
3420 return GL_UNSIGNED_INT_SAMPLER_CUBE;
3421 case EbtSamplerExternalOES:
3422 return GL_SAMPLER_EXTERNAL_OES;
3423 case EbtSampler3D:
3424 return GL_SAMPLER_3D_OES;
3425 case EbtISampler3D:
3426 return GL_INT_SAMPLER_3D;
3427 case EbtUSampler3D:
3428 return GL_UNSIGNED_INT_SAMPLER_3D;
3429 case EbtSampler2DArray:
3430 return GL_SAMPLER_2D_ARRAY;
3431 case EbtISampler2DArray:
3432 return GL_INT_SAMPLER_2D_ARRAY;
3433 case EbtUSampler2DArray:
3434 return GL_UNSIGNED_INT_SAMPLER_2D_ARRAY;
3435 case EbtSampler2DShadow:
3436 return GL_SAMPLER_2D_SHADOW;
3437 case EbtSamplerCubeShadow:
3438 return GL_SAMPLER_CUBE_SHADOW;
3439 case EbtSampler2DArrayShadow:
3440 return GL_SAMPLER_2D_ARRAY_SHADOW;
3441 default:
3442 UNREACHABLE(type.getBasicType());
3443 break;
3444 }
3445
3446 return GL_NONE;
3447 }
3448
3449 GLenum OutputASM::glVariablePrecision(const TType &type)
3450 {
3451 if(type.getBasicType() == EbtFloat)
3452 {
3453 switch(type.getPrecision())
3454 {
3455 case EbpHigh: return GL_HIGH_FLOAT;
3456 case EbpMedium: return GL_MEDIUM_FLOAT;
3457 case EbpLow: return GL_LOW_FLOAT;
3458 case EbpUndefined:
3459 // Should be defined as the default precision by the parser
3460 default: UNREACHABLE(type.getPrecision());
3461 }
3462 }
3463 else if(type.getBasicType() == EbtInt)
3464 {
3465 switch(type.getPrecision())
3466 {
3467 case EbpHigh: return GL_HIGH_INT;
3468 case EbpMedium: return GL_MEDIUM_INT;
3469 case EbpLow: return GL_LOW_INT;
3470 case EbpUndefined:
3471 // Should be defined as the default precision by the parser
3472 default: UNREACHABLE(type.getPrecision());
3473 }
3474 }
3475
3476 // Other types (boolean, sampler) don't have a precision
3477 return GL_NONE;
3478 }
3479
3480 int OutputASM::dim(TIntermNode *v)
3481 {
3482 TIntermTyped *vector = v->getAsTyped();
3483 ASSERT(vector && vector->isRegister());
3484 return vector->getNominalSize();
3485 }
3486
3487 int OutputASM::dim2(TIntermNode *m)
3488 {
3489 TIntermTyped *matrix = m->getAsTyped();
3490 ASSERT(matrix && matrix->isMatrix() && !matrix->isArray());
3491 return matrix->getSecondarySize();
3492 }
3493
3494 // Returns ~0u if no loop count could be determined
3495 unsigned int OutputASM::loopCount(TIntermLoop *node)
3496 {
3497 // Parse loops of the form:
3498 // for(int index = initial; index [comparator] limit; index += increment)
3499 TIntermSymbol *index = 0;
3500 TOperator comparator = EOpNull;
3501 int initial = 0;
3502 int limit = 0;
3503 int increment = 0;
3504
3505 // Parse index name and intial value
3506 if(node->getInit())
3507 {
3508 TIntermAggregate *init = node->getInit()->getAsAggregate();
3509
3510 if(init)
3511 {
3512 TIntermSequence &sequence = init->getSequence();
3513 TIntermTyped *variable = sequence[0]->getAsTyped();
3514
3515 if(variable && variable->getQualifier() == EvqTemporary)
3516 {
3517 TIntermBinary *assign = variable->getAsBinaryNode();
3518
3519 if(assign->getOp() == EOpInitialize)
3520 {
3521 TIntermSymbol *symbol = assign->getLeft()->getAsSymbolNode();
3522 TIntermConstantUnion *constant = assign->getRight()->getAsConstantUnion();
3523
3524 if(symbol && constant)
3525 {
3526 if(constant->getBasicType() == EbtInt && constant->getNominalSize() == 1)
3527 {
3528 index = symbol;
3529 initial = constant->getUnionArrayPointer()[0].getIConst();
3530 }
3531 }
3532 }
3533 }
3534 }
3535 }
3536
3537 // Parse comparator and limit value
3538 if(index && node->getCondition())
3539 {
3540 TIntermBinary *test = node->getCondition()->getAsBinaryNode();
Alexis Hetu7be70cf2016-05-11 10:56:43 -04003541 TIntermSymbol *left = test ? test->getLeft()->getAsSymbolNode() : nullptr;
Nicolas Capens0bac2852016-05-07 06:09:58 -04003542
Alexis Hetu7be70cf2016-05-11 10:56:43 -04003543 if(left && (left->getId() == index->getId()))
Nicolas Capens0bac2852016-05-07 06:09:58 -04003544 {
3545 TIntermConstantUnion *constant = test->getRight()->getAsConstantUnion();
3546
3547 if(constant)
3548 {
3549 if(constant->getBasicType() == EbtInt && constant->getNominalSize() == 1)
3550 {
3551 comparator = test->getOp();
3552 limit = constant->getUnionArrayPointer()[0].getIConst();
3553 }
3554 }
3555 }
3556 }
3557
3558 // Parse increment
3559 if(index && comparator != EOpNull && node->getExpression())
3560 {
3561 TIntermBinary *binaryTerminal = node->getExpression()->getAsBinaryNode();
3562 TIntermUnary *unaryTerminal = node->getExpression()->getAsUnaryNode();
3563
3564 if(binaryTerminal)
3565 {
3566 TOperator op = binaryTerminal->getOp();
3567 TIntermConstantUnion *constant = binaryTerminal->getRight()->getAsConstantUnion();
3568
3569 if(constant)
3570 {
3571 if(constant->getBasicType() == EbtInt && constant->getNominalSize() == 1)
3572 {
3573 int value = constant->getUnionArrayPointer()[0].getIConst();
3574
3575 switch(op)
3576 {
3577 case EOpAddAssign: increment = value; break;
3578 case EOpSubAssign: increment = -value; break;
3579 default: UNIMPLEMENTED();
3580 }
3581 }
3582 }
3583 }
3584 else if(unaryTerminal)
3585 {
3586 TOperator op = unaryTerminal->getOp();
3587
3588 switch(op)
3589 {
3590 case EOpPostIncrement: increment = 1; break;
3591 case EOpPostDecrement: increment = -1; break;
3592 case EOpPreIncrement: increment = 1; break;
3593 case EOpPreDecrement: increment = -1; break;
3594 default: UNIMPLEMENTED();
3595 }
3596 }
3597 }
3598
3599 if(index && comparator != EOpNull && increment != 0)
3600 {
3601 if(comparator == EOpLessThanEqual)
3602 {
3603 comparator = EOpLessThan;
3604 limit += 1;
3605 }
3606
3607 if(comparator == EOpLessThan)
3608 {
3609 int iterations = (limit - initial) / increment;
3610
3611 if(iterations <= 0)
3612 {
3613 iterations = 0;
3614 }
3615
3616 return iterations;
3617 }
3618 else UNIMPLEMENTED(); // Falls through
3619 }
3620
3621 return ~0u;
3622 }
3623
3624 bool LoopUnrollable::traverse(TIntermNode *node)
3625 {
3626 loopDepth = 0;
3627 loopUnrollable = true;
3628
3629 node->traverse(this);
3630
3631 return loopUnrollable;
3632 }
3633
3634 bool LoopUnrollable::visitLoop(Visit visit, TIntermLoop *loop)
3635 {
3636 if(visit == PreVisit)
3637 {
3638 loopDepth++;
3639 }
3640 else if(visit == PostVisit)
3641 {
3642 loopDepth++;
3643 }
3644
3645 return true;
3646 }
3647
3648 bool LoopUnrollable::visitBranch(Visit visit, TIntermBranch *node)
3649 {
3650 if(!loopUnrollable)
3651 {
3652 return false;
3653 }
3654
3655 if(!loopDepth)
3656 {
3657 return true;
3658 }
3659
3660 switch(node->getFlowOp())
3661 {
3662 case EOpKill:
3663 case EOpReturn:
3664 break;
3665 case EOpBreak:
3666 case EOpContinue:
3667 loopUnrollable = false;
3668 break;
3669 default: UNREACHABLE(node->getFlowOp());
3670 }
3671
3672 return loopUnrollable;
3673 }
3674
3675 bool LoopUnrollable::visitAggregate(Visit visit, TIntermAggregate *node)
3676 {
3677 return loopUnrollable;
3678 }
3679}