1 // Copyright 2016 The SwiftShader Authors. All Rights Reserved.
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
7 // http://www.apache.org/licenses/LICENSE-2.0
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.
15 #include "OutputASM.h"
16 #include "Common/Math.hpp"
18 #include "common/debug.h"
21 #include "libGLESv2/Shader.h"
23 #include <GLES2/gl2.h>
24 #include <GLES2/gl2ext.h>
25 #include <GLES3/gl3.h>
29 // Integer to TString conversion
33 sprintf(buffer, "%d", i);
37 class Temporary : public TIntermSymbol
40 Temporary(OutputASM *assembler) : TIntermSymbol(TSymbolTableLevel::nextUniqueId(), "tmp", TType(EbtFloat, EbpHigh, EvqTemporary, 4, 1, false)), assembler(assembler)
46 assembler->freeTemporary(this);
50 OutputASM *const assembler;
53 class Constant : public TIntermConstantUnion
56 Constant(float x, float y, float z, float w) : TIntermConstantUnion(constants, TType(EbtFloat, EbpHigh, EvqConstExpr, 4, 1, false))
58 constants[0].setFConst(x);
59 constants[1].setFConst(y);
60 constants[2].setFConst(z);
61 constants[3].setFConst(w);
64 Constant(bool b) : TIntermConstantUnion(constants, TType(EbtBool, EbpHigh, EvqConstExpr, 1, 1, false))
66 constants[0].setBConst(b);
69 Constant(int i) : TIntermConstantUnion(constants, TType(EbtInt, EbpHigh, EvqConstExpr, 1, 1, false))
71 constants[0].setIConst(i);
79 ConstantUnion constants[4];
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)
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)
94 BlockLayoutEncoder::BlockLayoutEncoder(bool rowMajor)
95 : mCurrentOffset(0), isRowMajor(rowMajor)
99 BlockMemberInfo BlockLayoutEncoder::encodeType(const TType &type)
104 getBlockLayoutInfo(type, type.getArraySize(), isRowMajor, &arrayStride, &matrixStride);
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);
111 advanceOffset(type, type.getArraySize(), isRowMajor, arrayStride, matrixStride);
117 size_t BlockLayoutEncoder::getBlockRegister(const BlockMemberInfo &info)
119 return (info.offset / BytesPerComponent) / ComponentsPerRegister;
123 size_t BlockLayoutEncoder::getBlockRegisterElement(const BlockMemberInfo &info)
125 return (info.offset / BytesPerComponent) % ComponentsPerRegister;
128 void BlockLayoutEncoder::nextRegister()
130 mCurrentOffset = sw::align(mCurrentOffset, ComponentsPerRegister);
133 Std140BlockEncoder::Std140BlockEncoder(bool rowMajor) : BlockLayoutEncoder(rowMajor)
137 void Std140BlockEncoder::enterAggregateType()
142 void Std140BlockEncoder::exitAggregateType()
147 void Std140BlockEncoder::getBlockLayoutInfo(const TType &type, unsigned int arraySize, bool isRowMajorMatrix, int *arrayStrideOut, int *matrixStrideOut)
149 size_t baseAlignment = 0;
150 int matrixStride = 0;
155 baseAlignment = ComponentsPerRegister;
156 matrixStride = ComponentsPerRegister;
160 const int numRegisters = isRowMajorMatrix ? type.getSecondarySize() : type.getNominalSize();
161 arrayStride = ComponentsPerRegister * numRegisters;
164 else if(arraySize > 0)
166 baseAlignment = ComponentsPerRegister;
167 arrayStride = ComponentsPerRegister;
171 const size_t numComponents = type.getElementSize();
172 baseAlignment = (numComponents == 3 ? 4u : numComponents);
175 mCurrentOffset = sw::align(mCurrentOffset, baseAlignment);
177 *matrixStrideOut = matrixStride;
178 *arrayStrideOut = arrayStride;
181 void Std140BlockEncoder::advanceOffset(const TType &type, unsigned int arraySize, bool isRowMajorMatrix, int arrayStride, int matrixStride)
185 mCurrentOffset += arrayStride * arraySize;
187 else if(type.isMatrix())
189 ASSERT(matrixStride == ComponentsPerRegister);
190 const int numRegisters = isRowMajorMatrix ? type.getSecondarySize() : type.getNominalSize();
191 mCurrentOffset += ComponentsPerRegister * numRegisters;
195 mCurrentOffset += type.getElementSize();
199 Attribute::Attribute()
206 Attribute::Attribute(GLenum type, const std::string &name, int arraySize, int location, int registerIndex)
210 this->arraySize = arraySize;
211 this->location = location;
212 this->registerIndex = registerIndex;
215 sw::PixelShader *Shader::getPixelShader() const
220 sw::VertexShader *Shader::getVertexShader() const
225 OutputASM::TextureFunction::TextureFunction(const TString& nodeName) : method(IMPLICIT), proj(false), offset(false)
227 TString name = TFunction::unmangleName(nodeName);
229 if(name == "texture2D" || name == "textureCube" || name == "texture" || name == "texture3D")
233 else if(name == "texture2DProj" || name == "textureProj")
238 else if(name == "texture2DLod" || name == "textureCubeLod" || name == "textureLod")
242 else if(name == "texture2DProjLod" || name == "textureProjLod")
247 else if(name == "textureSize")
251 else if(name == "textureOffset")
256 else if(name == "textureProjOffset")
262 else if(name == "textureLodOffset")
267 else if(name == "textureProjLodOffset")
273 else if(name == "texelFetch")
277 else if(name == "texelFetchOffset")
282 else if(name == "textureGrad")
286 else if(name == "textureGradOffset")
291 else if(name == "textureProjGrad")
296 else if(name == "textureProjGradOffset")
305 OutputASM::OutputASM(TParseContext &context, Shader *shaderObject) : TIntermTraverser(true, true, true), shaderObject(shaderObject), mContext(context)
313 shader = shaderObject->getShader();
314 pixelShader = shaderObject->getPixelShader();
315 vertexShader = shaderObject->getVertexShader();
318 functionArray.push_back(Function(0, "main(", 0, 0));
320 outputQualifier = EvqOutput; // Set outputQualifier to any value other than EvqFragColor or EvqFragData
323 OutputASM::~OutputASM()
327 void OutputASM::output()
333 if(functionArray.size() > 1) // Only call main() when there are other functions
335 Instruction *callMain = emit(sw::Shader::OPCODE_CALL);
336 callMain->dst.type = sw::Shader::PARAMETER_LABEL;
337 callMain->dst.index = 0; // main()
339 emit(sw::Shader::OPCODE_RET);
342 emitShader(FUNCTION);
346 void OutputASM::emitShader(Scope scope)
349 currentScope = GLOBAL;
350 mContext.getTreeRoot()->traverse(this);
353 void OutputASM::freeTemporary(Temporary *temporary)
355 free(temporaries, temporary);
358 sw::Shader::Opcode OutputASM::getOpcode(sw::Shader::Opcode op, TIntermTyped *in) const
360 TBasicType baseType = in->getType().getBasicType();
364 case sw::Shader::OPCODE_NEG:
369 return sw::Shader::OPCODE_INEG;
374 case sw::Shader::OPCODE_ABS:
378 return sw::Shader::OPCODE_IABS;
383 case sw::Shader::OPCODE_SGN:
387 return sw::Shader::OPCODE_ISGN;
392 case sw::Shader::OPCODE_ADD:
397 return sw::Shader::OPCODE_IADD;
402 case sw::Shader::OPCODE_SUB:
407 return sw::Shader::OPCODE_ISUB;
412 case sw::Shader::OPCODE_MUL:
417 return sw::Shader::OPCODE_IMUL;
422 case sw::Shader::OPCODE_DIV:
426 return sw::Shader::OPCODE_IDIV;
428 return sw::Shader::OPCODE_UDIV;
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:
441 return sw::Shader::OPCODE_IMIN;
443 return sw::Shader::OPCODE_UMIN;
448 case sw::Shader::OPCODE_MAX:
452 return sw::Shader::OPCODE_IMAX;
454 return sw::Shader::OPCODE_UMAX;
464 void OutputASM::visitSymbol(TIntermSymbol *symbol)
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)
470 if(symbol->getBasicType() != EbtInvariant) // Typeless declarations are not new varyings
472 declareVarying(symbol, -1);
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)))
483 uniformRegister(symbol);
487 bool OutputASM::visitBinary(Visit visit, TIntermBinary *node)
489 if(currentScope != emitScope)
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();
500 if(isSamplerRegister(result))
502 return false; // Don't traverse, the register index is determined statically
505 switch(node->getOp())
508 if(visit == PostVisit)
510 assignLvalue(left, right);
515 if(visit == PostVisit)
520 case EOpMatrixTimesScalarAssign:
521 if(visit == PostVisit)
523 for(int i = 0; i < leftType.getNominalSize(); i++)
525 emit(sw::Shader::OPCODE_MUL, result, i, left, i, right);
528 assignLvalue(left, result);
531 case EOpVectorTimesMatrixAssign:
532 if(visit == PostVisit)
534 int size = leftType.getNominalSize();
536 for(int i = 0; i < size; i++)
538 Instruction *dot = emit(sw::Shader::OPCODE_DP(size), result, 0, left, 0, right, i);
539 dot->dst.mask = 1 << i;
542 assignLvalue(left, result);
545 case EOpMatrixTimesMatrixAssign:
546 if(visit == PostVisit)
548 int dim = leftType.getNominalSize();
550 for(int i = 0; i < dim; i++)
552 Instruction *mul = emit(sw::Shader::OPCODE_MUL, result, i, left, 0, right, i);
553 mul->src[1].swizzle = 0x00;
555 for(int j = 1; j < dim; j++)
557 Instruction *mad = emit(sw::Shader::OPCODE_MAD, result, i, left, j, right, i, result, i);
558 mad->src[1].swizzle = j * 0x55;
562 assignLvalue(left, result);
566 if(visit == PostVisit)
568 int index = right->getAsConstantUnion()->getIConst(0);
570 if(result->isMatrix() || result->isStruct() || result->isInterfaceBlock())
572 ASSERT(left->isArray());
573 copy(result, left, index * left->elementRegisterCount());
575 else if(result->isRegister())
578 if(left->isRegister())
582 else if(left->isArray())
584 srcIndex = index * left->elementRegisterCount();
586 else if(left->isMatrix())
588 ASSERT(index < left->getNominalSize()); // FIXME: Report semantic error
593 Instruction *mov = emit(sw::Shader::OPCODE_MOV, result, 0, left, srcIndex);
595 if(left->isRegister())
597 mov->src[0].swizzle = index;
603 case EOpIndexIndirect:
604 if(visit == PostVisit)
606 if(left->isArray() || left->isMatrix())
608 for(int index = 0; index < result->totalRegisterCount(); index++)
610 Instruction *mov = emit(sw::Shader::OPCODE_MOV, result, index, left, index);
611 mov->dst.mask = writeMask(result, index);
613 if(left->totalRegisterCount() > 1)
615 sw::Shader::SourceParameter relativeRegister;
616 argument(relativeRegister, right);
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);
625 else if(left->isRegister())
627 emit(sw::Shader::OPCODE_EXTRACT, result, left, right);
632 case EOpIndexDirectStruct:
633 case EOpIndexDirectInterfaceBlock:
634 if(visit == PostVisit)
636 ASSERT(leftType.isStruct() || (leftType.isInterfaceBlock()));
638 const TFieldList& fields = (node->getOp() == EOpIndexDirectStruct) ?
639 leftType.getStruct()->fields() :
640 leftType.getInterfaceBlock()->fields();
641 int index = right->getAsConstantUnion()->getIConst(0);
644 for(int i = 0; i < index; i++)
646 fieldOffset += fields[i]->type()->totalRegisterCount();
649 copy(result, left, fieldOffset);
652 case EOpVectorSwizzle:
653 if(visit == PostVisit)
656 TIntermAggregate *components = right->getAsAggregate();
660 TIntermSequence &sequence = components->getSequence();
663 for(TIntermSequence::iterator sit = sequence.begin(); sit != sequence.end(); sit++)
665 TIntermConstantUnion *element = (*sit)->getAsConstantUnion();
669 int i = element->getUnionArrayPointer()[0].getIConst();
670 swizzle |= i << (component * 2);
678 Instruction *mov = emit(sw::Shader::OPCODE_MOV, result, left);
679 mov->src[0].swizzle = swizzle;
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;
703 if(visit == PostVisit)
705 emitBinary(sw::Shader::OPCODE_EQ, result, left, right);
707 for(int index = 1; index < left->totalRegisterCount(); index++)
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);
716 if(visit == PostVisit)
718 emitBinary(sw::Shader::OPCODE_NE, result, left, right);
720 for(int index = 1; index < left->totalRegisterCount(); index++)
722 Temporary notEqual(this);
723 emit(sw::Shader::OPCODE_NE, ¬Equal, 0, left, index, right, index);
724 emit(sw::Shader::OPCODE_OR, result, result, ¬Equal);
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)
739 for(int i = 0; i < leftType.getNominalSize(); i++)
741 emit(sw::Shader::OPCODE_MUL, result, i, left, i, right, 0);
744 else if(right->isMatrix())
746 for(int i = 0; i < rightType.getNominalSize(); i++)
748 emit(sw::Shader::OPCODE_MUL, result, i, left, 0, right, i);
754 case EOpVectorTimesMatrix:
755 if(visit == PostVisit)
757 sw::Shader::Opcode dpOpcode = sw::Shader::OPCODE_DP(leftType.getNominalSize());
759 int size = rightType.getNominalSize();
760 for(int i = 0; i < size; i++)
762 Instruction *dot = emit(dpOpcode, result, 0, left, 0, right, i);
763 dot->dst.mask = 1 << i;
767 case EOpMatrixTimesVector:
768 if(visit == PostVisit)
770 Instruction *mul = emit(sw::Shader::OPCODE_MUL, result, left, right);
771 mul->src[1].swizzle = 0x00;
773 int size = rightType.getNominalSize();
774 for(int i = 1; i < size; i++)
776 Instruction *mad = emit(sw::Shader::OPCODE_MAD, result, 0, left, i, right, 0, result);
777 mad->src[1].swizzle = i * 0x55;
781 case EOpMatrixTimesMatrix:
782 if(visit == PostVisit)
784 int dim = leftType.getNominalSize();
786 int size = rightType.getNominalSize();
787 for(int i = 0; i < size; i++)
789 Instruction *mul = emit(sw::Shader::OPCODE_MUL, result, i, left, 0, right, i);
790 mul->src[1].swizzle = 0x00;
792 for(int j = 1; j < dim; j++)
794 Instruction *mad = emit(sw::Shader::OPCODE_MAD, result, i, left, j, right, i, result, i);
795 mad->src[1].swizzle = j * 0x55;
801 if(trivial(right, 6))
803 if(visit == PostVisit)
805 emit(sw::Shader::OPCODE_OR, result, left, right);
808 else // Short-circuit evaluation
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;
816 else if(visit == PostVisit)
818 emit(sw::Shader::OPCODE_MOV, result, right);
819 emit(sw::Shader::OPCODE_ENDIF);
823 case EOpLogicalXor: if(visit == PostVisit) emit(sw::Shader::OPCODE_XOR, result, left, right); break;
825 if(trivial(right, 6))
827 if(visit == PostVisit)
829 emit(sw::Shader::OPCODE_AND, result, left, right);
832 else // Short-circuit evaluation
836 emit(sw::Shader::OPCODE_MOV, result, left);
837 emit(sw::Shader::OPCODE_IF, 0, result);
839 else if(visit == PostVisit)
841 emit(sw::Shader::OPCODE_MOV, result, right);
842 emit(sw::Shader::OPCODE_ENDIF);
846 default: UNREACHABLE(node->getOp());
852 void OutputASM::emitDeterminant(TIntermTyped *result, TIntermTyped *arg, int size, int col, int row, int outCol, int outRow)
856 case 1: // Used for cofactor computation only
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;
868 static const unsigned int swizzle[3] = { 0x99, 0x88, 0x44 }; // xy?? : yzyz, xzxz, xyxy
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));
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;
882 static const unsigned int swizzle[4] = { 0xF9, 0xF8, 0xF4, 0xE4 }; // xyz? : yzww, xzww, xyww, xyzw
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));
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;
897 Instruction *det = emit(sw::Shader::OPCODE_DET4, result, outCol, arg, 0, arg, 1, arg, 2, arg, 3);
898 det->dst.mask = 1 << outRow;
907 bool OutputASM::visitUnary(Visit visit, TIntermUnary *node)
909 if(currentScope != emitScope)
914 TIntermTyped *result = node;
915 TIntermTyped *arg = node->getOperand();
916 TBasicType basicType = arg->getType().getBasicType();
924 if(basicType == EbtInt || basicType == EbtUInt)
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);
937 switch(node->getOp())
940 if(visit == PostVisit)
942 sw::Shader::Opcode negOpcode = getOpcode(sw::Shader::OPCODE_NEG, arg);
943 for(int index = 0; index < arg->totalRegisterCount(); index++)
945 emit(negOpcode, result, index, arg, index);
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)
956 sw::Shader::Opcode addOpcode = getOpcode(sw::Shader::OPCODE_ADD, arg);
957 for(int index = 0; index < arg->totalRegisterCount(); index++)
959 emit(addOpcode, arg, index, arg, index, &one);
962 assignLvalue(arg, arg);
965 case EOpPostDecrement:
966 if(visit == PostVisit)
970 sw::Shader::Opcode subOpcode = getOpcode(sw::Shader::OPCODE_SUB, arg);
971 for(int index = 0; index < arg->totalRegisterCount(); index++)
973 emit(subOpcode, arg, index, arg, index, &one);
976 assignLvalue(arg, arg);
979 case EOpPreIncrement:
980 if(visit == PostVisit)
982 sw::Shader::Opcode addOpcode = getOpcode(sw::Shader::OPCODE_ADD, arg);
983 for(int index = 0; index < arg->totalRegisterCount(); index++)
985 emit(addOpcode, result, index, arg, index, &one);
988 assignLvalue(arg, result);
991 case EOpPreDecrement:
992 if(visit == PostVisit)
994 sw::Shader::Opcode subOpcode = getOpcode(sw::Shader::OPCODE_SUB, arg);
995 for(int index = 0; index < arg->totalRegisterCount(); index++)
997 emit(subOpcode, result, index, arg, index, &one);
1000 assignLvalue(arg, result);
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, °); 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;
1051 if(visit == PostVisit)
1053 int numCols = arg->getNominalSize();
1054 int numRows = arg->getSecondarySize();
1055 for(int i = 0; i < numCols; ++i)
1057 for(int j = 0; j < numRows; ++j)
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;
1066 case EOpDeterminant:
1067 if(visit == PostVisit)
1069 int size = arg->getNominalSize();
1070 ASSERT(size == arg->getSecondarySize());
1072 emitDeterminant(result, arg, size);
1076 if(visit == PostVisit)
1078 int size = arg->getNominalSize();
1079 ASSERT(size == arg->getSecondarySize());
1081 // Compute transposed matrix of cofactors
1082 for(int i = 0; i < size; ++i)
1084 for(int j = 0; j < size; ++j)
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);
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
1099 // Divide transposed matrix of cofactors by determinant
1100 for(int i = 0; i < size; ++i)
1102 emit(sw::Shader::OPCODE_MUL, result, i, result, i, &invDet);
1106 default: UNREACHABLE(node->getOp());
1112 bool OutputASM::visitAggregate(Visit visit, TIntermAggregate *node)
1114 if(currentScope != emitScope && node->getOp() != EOpFunction && node->getOp() != EOpSequence)
1119 Constant zero(0.0f, 0.0f, 0.0f, 0.0f);
1121 TIntermTyped *result = node;
1122 const TType &resultType = node->getType();
1123 TIntermSequence &arg = node->getSequence();
1124 size_t argumentCount = arg.size();
1126 switch(node->getOp())
1128 case EOpSequence: break;
1129 case EOpDeclaration: break;
1130 case EOpInvariantDeclaration: break;
1131 case EOpPrototype: break;
1133 if(visit == PostVisit)
1135 copy(result, arg[1]);
1139 if(visit == PreVisit)
1141 const TString &name = node->getName();
1143 if(emitScope == FUNCTION)
1145 if(functionArray.size() > 1) // No need for a label when there's only main()
1147 Instruction *label = emit(sw::Shader::OPCODE_LABEL);
1148 label->dst.type = sw::Shader::PARAMETER_LABEL;
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;
1156 else if(emitScope == GLOBAL)
1160 TIntermSequence &arguments = node->getSequence()[0]->getAsAggregate()->getSequence();
1161 functionArray.push_back(Function(functionArray.size(), name, &arguments, node));
1164 else UNREACHABLE(emitScope);
1166 currentScope = FUNCTION;
1168 else if(visit == PostVisit)
1170 if(emitScope == FUNCTION)
1172 if(functionArray.size() > 1) // No need to return when there's only main()
1174 emit(sw::Shader::OPCODE_RET);
1178 currentScope = GLOBAL;
1181 case EOpFunctionCall:
1182 if(visit == PostVisit)
1184 if(node->isUserDefined())
1186 const TString &name = node->getName();
1187 const Function *function = findFunction(name);
1191 mContext.error(node->getLine(), "function definition not found", name.c_str());
1195 TIntermSequence &arguments = *function->arg;
1197 for(size_t i = 0; i < argumentCount; i++)
1199 TIntermTyped *in = arguments[i]->getAsTyped();
1201 if(in->getQualifier() == EvqIn ||
1202 in->getQualifier() == EvqInOut ||
1203 in->getQualifier() == EvqConstReadOnly)
1209 Instruction *call = emit(sw::Shader::OPCODE_CALL);
1210 call->dst.type = sw::Shader::PARAMETER_LABEL;
1211 call->dst.index = function->label;
1213 if(function->ret && function->ret->getType().getBasicType() != EbtVoid)
1215 copy(result, function->ret);
1218 for(size_t i = 0; i < argumentCount; i++)
1220 TIntermTyped *argument = arguments[i]->getAsTyped();
1221 TIntermTyped *out = arg[i]->getAsTyped();
1223 if(argument->getQualifier() == EvqOut ||
1224 argument->getQualifier() == EvqInOut)
1226 assignLvalue(out, argument);
1232 const TextureFunction textureFunction(node->getName());
1233 TIntermTyped *t = arg[1]->getAsTyped();
1235 Temporary coord(this);
1237 if(textureFunction.proj)
1239 TIntermConstantUnion* constant = arg[1]->getAsConstantUnion();
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,
1247 emit(sw::Shader::OPCODE_MOV, &coord, &projCoord);
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;
1255 Instruction *mul = emit(sw::Shader::OPCODE_MUL, &coord, arg[1], &coord);
1256 mul->dst.mask = 0x7;
1261 emit(sw::Shader::OPCODE_MOV, &coord, arg[1]);
1264 switch(textureFunction.method)
1266 case TextureFunction::IMPLICIT:
1268 TIntermNode* offset = textureFunction.offset ? arg[2] : 0;
1270 if(argumentCount == 2 || (textureFunction.offset && argumentCount == 3))
1272 emit(textureFunction.offset ? sw::Shader::OPCODE_TEXOFFSET : sw::Shader::OPCODE_TEX,
1273 result, &coord, arg[0], offset);
1275 else if(argumentCount == 3 || (textureFunction.offset && argumentCount == 4)) // bias
1277 Instruction *bias = emit(sw::Shader::OPCODE_MOV, &coord, arg[textureFunction.offset ? 3 : 2]);
1278 bias->dst.mask = 0x8;
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
1284 else UNREACHABLE(argumentCount);
1287 case TextureFunction::LOD:
1289 Instruction *lod = emit(sw::Shader::OPCODE_MOV, &coord, arg[2]);
1290 lod->dst.mask = 0x8;
1292 emit(textureFunction.offset ? sw::Shader::OPCODE_TEXLDLOFFSET : sw::Shader::OPCODE_TEXLDL,
1293 result, &coord, arg[0], textureFunction.offset ? arg[3] : nullptr);
1296 case TextureFunction::FETCH:
1298 if(argumentCount == 3 || (textureFunction.offset && argumentCount == 4))
1300 TIntermNode *offset = textureFunction.offset ? arg[3] : nullptr;
1302 emit(textureFunction.offset ? sw::Shader::OPCODE_TEXELFETCHOFFSET : sw::Shader::OPCODE_TEXELFETCH,
1303 result, arg[1], arg[0], arg[2], offset);
1305 else UNREACHABLE(argumentCount);
1308 case TextureFunction::GRAD:
1310 if(argumentCount == 4 || (textureFunction.offset && argumentCount == 5))
1312 TIntermNode *offset = textureFunction.offset ? arg[4] : nullptr;
1314 emit(textureFunction.offset ? sw::Shader::OPCODE_TEXGRADOFFSET : sw::Shader::OPCODE_TEXGRAD,
1315 result, &coord, arg[0], arg[2], arg[3], offset);
1317 else UNREACHABLE(argumentCount);
1320 case TextureFunction::SIZE:
1321 emit(sw::Shader::OPCODE_TEXSIZE, result, arg[1], arg[0]);
1324 UNREACHABLE(textureFunction.method);
1331 case EOpConstructFloat:
1332 case EOpConstructVec2:
1333 case EOpConstructVec3:
1334 case EOpConstructVec4:
1335 case EOpConstructBool:
1336 case EOpConstructBVec2:
1337 case EOpConstructBVec3:
1338 case EOpConstructBVec4:
1339 case EOpConstructInt:
1340 case EOpConstructIVec2:
1341 case EOpConstructIVec3:
1342 case EOpConstructIVec4:
1343 case EOpConstructUInt:
1344 case EOpConstructUVec2:
1345 case EOpConstructUVec3:
1346 case EOpConstructUVec4:
1347 if(visit == PostVisit)
1351 for(size_t i = 0; i < argumentCount; i++)
1353 TIntermTyped *argi = arg[i]->getAsTyped();
1354 int size = argi->getNominalSize();
1356 if(!argi->isMatrix())
1358 Instruction *mov = emitCast(result, argi);
1359 mov->dst.mask = (0xF << component) & 0xF;
1360 mov->src[0].swizzle = readSwizzle(argi, size) << (component * 2);
1368 while(component < resultType.getNominalSize())
1370 Instruction *mov = emitCast(result, 0, argi, column);
1371 mov->dst.mask = (0xF << component) & 0xF;
1372 mov->src[0].swizzle = readSwizzle(argi, size) << (component * 2);
1381 case EOpConstructMat2:
1382 case EOpConstructMat2x3:
1383 case EOpConstructMat2x4:
1384 case EOpConstructMat3x2:
1385 case EOpConstructMat3:
1386 case EOpConstructMat3x4:
1387 case EOpConstructMat4x2:
1388 case EOpConstructMat4x3:
1389 case EOpConstructMat4:
1390 if(visit == PostVisit)
1392 TIntermTyped *arg0 = arg[0]->getAsTyped();
1393 const int outCols = result->getNominalSize();
1394 const int outRows = result->getSecondarySize();
1396 if(arg0->isScalar() && arg.size() == 1) // Construct scale matrix
1398 for(int i = 0; i < outCols; i++)
1400 emit(sw::Shader::OPCODE_MOV, result, i, &zero);
1401 Instruction *mov = emitCast(result, i, arg0, 0);
1402 mov->dst.mask = 1 << i;
1403 ASSERT(mov->src[0].swizzle == 0x00);
1406 else if(arg0->isMatrix())
1408 const int inCols = arg0->getNominalSize();
1409 const int inRows = arg0->getSecondarySize();
1411 for(int i = 0; i < outCols; i++)
1413 if(i >= inCols || outRows > inRows)
1415 // Initialize to identity matrix
1416 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));
1417 emitCast(result, i, &col, 0);
1422 Instruction *mov = emitCast(result, i, arg0, i);
1423 mov->dst.mask = 0xF >> (4 - inRows);
1432 for(size_t i = 0; i < argumentCount; i++)
1434 TIntermTyped *argi = arg[i]->getAsTyped();
1435 int size = argi->getNominalSize();
1438 while(element < size)
1440 Instruction *mov = emitCast(result, column, argi, 0);
1441 mov->dst.mask = (0xF << row) & 0xF;
1442 mov->src[0].swizzle = (readSwizzle(argi, size) << (row * 2)) + 0x55 * element;
1444 int end = row + size - element;
1445 column = end >= outRows ? column + 1 : column;
1446 element = element + outRows - row;
1447 row = end >= outRows ? 0 : end;
1453 case EOpConstructStruct:
1454 if(visit == PostVisit)
1457 for(size_t i = 0; i < argumentCount; i++)
1459 TIntermTyped *argi = arg[i]->getAsTyped();
1460 int size = argi->totalRegisterCount();
1462 for(int index = 0; index < size; index++)
1464 Instruction *mov = emit(sw::Shader::OPCODE_MOV, result, index + offset, argi, index);
1465 mov->dst.mask = writeMask(result, offset + index);
1472 case EOpLessThan: if(visit == PostVisit) emitCmp(sw::Shader::CONTROL_LT, result, arg[0], arg[1]); break;
1473 case EOpGreaterThan: if(visit == PostVisit) emitCmp(sw::Shader::CONTROL_GT, result, arg[0], arg[1]); break;
1474 case EOpLessThanEqual: if(visit == PostVisit) emitCmp(sw::Shader::CONTROL_LE, result, arg[0], arg[1]); break;
1475 case EOpGreaterThanEqual: if(visit == PostVisit) emitCmp(sw::Shader::CONTROL_GE, result, arg[0], arg[1]); break;
1476 case EOpVectorEqual: if(visit == PostVisit) emitCmp(sw::Shader::CONTROL_EQ, result, arg[0], arg[1]); break;
1477 case EOpVectorNotEqual: if(visit == PostVisit) emitCmp(sw::Shader::CONTROL_NE, result, arg[0], arg[1]); break;
1478 case EOpMod: if(visit == PostVisit) emit(sw::Shader::OPCODE_MOD, result, arg[0], arg[1]); break;
1480 if(visit == PostVisit)
1482 TIntermTyped* arg1 = arg[1]->getAsTyped();
1483 emit(sw::Shader::OPCODE_TRUNC, arg1, arg[0]);
1484 assignLvalue(arg1, arg1);
1485 emitBinary(sw::Shader::OPCODE_SUB, result, arg[0], arg1);
1488 case EOpPow: if(visit == PostVisit) emit(sw::Shader::OPCODE_POW, result, arg[0], arg[1]); break;
1489 case EOpAtan: if(visit == PostVisit) emit(sw::Shader::OPCODE_ATAN2, result, arg[0], arg[1]); break;
1490 case EOpMin: if(visit == PostVisit) emit(getOpcode(sw::Shader::OPCODE_MIN, result), result, arg[0], arg[1]); break;
1491 case EOpMax: if(visit == PostVisit) emit(getOpcode(sw::Shader::OPCODE_MAX, result), result, arg[0], arg[1]); break;
1493 if(visit == PostVisit)
1495 emit(getOpcode(sw::Shader::OPCODE_MAX, result), result, arg[0], arg[1]);
1496 emit(getOpcode(sw::Shader::OPCODE_MIN, result), result, result, arg[2]);
1499 case EOpMix: if(visit == PostVisit) emit(sw::Shader::OPCODE_LRP, result, arg[2], arg[1], arg[0]); break;
1500 case EOpStep: if(visit == PostVisit) emit(sw::Shader::OPCODE_STEP, result, arg[0], arg[1]); break;
1501 case EOpSmoothStep: if(visit == PostVisit) emit(sw::Shader::OPCODE_SMOOTH, result, arg[0], arg[1], arg[2]); break;
1502 case EOpDistance: if(visit == PostVisit) emit(sw::Shader::OPCODE_DIST(dim(arg[0])), result, arg[0], arg[1]); break;
1503 case EOpDot: if(visit == PostVisit) emit(sw::Shader::OPCODE_DP(dim(arg[0])), result, arg[0], arg[1]); break;
1504 case EOpCross: if(visit == PostVisit) emit(sw::Shader::OPCODE_CRS, result, arg[0], arg[1]); break;
1505 case EOpFaceForward: if(visit == PostVisit) emit(sw::Shader::OPCODE_FORWARD(dim(arg[0])), result, arg[0], arg[1], arg[2]); break;
1506 case EOpReflect: if(visit == PostVisit) emit(sw::Shader::OPCODE_REFLECT(dim(arg[0])), result, arg[0], arg[1]); break;
1507 case EOpRefract: if(visit == PostVisit) emit(sw::Shader::OPCODE_REFRACT(dim(arg[0])), result, arg[0], arg[1], arg[2]); break;
1509 if(visit == PostVisit)
1511 TIntermTyped *arg0 = arg[0]->getAsTyped();
1512 TIntermTyped *arg1 = arg[1]->getAsTyped();
1513 ASSERT((arg0->getNominalSize() == arg1->getNominalSize()) && (arg0->getSecondarySize() == arg1->getSecondarySize()));
1515 int size = arg0->getNominalSize();
1516 for(int i = 0; i < size; i++)
1518 emit(sw::Shader::OPCODE_MUL, result, i, arg[0], i, arg[1], i);
1522 case EOpOuterProduct:
1523 if(visit == PostVisit)
1525 for(int i = 0; i < dim(arg[1]); i++)
1527 Instruction *mul = emit(sw::Shader::OPCODE_MUL, result, i, arg[0], 0, arg[1]);
1528 mul->src[1].swizzle = 0x55 * i;
1532 default: UNREACHABLE(node->getOp());
1538 bool OutputASM::visitSelection(Visit visit, TIntermSelection *node)
1540 if(currentScope != emitScope)
1545 TIntermTyped *condition = node->getCondition();
1546 TIntermNode *trueBlock = node->getTrueBlock();
1547 TIntermNode *falseBlock = node->getFalseBlock();
1548 TIntermConstantUnion *constantCondition = condition->getAsConstantUnion();
1550 condition->traverse(this);
1552 if(node->usesTernaryOperator())
1554 if(constantCondition)
1556 bool trueCondition = constantCondition->getUnionArrayPointer()->getBConst();
1560 trueBlock->traverse(this);
1561 copy(node, trueBlock);
1565 falseBlock->traverse(this);
1566 copy(node, falseBlock);
1569 else if(trivial(node, 6)) // Fast to compute both potential results and no side effects
1571 trueBlock->traverse(this);
1572 falseBlock->traverse(this);
1573 emit(sw::Shader::OPCODE_SELECT, node, condition, trueBlock, falseBlock);
1577 emit(sw::Shader::OPCODE_IF, 0, condition);
1581 trueBlock->traverse(this);
1582 copy(node, trueBlock);
1587 emit(sw::Shader::OPCODE_ELSE);
1588 falseBlock->traverse(this);
1589 copy(node, falseBlock);
1592 emit(sw::Shader::OPCODE_ENDIF);
1595 else // if/else statement
1597 if(constantCondition)
1599 bool trueCondition = constantCondition->getUnionArrayPointer()->getBConst();
1605 trueBlock->traverse(this);
1612 falseBlock->traverse(this);
1618 emit(sw::Shader::OPCODE_IF, 0, condition);
1622 trueBlock->traverse(this);
1627 emit(sw::Shader::OPCODE_ELSE);
1628 falseBlock->traverse(this);
1631 emit(sw::Shader::OPCODE_ENDIF);
1638 bool OutputASM::visitLoop(Visit visit, TIntermLoop *node)
1640 if(currentScope != emitScope)
1645 unsigned int iterations = loopCount(node);
1652 bool unroll = (iterations <= 4);
1656 LoopUnrollable loopUnrollable;
1657 unroll = loopUnrollable.traverse(node);
1660 TIntermNode *init = node->getInit();
1661 TIntermTyped *condition = node->getCondition();
1662 TIntermTyped *expression = node->getExpression();
1663 TIntermNode *body = node->getBody();
1664 Constant True(true);
1666 if(node->getType() == ELoopDoWhile)
1668 Temporary iterate(this);
1669 emit(sw::Shader::OPCODE_MOV, &iterate, &True);
1671 emit(sw::Shader::OPCODE_WHILE, 0, &iterate); // FIXME: Implement real do-while
1675 body->traverse(this);
1678 emit(sw::Shader::OPCODE_TEST);
1680 condition->traverse(this);
1681 emit(sw::Shader::OPCODE_MOV, &iterate, condition);
1683 emit(sw::Shader::OPCODE_ENDWHILE);
1689 init->traverse(this);
1694 for(unsigned int i = 0; i < iterations; i++)
1696 // condition->traverse(this); // Condition could contain statements, but not in an unrollable loop
1700 body->traverse(this);
1705 expression->traverse(this);
1713 condition->traverse(this);
1720 emit(sw::Shader::OPCODE_WHILE, 0, condition);
1724 body->traverse(this);
1727 emit(sw::Shader::OPCODE_TEST);
1731 expression->traverse(this);
1736 condition->traverse(this);
1739 emit(sw::Shader::OPCODE_ENDWHILE);
1746 bool OutputASM::visitBranch(Visit visit, TIntermBranch *node)
1748 if(currentScope != emitScope)
1753 switch(node->getFlowOp())
1755 case EOpKill: if(visit == PostVisit) emit(sw::Shader::OPCODE_DISCARD); break;
1756 case EOpBreak: if(visit == PostVisit) emit(sw::Shader::OPCODE_BREAK); break;
1757 case EOpContinue: if(visit == PostVisit) emit(sw::Shader::OPCODE_CONTINUE); break;
1759 if(visit == PostVisit)
1761 TIntermTyped *value = node->getExpression();
1765 copy(functionArray[currentFunction].ret, value);
1768 emit(sw::Shader::OPCODE_LEAVE);
1771 default: UNREACHABLE(node->getFlowOp());
1777 bool OutputASM::visitSwitch(Visit visit, TIntermSwitch *node)
1779 if(currentScope != emitScope)
1784 TIntermTyped* switchValue = node->getInit();
1785 TIntermAggregate* opList = node->getStatementList();
1787 if(!switchValue || !opList)
1792 switchValue->traverse(this);
1794 emit(sw::Shader::OPCODE_SWITCH);
1796 TIntermSequence& sequence = opList->getSequence();
1797 TIntermSequence::iterator it = sequence.begin();
1798 TIntermSequence::iterator defaultIt = sequence.end();
1800 for(; it != sequence.end(); ++it)
1802 TIntermCase* currentCase = (*it)->getAsCaseNode();
1805 TIntermSequence::iterator caseIt = it;
1807 TIntermTyped* condition = currentCase->getCondition();
1808 if(condition) // non default case
1812 emit(sw::Shader::OPCODE_ELSE);
1815 condition->traverse(this);
1816 Temporary result(this);
1817 emitBinary(sw::Shader::OPCODE_EQ, &result, switchValue, condition);
1818 emit(sw::Shader::OPCODE_IF, 0, &result);
1821 for(++caseIt; caseIt != sequence.end(); ++caseIt)
1823 (*caseIt)->traverse(this);
1824 if((*caseIt)->getAsBranchNode()) // Kill, Break, Continue or Return
1832 defaultIt = it; // The default case might not be the last case, keep it for last
1837 // If there's a default case, traverse it here
1838 if(defaultIt != sequence.end())
1840 emit(sw::Shader::OPCODE_ELSE);
1841 for(++defaultIt; defaultIt != sequence.end(); ++defaultIt)
1843 (*defaultIt)->traverse(this);
1844 if((*defaultIt)->getAsBranchNode()) // Kill, Break, Continue or Return
1851 for(int i = 0; i < nbCases; ++i)
1853 emit(sw::Shader::OPCODE_ENDIF);
1856 emit(sw::Shader::OPCODE_ENDSWITCH);
1861 Instruction *OutputASM::emit(sw::Shader::Opcode op, TIntermTyped *dst, TIntermNode *src0, TIntermNode *src1, TIntermNode *src2, TIntermNode *src3, TIntermNode *src4)
1863 return emit(op, dst, 0, src0, 0, src1, 0, src2, 0, src3, 0, src4, 0);
1866 Instruction *OutputASM::emit(sw::Shader::Opcode op, TIntermTyped *dst, int dstIndex, TIntermNode *src0, int index0, TIntermNode *src1, int index1,
1867 TIntermNode *src2, int index2, TIntermNode *src3, int index3, TIntermNode *src4, int index4)
1869 Instruction *instruction = new Instruction(op);
1873 instruction->dst.type = registerType(dst);
1874 instruction->dst.index = registerIndex(dst) + dstIndex;
1875 instruction->dst.mask = writeMask(dst);
1876 instruction->dst.integer = (dst->getBasicType() == EbtInt);
1879 argument(instruction->src[0], src0, index0);
1880 argument(instruction->src[1], src1, index1);
1881 argument(instruction->src[2], src2, index2);
1882 argument(instruction->src[3], src3, index3);
1883 argument(instruction->src[4], src4, index4);
1885 shader->append(instruction);
1890 Instruction *OutputASM::emitCast(TIntermTyped *dst, TIntermTyped *src)
1892 return emitCast(dst, 0, src, 0);
1895 Instruction *OutputASM::emitCast(TIntermTyped *dst, int dstIndex, TIntermTyped *src, int srcIndex)
1897 switch(src->getBasicType())
1900 switch(dst->getBasicType())
1902 case EbtInt: return emit(sw::Shader::OPCODE_B2I, dst, dstIndex, src, srcIndex);
1903 case EbtUInt: return emit(sw::Shader::OPCODE_B2I, dst, dstIndex, src, srcIndex);
1904 case EbtFloat: return emit(sw::Shader::OPCODE_B2F, dst, dstIndex, src, srcIndex);
1909 switch(dst->getBasicType())
1911 case EbtBool: return emit(sw::Shader::OPCODE_I2B, dst, dstIndex, src, srcIndex);
1912 case EbtFloat: return emit(sw::Shader::OPCODE_I2F, dst, dstIndex, src, srcIndex);
1917 switch(dst->getBasicType())
1919 case EbtBool: return emit(sw::Shader::OPCODE_I2B, dst, dstIndex, src, srcIndex);
1920 case EbtFloat: return emit(sw::Shader::OPCODE_U2F, dst, dstIndex, src, srcIndex);
1925 switch(dst->getBasicType())
1927 case EbtBool: return emit(sw::Shader::OPCODE_F2B, dst, dstIndex, src, srcIndex);
1928 case EbtInt: return emit(sw::Shader::OPCODE_F2I, dst, dstIndex, src, srcIndex);
1929 case EbtUInt: return emit(sw::Shader::OPCODE_F2U, dst, dstIndex, src, srcIndex);
1937 ASSERT((src->getBasicType() == dst->getBasicType()) ||
1938 ((src->getBasicType() == EbtInt) && (dst->getBasicType() == EbtUInt)) ||
1939 ((src->getBasicType() == EbtUInt) && (dst->getBasicType() == EbtInt)));
1941 return emit(sw::Shader::OPCODE_MOV, dst, dstIndex, src, srcIndex);
1944 void OutputASM::emitBinary(sw::Shader::Opcode op, TIntermTyped *dst, TIntermNode *src0, TIntermNode *src1, TIntermNode *src2)
1946 for(int index = 0; index < dst->elementRegisterCount(); index++)
1948 emit(op, dst, index, src0, index, src1, index, src2, index);
1952 void OutputASM::emitAssign(sw::Shader::Opcode op, TIntermTyped *result, TIntermTyped *lhs, TIntermTyped *src0, TIntermTyped *src1)
1954 emitBinary(op, result, src0, src1);
1955 assignLvalue(lhs, result);
1958 void OutputASM::emitCmp(sw::Shader::Control cmpOp, TIntermTyped *dst, TIntermNode *left, TIntermNode *right, int index)
1960 sw::Shader::Opcode opcode;
1961 switch(left->getAsTyped()->getBasicType())
1965 opcode = sw::Shader::OPCODE_ICMP;
1968 opcode = sw::Shader::OPCODE_UCMP;
1971 opcode = sw::Shader::OPCODE_CMP;
1975 Instruction *cmp = emit(opcode, dst, 0, left, index, right, index);
1976 cmp->control = cmpOp;
1979 int componentCount(const TType &type, int registers)
1986 if(type.isArray() && registers >= type.elementRegisterCount())
1988 int index = registers / type.elementRegisterCount();
1989 registers -= index * type.elementRegisterCount();
1990 return index * type.getElementSize() + componentCount(type, registers);
1993 if(type.isStruct() || type.isInterfaceBlock())
1995 const TFieldList& fields = type.getStruct() ? type.getStruct()->fields() : type.getInterfaceBlock()->fields();
1998 for(TFieldList::const_iterator field = fields.begin(); field != fields.end(); field++)
2000 const TType &fieldType = *((*field)->type());
2002 if(fieldType.totalRegisterCount() <= registers)
2004 registers -= fieldType.totalRegisterCount();
2005 elements += fieldType.getObjectSize();
2007 else // Register within this field
2009 return elements + componentCount(fieldType, registers);
2013 else if(type.isMatrix())
2015 return registers * type.registerSize();
2022 int registerSize(const TType &type, int registers)
2028 return registerSize(*((*(type.getStruct()->fields().begin()))->type()), 0);
2030 else if(type.isInterfaceBlock())
2032 return registerSize(*((*(type.getInterfaceBlock()->fields().begin()))->type()), 0);
2035 return type.registerSize();
2038 if(type.isArray() && registers >= type.elementRegisterCount())
2040 int index = registers / type.elementRegisterCount();
2041 registers -= index * type.elementRegisterCount();
2042 return registerSize(type, registers);
2045 if(type.isStruct() || type.isInterfaceBlock())
2047 const TFieldList& fields = type.getStruct() ? type.getStruct()->fields() : type.getInterfaceBlock()->fields();
2050 for(TFieldList::const_iterator field = fields.begin(); field != fields.end(); field++)
2052 const TType &fieldType = *((*field)->type());
2054 if(fieldType.totalRegisterCount() <= registers)
2056 registers -= fieldType.totalRegisterCount();
2057 elements += fieldType.getObjectSize();
2059 else // Register within this field
2061 return registerSize(fieldType, registers);
2065 else if(type.isMatrix())
2067 return registerSize(type, 0);
2074 int OutputASM::getBlockId(TIntermTyped *arg)
2078 const TType &type = arg->getType();
2079 TInterfaceBlock* block = type.getInterfaceBlock();
2080 if(block && (type.getQualifier() == EvqUniform))
2082 // Make sure the uniform block is declared
2083 uniformRegister(arg);
2085 const char* blockName = block->name().c_str();
2087 // Fetch uniform block index from array of blocks
2088 for(ActiveUniformBlocks::const_iterator it = shaderObject->activeUniformBlocks.begin(); it != shaderObject->activeUniformBlocks.end(); ++it)
2090 if(blockName == it->name)
2103 OutputASM::ArgumentInfo OutputASM::getArgumentInfo(TIntermTyped *arg, int index)
2105 const TType &type = arg->getType();
2106 int blockId = getBlockId(arg);
2107 ArgumentInfo argumentInfo(BlockMemberInfo::getDefaultBlockInfo(), type, -1, -1);
2110 argumentInfo.bufferIndex = 0;
2111 for(int i = 0; i < blockId; ++i)
2113 int blockArraySize = shaderObject->activeUniformBlocks[i].arraySize;
2114 argumentInfo.bufferIndex += blockArraySize > 0 ? blockArraySize : 1;
2117 const BlockDefinitionIndexMap& blockDefinition = blockDefinitions[blockId];
2119 BlockDefinitionIndexMap::const_iterator itEnd = blockDefinition.end();
2120 BlockDefinitionIndexMap::const_iterator it = itEnd;
2122 argumentInfo.clampedIndex = index;
2123 if(type.isInterfaceBlock())
2125 // Offset index to the beginning of the selected instance
2126 int blockRegisters = type.elementRegisterCount();
2127 int bufferOffset = argumentInfo.clampedIndex / blockRegisters;
2128 argumentInfo.bufferIndex += bufferOffset;
2129 argumentInfo.clampedIndex -= bufferOffset * blockRegisters;
2132 int regIndex = registerIndex(arg);
2133 for(int i = regIndex + argumentInfo.clampedIndex; i >= regIndex; --i)
2135 it = blockDefinition.find(i);
2138 argumentInfo.clampedIndex -= (i - regIndex);
2142 ASSERT(it != itEnd);
2144 argumentInfo.typedMemberInfo = it->second;
2146 int registerCount = argumentInfo.typedMemberInfo.type.totalRegisterCount();
2147 argumentInfo.clampedIndex = (argumentInfo.clampedIndex >= registerCount) ? registerCount - 1 : argumentInfo.clampedIndex;
2151 argumentInfo.clampedIndex = (index >= arg->totalRegisterCount()) ? arg->totalRegisterCount() - 1 : index;
2154 return argumentInfo;
2157 void OutputASM::argument(sw::Shader::SourceParameter ¶meter, TIntermNode *argument, int index)
2161 TIntermTyped *arg = argument->getAsTyped();
2162 Temporary unpackedUniform(this);
2164 const TType& srcType = arg->getType();
2165 TInterfaceBlock* srcBlock = srcType.getInterfaceBlock();
2166 if(srcBlock && (srcType.getQualifier() == EvqUniform))
2168 const ArgumentInfo argumentInfo = getArgumentInfo(arg, index);
2169 const TType &memberType = argumentInfo.typedMemberInfo.type;
2171 if(memberType.getBasicType() == EbtBool)
2173 int arraySize = (memberType.isArray() ? memberType.getArraySize() : 1);
2174 ASSERT(argumentInfo.clampedIndex < arraySize);
2176 // Convert the packed bool, which is currently an int, to a true bool
2177 Instruction *instruction = new Instruction(sw::Shader::OPCODE_I2B);
2178 instruction->dst.type = sw::Shader::PARAMETER_TEMP;
2179 instruction->dst.index = registerIndex(&unpackedUniform);
2180 instruction->src[0].type = sw::Shader::PARAMETER_CONST;
2181 instruction->src[0].bufferIndex = argumentInfo.bufferIndex;
2182 instruction->src[0].index = argumentInfo.typedMemberInfo.offset + argumentInfo.clampedIndex * argumentInfo.typedMemberInfo.arrayStride;
2184 shader->append(instruction);
2186 arg = &unpackedUniform;
2189 else if((srcBlock->matrixPacking() == EmpRowMajor) && memberType.isMatrix())
2191 int numCols = memberType.getNominalSize();
2192 int numRows = memberType.getSecondarySize();
2193 int arraySize = (memberType.isArray() ? memberType.getArraySize() : 1);
2195 ASSERT(argumentInfo.clampedIndex < (numCols * arraySize));
2197 unsigned int dstIndex = registerIndex(&unpackedUniform);
2198 unsigned int srcSwizzle = (argumentInfo.clampedIndex % numCols) * 0x55;
2199 int arrayIndex = argumentInfo.clampedIndex / numCols;
2200 int matrixStartOffset = argumentInfo.typedMemberInfo.offset + arrayIndex * argumentInfo.typedMemberInfo.arrayStride;
2202 for(int j = 0; j < numRows; ++j)
2204 // Transpose the row major matrix
2205 Instruction *instruction = new Instruction(sw::Shader::OPCODE_MOV);
2206 instruction->dst.type = sw::Shader::PARAMETER_TEMP;
2207 instruction->dst.index = dstIndex;
2208 instruction->dst.mask = 1 << j;
2209 instruction->src[0].type = sw::Shader::PARAMETER_CONST;
2210 instruction->src[0].bufferIndex = argumentInfo.bufferIndex;
2211 instruction->src[0].index = matrixStartOffset + j * argumentInfo.typedMemberInfo.matrixStride;
2212 instruction->src[0].swizzle = srcSwizzle;
2214 shader->append(instruction);
2217 arg = &unpackedUniform;
2222 const ArgumentInfo argumentInfo = getArgumentInfo(arg, index);
2223 const TType &type = argumentInfo.typedMemberInfo.type;
2225 int size = registerSize(type, argumentInfo.clampedIndex);
2227 parameter.type = registerType(arg);
2228 parameter.bufferIndex = argumentInfo.bufferIndex;
2230 if(arg->getAsConstantUnion() && arg->getAsConstantUnion()->getUnionArrayPointer())
2232 int component = componentCount(type, argumentInfo.clampedIndex);
2233 ConstantUnion *constants = arg->getAsConstantUnion()->getUnionArrayPointer();
2235 for(int i = 0; i < 4; i++)
2237 if(size == 1) // Replicate
2239 parameter.value[i] = constants[component + 0].getAsFloat();
2243 parameter.value[i] = constants[component + i].getAsFloat();
2247 parameter.value[i] = 0.0f;
2253 parameter.index = registerIndex(arg) + argumentInfo.clampedIndex;
2255 if(parameter.bufferIndex != -1)
2257 int stride = (argumentInfo.typedMemberInfo.matrixStride > 0) ? argumentInfo.typedMemberInfo.matrixStride : argumentInfo.typedMemberInfo.arrayStride;
2258 parameter.index = argumentInfo.typedMemberInfo.offset + argumentInfo.clampedIndex * stride;
2262 if(!IsSampler(arg->getBasicType()))
2264 parameter.swizzle = readSwizzle(arg, size);
2269 void OutputASM::copy(TIntermTyped *dst, TIntermNode *src, int offset)
2271 for(int index = 0; index < dst->totalRegisterCount(); index++)
2273 Instruction *mov = emit(sw::Shader::OPCODE_MOV, dst, index, src, offset + index);
2274 mov->dst.mask = writeMask(dst, index);
2278 int swizzleElement(int swizzle, int index)
2280 return (swizzle >> (index * 2)) & 0x03;
2283 int swizzleSwizzle(int leftSwizzle, int rightSwizzle)
2285 return (swizzleElement(leftSwizzle, swizzleElement(rightSwizzle, 0)) << 0) |
2286 (swizzleElement(leftSwizzle, swizzleElement(rightSwizzle, 1)) << 2) |
2287 (swizzleElement(leftSwizzle, swizzleElement(rightSwizzle, 2)) << 4) |
2288 (swizzleElement(leftSwizzle, swizzleElement(rightSwizzle, 3)) << 6);
2291 void OutputASM::assignLvalue(TIntermTyped *dst, TIntermTyped *src)
2294 ((src->isVector() && (!dst->isVector() || (src->getNominalSize() != dst->getNominalSize()))) ||
2295 (src->isMatrix() && (!dst->isMatrix() || (src->getNominalSize() != dst->getNominalSize()) || (src->getSecondarySize() != dst->getSecondarySize())))))
2297 return mContext.error(src->getLine(), "Result type should match the l-value type in compound assignment", src->isVector() ? "vector" : "matrix");
2300 TIntermBinary *binary = dst->getAsBinaryNode();
2302 if(binary && binary->getOp() == EOpIndexIndirect && binary->getLeft()->isVector() && dst->isScalar())
2304 Instruction *insert = new Instruction(sw::Shader::OPCODE_INSERT);
2306 Temporary address(this);
2307 lvalue(insert->dst, address, dst);
2309 insert->src[0].type = insert->dst.type;
2310 insert->src[0].index = insert->dst.index;
2311 insert->src[0].rel = insert->dst.rel;
2312 argument(insert->src[1], src);
2313 argument(insert->src[2], binary->getRight());
2315 shader->append(insert);
2319 for(int offset = 0; offset < dst->totalRegisterCount(); offset++)
2321 Instruction *mov = new Instruction(sw::Shader::OPCODE_MOV);
2323 Temporary address(this);
2324 int swizzle = lvalue(mov->dst, address, dst);
2325 mov->dst.index += offset;
2329 mov->dst.mask = writeMask(dst, offset);
2332 argument(mov->src[0], src, offset);
2333 mov->src[0].swizzle = swizzleSwizzle(mov->src[0].swizzle, swizzle);
2335 shader->append(mov);
2340 int OutputASM::lvalue(sw::Shader::DestinationParameter &dst, Temporary &address, TIntermTyped *node)
2342 TIntermTyped *result = node;
2343 TIntermBinary *binary = node->getAsBinaryNode();
2344 TIntermSymbol *symbol = node->getAsSymbolNode();
2348 TIntermTyped *left = binary->getLeft();
2349 TIntermTyped *right = binary->getRight();
2351 int leftSwizzle = lvalue(dst, address, left); // Resolve the l-value of the left side
2353 switch(binary->getOp())
2355 case EOpIndexDirect:
2357 int rightIndex = right->getAsConstantUnion()->getIConst(0);
2359 if(left->isRegister())
2361 int leftMask = dst.mask;
2364 while((leftMask & dst.mask) == 0)
2366 dst.mask = dst.mask << 1;
2369 int element = swizzleElement(leftSwizzle, rightIndex);
2370 dst.mask = 1 << element;
2374 else if(left->isArray() || left->isMatrix())
2376 dst.index += rightIndex * result->totalRegisterCount();
2379 else UNREACHABLE(0);
2382 case EOpIndexIndirect:
2384 if(left->isRegister())
2386 // Requires INSERT instruction (handled by calling function)
2388 else if(left->isArray() || left->isMatrix())
2390 int scale = result->totalRegisterCount();
2392 if(dst.rel.type == sw::Shader::PARAMETER_VOID) // Use the index register as the relative address directly
2394 if(left->totalRegisterCount() > 1)
2396 sw::Shader::SourceParameter relativeRegister;
2397 argument(relativeRegister, right);
2399 dst.rel.index = relativeRegister.index;
2400 dst.rel.type = relativeRegister.type;
2401 dst.rel.scale = scale;
2402 dst.rel.deterministic = !(vertexShader && left->getQualifier() == EvqUniform);
2405 else if(dst.rel.index != registerIndex(&address)) // Move the previous index register to the address register
2409 Constant oldScale((int)dst.rel.scale);
2410 Instruction *mad = emit(sw::Shader::OPCODE_IMAD, &address, &address, &oldScale, right);
2411 mad->src[0].index = dst.rel.index;
2412 mad->src[0].type = dst.rel.type;
2416 Constant oldScale((int)dst.rel.scale);
2417 Instruction *mul = emit(sw::Shader::OPCODE_IMUL, &address, &address, &oldScale);
2418 mul->src[0].index = dst.rel.index;
2419 mul->src[0].type = dst.rel.type;
2421 Constant newScale(scale);
2422 emit(sw::Shader::OPCODE_IMAD, &address, right, &newScale, &address);
2425 dst.rel.type = sw::Shader::PARAMETER_TEMP;
2426 dst.rel.index = registerIndex(&address);
2429 else // Just add the new index to the address register
2433 emit(sw::Shader::OPCODE_IADD, &address, &address, right);
2437 Constant newScale(scale);
2438 emit(sw::Shader::OPCODE_IMAD, &address, right, &newScale, &address);
2442 else UNREACHABLE(0);
2445 case EOpIndexDirectStruct:
2446 case EOpIndexDirectInterfaceBlock:
2448 const TFieldList& fields = (binary->getOp() == EOpIndexDirectStruct) ?
2449 left->getType().getStruct()->fields() :
2450 left->getType().getInterfaceBlock()->fields();
2451 int index = right->getAsConstantUnion()->getIConst(0);
2452 int fieldOffset = 0;
2454 for(int i = 0; i < index; i++)
2456 fieldOffset += fields[i]->type()->totalRegisterCount();
2459 dst.type = registerType(left);
2460 dst.index += fieldOffset;
2461 dst.mask = writeMask(right);
2466 case EOpVectorSwizzle:
2468 ASSERT(left->isRegister());
2470 int leftMask = dst.mask;
2475 TIntermSequence &sequence = right->getAsAggregate()->getSequence();
2477 for(unsigned int i = 0; i < sequence.size(); i++)
2479 int index = sequence[i]->getAsConstantUnion()->getIConst(0);
2481 int element = swizzleElement(leftSwizzle, index);
2482 rightMask = rightMask | (1 << element);
2483 swizzle = swizzle | swizzleElement(leftSwizzle, i) << (element * 2);
2486 dst.mask = leftMask & rightMask;
2492 UNREACHABLE(binary->getOp()); // Not an l-value operator
2498 dst.type = registerType(symbol);
2499 dst.index = registerIndex(symbol);
2500 dst.mask = writeMask(symbol);
2507 sw::Shader::ParameterType OutputASM::registerType(TIntermTyped *operand)
2509 if(isSamplerRegister(operand))
2511 return sw::Shader::PARAMETER_SAMPLER;
2514 const TQualifier qualifier = operand->getQualifier();
2515 if((EvqFragColor == qualifier) || (EvqFragData == qualifier))
2517 if(((EvqFragData == qualifier) && (EvqFragColor == outputQualifier)) ||
2518 ((EvqFragColor == qualifier) && (EvqFragData == outputQualifier)))
2520 mContext.error(operand->getLine(), "static assignment to both gl_FragData and gl_FragColor", "");
2522 outputQualifier = qualifier;
2525 if(qualifier == EvqConstExpr && (!operand->getAsConstantUnion() || !operand->getAsConstantUnion()->getUnionArrayPointer()))
2527 return sw::Shader::PARAMETER_TEMP;
2532 case EvqTemporary: return sw::Shader::PARAMETER_TEMP;
2533 case EvqGlobal: return sw::Shader::PARAMETER_TEMP;
2534 case EvqConstExpr: return sw::Shader::PARAMETER_FLOAT4LITERAL; // All converted to float
2535 case EvqAttribute: return sw::Shader::PARAMETER_INPUT;
2536 case EvqVaryingIn: return sw::Shader::PARAMETER_INPUT;
2537 case EvqVaryingOut: return sw::Shader::PARAMETER_OUTPUT;
2538 case EvqVertexIn: return sw::Shader::PARAMETER_INPUT;
2539 case EvqFragmentOut: return sw::Shader::PARAMETER_COLOROUT;
2540 case EvqVertexOut: return sw::Shader::PARAMETER_OUTPUT;
2541 case EvqFragmentIn: return sw::Shader::PARAMETER_INPUT;
2542 case EvqInvariantVaryingIn: return sw::Shader::PARAMETER_INPUT; // FIXME: Guarantee invariance at the backend
2543 case EvqInvariantVaryingOut: return sw::Shader::PARAMETER_OUTPUT; // FIXME: Guarantee invariance at the backend
2544 case EvqSmooth: return sw::Shader::PARAMETER_OUTPUT;
2545 case EvqFlat: return sw::Shader::PARAMETER_OUTPUT;
2546 case EvqCentroidOut: return sw::Shader::PARAMETER_OUTPUT;
2547 case EvqSmoothIn: return sw::Shader::PARAMETER_INPUT;
2548 case EvqFlatIn: return sw::Shader::PARAMETER_INPUT;
2549 case EvqCentroidIn: return sw::Shader::PARAMETER_INPUT;
2550 case EvqUniform: return sw::Shader::PARAMETER_CONST;
2551 case EvqIn: return sw::Shader::PARAMETER_TEMP;
2552 case EvqOut: return sw::Shader::PARAMETER_TEMP;
2553 case EvqInOut: return sw::Shader::PARAMETER_TEMP;
2554 case EvqConstReadOnly: return sw::Shader::PARAMETER_TEMP;
2555 case EvqPosition: return sw::Shader::PARAMETER_OUTPUT;
2556 case EvqPointSize: return sw::Shader::PARAMETER_OUTPUT;
2557 case EvqInstanceID: return sw::Shader::PARAMETER_MISCTYPE;
2558 case EvqFragCoord: return sw::Shader::PARAMETER_MISCTYPE;
2559 case EvqFrontFacing: return sw::Shader::PARAMETER_MISCTYPE;
2560 case EvqPointCoord: return sw::Shader::PARAMETER_INPUT;
2561 case EvqFragColor: return sw::Shader::PARAMETER_COLOROUT;
2562 case EvqFragData: return sw::Shader::PARAMETER_COLOROUT;
2563 case EvqFragDepth: return sw::Shader::PARAMETER_DEPTHOUT;
2564 default: UNREACHABLE(qualifier);
2567 return sw::Shader::PARAMETER_VOID;
2570 bool OutputASM::hasFlatQualifier(TIntermTyped *operand)
2572 const TQualifier qualifier = operand->getQualifier();
2573 return qualifier == EvqFlat || qualifier == EvqFlatOut || qualifier == EvqFlatIn;
2576 unsigned int OutputASM::registerIndex(TIntermTyped *operand)
2578 if(isSamplerRegister(operand))
2580 return samplerRegister(operand);
2583 switch(operand->getQualifier())
2585 case EvqTemporary: return temporaryRegister(operand);
2586 case EvqGlobal: return temporaryRegister(operand);
2587 case EvqConstExpr: return temporaryRegister(operand); // Unevaluated constant expression
2588 case EvqAttribute: return attributeRegister(operand);
2589 case EvqVaryingIn: return varyingRegister(operand);
2590 case EvqVaryingOut: return varyingRegister(operand);
2591 case EvqVertexIn: return attributeRegister(operand);
2592 case EvqFragmentOut: return fragmentOutputRegister(operand);
2593 case EvqVertexOut: return varyingRegister(operand);
2594 case EvqFragmentIn: return varyingRegister(operand);
2595 case EvqInvariantVaryingIn: return varyingRegister(operand);
2596 case EvqInvariantVaryingOut: return varyingRegister(operand);
2597 case EvqSmooth: return varyingRegister(operand);
2598 case EvqFlat: return varyingRegister(operand);
2599 case EvqCentroidOut: return varyingRegister(operand);
2600 case EvqSmoothIn: return varyingRegister(operand);
2601 case EvqFlatIn: return varyingRegister(operand);
2602 case EvqCentroidIn: return varyingRegister(operand);
2603 case EvqUniform: return uniformRegister(operand);
2604 case EvqIn: return temporaryRegister(operand);
2605 case EvqOut: return temporaryRegister(operand);
2606 case EvqInOut: return temporaryRegister(operand);
2607 case EvqConstReadOnly: return temporaryRegister(operand);
2608 case EvqPosition: return varyingRegister(operand);
2609 case EvqPointSize: return varyingRegister(operand);
2610 case EvqInstanceID: vertexShader->instanceIdDeclared = true; return 0;
2611 case EvqFragCoord: pixelShader->vPosDeclared = true; return 0;
2612 case EvqFrontFacing: pixelShader->vFaceDeclared = true; return 1;
2613 case EvqPointCoord: return varyingRegister(operand);
2614 case EvqFragColor: return 0;
2615 case EvqFragData: return fragmentOutputRegister(operand);
2616 case EvqFragDepth: return 0;
2617 default: UNREACHABLE(operand->getQualifier());
2623 int OutputASM::writeMask(TIntermTyped *destination, int index)
2625 if(destination->getQualifier() == EvqPointSize)
2627 return 0x2; // Point size stored in the y component
2630 return 0xF >> (4 - registerSize(destination->getType(), index));
2633 int OutputASM::readSwizzle(TIntermTyped *argument, int size)
2635 if(argument->getQualifier() == EvqPointSize)
2637 return 0x55; // Point size stored in the y component
2640 static const unsigned char swizzleSize[5] = {0x00, 0x00, 0x54, 0xA4, 0xE4}; // (void), xxxx, xyyy, xyzz, xyzw
2642 return swizzleSize[size];
2645 // Conservatively checks whether an expression is fast to compute and has no side effects
2646 bool OutputASM::trivial(TIntermTyped *expression, int budget)
2648 if(!expression->isRegister())
2653 return cost(expression, budget) >= 0;
2656 // Returns the remaining computing budget (if < 0 the expression is too expensive or has side effects)
2657 int OutputASM::cost(TIntermNode *expression, int budget)
2664 if(expression->getAsSymbolNode())
2668 else if(expression->getAsConstantUnion())
2672 else if(expression->getAsBinaryNode())
2674 TIntermBinary *binary = expression->getAsBinaryNode();
2676 switch(binary->getOp())
2678 case EOpVectorSwizzle:
2679 case EOpIndexDirect:
2680 case EOpIndexDirectStruct:
2681 case EOpIndexDirectInterfaceBlock:
2682 return cost(binary->getLeft(), budget - 0);
2686 return cost(binary->getLeft(), cost(binary->getRight(), budget - 1));
2691 else if(expression->getAsUnaryNode())
2693 TIntermUnary *unary = expression->getAsUnaryNode();
2695 switch(unary->getOp())
2699 return cost(unary->getOperand(), budget - 1);
2704 else if(expression->getAsSelectionNode())
2706 TIntermSelection *selection = expression->getAsSelectionNode();
2708 if(selection->usesTernaryOperator())
2710 TIntermTyped *condition = selection->getCondition();
2711 TIntermNode *trueBlock = selection->getTrueBlock();
2712 TIntermNode *falseBlock = selection->getFalseBlock();
2713 TIntermConstantUnion *constantCondition = condition->getAsConstantUnion();
2715 if(constantCondition)
2717 bool trueCondition = constantCondition->getUnionArrayPointer()->getBConst();
2721 return cost(trueBlock, budget - 0);
2725 return cost(falseBlock, budget - 0);
2730 return cost(trueBlock, cost(falseBlock, budget - 2));
2738 const Function *OutputASM::findFunction(const TString &name)
2740 for(unsigned int f = 0; f < functionArray.size(); f++)
2742 if(functionArray[f].name == name)
2744 return &functionArray[f];
2751 int OutputASM::temporaryRegister(TIntermTyped *temporary)
2753 return allocate(temporaries, temporary);
2756 int OutputASM::varyingRegister(TIntermTyped *varying)
2758 int var = lookup(varyings, varying);
2762 var = allocate(varyings, varying);
2763 int componentCount = varying->registerSize();
2764 int registerCount = varying->totalRegisterCount();
2768 if((var + registerCount) > sw::MAX_FRAGMENT_INPUTS)
2770 mContext.error(varying->getLine(), "Varyings packing failed: Too many varyings", "fragment shader");
2774 if(varying->getQualifier() == EvqPointCoord)
2776 ASSERT(varying->isRegister());
2777 if(componentCount >= 1) pixelShader->semantic[var][0] = sw::Shader::Semantic(sw::Shader::USAGE_TEXCOORD, var);
2778 if(componentCount >= 2) pixelShader->semantic[var][1] = sw::Shader::Semantic(sw::Shader::USAGE_TEXCOORD, var);
2779 if(componentCount >= 3) pixelShader->semantic[var][2] = sw::Shader::Semantic(sw::Shader::USAGE_TEXCOORD, var);
2780 if(componentCount >= 4) pixelShader->semantic[var][3] = sw::Shader::Semantic(sw::Shader::USAGE_TEXCOORD, var);
2784 for(int i = 0; i < varying->totalRegisterCount(); i++)
2786 bool flat = hasFlatQualifier(varying);
2788 if(componentCount >= 1) pixelShader->semantic[var + i][0] = sw::Shader::Semantic(sw::Shader::USAGE_COLOR, var + i, flat);
2789 if(componentCount >= 2) pixelShader->semantic[var + i][1] = sw::Shader::Semantic(sw::Shader::USAGE_COLOR, var + i, flat);
2790 if(componentCount >= 3) pixelShader->semantic[var + i][2] = sw::Shader::Semantic(sw::Shader::USAGE_COLOR, var + i, flat);
2791 if(componentCount >= 4) pixelShader->semantic[var + i][3] = sw::Shader::Semantic(sw::Shader::USAGE_COLOR, var + i, flat);
2795 else if(vertexShader)
2797 if((var + registerCount) > sw::MAX_VERTEX_OUTPUTS)
2799 mContext.error(varying->getLine(), "Varyings packing failed: Too many varyings", "vertex shader");
2803 if(varying->getQualifier() == EvqPosition)
2805 ASSERT(varying->isRegister());
2806 vertexShader->output[var][0] = sw::Shader::Semantic(sw::Shader::USAGE_POSITION, 0);
2807 vertexShader->output[var][1] = sw::Shader::Semantic(sw::Shader::USAGE_POSITION, 0);
2808 vertexShader->output[var][2] = sw::Shader::Semantic(sw::Shader::USAGE_POSITION, 0);
2809 vertexShader->output[var][3] = sw::Shader::Semantic(sw::Shader::USAGE_POSITION, 0);
2810 vertexShader->positionRegister = var;
2812 else if(varying->getQualifier() == EvqPointSize)
2814 ASSERT(varying->isRegister());
2815 vertexShader->output[var][0] = sw::Shader::Semantic(sw::Shader::USAGE_PSIZE, 0);
2816 vertexShader->output[var][1] = sw::Shader::Semantic(sw::Shader::USAGE_PSIZE, 0);
2817 vertexShader->output[var][2] = sw::Shader::Semantic(sw::Shader::USAGE_PSIZE, 0);
2818 vertexShader->output[var][3] = sw::Shader::Semantic(sw::Shader::USAGE_PSIZE, 0);
2819 vertexShader->pointSizeRegister = var;
2823 // Semantic indexes for user varyings will be assigned during program link to match the pixel shader
2826 else UNREACHABLE(0);
2828 declareVarying(varying, var);
2834 void OutputASM::declareVarying(TIntermTyped *varying, int reg)
2836 if(varying->getQualifier() != EvqPointCoord) // gl_PointCoord does not need linking
2838 const TType &type = varying->getType();
2839 const char *name = varying->getAsSymbolNode()->getSymbol().c_str();
2840 VaryingList &activeVaryings = shaderObject->varyings;
2842 // Check if this varying has been declared before without having a register assigned
2843 for(VaryingList::iterator v = activeVaryings.begin(); v != activeVaryings.end(); v++)
2849 ASSERT(v->reg < 0 || v->reg == reg);
2857 activeVaryings.push_back(glsl::Varying(glVariableType(type), name, varying->getArraySize(), reg, 0));
2861 int OutputASM::uniformRegister(TIntermTyped *uniform)
2863 const TType &type = uniform->getType();
2864 ASSERT(!IsSampler(type.getBasicType()));
2865 TInterfaceBlock *block = type.getAsInterfaceBlock();
2866 TIntermSymbol *symbol = uniform->getAsSymbolNode();
2867 ASSERT(symbol || block);
2871 TInterfaceBlock* parentBlock = type.getInterfaceBlock();
2872 bool isBlockMember = (!block && parentBlock);
2873 int index = isBlockMember ? lookup(uniforms, parentBlock) : lookup(uniforms, uniform);
2875 if(index == -1 || isBlockMember)
2879 index = allocate(uniforms, uniform);
2882 // Verify if the current uniform is a member of an already declared block
2883 const TString &name = symbol ? symbol->getSymbol() : block->name();
2884 int blockMemberIndex = blockMemberLookup(type, name, index);
2885 if(blockMemberIndex == -1)
2887 declareUniform(type, name, index);
2891 index = blockMemberIndex;
2901 int OutputASM::attributeRegister(TIntermTyped *attribute)
2903 ASSERT(!attribute->isArray());
2905 int index = lookup(attributes, attribute);
2909 TIntermSymbol *symbol = attribute->getAsSymbolNode();
2914 index = allocate(attributes, attribute);
2915 const TType &type = attribute->getType();
2916 int registerCount = attribute->totalRegisterCount();
2918 if(vertexShader && (index + registerCount) <= sw::MAX_VERTEX_INPUTS)
2920 for(int i = 0; i < registerCount; i++)
2922 vertexShader->input[index + i] = sw::Shader::Semantic(sw::Shader::USAGE_TEXCOORD, index + i);
2926 ActiveAttributes &activeAttributes = shaderObject->activeAttributes;
2928 const char *name = symbol->getSymbol().c_str();
2929 activeAttributes.push_back(Attribute(glVariableType(type), name, type.getArraySize(), type.getLayoutQualifier().location, index));
2936 int OutputASM::fragmentOutputRegister(TIntermTyped *fragmentOutput)
2938 return allocate(fragmentOutputs, fragmentOutput);
2941 int OutputASM::samplerRegister(TIntermTyped *sampler)
2943 const TType &type = sampler->getType();
2944 ASSERT(IsSampler(type.getBasicType()) || type.isStruct()); // Structures can contain samplers
2946 TIntermSymbol *symbol = sampler->getAsSymbolNode();
2947 TIntermBinary *binary = sampler->getAsBinaryNode();
2949 if(symbol && type.getQualifier() == EvqUniform)
2951 return samplerRegister(symbol);
2955 TIntermTyped *left = binary->getLeft();
2956 TIntermTyped *right = binary->getRight();
2957 const TType &leftType = left->getType();
2958 int index = right->getAsConstantUnion() ? right->getAsConstantUnion()->getIConst(0) : 0;
2961 switch(binary->getOp())
2963 case EOpIndexDirect:
2964 ASSERT(left->isArray());
2965 offset = index * leftType.elementRegisterCount();
2967 case EOpIndexDirectStruct:
2968 ASSERT(leftType.isStruct());
2970 const TFieldList &fields = leftType.getStruct()->fields();
2972 for(int i = 0; i < index; i++)
2974 offset += fields[i]->type()->totalRegisterCount();
2978 case EOpIndexIndirect: // Indirect indexing produces a temporary, not a sampler register
2980 case EOpIndexDirectInterfaceBlock: // Interface blocks can't contain samplers
2982 UNREACHABLE(binary->getOp());
2986 int base = samplerRegister(left);
2993 return base + offset;
2997 return -1; // Not a sampler register
3000 int OutputASM::samplerRegister(TIntermSymbol *sampler)
3002 const TType &type = sampler->getType();
3003 ASSERT(IsSampler(type.getBasicType()) || type.isStruct()); // Structures can contain samplers
3005 int index = lookup(samplers, sampler);
3009 index = allocate(samplers, sampler);
3011 if(sampler->getQualifier() == EvqUniform)
3013 const char *name = sampler->getSymbol().c_str();
3014 declareUniform(type, name, index);
3021 bool OutputASM::isSamplerRegister(TIntermTyped *operand)
3023 return operand && IsSampler(operand->getBasicType()) && samplerRegister(operand) >= 0;
3026 int OutputASM::lookup(VariableArray &list, TIntermTyped *variable)
3028 for(unsigned int i = 0; i < list.size(); i++)
3030 if(list[i] == variable)
3032 return i; // Pointer match
3036 TIntermSymbol *varSymbol = variable->getAsSymbolNode();
3037 TInterfaceBlock *varBlock = variable->getType().getAsInterfaceBlock();
3041 for(unsigned int i = 0; i < list.size(); i++)
3045 TInterfaceBlock *listBlock = list[i]->getType().getAsInterfaceBlock();
3049 if(listBlock->name() == varBlock->name())
3051 ASSERT(listBlock->arraySize() == varBlock->arraySize());
3052 ASSERT(listBlock->fields() == varBlock->fields());
3053 ASSERT(listBlock->blockStorage() == varBlock->blockStorage());
3054 ASSERT(listBlock->matrixPacking() == varBlock->matrixPacking());
3064 for(unsigned int i = 0; i < list.size(); i++)
3068 TIntermSymbol *listSymbol = list[i]->getAsSymbolNode();
3072 if(listSymbol->getId() == varSymbol->getId())
3074 ASSERT(listSymbol->getSymbol() == varSymbol->getSymbol());
3075 ASSERT(listSymbol->getType() == varSymbol->getType());
3076 ASSERT(listSymbol->getQualifier() == varSymbol->getQualifier());
3088 int OutputASM::lookup(VariableArray &list, TInterfaceBlock *block)
3090 for(unsigned int i = 0; i < list.size(); i++)
3092 if(list[i] && (list[i]->getType().getInterfaceBlock() == block))
3094 return i; // Pointer match
3100 int OutputASM::allocate(VariableArray &list, TIntermTyped *variable)
3102 int index = lookup(list, variable);
3106 unsigned int registerCount = variable->blockRegisterCount();
3108 for(unsigned int i = 0; i < list.size(); i++)
3113 for( ; j < registerCount && (i + j) < list.size(); j++)
3115 if(list[i + j] != 0)
3121 if(j == registerCount) // Found free slots
3123 for(unsigned int j = 0; j < registerCount; j++)
3125 list[i + j] = variable;
3133 index = list.size();
3135 for(unsigned int i = 0; i < registerCount; i++)
3137 list.push_back(variable);
3144 void OutputASM::free(VariableArray &list, TIntermTyped *variable)
3146 int index = lookup(list, variable);
3154 int OutputASM::blockMemberLookup(const TType &type, const TString &name, int registerIndex)
3156 const TInterfaceBlock *block = type.getInterfaceBlock();
3160 ActiveUniformBlocks &activeUniformBlocks = shaderObject->activeUniformBlocks;
3161 const TFieldList& fields = block->fields();
3162 const TString &blockName = block->name();
3163 int fieldRegisterIndex = registerIndex;
3165 if(!type.isInterfaceBlock())
3167 // This is a uniform that's part of a block, let's see if the block is already defined
3168 for(size_t i = 0; i < activeUniformBlocks.size(); ++i)
3170 if(activeUniformBlocks[i].name == blockName.c_str())
3172 // The block is already defined, find the register for the current uniform and return it
3173 for(size_t j = 0; j < fields.size(); j++)
3175 const TString &fieldName = fields[j]->name();
3176 if(fieldName == name)
3178 return fieldRegisterIndex;
3181 fieldRegisterIndex += fields[j]->type()->totalRegisterCount();
3185 return fieldRegisterIndex;
3194 void OutputASM::declareUniform(const TType &type, const TString &name, int registerIndex, int blockId, BlockLayoutEncoder* encoder)
3196 const TStructure *structure = type.getStruct();
3197 const TInterfaceBlock *block = (type.isInterfaceBlock() || (blockId == -1)) ? type.getInterfaceBlock() : nullptr;
3199 if(!structure && !block)
3201 ActiveUniforms &activeUniforms = shaderObject->activeUniforms;
3202 const BlockMemberInfo blockInfo = encoder ? encoder->encodeType(type) : BlockMemberInfo::getDefaultBlockInfo();
3205 blockDefinitions[blockId][registerIndex] = TypedMemberInfo(blockInfo, type);
3206 shaderObject->activeUniformBlocks[blockId].fields.push_back(activeUniforms.size());
3208 int fieldRegisterIndex = encoder ? shaderObject->activeUniformBlocks[blockId].registerIndex + BlockLayoutEncoder::getBlockRegister(blockInfo) : registerIndex;
3209 activeUniforms.push_back(Uniform(glVariableType(type), glVariablePrecision(type), name.c_str(), type.getArraySize(),
3210 fieldRegisterIndex, blockId, blockInfo));
3211 if(IsSampler(type.getBasicType()))
3213 for(int i = 0; i < type.totalRegisterCount(); i++)
3215 shader->declareSampler(fieldRegisterIndex + i);
3221 ActiveUniformBlocks &activeUniformBlocks = shaderObject->activeUniformBlocks;
3222 const TFieldList& fields = block->fields();
3223 const TString &blockName = block->name();
3224 int fieldRegisterIndex = registerIndex;
3225 bool isUniformBlockMember = !type.isInterfaceBlock() && (blockId == -1);
3227 blockId = activeUniformBlocks.size();
3228 bool isRowMajor = block->matrixPacking() == EmpRowMajor;
3229 activeUniformBlocks.push_back(UniformBlock(blockName.c_str(), 0, block->arraySize(),
3230 block->blockStorage(), isRowMajor, registerIndex, blockId));
3231 blockDefinitions.push_back(BlockDefinitionIndexMap());
3233 Std140BlockEncoder currentBlockEncoder(isRowMajor);
3234 currentBlockEncoder.enterAggregateType();
3235 for(size_t i = 0; i < fields.size(); i++)
3237 const TType &fieldType = *(fields[i]->type());
3238 const TString &fieldName = fields[i]->name();
3239 if(isUniformBlockMember && (fieldName == name))
3241 registerIndex = fieldRegisterIndex;
3244 const TString uniformName = block->hasInstanceName() ? blockName + "." + fieldName : fieldName;
3246 declareUniform(fieldType, uniformName, fieldRegisterIndex, blockId, ¤tBlockEncoder);
3247 fieldRegisterIndex += fieldType.totalRegisterCount();
3249 currentBlockEncoder.exitAggregateType();
3250 activeUniformBlocks[blockId].dataSize = currentBlockEncoder.getBlockSize();
3254 int fieldRegisterIndex = registerIndex;
3256 const TFieldList& fields = structure->fields();
3257 if(type.isArray() && (structure || type.isInterfaceBlock()))
3259 for(int i = 0; i < type.getArraySize(); i++)
3263 encoder->enterAggregateType();
3265 for(size_t j = 0; j < fields.size(); j++)
3267 const TType &fieldType = *(fields[j]->type());
3268 const TString &fieldName = fields[j]->name();
3269 const TString uniformName = name + "[" + str(i) + "]." + fieldName;
3271 declareUniform(fieldType, uniformName, fieldRegisterIndex, blockId, encoder);
3272 fieldRegisterIndex += fieldType.totalRegisterCount();
3276 encoder->exitAggregateType();
3284 encoder->enterAggregateType();
3286 for(size_t i = 0; i < fields.size(); i++)
3288 const TType &fieldType = *(fields[i]->type());
3289 const TString &fieldName = fields[i]->name();
3290 const TString uniformName = name + "." + fieldName;
3292 declareUniform(fieldType, uniformName, fieldRegisterIndex, blockId, encoder);
3293 fieldRegisterIndex += fieldType.totalRegisterCount();
3297 encoder->exitAggregateType();
3303 GLenum OutputASM::glVariableType(const TType &type)
3305 switch(type.getBasicType())
3312 else if(type.isVector())
3314 switch(type.getNominalSize())
3316 case 2: return GL_FLOAT_VEC2;
3317 case 3: return GL_FLOAT_VEC3;
3318 case 4: return GL_FLOAT_VEC4;
3319 default: UNREACHABLE(type.getNominalSize());
3322 else if(type.isMatrix())
3324 switch(type.getNominalSize())
3327 switch(type.getSecondarySize())
3329 case 2: return GL_FLOAT_MAT2;
3330 case 3: return GL_FLOAT_MAT2x3;
3331 case 4: return GL_FLOAT_MAT2x4;
3332 default: UNREACHABLE(type.getSecondarySize());
3335 switch(type.getSecondarySize())
3337 case 2: return GL_FLOAT_MAT3x2;
3338 case 3: return GL_FLOAT_MAT3;
3339 case 4: return GL_FLOAT_MAT3x4;
3340 default: UNREACHABLE(type.getSecondarySize());
3343 switch(type.getSecondarySize())
3345 case 2: return GL_FLOAT_MAT4x2;
3346 case 3: return GL_FLOAT_MAT4x3;
3347 case 4: return GL_FLOAT_MAT4;
3348 default: UNREACHABLE(type.getSecondarySize());
3350 default: UNREACHABLE(type.getNominalSize());
3353 else UNREACHABLE(0);
3360 else if(type.isVector())
3362 switch(type.getNominalSize())
3364 case 2: return GL_INT_VEC2;
3365 case 3: return GL_INT_VEC3;
3366 case 4: return GL_INT_VEC4;
3367 default: UNREACHABLE(type.getNominalSize());
3370 else UNREACHABLE(0);
3375 return GL_UNSIGNED_INT;
3377 else if(type.isVector())
3379 switch(type.getNominalSize())
3381 case 2: return GL_UNSIGNED_INT_VEC2;
3382 case 3: return GL_UNSIGNED_INT_VEC3;
3383 case 4: return GL_UNSIGNED_INT_VEC4;
3384 default: UNREACHABLE(type.getNominalSize());
3387 else UNREACHABLE(0);
3394 else if(type.isVector())
3396 switch(type.getNominalSize())
3398 case 2: return GL_BOOL_VEC2;
3399 case 3: return GL_BOOL_VEC3;
3400 case 4: return GL_BOOL_VEC4;
3401 default: UNREACHABLE(type.getNominalSize());
3404 else UNREACHABLE(0);
3407 return GL_SAMPLER_2D;
3409 return GL_INT_SAMPLER_2D;
3411 return GL_UNSIGNED_INT_SAMPLER_2D;
3412 case EbtSamplerCube:
3413 return GL_SAMPLER_CUBE;
3414 case EbtISamplerCube:
3415 return GL_INT_SAMPLER_CUBE;
3416 case EbtUSamplerCube:
3417 return GL_UNSIGNED_INT_SAMPLER_CUBE;
3418 case EbtSamplerExternalOES:
3419 return GL_SAMPLER_EXTERNAL_OES;
3421 return GL_SAMPLER_3D_OES;
3423 return GL_INT_SAMPLER_3D;
3425 return GL_UNSIGNED_INT_SAMPLER_3D;
3426 case EbtSampler2DArray:
3427 return GL_SAMPLER_2D_ARRAY;
3428 case EbtISampler2DArray:
3429 return GL_INT_SAMPLER_2D_ARRAY;
3430 case EbtUSampler2DArray:
3431 return GL_UNSIGNED_INT_SAMPLER_2D_ARRAY;
3432 case EbtSampler2DShadow:
3433 return GL_SAMPLER_2D_SHADOW;
3434 case EbtSamplerCubeShadow:
3435 return GL_SAMPLER_CUBE_SHADOW;
3436 case EbtSampler2DArrayShadow:
3437 return GL_SAMPLER_2D_ARRAY_SHADOW;
3439 UNREACHABLE(type.getBasicType());
3446 GLenum OutputASM::glVariablePrecision(const TType &type)
3448 if(type.getBasicType() == EbtFloat)
3450 switch(type.getPrecision())
3452 case EbpHigh: return GL_HIGH_FLOAT;
3453 case EbpMedium: return GL_MEDIUM_FLOAT;
3454 case EbpLow: return GL_LOW_FLOAT;
3456 // Should be defined as the default precision by the parser
3457 default: UNREACHABLE(type.getPrecision());
3460 else if(type.getBasicType() == EbtInt)
3462 switch(type.getPrecision())
3464 case EbpHigh: return GL_HIGH_INT;
3465 case EbpMedium: return GL_MEDIUM_INT;
3466 case EbpLow: return GL_LOW_INT;
3468 // Should be defined as the default precision by the parser
3469 default: UNREACHABLE(type.getPrecision());
3473 // Other types (boolean, sampler) don't have a precision
3477 int OutputASM::dim(TIntermNode *v)
3479 TIntermTyped *vector = v->getAsTyped();
3480 ASSERT(vector && vector->isRegister());
3481 return vector->getNominalSize();
3484 int OutputASM::dim2(TIntermNode *m)
3486 TIntermTyped *matrix = m->getAsTyped();
3487 ASSERT(matrix && matrix->isMatrix() && !matrix->isArray());
3488 return matrix->getSecondarySize();
3491 // Returns ~0u if no loop count could be determined
3492 unsigned int OutputASM::loopCount(TIntermLoop *node)
3494 // Parse loops of the form:
3495 // for(int index = initial; index [comparator] limit; index += increment)
3496 TIntermSymbol *index = 0;
3497 TOperator comparator = EOpNull;
3502 // Parse index name and intial value
3505 TIntermAggregate *init = node->getInit()->getAsAggregate();
3509 TIntermSequence &sequence = init->getSequence();
3510 TIntermTyped *variable = sequence[0]->getAsTyped();
3512 if(variable && variable->getQualifier() == EvqTemporary)
3514 TIntermBinary *assign = variable->getAsBinaryNode();
3516 if(assign->getOp() == EOpInitialize)
3518 TIntermSymbol *symbol = assign->getLeft()->getAsSymbolNode();
3519 TIntermConstantUnion *constant = assign->getRight()->getAsConstantUnion();
3521 if(symbol && constant)
3523 if(constant->getBasicType() == EbtInt && constant->getNominalSize() == 1)
3526 initial = constant->getUnionArrayPointer()[0].getIConst();
3534 // Parse comparator and limit value
3535 if(index && node->getCondition())
3537 TIntermBinary *test = node->getCondition()->getAsBinaryNode();
3538 TIntermSymbol *left = test ? test->getLeft()->getAsSymbolNode() : nullptr;
3540 if(left && (left->getId() == index->getId()))
3542 TIntermConstantUnion *constant = test->getRight()->getAsConstantUnion();
3546 if(constant->getBasicType() == EbtInt && constant->getNominalSize() == 1)
3548 comparator = test->getOp();
3549 limit = constant->getUnionArrayPointer()[0].getIConst();
3556 if(index && comparator != EOpNull && node->getExpression())
3558 TIntermBinary *binaryTerminal = node->getExpression()->getAsBinaryNode();
3559 TIntermUnary *unaryTerminal = node->getExpression()->getAsUnaryNode();
3563 TOperator op = binaryTerminal->getOp();
3564 TIntermConstantUnion *constant = binaryTerminal->getRight()->getAsConstantUnion();
3568 if(constant->getBasicType() == EbtInt && constant->getNominalSize() == 1)
3570 int value = constant->getUnionArrayPointer()[0].getIConst();
3574 case EOpAddAssign: increment = value; break;
3575 case EOpSubAssign: increment = -value; break;
3576 default: UNIMPLEMENTED();
3581 else if(unaryTerminal)
3583 TOperator op = unaryTerminal->getOp();
3587 case EOpPostIncrement: increment = 1; break;
3588 case EOpPostDecrement: increment = -1; break;
3589 case EOpPreIncrement: increment = 1; break;
3590 case EOpPreDecrement: increment = -1; break;
3591 default: UNIMPLEMENTED();
3596 if(index && comparator != EOpNull && increment != 0)
3598 if(comparator == EOpLessThanEqual)
3600 comparator = EOpLessThan;
3604 if(comparator == EOpLessThan)
3606 int iterations = (limit - initial) / increment;
3615 else UNIMPLEMENTED(); // Falls through
3621 bool LoopUnrollable::traverse(TIntermNode *node)
3624 loopUnrollable = true;
3626 node->traverse(this);
3628 return loopUnrollable;
3631 bool LoopUnrollable::visitLoop(Visit visit, TIntermLoop *loop)
3633 if(visit == PreVisit)
3637 else if(visit == PostVisit)
3645 bool LoopUnrollable::visitBranch(Visit visit, TIntermBranch *node)
3657 switch(node->getFlowOp())
3664 loopUnrollable = false;
3666 default: UNREACHABLE(node->getFlowOp());
3669 return loopUnrollable;
3672 bool LoopUnrollable::visitAggregate(Visit visit, TIntermAggregate *node)
3674 return loopUnrollable;