2 //Copyright (C) 2016 Google, Inc.
3 //Copyright (C) 2016 LunarG, Inc.
7 //Redistribution and use in source and binary forms, with or without
8 //modification, are permitted provided that the following conditions
11 // Redistributions of source code must retain the above copyright
12 // notice, this list of conditions and the following disclaimer.
14 // Redistributions in binary form must reproduce the above
15 // copyright notice, this list of conditions and the following
16 // disclaimer in the documentation and/or other materials provided
17 // with the distribution.
19 // Neither the name of 3Dlabs Inc. Ltd. nor the names of its
20 // contributors may be used to endorse or promote products derived
21 // from this software without specific prior written permission.
23 //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24 //"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25 //LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26 //FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27 //COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28 //INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29 //BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30 //LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31 //CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 //LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33 //ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34 //POSSIBILITY OF SUCH DAMAGE.
37 #include "hlslParseHelper.h"
38 #include "hlslScanContext.h"
39 #include "hlslGrammar.h"
41 #include "../glslang/MachineIndependent/Scan.h"
42 #include "../glslang/MachineIndependent/preprocessor/PpContext.h"
44 #include "../glslang/OSDependent/osinclude.h"
51 HlslParseContext::HlslParseContext(TSymbolTable& symbolTable, TIntermediate& interm, bool /*parsingBuiltins*/,
52 int version, EProfile profile, int spv, int vulkan, EShLanguage language, TInfoSink& infoSink,
53 bool forwardCompatible, EShMessages messages) :
54 TParseContextBase(symbolTable, interm, version, profile, spv, vulkan, language, infoSink, forwardCompatible, messages),
55 contextPragma(true, false), loopNestingLevel(0), structNestingLevel(0), controlFlowNestingLevel(0),
56 postMainReturn(false),
57 limits(resources.limits),
60 // ensure we always have a linkage node, even if empty, to simplify tree topology algorithms
61 linkage = new TIntermAggregate;
63 globalUniformDefaults.clear();
64 globalUniformDefaults.layoutMatrix = ElmColumnMajor;
65 globalUniformDefaults.layoutPacking = vulkan > 0 ? ElpStd140 : ElpShared;
67 globalBufferDefaults.clear();
68 globalBufferDefaults.layoutMatrix = ElmColumnMajor;
69 globalBufferDefaults.layoutPacking = vulkan > 0 ? ElpStd430 : ElpShared;
71 globalInputDefaults.clear();
72 globalOutputDefaults.clear();
74 // "Shaders in the transform
75 // feedback capturing mode have an initial global default of
76 // layout(xfb_buffer = 0) out;"
77 if (language == EShLangVertex ||
78 language == EShLangTessControl ||
79 language == EShLangTessEvaluation ||
80 language == EShLangGeometry)
81 globalOutputDefaults.layoutXfbBuffer = 0;
83 if (language == EShLangGeometry)
84 globalOutputDefaults.layoutStream = 0;
87 HlslParseContext::~HlslParseContext()
91 void HlslParseContext::setLimits(const TBuiltInResource& r)
94 intermediate.setLimits(resources);
98 // Parse an array of strings using the parser in HlslRules.
100 // Returns true for successful acceptance of the shader, false if any errors.
102 bool HlslParseContext::parseShaderStrings(TPpContext& ppContext, TInputScanner& input, bool versionWillBeError)
104 currentScanner = &input;
105 ppContext.setInput(input, versionWillBeError);
107 HlslScanContext::fillInKeywordMap(); // TODO: right place, and include the delete too
109 HlslScanContext scanContext(*this, ppContext);
110 HlslGrammar grammar(scanContext, *this);
111 if (! grammar.parse())
112 printf("HLSL translation failed.\n");
114 return numErrors == 0;
117 void HlslParseContext::handlePragma(const TSourceLoc& loc, const TVector<TString>& tokens)
120 pragmaCallback(loc.line, tokens);
122 if (tokens.size() == 0)
127 // Look at a '.' field selector string and change it into offsets
128 // for a vector or scalar
130 // Returns true if there is no error.
132 bool HlslParseContext::parseVectorFields(const TSourceLoc& loc, const TString& compString, int vecSize, TVectorFields& fields)
134 fields.num = (int)compString.size();
135 if (fields.num > 4) {
136 error(loc, "illegal vector field selection", compString.c_str(), "");
146 for (int i = 0; i < fields.num; ++i) {
147 switch (compString[i]) {
149 fields.offsets[i] = 0;
153 fields.offsets[i] = 0;
157 fields.offsets[i] = 0;
161 fields.offsets[i] = 1;
165 fields.offsets[i] = 1;
169 fields.offsets[i] = 1;
173 fields.offsets[i] = 2;
177 fields.offsets[i] = 2;
181 fields.offsets[i] = 2;
186 fields.offsets[i] = 3;
190 fields.offsets[i] = 3;
194 fields.offsets[i] = 3;
198 error(loc, "illegal vector field selection", compString.c_str(), "");
203 for (int i = 0; i < fields.num; ++i) {
204 if (fields.offsets[i] >= vecSize) {
205 error(loc, "vector field selection out of range", compString.c_str(), "");
210 if (fieldSet[i] != fieldSet[i - 1]) {
211 error(loc, "illegal - vector component fields not from the same set", compString.c_str(), "");
221 // Used to output syntax, parsing, and semantic errors.
224 void HlslParseContext::outputMessage(const TSourceLoc& loc, const char* szReason,
226 const char* szExtraInfoFormat,
227 TPrefixType prefix, va_list args)
229 const int maxSize = MaxTokenLength + 200;
230 char szExtraInfo[maxSize];
232 safe_vsprintf(szExtraInfo, maxSize, szExtraInfoFormat, args);
234 infoSink.info.prefix(prefix);
235 infoSink.info.location(loc);
236 infoSink.info << "'" << szToken << "' : " << szReason << " " << szExtraInfo << "\n";
238 if (prefix == EPrefixError) {
243 void C_DECL HlslParseContext::error(const TSourceLoc& loc, const char* szReason, const char* szToken,
244 const char* szExtraInfoFormat, ...)
246 if (messages & EShMsgOnlyPreprocessor)
249 va_start(args, szExtraInfoFormat);
250 outputMessage(loc, szReason, szToken, szExtraInfoFormat, EPrefixError, args);
254 void C_DECL HlslParseContext::warn(const TSourceLoc& loc, const char* szReason, const char* szToken,
255 const char* szExtraInfoFormat, ...)
257 if (suppressWarnings())
260 va_start(args, szExtraInfoFormat);
261 outputMessage(loc, szReason, szToken, szExtraInfoFormat, EPrefixWarning, args);
265 void C_DECL HlslParseContext::ppError(const TSourceLoc& loc, const char* szReason, const char* szToken,
266 const char* szExtraInfoFormat, ...)
269 va_start(args, szExtraInfoFormat);
270 outputMessage(loc, szReason, szToken, szExtraInfoFormat, EPrefixError, args);
274 void C_DECL HlslParseContext::ppWarn(const TSourceLoc& loc, const char* szReason, const char* szToken,
275 const char* szExtraInfoFormat, ...)
278 va_start(args, szExtraInfoFormat);
279 outputMessage(loc, szReason, szToken, szExtraInfoFormat, EPrefixWarning, args);
284 // Handle seeing a variable identifier in the grammar.
286 TIntermTyped* HlslParseContext::handleVariable(const TSourceLoc& loc, TSymbol* symbol, const TString* string)
288 if (symbol == nullptr)
289 symbol = symbolTable.find(*string);
290 if (symbol && symbol->getAsVariable() && symbol->getAsVariable()->isUserType()) {
291 error(loc, "expected symbol, not user-defined type", string->c_str(), "");
295 // Error check for requiring specific extensions present.
296 if (symbol && symbol->getNumExtensions())
297 requireExtensions(loc, symbol->getNumExtensions(), symbol->getExtensions(), symbol->getName().c_str());
299 if (symbol && symbol->isReadOnly()) {
300 // All shared things containing an implicitly sized array must be copied up
301 // on first use, so that all future references will share its array structure,
302 // so that editing the implicit size will effect all nodes consuming it,
303 // and so that editing the implicit size won't change the shared one.
305 // If this is a variable or a block, check it and all it contains, but if this
306 // is a member of an anonymous block, check the whole block, as the whole block
307 // will need to be copied up if it contains an implicitly-sized array.
308 if (symbol->getType().containsImplicitlySizedArray() || (symbol->getAsAnonMember() && symbol->getAsAnonMember()->getAnonContainer().getType().containsImplicitlySizedArray()))
309 makeEditable(symbol);
312 const TVariable* variable;
313 const TAnonMember* anon = symbol ? symbol->getAsAnonMember() : nullptr;
314 TIntermTyped* node = nullptr;
316 // It was a member of an anonymous container.
318 // Create a subtree for its dereference.
319 variable = anon->getAnonContainer().getAsVariable();
320 TIntermTyped* container = intermediate.addSymbol(*variable, loc);
321 TIntermTyped* constNode = intermediate.addConstantUnion(anon->getMemberNumber(), loc);
322 node = intermediate.addIndex(EOpIndexDirectStruct, container, constNode, loc);
324 node->setType(*(*variable->getType().getStruct())[anon->getMemberNumber()].type);
325 if (node->getType().hiddenMember())
326 error(loc, "member of nameless block was not redeclared", string->c_str(), "");
328 // Not a member of an anonymous container.
330 // The symbol table search was done in the lexical phase.
331 // See if it was a variable.
332 variable = symbol ? symbol->getAsVariable() : nullptr;
334 if ((variable->getType().getBasicType() == EbtBlock ||
335 variable->getType().getBasicType() == EbtStruct) && variable->getType().getStruct() == nullptr) {
336 error(loc, "cannot be used (maybe an instance name is needed)", string->c_str(), "");
341 error(loc, "variable name expected", string->c_str(), "");
344 // Recovery, if it wasn't found or was not a variable.
346 variable = new TVariable(string, TType(EbtVoid));
348 if (variable->getType().getQualifier().isFrontEndConstant())
349 node = intermediate.addConstantUnion(variable->getConstArray(), variable->getType(), loc);
351 node = intermediate.addSymbol(*variable, loc);
354 if (variable->getType().getQualifier().isIo())
355 intermediate.addIoAccessed(*string);
361 // Handle seeing a base[index] dereference in the grammar.
363 TIntermTyped* HlslParseContext::handleBracketDereference(const TSourceLoc& loc, TIntermTyped* base, TIntermTyped* index)
365 TIntermTyped* result = nullptr;
368 if (index->getQualifier().storage == EvqConst) {
369 indexValue = index->getAsConstantUnion()->getConstArray()[0].getIConst();
370 checkIndex(loc, base->getType(), indexValue);
374 if (! base->isArray() && ! base->isMatrix() && ! base->isVector()) {
375 if (base->getAsSymbolNode())
376 error(loc, " left of '[' is not of type array, matrix, or vector ", base->getAsSymbolNode()->getName().c_str(), "");
378 error(loc, " left of '[' is not of type array, matrix, or vector ", "expression", "");
379 } else if (base->getType().getQualifier().storage == EvqConst && index->getQualifier().storage == EvqConst)
380 return intermediate.foldDereference(base, indexValue, loc);
382 // at least one of base and index is variable...
384 if (base->getAsSymbolNode() && isIoResizeArray(base->getType()))
385 handleIoResizeArrayAccess(loc, base);
387 if (index->getQualifier().storage == EvqConst) {
388 if (base->getType().isImplicitlySizedArray())
389 updateImplicitArraySize(loc, base, indexValue);
390 result = intermediate.addIndex(EOpIndexDirect, base, index, loc);
392 result = intermediate.addIndex(EOpIndexIndirect, base, index, loc);
396 if (result == nullptr) {
397 // Insert dummy error-recovery result
398 result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
400 // Insert valid dereferenced result
401 TType newType(base->getType(), 0); // dereferenced type
402 if (base->getType().getQualifier().storage == EvqConst && index->getQualifier().storage == EvqConst)
403 newType.getQualifier().storage = EvqConst;
405 newType.getQualifier().storage = EvqTemporary;
406 result->setType(newType);
412 void HlslParseContext::checkIndex(const TSourceLoc& loc, const TType& type, int& index)
414 // HLSL todo: any rules for index fixups?
417 // Make a shared symbol have a non-shared version that can be edited by the current
418 // compile, such that editing its type will not change the shared version and will
419 // effect all nodes sharing it.
420 void HlslParseContext::makeEditable(TSymbol*& symbol)
422 // copyUp() does a deep copy of the type.
423 symbol = symbolTable.copyUp(symbol);
425 // Also, see if it's tied to IO resizing
426 if (isIoResizeArray(symbol->getType()))
427 ioArraySymbolResizeList.push_back(symbol);
429 // Also, save it in the AST for linker use.
430 intermediate.addSymbolLinkageNode(linkage, *symbol);
433 TVariable* HlslParseContext::getEditableVariable(const char* name)
436 TSymbol* symbol = symbolTable.find(name, &builtIn);
438 makeEditable(symbol);
440 return symbol->getAsVariable();
443 // Return true if this is a geometry shader input array or tessellation control output array.
444 bool HlslParseContext::isIoResizeArray(const TType& type) const
446 return type.isArray() &&
447 ((language == EShLangGeometry && type.getQualifier().storage == EvqVaryingIn) ||
448 (language == EShLangTessControl && type.getQualifier().storage == EvqVaryingOut && ! type.getQualifier().patch));
451 // If an array is not isIoResizeArray() but is an io array, make sure it has the right size
452 void HlslParseContext::fixIoArraySize(const TSourceLoc& loc, TType& type)
454 if (! type.isArray() || type.getQualifier().patch || symbolTable.atBuiltInLevel())
457 assert(! isIoResizeArray(type));
459 if (type.getQualifier().storage != EvqVaryingIn || type.getQualifier().patch)
462 if (language == EShLangTessControl || language == EShLangTessEvaluation) {
463 if (type.getOuterArraySize() != resources.maxPatchVertices) {
464 if (type.isExplicitlySizedArray())
465 error(loc, "tessellation input array size must be gl_MaxPatchVertices or implicitly sized", "[]", "");
466 type.changeOuterArraySize(resources.maxPatchVertices);
471 // Handle a dereference of a geometry shader input array or tessellation control output array.
472 // See ioArraySymbolResizeList comment in ParseHelper.h.
474 void HlslParseContext::handleIoResizeArrayAccess(const TSourceLoc& /*loc*/, TIntermTyped* base)
476 TIntermSymbol* symbolNode = base->getAsSymbolNode();
481 // fix array size, if it can be fixed and needs to be fixed (will allow variable indexing)
482 if (symbolNode->getType().isImplicitlySizedArray()) {
483 int newSize = getIoArrayImplicitSize();
485 symbolNode->getWritableType().changeOuterArraySize(newSize);
489 // If there has been an input primitive declaration (geometry shader) or an output
490 // number of vertices declaration(tessellation shader), make sure all input array types
491 // match it in size. Types come either from nodes in the AST or symbols in the
494 // Types without an array size will be given one.
495 // Types already having a size that is wrong will get an error.
497 void HlslParseContext::checkIoArraysConsistency(const TSourceLoc& loc, bool tailOnly)
499 int requiredSize = getIoArrayImplicitSize();
500 if (requiredSize == 0)
504 if (language == EShLangGeometry)
505 feature = TQualifier::getGeometryString(intermediate.getInputPrimitive());
506 else if (language == EShLangTessControl)
507 feature = "vertices";
512 checkIoArrayConsistency(loc, requiredSize, feature, ioArraySymbolResizeList.back()->getWritableType(), ioArraySymbolResizeList.back()->getName());
516 for (size_t i = 0; i < ioArraySymbolResizeList.size(); ++i)
517 checkIoArrayConsistency(loc, requiredSize, feature, ioArraySymbolResizeList[i]->getWritableType(), ioArraySymbolResizeList[i]->getName());
520 int HlslParseContext::getIoArrayImplicitSize() const
522 if (language == EShLangGeometry)
523 return TQualifier::mapGeometryToSize(intermediate.getInputPrimitive());
524 else if (language == EShLangTessControl)
525 return intermediate.getVertices() != TQualifier::layoutNotSet ? intermediate.getVertices() : 0;
530 void HlslParseContext::checkIoArrayConsistency(const TSourceLoc& loc, int requiredSize, const char* feature, TType& type, const TString& name)
532 if (type.isImplicitlySizedArray())
533 type.changeOuterArraySize(requiredSize);
536 // Handle seeing a binary node with a math operation.
537 TIntermTyped* HlslParseContext::handleBinaryMath(const TSourceLoc& loc, const char* str, TOperator op, TIntermTyped* left, TIntermTyped* right)
539 TIntermTyped* result = intermediate.addBinaryMath(op, left, right, loc);
541 binaryOpError(loc, str, left->getCompleteString(), right->getCompleteString());
546 // Handle seeing a unary node with a math operation.
547 TIntermTyped* HlslParseContext::handleUnaryMath(const TSourceLoc& loc, const char* str, TOperator op, TIntermTyped* childNode)
549 TIntermTyped* result = intermediate.addUnaryMath(op, childNode, loc);
554 unaryOpError(loc, str, childNode->getCompleteString());
560 // Handle seeing a base.field dereference in the grammar.
562 TIntermTyped* HlslParseContext::handleDotDereference(const TSourceLoc& loc, TIntermTyped* base, const TString& field)
567 // .length() can't be resolved until we later see the function-calling syntax.
568 // Save away the name in the AST for now. Processing is completed in
569 // handleLengthMethod().
571 if (field == "length") {
572 return intermediate.addMethod(base, TType(EbtInt), &field, loc);
575 // It's not .length() if we get to here.
577 if (base->isArray()) {
578 error(loc, "cannot apply to an array:", ".", field.c_str());
583 // It's neither an array nor .length() if we get here,
584 // leaving swizzles and struct/block dereferences.
586 TIntermTyped* result = base;
587 if (base->isVector() || base->isScalar()) {
588 TVectorFields fields;
589 if (! parseVectorFields(loc, field, base->getVectorSize(), fields)) {
591 fields.offsets[0] = 0;
594 if (base->isScalar()) {
598 TType type(base->getBasicType(), EvqTemporary, fields.num);
599 return addConstructor(loc, base, type, mapTypeToConstructorOp(type));
603 if (base->getType().getQualifier().isFrontEndConstant())
604 result = intermediate.foldSwizzle(base, fields, loc);
606 if (fields.num == 1) {
607 TIntermTyped* index = intermediate.addConstantUnion(fields.offsets[0], loc);
608 result = intermediate.addIndex(EOpIndexDirect, base, index, loc);
609 result->setType(TType(base->getBasicType(), EvqTemporary, base->getType().getQualifier().precision));
611 TString vectorString = field;
612 TIntermTyped* index = intermediate.addSwizzle(fields, loc);
613 result = intermediate.addIndex(EOpVectorSwizzle, base, index, loc);
614 result->setType(TType(base->getBasicType(), EvqTemporary, base->getType().getQualifier().precision, (int)vectorString.size()));
617 } else if (base->getBasicType() == EbtStruct || base->getBasicType() == EbtBlock) {
618 const TTypeList* fields = base->getType().getStruct();
619 bool fieldFound = false;
621 for (member = 0; member < (int)fields->size(); ++member) {
622 if ((*fields)[member].type->getFieldName() == field) {
628 if (base->getType().getQualifier().storage == EvqConst)
629 result = intermediate.foldDereference(base, member, loc);
631 TIntermTyped* index = intermediate.addConstantUnion(member, loc);
632 result = intermediate.addIndex(EOpIndexDirectStruct, base, index, loc);
633 result->setType(*(*fields)[member].type);
636 error(loc, "no such field in structure", field.c_str(), "");
638 error(loc, "does not apply to this type:", field.c_str(), base->getType().getCompleteString().c_str());
644 // Handle seeing a function declarator in the grammar. This is the precursor
645 // to recognizing a function prototype or function definition.
647 TFunction* HlslParseContext::handleFunctionDeclarator(const TSourceLoc& loc, TFunction& function, bool prototype)
650 // Multiple declarations of the same function name are allowed.
652 // If this is a definition, the definition production code will check for redefinitions
653 // (we don't know at this point if it's a definition or not).
655 // Redeclarations (full signature match) are allowed. But, return types and parameter qualifiers must also match.
656 // - except ES 100, which only allows a single prototype
658 // ES 100 does not allow redefining, but does allow overloading of built-in functions.
659 // ES 300 does not allow redefining or overloading of built-in functions.
662 TSymbol* symbol = symbolTable.find(function.getMangledName(), &builtIn);
663 const TFunction* prevDec = symbol ? symbol->getAsFunction() : 0;
666 // All built-in functions are defined, even though they don't have a body.
667 // Count their prototype as a definition instead.
668 if (symbolTable.atBuiltInLevel())
669 function.setDefined();
671 if (prevDec && ! builtIn)
672 symbol->getAsFunction()->setPrototyped(); // need a writable one, but like having prevDec as a const
673 function.setPrototyped();
677 // This insert won't actually insert it if it's a duplicate signature, but it will still check for
678 // other forms of name collisions.
679 if (! symbolTable.insert(function))
680 error(loc, "function name is redeclaration of existing name", function.getName().c_str(), "");
683 // If this is a redeclaration, it could also be a definition,
684 // in which case, we need to use the parameter names from this one, and not the one that's
685 // being redeclared. So, pass back this declaration, not the one in the symbol table.
691 // Handle seeing the function prototype in front of a function definition in the grammar.
692 // The body is handled after this function returns.
694 TIntermAggregate* HlslParseContext::handleFunctionDefinition(const TSourceLoc& loc, TFunction& function)
696 currentCaller = function.getMangledName();
697 TSymbol* symbol = symbolTable.find(function.getMangledName());
698 TFunction* prevDec = symbol ? symbol->getAsFunction() : nullptr;
701 error(loc, "can't find function", function.getName().c_str(), "");
702 // Note: 'prevDec' could be 'function' if this is the first time we've seen function
703 // as it would have just been put in the symbol table. Otherwise, we're looking up
704 // an earlier occurrence.
706 if (prevDec && prevDec->isDefined()) {
707 // Then this function already has a body.
708 error(loc, "function already has a body", function.getName().c_str(), "");
710 if (prevDec && ! prevDec->isDefined()) {
711 prevDec->setDefined();
713 // Remember the return type for later checking for RETURN statements.
714 currentFunctionType = &(prevDec->getType());
716 currentFunctionType = new TType(EbtVoid);
717 functionReturnsValue = false;
719 inEntrypoint = (function.getName() == intermediate.getEntryPoint().c_str());
722 // New symbol table scope for body of function plus its arguments
727 // Insert parameters into the symbol table.
728 // If the parameter has no name, it's not an error, just don't insert it
729 // (could be used for unused args).
731 // Also, accumulate the list of parameters into the HIL, so lower level code
732 // knows where to find parameters.
734 TIntermAggregate* paramNodes = new TIntermAggregate;
735 for (int i = 0; i < function.getParamCount(); i++) {
736 TParameter& param = function[i];
737 if (param.name != nullptr) {
738 TVariable *variable = new TVariable(param.name, *param.type);
740 // Insert the parameters with name in the symbol table.
741 if (! symbolTable.insert(*variable))
742 error(loc, "redefinition", variable->getName().c_str(), "");
744 // Transfer ownership of name pointer to symbol table.
745 param.name = nullptr;
747 // Add the parameter to the HIL
748 paramNodes = intermediate.growAggregate(paramNodes,
749 intermediate.addSymbol(*variable, loc),
753 paramNodes = intermediate.growAggregate(paramNodes, intermediate.addSymbol(*param.type, loc), loc);
755 intermediate.setAggregateOperator(paramNodes, EOpParameters, TType(EbtVoid), loc);
756 loopNestingLevel = 0;
757 controlFlowNestingLevel = 0;
758 postMainReturn = false;
763 void HlslParseContext::handleFunctionArgument(TFunction* function, TIntermTyped*& arguments, TIntermTyped* newArg)
765 TParameter param = { 0, new TType };
766 param.type->shallowCopy(newArg->getType());
767 function->addParameter(param);
769 arguments = intermediate.growAggregate(arguments, newArg);
775 // HLSL atomic operations have slightly different arguments than
776 // GLSL/AST/SPIRV. The semantics are converted below in decomposeIntrinsic.
777 // This provides the post-decomposition equivalent opcode.
779 TOperator HlslParseContext::mapAtomicOp(const TSourceLoc& loc, TOperator op, bool isImage)
782 case EOpInterlockedAdd: return isImage ? EOpImageAtomicAdd : EOpAtomicAdd;
783 case EOpInterlockedAnd: return isImage ? EOpImageAtomicAnd : EOpAtomicAnd;
784 case EOpInterlockedCompareExchange: return isImage ? EOpImageAtomicCompSwap : EOpAtomicCompSwap;
785 case EOpInterlockedMax: return isImage ? EOpImageAtomicMax : EOpAtomicMax;
786 case EOpInterlockedMin: return isImage ? EOpImageAtomicMin : EOpAtomicMin;
787 case EOpInterlockedOr: return isImage ? EOpImageAtomicOr : EOpAtomicOr;
788 case EOpInterlockedXor: return isImage ? EOpImageAtomicXor : EOpAtomicXor;
789 case EOpInterlockedExchange: return isImage ? EOpImageAtomicExchange : EOpAtomicExchange;
790 case EOpInterlockedCompareStore: // TODO: ...
792 error(loc, "unknown atomic operation", "unknown op", "");
797 // Optionally decompose intrinsics to AST opcodes.
799 void HlslParseContext::decomposeIntrinsic(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
801 // HLSL intrinsics can be pass through to native AST opcodes, or decomposed here to existing AST
802 // opcodes for compatibility with existing software stacks.
803 static const bool decomposeHlslIntrinsics = true;
805 if (!decomposeHlslIntrinsics || !node || !node->getAsOperator())
808 const TIntermAggregate* argAggregate = arguments ? arguments->getAsAggregate() : nullptr;
809 TIntermUnary* fnUnary = node->getAsUnaryNode();
810 const TOperator op = node->getAsOperator()->getOp();
815 // mul(a,b) -> MatrixTimesMatrix, MatrixTimesVector, MatrixTimesScalar, VectorTimesScalar, Dot, Mul
816 TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
817 TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
819 if (arg0->isVector() && arg1->isVector()) { // vec * vec
820 node->getAsAggregate()->setOperator(EOpDot);
822 node = handleBinaryMath(loc, "mul", EOpMul, arg0, arg1);
831 TIntermTyped* arg0 = fnUnary->getOperand();
832 TBasicType type0 = arg0->getBasicType();
833 TIntermTyped* one = intermediate.addConstantUnion(1, type0, loc, true);
834 node = handleBinaryMath(loc, "rcp", EOpDiv, one, arg0);
841 // saturate(a) -> clamp(a,0,1)
842 TIntermTyped* arg0 = fnUnary->getOperand();
843 TBasicType type0 = arg0->getBasicType();
844 TIntermAggregate* clamp = new TIntermAggregate(EOpClamp);
846 clamp->getSequence().push_back(arg0);
847 clamp->getSequence().push_back(intermediate.addConstantUnion(0, type0, loc, true));
848 clamp->getSequence().push_back(intermediate.addConstantUnion(1, type0, loc, true));
850 clamp->setType(node->getType());
851 clamp->getWritableType().getQualifier().makeTemporary();
859 // sincos(a,b,c) -> b = sin(a), c = cos(a)
860 TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
861 TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
862 TIntermTyped* arg2 = argAggregate->getSequence()[2]->getAsTyped();
864 TIntermTyped* sinStatement = handleUnaryMath(loc, "sin", EOpSin, arg0);
865 TIntermTyped* cosStatement = handleUnaryMath(loc, "cos", EOpCos, arg0);
866 TIntermTyped* sinAssign = intermediate.addAssign(EOpAssign, arg1, sinStatement, loc);
867 TIntermTyped* cosAssign = intermediate.addAssign(EOpAssign, arg2, cosStatement, loc);
869 TIntermAggregate* compoundStatement = intermediate.makeAggregate(sinAssign, loc);
870 compoundStatement = intermediate.growAggregate(compoundStatement, cosAssign);
871 compoundStatement->setOperator(EOpSequence);
872 compoundStatement->setLoc(loc);
874 node = compoundStatement;
881 // clip(a) -> if (any(a<0)) discard;
882 TIntermTyped* arg0 = fnUnary->getOperand();
883 TBasicType type0 = arg0->getBasicType();
884 TIntermTyped* compareNode = nullptr;
886 // For non-scalars: per experiment with FXC compiler, discard if any component < 0.
887 if (!arg0->isScalar()) {
888 // component-wise compare: a < 0
889 TIntermAggregate* less = new TIntermAggregate(EOpLessThan);
890 less->getSequence().push_back(arg0);
893 // make vec or mat of bool matching dimensions of input
894 less->setType(TType(EbtBool, EvqTemporary,
895 arg0->getType().getVectorSize(),
896 arg0->getType().getMatrixCols(),
897 arg0->getType().getMatrixRows(),
898 arg0->getType().isVector()));
900 // calculate # of components for comparison const
901 const int constComponentCount =
902 std::max(arg0->getType().getVectorSize(), 1) *
903 std::max(arg0->getType().getMatrixCols(), 1) *
904 std::max(arg0->getType().getMatrixRows(), 1);
908 TConstUnionArray zeros(constComponentCount, zero);
910 less->getSequence().push_back(intermediate.addConstantUnion(zeros, arg0->getType(), loc, true));
912 compareNode = intermediate.addBuiltInFunctionCall(loc, EOpAny, true, less, TType(EbtBool));
914 TIntermTyped* zero = intermediate.addConstantUnion(0, type0, loc, true);
915 compareNode = handleBinaryMath(loc, "clip", EOpLessThan, arg0, zero);
918 TIntermBranch* killNode = intermediate.addBranch(EOpKill, loc);
920 node = new TIntermSelection(compareNode, killNode, nullptr);
928 // log10(a) -> log2(a) * 0.301029995663981 (== 1/log2(10))
929 TIntermTyped* arg0 = fnUnary->getOperand();
930 TIntermTyped* log2 = handleUnaryMath(loc, "log2", EOpLog2, arg0);
931 TIntermTyped* base = intermediate.addConstantUnion(0.301029995663981f, EbtFloat, loc, true);
933 node = handleBinaryMath(loc, "mul", EOpMul, log2, base);
941 // dest.y = src0.y * src1.y;
945 TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
946 TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
947 TBasicType type0 = arg0->getBasicType();
949 TIntermTyped* x = intermediate.addConstantUnion(0, loc, true);
950 TIntermTyped* y = intermediate.addConstantUnion(1, loc, true);
951 TIntermTyped* z = intermediate.addConstantUnion(2, loc, true);
952 TIntermTyped* w = intermediate.addConstantUnion(3, loc, true);
954 TIntermTyped* src0y = intermediate.addIndex(EOpIndexDirect, arg0, y, loc);
955 TIntermTyped* src1y = intermediate.addIndex(EOpIndexDirect, arg1, y, loc);
956 TIntermTyped* src0z = intermediate.addIndex(EOpIndexDirect, arg0, z, loc);
957 TIntermTyped* src1w = intermediate.addIndex(EOpIndexDirect, arg1, w, loc);
959 TIntermAggregate* dst = new TIntermAggregate(EOpConstructVec4);
961 dst->getSequence().push_back(intermediate.addConstantUnion(1.0, EbtFloat, loc, true));
962 dst->getSequence().push_back(handleBinaryMath(loc, "mul", EOpMul, src0y, src1y));
963 dst->getSequence().push_back(src0z);
964 dst->getSequence().push_back(src1w);
971 case EOpInterlockedAdd: // optional last argument (if present) is assigned from return value
972 case EOpInterlockedMin: // ...
973 case EOpInterlockedMax: // ...
974 case EOpInterlockedAnd: // ...
975 case EOpInterlockedOr: // ...
976 case EOpInterlockedXor: // ...
977 case EOpInterlockedExchange: // always has output arg
979 TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
980 TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
982 const bool isImage = arg0->getType().isImage();
983 const TOperator atomicOp = mapAtomicOp(loc, op, isImage);
985 if (argAggregate->getSequence().size() > 2) {
986 // optional output param is present. return value goes to arg2.
987 TIntermTyped* arg2 = argAggregate->getSequence()[2]->getAsTyped();
989 TIntermAggregate* atomic = new TIntermAggregate(atomicOp);
990 atomic->getSequence().push_back(arg0);
991 atomic->getSequence().push_back(arg1);
993 atomic->setType(arg0->getType());
994 atomic->getWritableType().getQualifier().makeTemporary();
996 node = intermediate.addAssign(EOpAssign, arg2, atomic, loc);
998 // Set the matching operator. Since output is absent, this is all we need to do.
999 node->getAsAggregate()->setOperator(atomicOp);
1005 case EOpInterlockedCompareExchange:
1007 TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped(); // dest
1008 TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped(); // cmp
1009 TIntermTyped* arg2 = argAggregate->getSequence()[2]->getAsTyped(); // value
1010 TIntermTyped* arg3 = argAggregate->getSequence()[3]->getAsTyped(); // orig
1012 const bool isImage = arg0->getType().isImage();
1013 TIntermAggregate* atomic = new TIntermAggregate(mapAtomicOp(loc, op, isImage));
1014 atomic->getSequence().push_back(arg0);
1015 atomic->getSequence().push_back(arg1);
1016 atomic->getSequence().push_back(arg2);
1017 atomic->setLoc(loc);
1018 atomic->setType(arg2->getType());
1019 atomic->getWritableType().getQualifier().makeTemporary();
1021 node = intermediate.addAssign(EOpAssign, arg3, atomic, loc);
1027 break; // most pass through unchanged
1032 // Handle seeing function call syntax in the grammar, which could be any of
1033 // - .length() method
1035 // - a call to a built-in function mapped to an operator
1036 // - a call to a built-in function that will remain a function call (e.g., texturing)
1038 // - subroutine call (not implemented yet)
1040 TIntermTyped* HlslParseContext::handleFunctionCall(const TSourceLoc& loc, TFunction* function, TIntermNode* arguments)
1042 TIntermTyped* result = nullptr;
1044 TOperator op = function->getBuiltInOp();
1045 if (op == EOpArrayLength)
1046 result = handleLengthMethod(loc, function, arguments);
1047 else if (op != EOpNull) {
1049 // Then this should be a constructor.
1050 // Don't go through the symbol table for constructors.
1051 // Their parameters will be verified algorithmically.
1053 TType type(EbtVoid); // use this to get the type back
1054 if (! constructorError(loc, arguments, *function, op, type)) {
1056 // It's a constructor, of type 'type'.
1058 result = addConstructor(loc, arguments, type, op);
1059 if (result == nullptr)
1060 error(loc, "cannot construct with these arguments", type.getCompleteString().c_str(), "");
1064 // Find it in the symbol table.
1066 const TFunction* fnCandidate;
1068 fnCandidate = findFunction(loc, *function, builtIn);
1070 // This is a declared function that might map to
1071 // - a built-in operator,
1072 // - a built-in function not mapped to an operator, or
1073 // - a user function.
1075 // Error check for a function requiring specific extensions present.
1076 if (builtIn && fnCandidate->getNumExtensions())
1077 requireExtensions(loc, fnCandidate->getNumExtensions(), fnCandidate->getExtensions(), fnCandidate->getName().c_str());
1080 // Make sure qualifications work for these arguments.
1081 TIntermAggregate* aggregate = arguments->getAsAggregate();
1082 for (int i = 0; i < fnCandidate->getParamCount(); ++i) {
1083 // At this early point there is a slight ambiguity between whether an aggregate 'arguments'
1084 // is the single argument itself or its children are the arguments. Only one argument
1085 // means take 'arguments' itself as the one argument.
1086 TIntermNode* arg = fnCandidate->getParamCount() == 1 ? arguments : (aggregate ? aggregate->getSequence()[i] : arguments);
1087 TQualifier& formalQualifier = (*fnCandidate)[i].type->getQualifier();
1088 TQualifier& argQualifier = arg->getAsTyped()->getQualifier();
1091 // Convert 'in' arguments
1092 addInputArgumentConversions(*fnCandidate, arguments); // arguments may be modified if it's just a single argument node
1095 op = fnCandidate->getBuiltInOp();
1096 if (builtIn && op != EOpNull) {
1097 // A function call mapped to a built-in operation.
1098 result = intermediate.addBuiltInFunctionCall(loc, op, fnCandidate->getParamCount() == 1, arguments, fnCandidate->getType());
1099 if (result == nullptr) {
1100 error(arguments->getLoc(), " wrong operand type", "Internal Error",
1101 "built in unary operator function. Type: %s",
1102 static_cast<TIntermTyped*>(arguments)->getCompleteString().c_str());
1103 } else if (result->getAsOperator()) {
1104 builtInOpCheck(loc, *fnCandidate, *result->getAsOperator());
1107 // This is a function call not mapped to built-in operator.
1108 // It could still be a built-in function, but only if PureOperatorBuiltins == false.
1109 result = intermediate.setAggregateOperator(arguments, EOpFunctionCall, fnCandidate->getType(), loc);
1110 TIntermAggregate* call = result->getAsAggregate();
1111 call->setName(fnCandidate->getMangledName());
1113 // this is how we know whether the given function is a built-in function or a user-defined function
1114 // if builtIn == false, it's a userDefined -> could be an overloaded built-in function also
1115 // if builtIn == true, it's definitely a built-in function with EOpNull
1117 call->setUserDefined();
1118 intermediate.addToCallGraph(infoSink, currentCaller, fnCandidate->getMangledName());
1122 // Convert 'out' arguments. If it was a constant folded built-in, it won't be an aggregate anymore.
1123 // Built-ins with a single argument aren't called with an aggregate, but they also don't have an output.
1124 // Also, build the qualifier list for user function calls, which are always called with an aggregate.
1125 if (result->getAsAggregate()) {
1126 TQualifierList& qualifierList = result->getAsAggregate()->getQualifierList();
1127 for (int i = 0; i < fnCandidate->getParamCount(); ++i) {
1128 TStorageQualifier qual = (*fnCandidate)[i].type->getQualifier().storage;
1129 qualifierList.push_back(qual);
1131 result = addOutputArgumentConversions(*fnCandidate, *result->getAsAggregate());
1134 decomposeIntrinsic(loc, result, arguments);
1138 // generic error recovery
1139 // TODO: simplification: localize all the error recoveries that look like this, and taking type into account to reduce cascades
1140 if (result == nullptr)
1141 result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
1146 // Finish processing object.length(). This started earlier in handleDotDereference(), where
1147 // the ".length" part was recognized and semantically checked, and finished here where the
1148 // function syntax "()" is recognized.
1150 // Return resulting tree node.
1151 TIntermTyped* HlslParseContext::handleLengthMethod(const TSourceLoc& loc, TFunction* function, TIntermNode* intermNode)
1155 if (function->getParamCount() > 0)
1156 error(loc, "method does not accept any arguments", function->getName().c_str(), "");
1158 const TType& type = intermNode->getAsTyped()->getType();
1159 if (type.isArray()) {
1160 if (type.isRuntimeSizedArray()) {
1161 // Create a unary op and let the back end handle it
1162 return intermediate.addBuiltInFunctionCall(loc, EOpArrayLength, true, intermNode, TType(EbtInt));
1163 } else if (type.isImplicitlySizedArray()) {
1164 if (intermNode->getAsSymbolNode() && isIoResizeArray(type)) {
1165 // We could be between a layout declaration that gives a built-in io array implicit size and
1166 // a user redeclaration of that array, meaning we have to substitute its implicit size here
1167 // without actually redeclaring the array. (It is an error to use a member before the
1168 // redeclaration, but not an error to use the array name itself.)
1169 const TString& name = intermNode->getAsSymbolNode()->getName();
1170 if (name == "gl_in" || name == "gl_out")
1171 length = getIoArrayImplicitSize();
1174 if (intermNode->getAsSymbolNode() && isIoResizeArray(type))
1175 error(loc, "", function->getName().c_str(), "array must first be sized by a redeclaration or layout qualifier");
1177 error(loc, "", function->getName().c_str(), "array must be declared with a size before using this method");
1180 length = type.getOuterArraySize();
1181 } else if (type.isMatrix())
1182 length = type.getMatrixCols();
1183 else if (type.isVector())
1184 length = type.getVectorSize();
1186 // we should not get here, because earlier semantic checking should have prevented this path
1187 error(loc, ".length()", "unexpected use of .length()", "");
1194 return intermediate.addConstantUnion(length, loc);
1198 // Add any needed implicit conversions for function-call arguments to input parameters.
1200 void HlslParseContext::addInputArgumentConversions(const TFunction& function, TIntermNode*& arguments) const
1202 TIntermAggregate* aggregate = arguments->getAsAggregate();
1204 // Process each argument's conversion
1205 for (int i = 0; i < function.getParamCount(); ++i) {
1206 // At this early point there is a slight ambiguity between whether an aggregate 'arguments'
1207 // is the single argument itself or its children are the arguments. Only one argument
1208 // means take 'arguments' itself as the one argument.
1209 TIntermTyped* arg = function.getParamCount() == 1 ? arguments->getAsTyped() : (aggregate ? aggregate->getSequence()[i]->getAsTyped() : arguments->getAsTyped());
1210 if (*function[i].type != arg->getType()) {
1211 if (function[i].type->getQualifier().isParamInput()) {
1212 // In-qualified arguments just need an extra node added above the argument to
1213 // convert to the correct type.
1214 arg = intermediate.addConversion(EOpFunctionCall, *function[i].type, arg);
1216 if (function.getParamCount() == 1)
1220 aggregate->getSequence()[i] = arg;
1231 // Add any needed implicit output conversions for function-call arguments. This
1232 // can require a new tree topology, complicated further by whether the function
1233 // has a return value.
1235 // Returns a node of a subtree that evaluates to the return value of the function.
1237 TIntermTyped* HlslParseContext::addOutputArgumentConversions(const TFunction& function, TIntermAggregate& intermNode) const
1239 TIntermSequence& arguments = intermNode.getSequence();
1241 // Will there be any output conversions?
1242 bool outputConversions = false;
1243 for (int i = 0; i < function.getParamCount(); ++i) {
1244 if (*function[i].type != arguments[i]->getAsTyped()->getType() && function[i].type->getQualifier().storage == EvqOut) {
1245 outputConversions = true;
1250 if (! outputConversions)
1253 // Setup for the new tree, if needed:
1255 // Output conversions need a different tree topology.
1256 // Out-qualified arguments need a temporary of the correct type, with the call
1257 // followed by an assignment of the temporary to the original argument:
1258 // void: function(arg, ...) -> ( function(tempArg, ...), arg = tempArg, ...)
1259 // ret = function(arg, ...) -> ret = (tempRet = function(tempArg, ...), arg = tempArg, ..., tempRet)
1260 // Where the "tempArg" type needs no conversion as an argument, but will convert on assignment.
1261 TIntermTyped* conversionTree = nullptr;
1262 TVariable* tempRet = nullptr;
1263 if (intermNode.getBasicType() != EbtVoid) {
1264 // do the "tempRet = function(...), " bit from above
1265 tempRet = makeInternalVariable("tempReturn", intermNode.getType());
1266 TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, intermNode.getLoc());
1267 conversionTree = intermediate.addAssign(EOpAssign, tempRetNode, &intermNode, intermNode.getLoc());
1269 conversionTree = &intermNode;
1271 conversionTree = intermediate.makeAggregate(conversionTree);
1273 // Process each argument's conversion
1274 for (int i = 0; i < function.getParamCount(); ++i) {
1275 if (*function[i].type != arguments[i]->getAsTyped()->getType()) {
1276 if (function[i].type->getQualifier().isParamOutput()) {
1277 // Out-qualified arguments need to use the topology set up above.
1278 // do the " ...(tempArg, ...), arg = tempArg" bit from above
1279 TVariable* tempArg = makeInternalVariable("tempArg", *function[i].type);
1280 tempArg->getWritableType().getQualifier().makeTemporary();
1281 TIntermSymbol* tempArgNode = intermediate.addSymbol(*tempArg, intermNode.getLoc());
1282 TIntermTyped* tempAssign = intermediate.addAssign(EOpAssign, arguments[i]->getAsTyped(), tempArgNode, arguments[i]->getLoc());
1283 conversionTree = intermediate.growAggregate(conversionTree, tempAssign, arguments[i]->getLoc());
1284 // replace the argument with another node for the same tempArg variable
1285 arguments[i] = intermediate.addSymbol(*tempArg, intermNode.getLoc());
1290 // Finalize the tree topology (see bigger comment above).
1292 // do the "..., tempRet" bit from above
1293 TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, intermNode.getLoc());
1294 conversionTree = intermediate.growAggregate(conversionTree, tempRetNode, intermNode.getLoc());
1296 conversionTree = intermediate.setAggregateOperator(conversionTree, EOpComma, intermNode.getType(), intermNode.getLoc());
1298 return conversionTree;
1302 // Do additional checking of built-in function calls that is not caught
1303 // by normal semantic checks on argument type, extension tagging, etc.
1305 // Assumes there has been a semantically correct match to a built-in function prototype.
1307 void HlslParseContext::builtInOpCheck(const TSourceLoc& loc, const TFunction& fnCandidate, TIntermOperator& callNode)
1309 // Set up convenience accessors to the argument(s). There is almost always
1310 // multiple arguments for the cases below, but when there might be one,
1311 // check the unaryArg first.
1312 const TIntermSequence* argp = nullptr; // confusing to use [] syntax on a pointer, so this is to help get a reference
1313 const TIntermTyped* unaryArg = nullptr;
1314 const TIntermTyped* arg0 = nullptr;
1315 if (callNode.getAsAggregate()) {
1316 argp = &callNode.getAsAggregate()->getSequence();
1317 if (argp->size() > 0)
1318 arg0 = (*argp)[0]->getAsTyped();
1320 assert(callNode.getAsUnaryNode());
1321 unaryArg = callNode.getAsUnaryNode()->getOperand();
1324 const TIntermSequence& aggArgs = *argp; // only valid when unaryArg is nullptr
1326 // built-in texturing functions get their return value precision from the precision of the sampler
1327 if (fnCandidate.getType().getQualifier().precision == EpqNone &&
1328 fnCandidate.getParamCount() > 0 && fnCandidate[0].type->getBasicType() == EbtSampler)
1329 callNode.getQualifier().precision = arg0->getQualifier().precision;
1331 switch (callNode.getOp()) {
1332 case EOpTextureGather:
1333 case EOpTextureGatherOffset:
1334 case EOpTextureGatherOffsets:
1336 // Figure out which variants are allowed by what extensions,
1337 // and what arguments must be constant for which situations.
1339 TString featureString = fnCandidate.getName() + "(...)";
1340 const char* feature = featureString.c_str();
1341 int compArg = -1; // track which argument, if any, is the constant component argument
1342 switch (callNode.getOp()) {
1343 case EOpTextureGather:
1344 // More than two arguments needs gpu_shader5, and rectangular or shadow needs gpu_shader5,
1345 // otherwise, need GL_ARB_texture_gather.
1346 if (fnCandidate.getParamCount() > 2 || fnCandidate[0].type->getSampler().dim == EsdRect || fnCandidate[0].type->getSampler().shadow) {
1347 if (! fnCandidate[0].type->getSampler().shadow)
1351 case EOpTextureGatherOffset:
1352 // GL_ARB_texture_gather is good enough for 2D non-shadow textures with no component argument
1353 if (! fnCandidate[0].type->getSampler().shadow)
1356 case EOpTextureGatherOffsets:
1357 if (! fnCandidate[0].type->getSampler().shadow)
1364 if (compArg > 0 && compArg < fnCandidate.getParamCount()) {
1365 if (aggArgs[compArg]->getAsConstantUnion()) {
1366 int value = aggArgs[compArg]->getAsConstantUnion()->getConstArray()[0].getIConst();
1367 if (value < 0 || value > 3)
1368 error(loc, "must be 0, 1, 2, or 3:", feature, "component argument");
1370 error(loc, "must be a compile-time constant:", feature, "component argument");
1376 case EOpTextureOffset:
1377 case EOpTextureFetchOffset:
1378 case EOpTextureProjOffset:
1379 case EOpTextureLodOffset:
1380 case EOpTextureProjLodOffset:
1381 case EOpTextureGradOffset:
1382 case EOpTextureProjGradOffset:
1384 // Handle texture-offset limits checking
1385 // Pick which argument has to hold constant offsets
1387 switch (callNode.getOp()) {
1388 case EOpTextureOffset: arg = 2; break;
1389 case EOpTextureFetchOffset: arg = (arg0->getType().getSampler().dim != EsdRect) ? 3 : 2; break;
1390 case EOpTextureProjOffset: arg = 2; break;
1391 case EOpTextureLodOffset: arg = 3; break;
1392 case EOpTextureProjLodOffset: arg = 3; break;
1393 case EOpTextureGradOffset: arg = 4; break;
1394 case EOpTextureProjGradOffset: arg = 4; break;
1401 if (! aggArgs[arg]->getAsConstantUnion())
1402 error(loc, "argument must be compile-time constant", "texel offset", "");
1404 const TType& type = aggArgs[arg]->getAsTyped()->getType();
1405 for (int c = 0; c < type.getVectorSize(); ++c) {
1406 int offset = aggArgs[arg]->getAsConstantUnion()->getConstArray()[c].getIConst();
1407 if (offset > resources.maxProgramTexelOffset || offset < resources.minProgramTexelOffset)
1408 error(loc, "value is out of range:", "texel offset", "[gl_MinProgramTexelOffset, gl_MaxProgramTexelOffset]");
1416 case EOpTextureQuerySamples:
1417 case EOpImageQuerySamples:
1420 case EOpImageAtomicAdd:
1421 case EOpImageAtomicMin:
1422 case EOpImageAtomicMax:
1423 case EOpImageAtomicAnd:
1424 case EOpImageAtomicOr:
1425 case EOpImageAtomicXor:
1426 case EOpImageAtomicExchange:
1427 case EOpImageAtomicCompSwap:
1430 case EOpInterpolateAtCentroid:
1431 case EOpInterpolateAtSample:
1432 case EOpInterpolateAtOffset:
1433 // "For the interpolateAt* functions, the call will return a precision
1434 // qualification matching the precision of the 'interpolant' argument to
1435 // the function call."
1436 callNode.getQualifier().precision = arg0->getQualifier().precision;
1438 // Make sure the first argument is an interpolant, or an array element of an interpolant
1439 if (arg0->getType().getQualifier().storage != EvqVaryingIn) {
1440 // It might still be an array element.
1442 // We could check more, but the semantics of the first argument are already met; the
1443 // only way to turn an array into a float/vec* is array dereference and swizzle.
1445 // ES and desktop 4.3 and earlier: swizzles may not be used
1446 // desktop 4.4 and later: swizzles may be used
1447 const TIntermTyped* base = TIntermediate::findLValueBase(arg0, true);
1448 if (base == nullptr || base->getType().getQualifier().storage != EvqVaryingIn)
1449 error(loc, "first argument must be an interpolant, or interpolant-array element", fnCandidate.getName().c_str(), "");
1459 // Handle seeing a built-in constructor in a grammar production.
1461 TFunction* HlslParseContext::handleConstructorCall(const TSourceLoc& loc, const TType& type)
1463 TOperator op = mapTypeToConstructorOp(type);
1465 if (op == EOpNull) {
1466 error(loc, "cannot construct this type", type.getBasicString(), "");
1472 return new TFunction(&empty, type, op);
1476 // Handle seeing a "COLON semantic" at the end of a type declaration,
1477 // by updating the type according to the semantic.
1479 void HlslParseContext::handleSemantic(TType& type, const TString& semantic)
1481 // TODO: need to know if it's an input or an output
1482 // The following sketches what needs to be done, but can't be right
1483 // without taking into account stage and input/output.
1485 if (semantic == "PSIZE")
1486 type.getQualifier().builtIn = EbvPointSize;
1487 else if (semantic == "POSITION")
1488 type.getQualifier().builtIn = EbvPosition;
1489 else if (semantic == "FOG")
1490 type.getQualifier().builtIn = EbvFogFragCoord;
1491 else if (semantic == "DEPTH" || semantic == "SV_Depth")
1492 type.getQualifier().builtIn = EbvFragDepth;
1493 else if (semantic == "VFACE" || semantic == "SV_IsFrontFace")
1494 type.getQualifier().builtIn = EbvFace;
1495 else if (semantic == "VPOS" || semantic == "SV_Position")
1496 type.getQualifier().builtIn = EbvFragCoord;
1497 else if (semantic == "SV_ClipDistance")
1498 type.getQualifier().builtIn = EbvClipDistance;
1499 else if (semantic == "SV_CullDistance")
1500 type.getQualifier().builtIn = EbvCullDistance;
1501 else if (semantic == "SV_VertexID")
1502 type.getQualifier().builtIn = EbvVertexId;
1503 else if (semantic == "SV_ViewportArrayIndex")
1504 type.getQualifier().builtIn = EbvViewportIndex;
1508 // Given a type, find what operation would fully construct it.
1510 TOperator HlslParseContext::mapTypeToConstructorOp(const TType& type) const
1512 TOperator op = EOpNull;
1514 switch (type.getBasicType()) {
1516 op = EOpConstructStruct;
1519 if (type.getSampler().combined)
1520 op = EOpConstructTextureSampler;
1523 if (type.isMatrix()) {
1524 switch (type.getMatrixCols()) {
1526 switch (type.getMatrixRows()) {
1527 case 2: op = EOpConstructMat2x2; break;
1528 case 3: op = EOpConstructMat2x3; break;
1529 case 4: op = EOpConstructMat2x4; break;
1530 default: break; // some compilers want this
1534 switch (type.getMatrixRows()) {
1535 case 2: op = EOpConstructMat3x2; break;
1536 case 3: op = EOpConstructMat3x3; break;
1537 case 4: op = EOpConstructMat3x4; break;
1538 default: break; // some compilers want this
1542 switch (type.getMatrixRows()) {
1543 case 2: op = EOpConstructMat4x2; break;
1544 case 3: op = EOpConstructMat4x3; break;
1545 case 4: op = EOpConstructMat4x4; break;
1546 default: break; // some compilers want this
1549 default: break; // some compilers want this
1552 switch (type.getVectorSize()) {
1553 case 1: op = EOpConstructFloat; break;
1554 case 2: op = EOpConstructVec2; break;
1555 case 3: op = EOpConstructVec3; break;
1556 case 4: op = EOpConstructVec4; break;
1557 default: break; // some compilers want this
1562 if (type.getMatrixCols()) {
1563 switch (type.getMatrixCols()) {
1565 switch (type.getMatrixRows()) {
1566 case 2: op = EOpConstructDMat2x2; break;
1567 case 3: op = EOpConstructDMat2x3; break;
1568 case 4: op = EOpConstructDMat2x4; break;
1569 default: break; // some compilers want this
1573 switch (type.getMatrixRows()) {
1574 case 2: op = EOpConstructDMat3x2; break;
1575 case 3: op = EOpConstructDMat3x3; break;
1576 case 4: op = EOpConstructDMat3x4; break;
1577 default: break; // some compilers want this
1581 switch (type.getMatrixRows()) {
1582 case 2: op = EOpConstructDMat4x2; break;
1583 case 3: op = EOpConstructDMat4x3; break;
1584 case 4: op = EOpConstructDMat4x4; break;
1585 default: break; // some compilers want this
1590 switch (type.getVectorSize()) {
1591 case 1: op = EOpConstructDouble; break;
1592 case 2: op = EOpConstructDVec2; break;
1593 case 3: op = EOpConstructDVec3; break;
1594 case 4: op = EOpConstructDVec4; break;
1595 default: break; // some compilers want this
1600 switch (type.getVectorSize()) {
1601 case 1: op = EOpConstructInt; break;
1602 case 2: op = EOpConstructIVec2; break;
1603 case 3: op = EOpConstructIVec3; break;
1604 case 4: op = EOpConstructIVec4; break;
1605 default: break; // some compilers want this
1609 switch (type.getVectorSize()) {
1610 case 1: op = EOpConstructUint; break;
1611 case 2: op = EOpConstructUVec2; break;
1612 case 3: op = EOpConstructUVec3; break;
1613 case 4: op = EOpConstructUVec4; break;
1614 default: break; // some compilers want this
1618 switch (type.getVectorSize()) {
1619 case 1: op = EOpConstructBool; break;
1620 case 2: op = EOpConstructBVec2; break;
1621 case 3: op = EOpConstructBVec3; break;
1622 case 4: op = EOpConstructBVec4; break;
1623 default: break; // some compilers want this
1634 // Same error message for all places assignments don't work.
1636 void HlslParseContext::assignError(const TSourceLoc& loc, const char* op, TString left, TString right)
1638 error(loc, "", op, "cannot convert from '%s' to '%s'",
1639 right.c_str(), left.c_str());
1643 // Same error message for all places unary operations don't work.
1645 void HlslParseContext::unaryOpError(const TSourceLoc& loc, const char* op, TString operand)
1647 error(loc, " wrong operand type", op,
1648 "no operation '%s' exists that takes an operand of type %s (or there is no acceptable conversion)",
1649 op, operand.c_str());
1653 // Same error message for all binary operations don't work.
1655 void HlslParseContext::binaryOpError(const TSourceLoc& loc, const char* op, TString left, TString right)
1657 error(loc, " wrong operand types:", op,
1658 "no operation '%s' exists that takes a left-hand operand of type '%s' and "
1659 "a right operand of type '%s' (or there is no acceptable conversion)",
1660 op, left.c_str(), right.c_str());
1664 // A basic type of EbtVoid is a key that the name string was seen in the source, but
1665 // it was not found as a variable in the symbol table. If so, give the error
1666 // message and insert a dummy variable in the symbol table to prevent future errors.
1668 void HlslParseContext::variableCheck(TIntermTyped*& nodePtr)
1670 TIntermSymbol* symbol = nodePtr->getAsSymbolNode();
1674 if (symbol->getType().getBasicType() == EbtVoid) {
1675 error(symbol->getLoc(), "undeclared identifier", symbol->getName().c_str(), "");
1677 // Add to symbol table to prevent future error messages on the same name
1678 if (symbol->getName().size() > 0) {
1679 TVariable* fakeVariable = new TVariable(&symbol->getName(), TType(EbtFloat));
1680 symbolTable.insert(*fakeVariable);
1682 // substitute a symbol node for this new variable
1683 nodePtr = intermediate.addSymbol(*fakeVariable, symbol->getLoc());
1689 // Both test, and if necessary spit out an error, to see if the node is really
1692 void HlslParseContext::constantValueCheck(TIntermTyped* node, const char* token)
1694 if (node->getQualifier().storage != EvqConst)
1695 error(node->getLoc(), "constant expression required", token, "");
1699 // Both test, and if necessary spit out an error, to see if the node is really
1702 void HlslParseContext::integerCheck(const TIntermTyped* node, const char* token)
1704 if ((node->getBasicType() == EbtInt || node->getBasicType() == EbtUint) && node->isScalar())
1707 error(node->getLoc(), "scalar integer expression required", token, "");
1711 // Both test, and if necessary spit out an error, to see if we are currently
1714 void HlslParseContext::globalCheck(const TSourceLoc& loc, const char* token)
1716 if (! symbolTable.atGlobalLevel())
1717 error(loc, "not allowed in nested scope", token, "");
1721 bool HlslParseContext::builtInName(const TString& identifier)
1727 // Make sure there is enough data and not too many arguments provided to the
1728 // constructor to build something of the type of the constructor. Also returns
1729 // the type of the constructor.
1731 // Returns true if there was an error in construction.
1733 bool HlslParseContext::constructorError(const TSourceLoc& loc, TIntermNode* node, TFunction& function, TOperator op, TType& type)
1735 type.shallowCopy(function.getType());
1737 bool constructingMatrix = false;
1739 case EOpConstructTextureSampler:
1740 return constructorTextureSamplerError(loc, function);
1741 case EOpConstructMat2x2:
1742 case EOpConstructMat2x3:
1743 case EOpConstructMat2x4:
1744 case EOpConstructMat3x2:
1745 case EOpConstructMat3x3:
1746 case EOpConstructMat3x4:
1747 case EOpConstructMat4x2:
1748 case EOpConstructMat4x3:
1749 case EOpConstructMat4x4:
1750 case EOpConstructDMat2x2:
1751 case EOpConstructDMat2x3:
1752 case EOpConstructDMat2x4:
1753 case EOpConstructDMat3x2:
1754 case EOpConstructDMat3x3:
1755 case EOpConstructDMat3x4:
1756 case EOpConstructDMat4x2:
1757 case EOpConstructDMat4x3:
1758 case EOpConstructDMat4x4:
1759 constructingMatrix = true;
1766 // Walk the arguments for first-pass checks and collection of information.
1770 bool constType = true;
1772 bool overFull = false;
1773 bool matrixInMatrix = false;
1774 bool arrayArg = false;
1775 for (int arg = 0; arg < function.getParamCount(); ++arg) {
1776 if (function[arg].type->isArray()) {
1777 if (! function[arg].type->isExplicitlySizedArray()) {
1778 // Can't construct from an unsized array.
1779 error(loc, "array argument must be sized", "constructor", "");
1784 if (constructingMatrix && function[arg].type->isMatrix())
1785 matrixInMatrix = true;
1787 // 'full' will go to true when enough args have been seen. If we loop
1788 // again, there is an extra argument.
1790 // For vectors and matrices, it's okay to have too many components
1791 // available, but not okay to have unused arguments.
1795 size += function[arg].type->computeNumComponents();
1796 if (op != EOpConstructStruct && ! type.isArray() && size >= type.computeNumComponents())
1799 if (function[arg].type->getQualifier().storage != EvqConst)
1804 type.getQualifier().storage = EvqConst;
1806 if (type.isArray()) {
1807 if (function.getParamCount() == 0) {
1808 error(loc, "array constructor must have at least one argument", "constructor", "");
1812 if (type.isImplicitlySizedArray()) {
1813 // auto adapt the constructor type to the number of arguments
1814 type.changeOuterArraySize(function.getParamCount());
1815 } else if (type.getOuterArraySize() != function.getParamCount()) {
1816 error(loc, "array constructor needs one argument per array element", "constructor", "");
1820 if (type.isArrayOfArrays()) {
1821 // Types have to match, but we're still making the type.
1822 // Finish making the type, and the comparison is done later
1823 // when checking for conversion.
1824 TArraySizes& arraySizes = type.getArraySizes();
1826 // At least the dimensionalities have to match.
1827 if (! function[0].type->isArray() || arraySizes.getNumDims() != function[0].type->getArraySizes().getNumDims() + 1) {
1828 error(loc, "array constructor argument not correct type to construct array element", "constructior", "");
1832 if (arraySizes.isInnerImplicit()) {
1833 // "Arrays of arrays ..., and the size for any dimension is optional"
1834 // That means we need to adopt (from the first argument) the other array sizes into the type.
1835 for (int d = 1; d < arraySizes.getNumDims(); ++d) {
1836 if (arraySizes.getDimSize(d) == UnsizedArraySize) {
1837 arraySizes.setDimSize(d, function[0].type->getArraySizes().getDimSize(d - 1));
1844 if (arrayArg && op != EOpConstructStruct && ! type.isArrayOfArrays()) {
1845 error(loc, "constructing non-array constituent from array argument", "constructor", "");
1849 if (matrixInMatrix && ! type.isArray()) {
1854 error(loc, "too many arguments", "constructor", "");
1858 if (op == EOpConstructStruct && ! type.isArray() && (int)type.getStruct()->size() != function.getParamCount()) {
1859 error(loc, "Number of constructor parameters does not match the number of structure fields", "constructor", "");
1863 if ((op != EOpConstructStruct && size != 1 && size < type.computeNumComponents()) ||
1864 (op == EOpConstructStruct && size < type.computeNumComponents())) {
1865 error(loc, "not enough data provided for construction", "constructor", "");
1869 TIntermTyped* typed = node->getAsTyped();
1874 // Verify all the correct semantics for constructing a combined texture/sampler.
1875 // Return true if the semantics are incorrect.
1876 bool HlslParseContext::constructorTextureSamplerError(const TSourceLoc& loc, const TFunction& function)
1878 TString constructorName = function.getType().getBasicTypeString(); // TODO: performance: should not be making copy; interface needs to change
1879 const char* token = constructorName.c_str();
1881 // exactly two arguments needed
1882 if (function.getParamCount() != 2) {
1883 error(loc, "sampler-constructor requires two arguments", token, "");
1887 // For now, not allowing arrayed constructors, the rest of this function
1888 // is set up to allow them, if this test is removed:
1889 if (function.getType().isArray()) {
1890 error(loc, "sampler-constructor cannot make an array of samplers", token, "");
1895 // * the constructor's first argument must be a texture type
1896 // * the dimensionality (1D, 2D, 3D, Cube, Rect, Buffer, MS, and Array)
1897 // of the texture type must match that of the constructed sampler type
1898 // (that is, the suffixes of the type of the first argument and the
1899 // type of the constructor will be spelled the same way)
1900 if (function[0].type->getBasicType() != EbtSampler ||
1901 ! function[0].type->getSampler().isTexture() ||
1902 function[0].type->isArray()) {
1903 error(loc, "sampler-constructor first argument must be a scalar textureXXX type", token, "");
1906 // simulate the first argument's impact on the result type, so it can be compared with the encapsulated operator!=()
1907 TSampler texture = function.getType().getSampler();
1908 texture.combined = false;
1909 texture.shadow = false;
1910 if (texture != function[0].type->getSampler()) {
1911 error(loc, "sampler-constructor first argument must match type and dimensionality of constructor type", token, "");
1916 // * the constructor's second argument must be a scalar of type
1917 // *sampler* or *samplerShadow*
1918 // * the presence or absence of depth comparison (Shadow) must match
1919 // between the constructed sampler type and the type of the second argument
1920 if (function[1].type->getBasicType() != EbtSampler ||
1921 ! function[1].type->getSampler().isPureSampler() ||
1922 function[1].type->isArray()) {
1923 error(loc, "sampler-constructor second argument must be a scalar type 'sampler'", token, "");
1926 if (function.getType().getSampler().shadow != function[1].type->getSampler().shadow) {
1927 error(loc, "sampler-constructor second argument presence of shadow must match constructor presence of shadow", token, "");
1934 // Checks to see if a void variable has been declared and raise an error message for such a case
1936 // returns true in case of an error
1938 bool HlslParseContext::voidErrorCheck(const TSourceLoc& loc, const TString& identifier, const TBasicType basicType)
1940 if (basicType == EbtVoid) {
1941 error(loc, "illegal use of type 'void'", identifier.c_str(), "");
1948 // Checks to see if the node (for the expression) contains a scalar boolean expression or not
1949 void HlslParseContext::boolCheck(const TSourceLoc& loc, const TIntermTyped* type)
1951 if (type->getBasicType() != EbtBool || type->isArray() || type->isMatrix() || type->isVector())
1952 error(loc, "boolean expression expected", "", "");
1956 // Fix just a full qualifier (no variables or types yet, but qualifier is complete) at global level.
1958 void HlslParseContext::globalQualifierFix(const TSourceLoc& loc, TQualifier& qualifier)
1960 // move from parameter/unknown qualifiers to pipeline in/out qualifiers
1961 switch (qualifier.storage) {
1963 qualifier.storage = EvqVaryingIn;
1966 qualifier.storage = EvqVaryingOut;
1974 // Merge characteristics of the 'src' qualifier into the 'dst'.
1975 // If there is duplication, issue error messages, unless 'force'
1976 // is specified, which means to just override default settings.
1978 // Also, when force is false, it will be assumed that 'src' follows
1979 // 'dst', for the purpose of error checking order for versions
1980 // that require specific orderings of qualifiers.
1982 void HlslParseContext::mergeQualifiers(const TSourceLoc& loc, TQualifier& dst, const TQualifier& src, bool force)
1984 // Storage qualification
1985 if (dst.storage == EvqTemporary || dst.storage == EvqGlobal)
1986 dst.storage = src.storage;
1987 else if ((dst.storage == EvqIn && src.storage == EvqOut) ||
1988 (dst.storage == EvqOut && src.storage == EvqIn))
1989 dst.storage = EvqInOut;
1990 else if ((dst.storage == EvqIn && src.storage == EvqConst) ||
1991 (dst.storage == EvqConst && src.storage == EvqIn))
1992 dst.storage = EvqConstReadOnly;
1993 else if (src.storage != EvqTemporary && src.storage != EvqGlobal)
1994 error(loc, "too many storage qualifiers", GetStorageQualifierString(src.storage), "");
1996 // Precision qualifiers
1997 if (dst.precision == EpqNone || (force && src.precision != EpqNone))
1998 dst.precision = src.precision;
2000 // Layout qualifiers
2001 mergeObjectLayoutQualifiers(dst, src, false);
2003 // individual qualifiers
2004 bool repeated = false;
2005 #define MERGE_SINGLETON(field) repeated |= dst.field && src.field; dst.field |= src.field;
2006 MERGE_SINGLETON(invariant);
2007 MERGE_SINGLETON(noContraction);
2008 MERGE_SINGLETON(centroid);
2009 MERGE_SINGLETON(smooth);
2010 MERGE_SINGLETON(flat);
2011 MERGE_SINGLETON(nopersp);
2012 MERGE_SINGLETON(patch);
2013 MERGE_SINGLETON(sample);
2014 MERGE_SINGLETON(coherent);
2015 MERGE_SINGLETON(volatil);
2016 MERGE_SINGLETON(restrict);
2017 MERGE_SINGLETON(readonly);
2018 MERGE_SINGLETON(writeonly);
2019 MERGE_SINGLETON(specConstant);
2022 // used to flatten the sampler type space into a single dimension
2023 // correlates with the declaration of defaultSamplerPrecision[]
2024 int HlslParseContext::computeSamplerTypeIndex(TSampler& sampler)
2026 int arrayIndex = sampler.arrayed ? 1 : 0;
2027 int shadowIndex = sampler.shadow ? 1 : 0;
2028 int externalIndex = sampler.external ? 1 : 0;
2030 return EsdNumDims * (EbtNumTypes * (2 * (2 * arrayIndex + shadowIndex) + externalIndex) + sampler.type) + sampler.dim;
2034 // Do size checking for an array type's size.
2036 void HlslParseContext::arraySizeCheck(const TSourceLoc& loc, TIntermTyped* expr, TArraySize& sizePair)
2038 bool isConst = false;
2040 sizePair.node = nullptr;
2042 TIntermConstantUnion* constant = expr->getAsConstantUnion();
2044 // handle true (non-specialization) constant
2045 sizePair.size = constant->getConstArray()[0].getIConst();
2048 // see if it's a specialization constant instead
2049 if (expr->getQualifier().isSpecConstant()) {
2051 sizePair.node = expr;
2052 TIntermSymbol* symbol = expr->getAsSymbolNode();
2053 if (symbol && symbol->getConstArray().size() > 0)
2054 sizePair.size = symbol->getConstArray()[0].getIConst();
2058 if (! isConst || (expr->getBasicType() != EbtInt && expr->getBasicType() != EbtUint)) {
2059 error(loc, "array size must be a constant integer expression", "", "");
2063 if (sizePair.size <= 0) {
2064 error(loc, "array size must be a positive integer", "", "");
2070 // Require array to be completely sized
2072 void HlslParseContext::arraySizeRequiredCheck(const TSourceLoc& loc, const TArraySizes& arraySizes)
2074 if (arraySizes.isImplicit())
2075 error(loc, "array size required", "", "");
2078 void HlslParseContext::structArrayCheck(const TSourceLoc& /*loc*/, const TType& type)
2080 const TTypeList& structure = *type.getStruct();
2081 for (int m = 0; m < (int)structure.size(); ++m) {
2082 const TType& member = *structure[m].type;
2083 if (member.isArray())
2084 arraySizeRequiredCheck(structure[m].loc, *member.getArraySizes());
2088 // Merge array dimensions listed in 'sizes' onto the type's array dimensions.
2090 // From the spec: "vec4[2] a[3]; // size-3 array of size-2 array of vec4"
2092 // That means, the 'sizes' go in front of the 'type' as outermost sizes.
2093 // 'type' is the type part of the declaration (to the left)
2094 // 'sizes' is the arrayness tagged on the identifier (to the right)
2096 void HlslParseContext::arrayDimMerge(TType& type, const TArraySizes* sizes)
2099 type.addArrayOuterSizes(*sizes);
2103 // Do all the semantic checking for declaring or redeclaring an array, with and
2104 // without a size, and make the right changes to the symbol table.
2106 void HlslParseContext::declareArray(const TSourceLoc& loc, TString& identifier, const TType& type, TSymbol*& symbol, bool& newDeclaration)
2110 symbol = symbolTable.find(identifier, nullptr, ¤tScope);
2112 if (symbol && builtInName(identifier) && ! symbolTable.atBuiltInLevel()) {
2113 // bad shader (errors already reported) trying to redeclare a built-in name as an array
2116 if (symbol == nullptr || ! currentScope) {
2118 // Successfully process a new definition.
2119 // (Redeclarations have to take place at the same scope; otherwise they are hiding declarations)
2121 symbol = new TVariable(&identifier, type);
2122 symbolTable.insert(*symbol);
2123 newDeclaration = true;
2125 if (! symbolTable.atBuiltInLevel()) {
2126 if (isIoResizeArray(type)) {
2127 ioArraySymbolResizeList.push_back(symbol);
2128 checkIoArraysConsistency(loc, true);
2130 fixIoArraySize(loc, symbol->getWritableType());
2135 if (symbol->getAsAnonMember()) {
2136 error(loc, "cannot redeclare a user-block member array", identifier.c_str(), "");
2143 // Process a redeclaration.
2147 error(loc, "array variable name expected", identifier.c_str(), "");
2151 // redeclareBuiltinVariable() should have already done the copyUp()
2152 TType& existingType = symbol->getWritableType();
2155 if (existingType.isExplicitlySizedArray()) {
2156 // be more lenient for input arrays to geometry shaders and tessellation control outputs, where the redeclaration is the same size
2157 if (! (isIoResizeArray(type) && existingType.getOuterArraySize() == type.getOuterArraySize()))
2158 error(loc, "redeclaration of array with size", identifier.c_str(), "");
2162 existingType.updateArraySizes(type);
2164 if (isIoResizeArray(type))
2165 checkIoArraysConsistency(loc);
2168 void HlslParseContext::updateImplicitArraySize(const TSourceLoc& loc, TIntermNode *node, int index)
2170 // maybe there is nothing to do...
2171 TIntermTyped* typedNode = node->getAsTyped();
2172 if (typedNode->getType().getImplicitArraySize() > index)
2175 // something to do...
2177 // Figure out what symbol to lookup, as we will use its type to edit for the size change,
2178 // as that type will be shared through shallow copies for future references.
2179 TSymbol* symbol = nullptr;
2180 int blockIndex = -1;
2181 const TString* lookupName = nullptr;
2182 if (node->getAsSymbolNode())
2183 lookupName = &node->getAsSymbolNode()->getName();
2184 else if (node->getAsBinaryNode()) {
2185 const TIntermBinary* deref = node->getAsBinaryNode();
2186 // This has to be the result of a block dereference, unless it's bad shader code
2187 // If it's a uniform block, then an error will be issued elsewhere, but
2188 // return early now to avoid crashing later in this function.
2189 if (! deref->getLeft()->getAsSymbolNode() || deref->getLeft()->getBasicType() != EbtBlock ||
2190 deref->getLeft()->getType().getQualifier().storage == EvqUniform ||
2191 deref->getRight()->getAsConstantUnion() == nullptr)
2194 blockIndex = deref->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
2196 lookupName = &deref->getLeft()->getAsSymbolNode()->getName();
2197 if (IsAnonymous(*lookupName))
2198 lookupName = &(*deref->getLeft()->getType().getStruct())[blockIndex].type->getFieldName();
2201 // Lookup the symbol, should only fail if shader code is incorrect
2202 symbol = symbolTable.find(*lookupName);
2203 if (symbol == nullptr)
2206 if (symbol->getAsFunction()) {
2207 error(loc, "array variable name expected", symbol->getName().c_str(), "");
2211 symbol->getWritableType().setImplicitArraySize(index + 1);
2215 // See if the identifier is a built-in symbol that can be redeclared, and if so,
2216 // copy the symbol table's read-only built-in variable to the current
2217 // global level, where it can be modified based on the passed in type.
2219 // Returns nullptr if no redeclaration took place; meaning a normal declaration still
2220 // needs to occur for it, not necessarily an error.
2222 // Returns a redeclared and type-modified variable if a redeclared occurred.
2224 TSymbol* HlslParseContext::redeclareBuiltinVariable(const TSourceLoc& loc, const TString& identifier, const TQualifier& qualifier, const TShaderQualifiers& publicType, bool& newDeclaration)
2226 if (! builtInName(identifier) || symbolTable.atBuiltInLevel() || ! symbolTable.atGlobalLevel())
2233 // Either redeclare the requested block, or give an error message why it can't be done.
2235 // TODO: functionality: explicitly sizing members of redeclared blocks is not giving them an explicit size
2236 void HlslParseContext::redeclareBuiltinBlock(const TSourceLoc& loc, TTypeList& newTypeList, const TString& blockName, const TString* instanceName, TArraySizes* arraySizes)
2238 // Redeclaring a built-in block...
2240 // Blocks with instance names are easy to find, lookup the instance name,
2241 // Anonymous blocks need to be found via a member.
2245 block = symbolTable.find(*instanceName, &builtIn);
2247 block = symbolTable.find(newTypeList.front().type->getFieldName(), &builtIn);
2249 // If the block was not found, this must be a version/profile/stage
2250 // that doesn't have it, or the instance name is wrong.
2251 const char* errorName = instanceName ? instanceName->c_str() : newTypeList.front().type->getFieldName().c_str();
2253 error(loc, "no declaration found for redeclaration", errorName, "");
2256 // Built-in blocks cannot be redeclared more than once, which if happened,
2257 // we'd be finding the already redeclared one here, rather than the built in.
2259 error(loc, "can only redeclare a built-in block once, and before any use", blockName.c_str(), "");
2263 // Copy the block to make a writable version, to insert into the block table after editing.
2264 block = symbolTable.copyUpDeferredInsert(block);
2266 if (block->getType().getBasicType() != EbtBlock) {
2267 error(loc, "cannot redeclare a non block as a block", errorName, "");
2271 // Edit and error check the container against the redeclaration
2272 // - remove unused members
2273 // - ensure remaining qualifiers/types match
2274 TType& type = block->getWritableType();
2275 TTypeList::iterator member = type.getWritableStruct()->begin();
2276 size_t numOriginalMembersFound = 0;
2277 while (member != type.getStruct()->end()) {
2280 TTypeList::const_iterator newMember;
2281 TSourceLoc memberLoc;
2283 for (newMember = newTypeList.begin(); newMember != newTypeList.end(); ++newMember) {
2284 if (member->type->getFieldName() == newMember->type->getFieldName()) {
2286 memberLoc = newMember->loc;
2292 ++numOriginalMembersFound;
2293 // - ensure match between redeclared members' types
2294 // - check for things that can't be changed
2295 // - update things that can be changed
2296 TType& oldType = *member->type;
2297 const TType& newType = *newMember->type;
2298 if (! newType.sameElementType(oldType))
2299 error(memberLoc, "cannot redeclare block member with a different type", member->type->getFieldName().c_str(), "");
2300 if (oldType.isArray() != newType.isArray())
2301 error(memberLoc, "cannot change arrayness of redeclared block member", member->type->getFieldName().c_str(), "");
2302 else if (! oldType.sameArrayness(newType) && oldType.isExplicitlySizedArray())
2303 error(memberLoc, "cannot change array size of redeclared block member", member->type->getFieldName().c_str(), "");
2304 if (newType.getQualifier().isMemory())
2305 error(memberLoc, "cannot add memory qualifier to redeclared block member", member->type->getFieldName().c_str(), "");
2306 if (newType.getQualifier().hasLayout())
2307 error(memberLoc, "cannot add layout to redeclared block member", member->type->getFieldName().c_str(), "");
2308 if (newType.getQualifier().patch)
2309 error(memberLoc, "cannot add patch to redeclared block member", member->type->getFieldName().c_str(), "");
2310 oldType.getQualifier().centroid = newType.getQualifier().centroid;
2311 oldType.getQualifier().sample = newType.getQualifier().sample;
2312 oldType.getQualifier().invariant = newType.getQualifier().invariant;
2313 oldType.getQualifier().noContraction = newType.getQualifier().noContraction;
2314 oldType.getQualifier().smooth = newType.getQualifier().smooth;
2315 oldType.getQualifier().flat = newType.getQualifier().flat;
2316 oldType.getQualifier().nopersp = newType.getQualifier().nopersp;
2318 // go to next member
2321 // For missing members of anonymous blocks that have been redeclared,
2322 // hide the original (shared) declaration.
2323 // Instance-named blocks can just have the member removed.
2325 member = type.getWritableStruct()->erase(member);
2327 member->type->hideMember();
2333 if (numOriginalMembersFound < newTypeList.size())
2334 error(loc, "block redeclaration has extra members", blockName.c_str(), "");
2335 if (type.isArray() != (arraySizes != nullptr))
2336 error(loc, "cannot change arrayness of redeclared block", blockName.c_str(), "");
2337 else if (type.isArray()) {
2338 if (type.isExplicitlySizedArray() && arraySizes->getOuterSize() == UnsizedArraySize)
2339 error(loc, "block already declared with size, can't redeclare as implicitly-sized", blockName.c_str(), "");
2340 else if (type.isExplicitlySizedArray() && type.getArraySizes() != *arraySizes)
2341 error(loc, "cannot change array size of redeclared block", blockName.c_str(), "");
2342 else if (type.isImplicitlySizedArray() && arraySizes->getOuterSize() != UnsizedArraySize)
2343 type.changeOuterArraySize(arraySizes->getOuterSize());
2346 symbolTable.insert(*block);
2348 // Tracking for implicit sizing of array
2349 if (isIoResizeArray(block->getType())) {
2350 ioArraySymbolResizeList.push_back(block);
2351 checkIoArraysConsistency(loc, true);
2352 } else if (block->getType().isArray())
2353 fixIoArraySize(loc, block->getWritableType());
2355 // Save it in the AST for linker use.
2356 intermediate.addSymbolLinkageNode(linkage, *block);
2359 void HlslParseContext::paramCheckFix(const TSourceLoc& loc, const TStorageQualifier& qualifier, TType& type)
2361 switch (qualifier) {
2363 case EvqConstReadOnly:
2364 type.getQualifier().storage = EvqConstReadOnly;
2369 type.getQualifier().storage = qualifier;
2373 type.getQualifier().storage = EvqIn;
2376 type.getQualifier().storage = EvqIn;
2377 error(loc, "storage qualifier not allowed on function parameter", GetStorageQualifierString(qualifier), "");
2382 void HlslParseContext::paramCheckFix(const TSourceLoc& loc, const TQualifier& qualifier, TType& type)
2384 if (qualifier.isMemory()) {
2385 type.getQualifier().volatil = qualifier.volatil;
2386 type.getQualifier().coherent = qualifier.coherent;
2387 type.getQualifier().readonly = qualifier.readonly;
2388 type.getQualifier().writeonly = qualifier.writeonly;
2389 type.getQualifier().restrict = qualifier.restrict;
2392 paramCheckFix(loc, qualifier.storage, type);
2395 void HlslParseContext::specializationCheck(const TSourceLoc& loc, const TType& type, const char* op)
2397 if (type.containsSpecializationSize())
2398 error(loc, "can't use with types containing arrays sized with a specialization constant", op, "");
2402 // Layout qualifier stuff.
2405 // Put the id's layout qualification into the public type, for qualifiers not having a number set.
2406 // This is before we know any type information for error checking.
2407 void HlslParseContext::setLayoutQualifier(const TSourceLoc& loc, TPublicType& publicType, TString& id)
2409 std::transform(id.begin(), id.end(), id.begin(), ::tolower);
2411 if (id == TQualifier::getLayoutMatrixString(ElmColumnMajor)) {
2412 publicType.qualifier.layoutMatrix = ElmColumnMajor;
2415 if (id == TQualifier::getLayoutMatrixString(ElmRowMajor)) {
2416 publicType.qualifier.layoutMatrix = ElmRowMajor;
2419 if (id == TQualifier::getLayoutPackingString(ElpPacked)) {
2421 vulkanRemoved(loc, "packed");
2422 publicType.qualifier.layoutPacking = ElpPacked;
2425 if (id == TQualifier::getLayoutPackingString(ElpShared)) {
2427 vulkanRemoved(loc, "shared");
2428 publicType.qualifier.layoutPacking = ElpShared;
2431 if (id == "push_constant") {
2432 requireVulkan(loc, "push_constant");
2433 publicType.qualifier.layoutPushConstant = true;
2436 if (language == EShLangGeometry || language == EShLangTessEvaluation) {
2437 if (id == TQualifier::getGeometryString(ElgTriangles)) {
2438 publicType.shaderQualifiers.geometry = ElgTriangles;
2441 if (language == EShLangGeometry) {
2442 if (id == TQualifier::getGeometryString(ElgPoints)) {
2443 publicType.shaderQualifiers.geometry = ElgPoints;
2446 if (id == TQualifier::getGeometryString(ElgLineStrip)) {
2447 publicType.shaderQualifiers.geometry = ElgLineStrip;
2450 if (id == TQualifier::getGeometryString(ElgLines)) {
2451 publicType.shaderQualifiers.geometry = ElgLines;
2454 if (id == TQualifier::getGeometryString(ElgLinesAdjacency)) {
2455 publicType.shaderQualifiers.geometry = ElgLinesAdjacency;
2458 if (id == TQualifier::getGeometryString(ElgTrianglesAdjacency)) {
2459 publicType.shaderQualifiers.geometry = ElgTrianglesAdjacency;
2462 if (id == TQualifier::getGeometryString(ElgTriangleStrip)) {
2463 publicType.shaderQualifiers.geometry = ElgTriangleStrip;
2467 assert(language == EShLangTessEvaluation);
2470 if (id == TQualifier::getGeometryString(ElgTriangles)) {
2471 publicType.shaderQualifiers.geometry = ElgTriangles;
2474 if (id == TQualifier::getGeometryString(ElgQuads)) {
2475 publicType.shaderQualifiers.geometry = ElgQuads;
2478 if (id == TQualifier::getGeometryString(ElgIsolines)) {
2479 publicType.shaderQualifiers.geometry = ElgIsolines;
2484 if (id == TQualifier::getVertexSpacingString(EvsEqual)) {
2485 publicType.shaderQualifiers.spacing = EvsEqual;
2488 if (id == TQualifier::getVertexSpacingString(EvsFractionalEven)) {
2489 publicType.shaderQualifiers.spacing = EvsFractionalEven;
2492 if (id == TQualifier::getVertexSpacingString(EvsFractionalOdd)) {
2493 publicType.shaderQualifiers.spacing = EvsFractionalOdd;
2498 if (id == TQualifier::getVertexOrderString(EvoCw)) {
2499 publicType.shaderQualifiers.order = EvoCw;
2502 if (id == TQualifier::getVertexOrderString(EvoCcw)) {
2503 publicType.shaderQualifiers.order = EvoCcw;
2508 if (id == "point_mode") {
2509 publicType.shaderQualifiers.pointMode = true;
2514 if (language == EShLangFragment) {
2515 if (id == "origin_upper_left") {
2516 publicType.shaderQualifiers.originUpperLeft = true;
2519 if (id == "pixel_center_integer") {
2520 publicType.shaderQualifiers.pixelCenterInteger = true;
2523 if (id == "early_fragment_tests") {
2524 publicType.shaderQualifiers.earlyFragmentTests = true;
2527 for (TLayoutDepth depth = (TLayoutDepth)(EldNone + 1); depth < EldCount; depth = (TLayoutDepth)(depth + 1)) {
2528 if (id == TQualifier::getLayoutDepthString(depth)) {
2529 publicType.shaderQualifiers.layoutDepth = depth;
2533 if (id.compare(0, 13, "blend_support") == 0) {
2535 for (TBlendEquationShift be = (TBlendEquationShift)0; be < EBlendCount; be = (TBlendEquationShift)(be + 1)) {
2536 if (id == TQualifier::getBlendEquationString(be)) {
2537 requireExtensions(loc, 1, &E_GL_KHR_blend_equation_advanced, "blend equation");
2538 intermediate.addBlendEquation(be);
2539 publicType.shaderQualifiers.blendEquation = true;
2545 error(loc, "unknown blend equation", "blend_support", "");
2549 error(loc, "unrecognized layout identifier, or qualifier requires assignment (e.g., binding = 4)", id.c_str(), "");
2552 // Put the id's layout qualifier value into the public type, for qualifiers having a number set.
2553 // This is before we know any type information for error checking.
2554 void HlslParseContext::setLayoutQualifier(const TSourceLoc& loc, TPublicType& publicType, TString& id, const TIntermTyped* node)
2556 const char* feature = "layout-id value";
2557 const char* nonLiteralFeature = "non-literal layout-id value";
2559 integerCheck(node, feature);
2560 const TIntermConstantUnion* constUnion = node->getAsConstantUnion();
2563 value = constUnion->getConstArray()[0].getIConst();
2566 std::transform(id.begin(), id.end(), id.begin(), ::tolower);
2568 if (id == "offset") {
2569 publicType.qualifier.layoutOffset = value;
2571 } else if (id == "align") {
2572 // "The specified alignment must be a power of 2, or a compile-time error results."
2573 if (! IsPow2(value))
2574 error(loc, "must be a power of 2", "align", "");
2576 publicType.qualifier.layoutAlign = value;
2578 } else if (id == "location") {
2579 if ((unsigned int)value >= TQualifier::layoutLocationEnd)
2580 error(loc, "location is too large", id.c_str(), "");
2582 publicType.qualifier.layoutLocation = value;
2584 } else if (id == "set") {
2585 if ((unsigned int)value >= TQualifier::layoutSetEnd)
2586 error(loc, "set is too large", id.c_str(), "");
2588 publicType.qualifier.layoutSet = value;
2590 } else if (id == "binding") {
2591 if ((unsigned int)value >= TQualifier::layoutBindingEnd)
2592 error(loc, "binding is too large", id.c_str(), "");
2594 publicType.qualifier.layoutBinding = value;
2596 } else if (id == "component") {
2597 if ((unsigned)value >= TQualifier::layoutComponentEnd)
2598 error(loc, "component is too large", id.c_str(), "");
2600 publicType.qualifier.layoutComponent = value;
2602 } else if (id.compare(0, 4, "xfb_") == 0) {
2603 // "Any shader making any static use (after preprocessing) of any of these
2604 // *xfb_* qualifiers will cause the shader to be in a transform feedback
2605 // capturing mode and hence responsible for describing the transform feedback
2607 intermediate.setXfbMode();
2608 if (id == "xfb_buffer") {
2609 // "It is a compile-time error to specify an *xfb_buffer* that is greater than
2610 // the implementation-dependent constant gl_MaxTransformFeedbackBuffers."
2611 if (value >= resources.maxTransformFeedbackBuffers)
2612 error(loc, "buffer is too large:", id.c_str(), "gl_MaxTransformFeedbackBuffers is %d", resources.maxTransformFeedbackBuffers);
2613 if (value >= (int)TQualifier::layoutXfbBufferEnd)
2614 error(loc, "buffer is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbBufferEnd - 1);
2616 publicType.qualifier.layoutXfbBuffer = value;
2618 } else if (id == "xfb_offset") {
2619 if (value >= (int)TQualifier::layoutXfbOffsetEnd)
2620 error(loc, "offset is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbOffsetEnd - 1);
2622 publicType.qualifier.layoutXfbOffset = value;
2624 } else if (id == "xfb_stride") {
2625 // "The resulting stride (implicit or explicit), when divided by 4, must be less than or equal to the
2626 // implementation-dependent constant gl_MaxTransformFeedbackInterleavedComponents."
2627 if (value > 4 * resources.maxTransformFeedbackInterleavedComponents)
2628 error(loc, "1/4 stride is too large:", id.c_str(), "gl_MaxTransformFeedbackInterleavedComponents is %d", resources.maxTransformFeedbackInterleavedComponents);
2629 else if (value >= (int)TQualifier::layoutXfbStrideEnd)
2630 error(loc, "stride is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbStrideEnd - 1);
2631 if (value < (int)TQualifier::layoutXfbStrideEnd)
2632 publicType.qualifier.layoutXfbStride = value;
2637 if (id == "input_attachment_index") {
2638 requireVulkan(loc, "input_attachment_index");
2639 if (value >= (int)TQualifier::layoutAttachmentEnd)
2640 error(loc, "attachment index is too large", id.c_str(), "");
2642 publicType.qualifier.layoutAttachment = value;
2645 if (id == "constant_id") {
2646 requireSpv(loc, "constant_id");
2647 if (value >= (int)TQualifier::layoutSpecConstantIdEnd) {
2648 error(loc, "specialization-constant id is too large", id.c_str(), "");
2650 publicType.qualifier.layoutSpecConstantId = value;
2651 publicType.qualifier.specConstant = true;
2652 if (! intermediate.addUsedConstantId(value))
2653 error(loc, "specialization-constant id already used", id.c_str(), "");
2662 case EShLangTessControl:
2663 if (id == "vertices") {
2665 error(loc, "must be greater than 0", "vertices", "");
2667 publicType.shaderQualifiers.vertices = value;
2672 case EShLangTessEvaluation:
2675 case EShLangGeometry:
2676 if (id == "invocations") {
2678 error(loc, "must be at least 1", "invocations", "");
2680 publicType.shaderQualifiers.invocations = value;
2683 if (id == "max_vertices") {
2684 publicType.shaderQualifiers.vertices = value;
2685 if (value > resources.maxGeometryOutputVertices)
2686 error(loc, "too large, must be less than gl_MaxGeometryOutputVertices", "max_vertices", "");
2689 if (id == "stream") {
2690 publicType.qualifier.layoutStream = value;
2695 case EShLangFragment:
2696 if (id == "index") {
2697 const char* exts[2] = { E_GL_ARB_separate_shader_objects, E_GL_ARB_explicit_attrib_location };
2698 publicType.qualifier.layoutIndex = value;
2703 case EShLangCompute:
2704 if (id.compare(0, 11, "local_size_") == 0) {
2705 if (id == "local_size_x") {
2706 publicType.shaderQualifiers.localSize[0] = value;
2709 if (id == "local_size_y") {
2710 publicType.shaderQualifiers.localSize[1] = value;
2713 if (id == "local_size_z") {
2714 publicType.shaderQualifiers.localSize[2] = value;
2718 if (id == "local_size_x_id") {
2719 publicType.shaderQualifiers.localSizeSpecId[0] = value;
2722 if (id == "local_size_y_id") {
2723 publicType.shaderQualifiers.localSizeSpecId[1] = value;
2726 if (id == "local_size_z_id") {
2727 publicType.shaderQualifiers.localSizeSpecId[2] = value;
2738 error(loc, "there is no such layout identifier for this stage taking an assigned value", id.c_str(), "");
2741 // Merge any layout qualifier information from src into dst, leaving everything else in dst alone
2743 // "More than one layout qualifier may appear in a single declaration.
2744 // Additionally, the same layout-qualifier-name can occur multiple times
2745 // within a layout qualifier or across multiple layout qualifiers in the
2746 // same declaration. When the same layout-qualifier-name occurs
2747 // multiple times, in a single declaration, the last occurrence overrides
2748 // the former occurrence(s). Further, if such a layout-qualifier-name
2749 // will effect subsequent declarations or other observable behavior, it
2750 // is only the last occurrence that will have any effect, behaving as if
2751 // the earlier occurrence(s) within the declaration are not present.
2752 // This is also true for overriding layout-qualifier-names, where one
2753 // overrides the other (e.g., row_major vs. column_major); only the last
2754 // occurrence has any effect."
2756 void HlslParseContext::mergeObjectLayoutQualifiers(TQualifier& dst, const TQualifier& src, bool inheritOnly)
2758 if (src.hasMatrix())
2759 dst.layoutMatrix = src.layoutMatrix;
2760 if (src.hasPacking())
2761 dst.layoutPacking = src.layoutPacking;
2763 if (src.hasStream())
2764 dst.layoutStream = src.layoutStream;
2766 if (src.hasFormat())
2767 dst.layoutFormat = src.layoutFormat;
2769 if (src.hasXfbBuffer())
2770 dst.layoutXfbBuffer = src.layoutXfbBuffer;
2773 dst.layoutAlign = src.layoutAlign;
2775 if (! inheritOnly) {
2776 if (src.hasLocation())
2777 dst.layoutLocation = src.layoutLocation;
2778 if (src.hasComponent())
2779 dst.layoutComponent = src.layoutComponent;
2781 dst.layoutIndex = src.layoutIndex;
2783 if (src.hasOffset())
2784 dst.layoutOffset = src.layoutOffset;
2787 dst.layoutSet = src.layoutSet;
2788 if (src.layoutBinding != TQualifier::layoutBindingEnd)
2789 dst.layoutBinding = src.layoutBinding;
2791 if (src.hasXfbStride())
2792 dst.layoutXfbStride = src.layoutXfbStride;
2793 if (src.hasXfbOffset())
2794 dst.layoutXfbOffset = src.layoutXfbOffset;
2795 if (src.hasAttachment())
2796 dst.layoutAttachment = src.layoutAttachment;
2797 if (src.hasSpecConstantId())
2798 dst.layoutSpecConstantId = src.layoutSpecConstantId;
2800 if (src.layoutPushConstant)
2801 dst.layoutPushConstant = true;
2806 // Look up a function name in the symbol table, and make sure it is a function.
2808 // Return the function symbol if found, otherwise nullptr.
2810 const TFunction* HlslParseContext::findFunction(const TSourceLoc& loc, const TFunction& call, bool& builtIn)
2812 const TFunction* function = nullptr;
2814 if (symbolTable.isFunctionNameVariable(call.getName())) {
2815 error(loc, "can't use function syntax on variable", call.getName().c_str(), "");
2819 // first, look for an exact match
2820 TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn);
2822 return symbol->getAsFunction();
2824 // exact match not found, look through a list of overloaded functions of the same name
2826 const TFunction* candidate = nullptr;
2827 TVector<TFunction*> candidateList;
2828 symbolTable.findFunctionNameList(call.getMangledName(), candidateList, builtIn);
2830 for (TVector<TFunction*>::const_iterator it = candidateList.begin(); it != candidateList.end(); ++it) {
2831 const TFunction& function = *(*it);
2833 // to even be a potential match, number of arguments has to match
2834 if (call.getParamCount() != function.getParamCount())
2837 bool possibleMatch = true;
2838 for (int i = 0; i < function.getParamCount(); ++i) {
2839 // same types is easy
2840 if (*function[i].type == *call[i].type)
2843 // We have a mismatch in type, see if it is implicitly convertible
2845 if (function[i].type->isArray() || call[i].type->isArray() ||
2846 ! function[i].type->sameElementShape(*call[i].type))
2847 possibleMatch = false;
2849 // do direction-specific checks for conversion of basic type
2850 if (function[i].type->getQualifier().isParamInput()) {
2851 if (! intermediate.canImplicitlyPromote(call[i].type->getBasicType(), function[i].type->getBasicType()))
2852 possibleMatch = false;
2854 if (function[i].type->getQualifier().isParamOutput()) {
2855 if (! intermediate.canImplicitlyPromote(function[i].type->getBasicType(), call[i].type->getBasicType()))
2856 possibleMatch = false;
2859 if (! possibleMatch)
2862 if (possibleMatch) {
2864 // our second match, meaning ambiguity
2865 error(loc, "ambiguous function signature match: multiple signatures match under implicit type conversion", call.getName().c_str(), "");
2867 candidate = &function;
2871 if (candidate == nullptr)
2872 error(loc, "no matching overloaded function found", call.getName().c_str(), "");
2878 // Do everything necessary to handle a variable (non-block) declaration.
2879 // Either redeclaring a variable, or making a new one, updating the symbol
2880 // table, and all error checking.
2882 // Returns a subtree node that computes an initializer, if needed.
2883 // Returns nullptr if there is no code to execute for initialization.
2885 // 'publicType' is the type part of the declaration (to the left)
2886 // 'arraySizes' is the arrayness tagged on the identifier (to the right)
2888 TIntermNode* HlslParseContext::declareVariable(const TSourceLoc& loc, TString& identifier, const TType& parseType, TArraySizes* arraySizes, TIntermTyped* initializer)
2891 type.shallowCopy(parseType);
2892 if (type.isImplicitlySizedArray()) {
2893 // Because "int[] a = int[2](...), b = int[3](...)" makes two arrays a and b
2894 // of different sizes, for this case sharing the shallow copy of arrayness
2895 // with the publicType oversubscribes it, so get a deep copy of the arrayness.
2896 type.newArraySizes(*parseType.getArraySizes());
2899 if (voidErrorCheck(loc, identifier, type.getBasicType()))
2902 // Check for redeclaration of built-ins and/or attempting to declare a reserved name
2903 bool newDeclaration = false; // true if a new entry gets added to the symbol table
2904 TSymbol* symbol = nullptr; // = redeclareBuiltinVariable(loc, identifier, type.getQualifier(), publicType.shaderQualifiers, newDeclaration);
2906 inheritGlobalDefaults(type.getQualifier());
2908 // Declare the variable
2909 if (arraySizes || type.isArray()) {
2910 // Arrayness is potentially coming both from the type and from the
2911 // variable: "int[] a[];" or just one or the other.
2912 // Merge it all to the type, so all arrayness is part of the type.
2913 arrayDimMerge(type, arraySizes);
2914 declareArray(loc, identifier, type, symbol, newDeclaration);
2918 symbol = declareNonArray(loc, identifier, type, newDeclaration);
2919 else if (type != symbol->getType())
2920 error(loc, "cannot change the type of", "redeclaration", symbol->getName().c_str());
2926 // Deal with initializer
2927 TIntermNode* initNode = nullptr;
2928 if (symbol && initializer) {
2929 TVariable* variable = symbol->getAsVariable();
2931 error(loc, "initializer requires a variable, not a member", identifier.c_str(), "");
2934 initNode = executeInitializer(loc, initializer, variable);
2937 // see if it's a linker-level object to track
2938 if (newDeclaration && symbolTable.atGlobalLevel())
2939 intermediate.addSymbolLinkageNode(linkage, *symbol);
2944 // Pick up global defaults from the provide global defaults into dst.
2945 void HlslParseContext::inheritGlobalDefaults(TQualifier& dst) const
2947 if (dst.storage == EvqVaryingOut) {
2948 if (! dst.hasStream() && language == EShLangGeometry)
2949 dst.layoutStream = globalOutputDefaults.layoutStream;
2950 if (! dst.hasXfbBuffer())
2951 dst.layoutXfbBuffer = globalOutputDefaults.layoutXfbBuffer;
2956 // Make an internal-only variable whose name is for debug purposes only
2957 // and won't be searched for. Callers will only use the return value to use
2958 // the variable, not the name to look it up. It is okay if the name
2959 // is the same as other names; there won't be any conflict.
2961 TVariable* HlslParseContext::makeInternalVariable(const char* name, const TType& type) const
2963 TString* nameString = new TString(name);
2964 TVariable* variable = new TVariable(nameString, type);
2965 symbolTable.makeInternalVariable(*variable);
2971 // Declare a non-array variable, the main point being there is no redeclaration
2972 // for resizing allowed.
2974 // Return the successfully declared variable.
2976 TVariable* HlslParseContext::declareNonArray(const TSourceLoc& loc, TString& identifier, TType& type, bool& newDeclaration)
2978 // make a new variable
2979 TVariable* variable = new TVariable(&identifier, type);
2981 // add variable to symbol table
2982 if (! symbolTable.insert(*variable)) {
2983 error(loc, "redefinition", variable->getName().c_str(), "");
2986 newDeclaration = true;
2992 // Handle all types of initializers from the grammar.
2994 // Returning nullptr just means there is no code to execute to handle the
2995 // initializer, which will, for example, be the case for constant initializers.
2997 TIntermNode* HlslParseContext::executeInitializer(const TSourceLoc& loc, TIntermTyped* initializer, TVariable* variable)
3000 // Identifier must be of type constant, a global, or a temporary, and
3001 // starting at version 120, desktop allows uniforms to have initializers.
3003 TStorageQualifier qualifier = variable->getType().getQualifier().storage;
3006 // If the initializer was from braces { ... }, we convert the whole subtree to a
3007 // constructor-style subtree, allowing the rest of the code to operate
3008 // identically for both kinds of initializers.
3010 initializer = convertInitializerList(loc, variable->getType(), initializer);
3011 if (! initializer) {
3012 // error recovery; don't leave const without constant values
3013 if (qualifier == EvqConst)
3014 variable->getWritableType().getQualifier().storage = EvqTemporary;
3018 // Fix outer arrayness if variable is unsized, getting size from the initializer
3019 if (initializer->getType().isExplicitlySizedArray() &&
3020 variable->getType().isImplicitlySizedArray())
3021 variable->getWritableType().changeOuterArraySize(initializer->getType().getOuterArraySize());
3023 // Inner arrayness can also get set by an initializer
3024 if (initializer->getType().isArrayOfArrays() && variable->getType().isArrayOfArrays() &&
3025 initializer->getType().getArraySizes()->getNumDims() ==
3026 variable->getType().getArraySizes()->getNumDims()) {
3027 // adopt unsized sizes from the initializer's sizes
3028 for (int d = 1; d < variable->getType().getArraySizes()->getNumDims(); ++d) {
3029 if (variable->getType().getArraySizes()->getDimSize(d) == UnsizedArraySize)
3030 variable->getWritableType().getArraySizes().setDimSize(d, initializer->getType().getArraySizes()->getDimSize(d));
3034 // Uniform and global consts require a constant initializer
3035 if (qualifier == EvqUniform && initializer->getType().getQualifier().storage != EvqConst) {
3036 error(loc, "uniform initializers must be constant", "=", "'%s'", variable->getType().getCompleteString().c_str());
3037 variable->getWritableType().getQualifier().storage = EvqTemporary;
3040 if (qualifier == EvqConst && symbolTable.atGlobalLevel() && initializer->getType().getQualifier().storage != EvqConst) {
3041 error(loc, "global const initializers must be constant", "=", "'%s'", variable->getType().getCompleteString().c_str());
3042 variable->getWritableType().getQualifier().storage = EvqTemporary;
3046 // Const variables require a constant initializer, depending on version
3047 if (qualifier == EvqConst) {
3048 if (initializer->getType().getQualifier().storage != EvqConst) {
3049 variable->getWritableType().getQualifier().storage = EvqConstReadOnly;
3050 qualifier = EvqConstReadOnly;
3054 if (qualifier == EvqConst || qualifier == EvqUniform) {
3055 // Compile-time tagging of the variable with its constant value...
3057 initializer = intermediate.addConversion(EOpAssign, variable->getType(), initializer);
3058 if (! initializer || ! initializer->getAsConstantUnion() || variable->getType() != initializer->getType()) {
3059 error(loc, "non-matching or non-convertible constant type for const initializer",
3060 variable->getType().getStorageQualifierString(), "");
3061 variable->getWritableType().getQualifier().storage = EvqTemporary;
3065 variable->setConstArray(initializer->getAsConstantUnion()->getConstArray());
3067 // normal assigning of a value to a variable...
3068 specializationCheck(loc, initializer->getType(), "initializer");
3069 TIntermSymbol* intermSymbol = intermediate.addSymbol(*variable, loc);
3070 TIntermNode* initNode = intermediate.addAssign(EOpAssign, intermSymbol, initializer, loc);
3072 assignError(loc, "=", intermSymbol->getCompleteString(), initializer->getCompleteString());
3081 // Reprocess any initializer-list { ... } parts of the initializer.
3082 // Need to hierarchically assign correct types and implicit
3083 // conversions. Will do this mimicking the same process used for
3084 // creating a constructor-style initializer, ensuring we get the
3087 TIntermTyped* HlslParseContext::convertInitializerList(const TSourceLoc& loc, const TType& type, TIntermTyped* initializer)
3089 // Will operate recursively. Once a subtree is found that is constructor style,
3090 // everything below it is already good: Only the "top part" of the initializer
3091 // can be an initializer list, where "top part" can extend for several (or all) levels.
3093 // see if we have bottomed out in the tree within the initializer-list part
3094 TIntermAggregate* initList = initializer->getAsAggregate();
3095 if (! initList || initList->getOp() != EOpNull)
3098 // Of the initializer-list set of nodes, need to process bottom up,
3099 // so recurse deep, then process on the way up.
3101 // Go down the tree here...
3102 if (type.isArray()) {
3103 // The type's array might be unsized, which could be okay, so base sizes on the size of the aggregate.
3104 // Later on, initializer execution code will deal with array size logic.
3106 arrayType.shallowCopy(type); // sharing struct stuff is fine
3107 arrayType.newArraySizes(*type.getArraySizes()); // but get a fresh copy of the array information, to edit below
3109 // edit array sizes to fill in unsized dimensions
3110 arrayType.changeOuterArraySize((int)initList->getSequence().size());
3111 TIntermTyped* firstInit = initList->getSequence()[0]->getAsTyped();
3112 if (arrayType.isArrayOfArrays() && firstInit->getType().isArray() &&
3113 arrayType.getArraySizes().getNumDims() == firstInit->getType().getArraySizes()->getNumDims() + 1) {
3114 for (int d = 1; d < arrayType.getArraySizes().getNumDims(); ++d) {
3115 if (arrayType.getArraySizes().getDimSize(d) == UnsizedArraySize)
3116 arrayType.getArraySizes().setDimSize(d, firstInit->getType().getArraySizes()->getDimSize(d - 1));
3120 TType elementType(arrayType, 0); // dereferenced type
3121 for (size_t i = 0; i < initList->getSequence().size(); ++i) {
3122 initList->getSequence()[i] = convertInitializerList(loc, elementType, initList->getSequence()[i]->getAsTyped());
3123 if (initList->getSequence()[i] == nullptr)
3127 return addConstructor(loc, initList, arrayType, mapTypeToConstructorOp(arrayType));
3128 } else if (type.isStruct()) {
3129 if (type.getStruct()->size() != initList->getSequence().size()) {
3130 error(loc, "wrong number of structure members", "initializer list", "");
3133 for (size_t i = 0; i < type.getStruct()->size(); ++i) {
3134 initList->getSequence()[i] = convertInitializerList(loc, *(*type.getStruct())[i].type, initList->getSequence()[i]->getAsTyped());
3135 if (initList->getSequence()[i] == nullptr)
3138 } else if (type.isMatrix()) {
3139 if (type.getMatrixCols() != (int)initList->getSequence().size()) {
3140 error(loc, "wrong number of matrix columns:", "initializer list", type.getCompleteString().c_str());
3143 TType vectorType(type, 0); // dereferenced type
3144 for (int i = 0; i < type.getMatrixCols(); ++i) {
3145 initList->getSequence()[i] = convertInitializerList(loc, vectorType, initList->getSequence()[i]->getAsTyped());
3146 if (initList->getSequence()[i] == nullptr)
3149 } else if (type.isVector()) {
3150 if (type.getVectorSize() != (int)initList->getSequence().size()) {
3151 error(loc, "wrong vector size (or rows in a matrix column):", "initializer list", type.getCompleteString().c_str());
3155 error(loc, "unexpected initializer-list type:", "initializer list", type.getCompleteString().c_str());
3159 // now that the subtree is processed, process this node
3160 return addConstructor(loc, initList, type, mapTypeToConstructorOp(type));
3164 // Test for the correctness of the parameters passed to various constructor functions
3165 // and also convert them to the right data type, if allowed and required.
3167 // Returns nullptr for an error or the constructed node (aggregate or typed) for no error.
3169 TIntermTyped* HlslParseContext::addConstructor(const TSourceLoc& loc, TIntermNode* node, const TType& type, TOperator op)
3171 if (node == nullptr || node->getAsTyped() == nullptr)
3174 TIntermAggregate* aggrNode = node->getAsAggregate();
3176 // Combined texture-sampler constructors are completely semantic checked
3177 // in constructorTextureSamplerError()
3178 if (op == EOpConstructTextureSampler)
3179 return intermediate.setAggregateOperator(aggrNode, op, type, loc);
3181 TTypeList::const_iterator memberTypes;
3182 if (op == EOpConstructStruct)
3183 memberTypes = type.getStruct()->begin();
3186 if (type.isArray()) {
3187 TType dereferenced(type, 0);
3188 elementType.shallowCopy(dereferenced);
3190 elementType.shallowCopy(type);
3194 if (aggrNode->getOp() != EOpNull || aggrNode->getSequence().size() == 1)
3201 TIntermTyped *newNode;
3203 // If structure constructor or array constructor is being called
3204 // for only one parameter inside the structure, we need to call constructAggregate function once.
3206 newNode = constructAggregate(node, elementType, 1, node->getLoc());
3207 else if (op == EOpConstructStruct)
3208 newNode = constructAggregate(node, *(*memberTypes).type, 1, node->getLoc());
3210 newNode = constructBuiltIn(type, op, node->getAsTyped(), node->getLoc(), false);
3212 if (newNode && (type.isArray() || op == EOpConstructStruct))
3213 newNode = intermediate.setAggregateOperator(newNode, EOpConstructStruct, type, loc);
3219 // Handle list of arguments.
3221 TIntermSequence &sequenceVector = aggrNode->getSequence(); // Stores the information about the parameter to the constructor
3222 // if the structure constructor contains more than one parameter, then construct
3225 int paramCount = 0; // keeps a track of the constructor parameter number being checked
3227 // for each parameter to the constructor call, check to see if the right type is passed or convert them
3228 // to the right type if possible (and allowed).
3229 // for structure constructors, just check if the right type is passed, no conversion is allowed.
3231 for (TIntermSequence::iterator p = sequenceVector.begin();
3232 p != sequenceVector.end(); p++, paramCount++) {
3234 newNode = constructAggregate(*p, elementType, paramCount + 1, node->getLoc());
3235 else if (op == EOpConstructStruct)
3236 newNode = constructAggregate(*p, *(memberTypes[paramCount]).type, paramCount + 1, node->getLoc());
3238 newNode = constructBuiltIn(type, op, (*p)->getAsTyped(), node->getLoc(), true);
3246 TIntermTyped* constructor = intermediate.setAggregateOperator(aggrNode, op, type, loc);
3251 // Function for constructor implementation. Calls addUnaryMath with appropriate EOp value
3252 // for the parameter to the constructor (passed to this function). Essentially, it converts
3253 // the parameter types correctly. If a constructor expects an int (like ivec2) and is passed a
3254 // float, then float is converted to int.
3256 // Returns nullptr for an error or the constructed node.
3258 TIntermTyped* HlslParseContext::constructBuiltIn(const TType& type, TOperator op, TIntermTyped* node, const TSourceLoc& loc, bool subset)
3260 TIntermTyped* newNode;
3264 // First, convert types as needed.
3267 case EOpConstructVec2:
3268 case EOpConstructVec3:
3269 case EOpConstructVec4:
3270 case EOpConstructMat2x2:
3271 case EOpConstructMat2x3:
3272 case EOpConstructMat2x4:
3273 case EOpConstructMat3x2:
3274 case EOpConstructMat3x3:
3275 case EOpConstructMat3x4:
3276 case EOpConstructMat4x2:
3277 case EOpConstructMat4x3:
3278 case EOpConstructMat4x4:
3279 case EOpConstructFloat:
3280 basicOp = EOpConstructFloat;
3283 case EOpConstructDVec2:
3284 case EOpConstructDVec3:
3285 case EOpConstructDVec4:
3286 case EOpConstructDMat2x2:
3287 case EOpConstructDMat2x3:
3288 case EOpConstructDMat2x4:
3289 case EOpConstructDMat3x2:
3290 case EOpConstructDMat3x3:
3291 case EOpConstructDMat3x4:
3292 case EOpConstructDMat4x2:
3293 case EOpConstructDMat4x3:
3294 case EOpConstructDMat4x4:
3295 case EOpConstructDouble:
3296 basicOp = EOpConstructDouble;
3299 case EOpConstructIVec2:
3300 case EOpConstructIVec3:
3301 case EOpConstructIVec4:
3302 case EOpConstructInt:
3303 basicOp = EOpConstructInt;
3306 case EOpConstructUVec2:
3307 case EOpConstructUVec3:
3308 case EOpConstructUVec4:
3309 case EOpConstructUint:
3310 basicOp = EOpConstructUint;
3313 case EOpConstructBVec2:
3314 case EOpConstructBVec3:
3315 case EOpConstructBVec4:
3316 case EOpConstructBool:
3317 basicOp = EOpConstructBool;
3321 error(loc, "unsupported construction", "", "");
3325 newNode = intermediate.addUnaryMath(basicOp, node, node->getLoc());
3326 if (newNode == nullptr) {
3327 error(loc, "can't convert", "constructor", "");
3332 // Now, if there still isn't an operation to do the construction, and we need one, add one.
3335 // Otherwise, skip out early.
3336 if (subset || (newNode != node && newNode->getType() == type))
3339 // setAggregateOperator will insert a new node for the constructor, as needed.
3340 return intermediate.setAggregateOperator(newNode, op, type, loc);
3343 // This function tests for the type of the parameters to the structure or array constructor. Raises
3344 // an error message if the expected type does not match the parameter passed to the constructor.
3346 // Returns nullptr for an error or the input node itself if the expected and the given parameter types match.
3348 TIntermTyped* HlslParseContext::constructAggregate(TIntermNode* node, const TType& type, int paramCount, const TSourceLoc& loc)
3350 TIntermTyped* converted = intermediate.addConversion(EOpConstructStruct, type, node->getAsTyped());
3351 if (! converted || converted->getType() != type) {
3352 error(loc, "", "constructor", "cannot convert parameter %d from '%s' to '%s'", paramCount,
3353 node->getAsTyped()->getType().getCompleteString().c_str(), type.getCompleteString().c_str());
3362 // Do everything needed to add an interface block.
3364 void HlslParseContext::declareBlock(const TSourceLoc& loc, TTypeList& typeList, const TString* instanceName, TArraySizes* arraySizes)
3366 // fix and check for member storage qualifiers and types that don't belong within a block
3367 for (unsigned int member = 0; member < typeList.size(); ++member) {
3368 TType& memberType = *typeList[member].type;
3369 TQualifier& memberQualifier = memberType.getQualifier();
3370 const TSourceLoc& memberLoc = typeList[member].loc;
3371 globalQualifierFix(memberLoc, memberQualifier);
3372 memberQualifier.storage = currentBlockQualifier.storage;
3375 // This might be a redeclaration of a built-in block. If so, redeclareBuiltinBlock() will
3377 if (! symbolTable.atBuiltInLevel() && builtInName(*blockName)) {
3378 redeclareBuiltinBlock(loc, typeList, *blockName, instanceName, arraySizes);
3382 // Make default block qualification, and adjust the member qualifications
3384 TQualifier defaultQualification;
3385 switch (currentBlockQualifier.storage) {
3386 case EvqUniform: defaultQualification = globalUniformDefaults; break;
3387 case EvqBuffer: defaultQualification = globalBufferDefaults; break;
3388 case EvqVaryingIn: defaultQualification = globalInputDefaults; break;
3389 case EvqVaryingOut: defaultQualification = globalOutputDefaults; break;
3390 default: defaultQualification.clear(); break;
3393 // Special case for "push_constant uniform", which has a default of std430,
3394 // contrary to normal uniform defaults, and can't have a default tracked for it.
3395 if (currentBlockQualifier.layoutPushConstant && ! currentBlockQualifier.hasPacking())
3396 currentBlockQualifier.layoutPacking = ElpStd430;
3398 // fix and check for member layout qualifiers
3400 mergeObjectLayoutQualifiers(defaultQualification, currentBlockQualifier, true);
3402 bool memberWithLocation = false;
3403 bool memberWithoutLocation = false;
3404 for (unsigned int member = 0; member < typeList.size(); ++member) {
3405 TQualifier& memberQualifier = typeList[member].type->getQualifier();
3406 const TSourceLoc& memberLoc = typeList[member].loc;
3407 if (memberQualifier.hasStream()) {
3408 if (defaultQualification.layoutStream != memberQualifier.layoutStream)
3409 error(memberLoc, "member cannot contradict block", "stream", "");
3412 // "This includes a block's inheritance of the
3413 // current global default buffer, a block member's inheritance of the block's
3414 // buffer, and the requirement that any *xfb_buffer* declared on a block
3415 // member must match the buffer inherited from the block."
3416 if (memberQualifier.hasXfbBuffer()) {
3417 if (defaultQualification.layoutXfbBuffer != memberQualifier.layoutXfbBuffer)
3418 error(memberLoc, "member cannot contradict block (or what block inherited from global)", "xfb_buffer", "");
3421 if (memberQualifier.hasPacking())
3422 error(memberLoc, "member of block cannot have a packing layout qualifier", typeList[member].type->getFieldName().c_str(), "");
3423 if (memberQualifier.hasLocation()) {
3424 switch (currentBlockQualifier.storage) {
3427 memberWithLocation = true;
3433 memberWithoutLocation = true;
3434 if (memberQualifier.hasAlign()) {
3435 if (defaultQualification.layoutPacking != ElpStd140 && defaultQualification.layoutPacking != ElpStd430)
3436 error(memberLoc, "can only be used with std140 or std430 layout packing", "align", "");
3439 TQualifier newMemberQualification = defaultQualification;
3440 mergeQualifiers(memberLoc, newMemberQualification, memberQualifier, false);
3441 memberQualifier = newMemberQualification;
3444 // Process the members
3445 fixBlockLocations(loc, currentBlockQualifier, typeList, memberWithLocation, memberWithoutLocation);
3446 fixBlockXfbOffsets(currentBlockQualifier, typeList);
3447 fixBlockUniformOffsets(currentBlockQualifier, typeList);
3449 // reverse merge, so that currentBlockQualifier now has all layout information
3450 // (can't use defaultQualification directly, it's missing other non-layout-default-class qualifiers)
3451 mergeObjectLayoutQualifiers(currentBlockQualifier, defaultQualification, true);
3454 // Build and add the interface block as a new type named 'blockName'
3457 TType blockType(&typeList, *blockName, currentBlockQualifier);
3459 blockType.newArraySizes(*arraySizes);
3462 // Don't make a user-defined type out of block name; that will cause an error
3463 // if the same block name gets reused in a different interface.
3465 // "Block names have no other use within a shader
3466 // beyond interface matching; it is a compile-time error to use a block name at global scope for anything
3467 // other than as a block name (e.g., use of a block name for a global variable name or function name is
3468 // currently reserved)."
3470 // Use the symbol table to prevent normal reuse of the block's name, as a variable entry,
3471 // whose type is EbtBlock, but without all the structure; that will come from the type
3472 // the instances point to.
3474 TType blockNameType(EbtBlock, blockType.getQualifier().storage);
3475 TVariable* blockNameVar = new TVariable(blockName, blockNameType);
3476 if (! symbolTable.insert(*blockNameVar)) {
3477 TSymbol* existingName = symbolTable.find(*blockName);
3478 if (existingName->getType().getBasicType() == EbtBlock) {
3479 if (existingName->getType().getQualifier().storage == blockType.getQualifier().storage) {
3480 error(loc, "Cannot reuse block name within the same interface:", blockName->c_str(), blockType.getStorageQualifierString());
3484 error(loc, "block name cannot redefine a non-block name", blockName->c_str(), "");
3489 // Add the variable, as anonymous or named instanceName.
3490 // Make an anonymous variable if no name was provided.
3492 instanceName = NewPoolTString("");
3494 TVariable& variable = *new TVariable(instanceName, blockType);
3495 if (! symbolTable.insert(variable)) {
3496 if (*instanceName == "")
3497 error(loc, "nameless block contains a member that already has a name at global scope", blockName->c_str(), "");
3499 error(loc, "block instance name redefinition", variable.getName().c_str(), "");
3504 if (isIoResizeArray(blockType)) {
3505 ioArraySymbolResizeList.push_back(&variable);
3506 checkIoArraysConsistency(loc, true);
3508 fixIoArraySize(loc, variable.getWritableType());
3510 // Save it in the AST for linker use.
3511 intermediate.addSymbolLinkageNode(linkage, variable);
3515 // "For a block, this process applies to the entire block, or until the first member
3516 // is reached that has a location layout qualifier. When a block member is declared with a location
3517 // qualifier, its location comes from that qualifier: The member's location qualifier overrides the block-level
3518 // declaration. Subsequent members are again assigned consecutive locations, based on the newest location,
3519 // until the next member declared with a location qualifier. The values used for locations do not have to be
3520 // declared in increasing order."
3521 void HlslParseContext::fixBlockLocations(const TSourceLoc& loc, TQualifier& qualifier, TTypeList& typeList, bool memberWithLocation, bool memberWithoutLocation)
3523 // "If a block has no block-level location layout qualifier, it is required that either all or none of its members
3524 // have a location layout qualifier, or a compile-time error results."
3525 if (! qualifier.hasLocation() && memberWithLocation && memberWithoutLocation)
3526 error(loc, "either the block needs a location, or all members need a location, or no members have a location", "location", "");
3528 if (memberWithLocation) {
3529 // remove any block-level location and make it per *every* member
3530 int nextLocation = 0; // by the rule above, initial value is not relevant
3531 if (qualifier.hasAnyLocation()) {
3532 nextLocation = qualifier.layoutLocation;
3533 qualifier.layoutLocation = TQualifier::layoutLocationEnd;
3534 if (qualifier.hasComponent()) {
3535 // "It is a compile-time error to apply the *component* qualifier to a ... block"
3536 error(loc, "cannot apply to a block", "component", "");
3538 if (qualifier.hasIndex()) {
3539 error(loc, "cannot apply to a block", "index", "");
3542 for (unsigned int member = 0; member < typeList.size(); ++member) {
3543 TQualifier& memberQualifier = typeList[member].type->getQualifier();
3544 const TSourceLoc& memberLoc = typeList[member].loc;
3545 if (! memberQualifier.hasLocation()) {
3546 if (nextLocation >= (int)TQualifier::layoutLocationEnd)
3547 error(memberLoc, "location is too large", "location", "");
3548 memberQualifier.layoutLocation = nextLocation;
3549 memberQualifier.layoutComponent = 0;
3551 nextLocation = memberQualifier.layoutLocation + intermediate.computeTypeLocationSize(*typeList[member].type);
3557 void HlslParseContext::fixBlockXfbOffsets(TQualifier& qualifier, TTypeList& typeList)
3559 // "If a block is qualified with xfb_offset, all its
3560 // members are assigned transform feedback buffer offsets. If a block is not qualified with xfb_offset, any
3561 // members of that block not qualified with an xfb_offset will not be assigned transform feedback buffer
3564 if (! qualifier.hasXfbBuffer() || ! qualifier.hasXfbOffset())
3567 int nextOffset = qualifier.layoutXfbOffset;
3568 for (unsigned int member = 0; member < typeList.size(); ++member) {
3569 TQualifier& memberQualifier = typeList[member].type->getQualifier();
3570 bool containsDouble = false;
3571 int memberSize = intermediate.computeTypeXfbSize(*typeList[member].type, containsDouble);
3572 // see if we need to auto-assign an offset to this member
3573 if (! memberQualifier.hasXfbOffset()) {
3574 // "if applied to an aggregate containing a double, the offset must also be a multiple of 8"
3576 RoundToPow2(nextOffset, 8);
3577 memberQualifier.layoutXfbOffset = nextOffset;
3579 nextOffset = memberQualifier.layoutXfbOffset;
3580 nextOffset += memberSize;
3583 // The above gave all block members an offset, so we can take it off the block now,
3584 // which will avoid double counting the offset usage.
3585 qualifier.layoutXfbOffset = TQualifier::layoutXfbOffsetEnd;
3588 // Calculate and save the offset of each block member, using the recursively
3589 // defined block offset rules and the user-provided offset and align.
3591 // Also, compute and save the total size of the block. For the block's size, arrayness
3592 // is not taken into account, as each element is backed by a separate buffer.
3594 void HlslParseContext::fixBlockUniformOffsets(TQualifier& qualifier, TTypeList& typeList)
3596 if (! qualifier.isUniformOrBuffer())
3598 if (qualifier.layoutPacking != ElpStd140 && qualifier.layoutPacking != ElpStd430)
3603 for (unsigned int member = 0; member < typeList.size(); ++member) {
3604 TQualifier& memberQualifier = typeList[member].type->getQualifier();
3605 const TSourceLoc& memberLoc = typeList[member].loc;
3607 // "When align is applied to an array, it effects only the start of the array, not the array's internal stride."
3609 // modify just the children's view of matrix layout, if there is one for this member
3610 TLayoutMatrix subMatrixLayout = typeList[member].type->getQualifier().layoutMatrix;
3612 int memberAlignment = intermediate.getBaseAlignment(*typeList[member].type, memberSize, dummyStride, qualifier.layoutPacking == ElpStd140,
3613 subMatrixLayout != ElmNone ? subMatrixLayout == ElmRowMajor : qualifier.layoutMatrix == ElmRowMajor);
3614 if (memberQualifier.hasOffset()) {
3615 // "The specified offset must be a multiple
3616 // of the base alignment of the type of the block member it qualifies, or a compile-time error results."
3617 if (! IsMultipleOfPow2(memberQualifier.layoutOffset, memberAlignment))
3618 error(memberLoc, "must be a multiple of the member's alignment", "offset", "");
3620 // "It is a compile-time error to specify an offset that is smaller than the offset of the previous
3621 // member in the block or that lies within the previous member of the block"
3622 if (memberQualifier.layoutOffset < offset)
3623 error(memberLoc, "cannot lie in previous members", "offset", "");
3625 // "The offset qualifier forces the qualified member to start at or after the specified
3626 // integral-constant expression, which will be its byte offset from the beginning of the buffer.
3627 // "The actual offset of a member is computed as
3628 // follows: If offset was declared, start with that offset, otherwise start with the next available offset."
3629 offset = std::max(offset, memberQualifier.layoutOffset);
3632 // "The actual alignment of a member will be the greater of the specified align alignment and the standard
3633 // (e.g., std140) base alignment for the member's type."
3634 if (memberQualifier.hasAlign())
3635 memberAlignment = std::max(memberAlignment, memberQualifier.layoutAlign);
3637 // "If the resulting offset is not a multiple of the actual alignment,
3638 // increase it to the first offset that is a multiple of
3639 // the actual alignment."
3640 RoundToPow2(offset, memberAlignment);
3641 typeList[member].type->getQualifier().layoutOffset = offset;
3642 offset += memberSize;
3646 // For an identifier that is already declared, add more qualification to it.
3647 void HlslParseContext::addQualifierToExisting(const TSourceLoc& loc, TQualifier qualifier, const TString& identifier)
3649 TSymbol* symbol = symbolTable.find(identifier);
3651 error(loc, "identifier not previously declared", identifier.c_str(), "");
3654 if (symbol->getAsFunction()) {
3655 error(loc, "cannot re-qualify a function name", identifier.c_str(), "");
3659 if (qualifier.isAuxiliary() ||
3660 qualifier.isMemory() ||
3661 qualifier.isInterpolation() ||
3662 qualifier.hasLayout() ||
3663 qualifier.storage != EvqTemporary ||
3664 qualifier.precision != EpqNone) {
3665 error(loc, "cannot add storage, auxiliary, memory, interpolation, layout, or precision qualifier to an existing variable", identifier.c_str(), "");
3669 // For read-only built-ins, add a new symbol for holding the modified qualifier.
3670 // This will bring up an entire block, if a block type has to be modified (e.g., gl_Position inside a block)
3671 if (symbol->isReadOnly())
3672 symbol = symbolTable.copyUp(symbol);
3674 if (qualifier.invariant) {
3675 if (intermediate.inIoAccessed(identifier))
3676 error(loc, "cannot change qualification after use", "invariant", "");
3677 symbol->getWritableType().getQualifier().invariant = true;
3678 } else if (qualifier.noContraction) {
3679 if (intermediate.inIoAccessed(identifier))
3680 error(loc, "cannot change qualification after use", "precise", "");
3681 symbol->getWritableType().getQualifier().noContraction = true;
3682 } else if (qualifier.specConstant) {
3683 symbol->getWritableType().getQualifier().makeSpecConstant();
3684 if (qualifier.hasSpecConstantId())
3685 symbol->getWritableType().getQualifier().layoutSpecConstantId = qualifier.layoutSpecConstantId;
3687 warn(loc, "unknown requalification", "", "");
3690 void HlslParseContext::addQualifierToExisting(const TSourceLoc& loc, TQualifier qualifier, TIdentifierList& identifiers)
3692 for (unsigned int i = 0; i < identifiers.size(); ++i)
3693 addQualifierToExisting(loc, qualifier, *identifiers[i]);
3697 // Updating default qualifier for the case of a declaration with just a qualifier,
3698 // no type, block, or identifier.
3700 void HlslParseContext::updateStandaloneQualifierDefaults(const TSourceLoc& loc, const TPublicType& publicType)
3702 if (publicType.shaderQualifiers.vertices != TQualifier::layoutNotSet) {
3703 assert(language == EShLangTessControl || language == EShLangGeometry);
3704 const char* id = (language == EShLangTessControl) ? "vertices" : "max_vertices";
3706 if (language == EShLangTessControl)
3707 checkIoArraysConsistency(loc);
3709 if (publicType.shaderQualifiers.invocations != TQualifier::layoutNotSet) {
3710 if (! intermediate.setInvocations(publicType.shaderQualifiers.invocations))
3711 error(loc, "cannot change previously set layout value", "invocations", "");
3713 if (publicType.shaderQualifiers.geometry != ElgNone) {
3714 if (publicType.qualifier.storage == EvqVaryingIn) {
3715 switch (publicType.shaderQualifiers.geometry) {
3718 case ElgLinesAdjacency:
3720 case ElgTrianglesAdjacency:
3723 if (intermediate.setInputPrimitive(publicType.shaderQualifiers.geometry)) {
3724 if (language == EShLangGeometry)
3725 checkIoArraysConsistency(loc);
3727 error(loc, "cannot change previously set input primitive", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
3730 error(loc, "cannot apply to input", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
3732 } else if (publicType.qualifier.storage == EvqVaryingOut) {
3733 switch (publicType.shaderQualifiers.geometry) {
3736 case ElgTriangleStrip:
3737 if (! intermediate.setOutputPrimitive(publicType.shaderQualifiers.geometry))
3738 error(loc, "cannot change previously set output primitive", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
3741 error(loc, "cannot apply to 'out'", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
3744 error(loc, "cannot apply to:", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), GetStorageQualifierString(publicType.qualifier.storage));
3746 if (publicType.shaderQualifiers.spacing != EvsNone)
3747 intermediate.setVertexSpacing(publicType.shaderQualifiers.spacing);
3748 if (publicType.shaderQualifiers.order != EvoNone)
3749 intermediate.setVertexOrder(publicType.shaderQualifiers.order);
3750 if (publicType.shaderQualifiers.pointMode)
3751 intermediate.setPointMode();
3752 for (int i = 0; i < 3; ++i) {
3753 if (publicType.shaderQualifiers.localSize[i] > 1) {
3756 case 0: max = resources.maxComputeWorkGroupSizeX; break;
3757 case 1: max = resources.maxComputeWorkGroupSizeY; break;
3758 case 2: max = resources.maxComputeWorkGroupSizeZ; break;
3761 if (intermediate.getLocalSize(i) > (unsigned int)max)
3762 error(loc, "too large; see gl_MaxComputeWorkGroupSize", "local_size", "");
3764 // Fix the existing constant gl_WorkGroupSize with this new information.
3765 TVariable* workGroupSize = getEditableVariable("gl_WorkGroupSize");
3766 workGroupSize->getWritableConstArray()[i].setUConst(intermediate.getLocalSize(i));
3768 if (publicType.shaderQualifiers.localSizeSpecId[i] != TQualifier::layoutNotSet) {
3769 intermediate.setLocalSizeSpecId(i, publicType.shaderQualifiers.localSizeSpecId[i]);
3770 // Set the workgroup built-in variable as a specialization constant
3771 TVariable* workGroupSize = getEditableVariable("gl_WorkGroupSize");
3772 workGroupSize->getWritableType().getQualifier().specConstant = true;
3775 if (publicType.shaderQualifiers.earlyFragmentTests)
3776 intermediate.setEarlyFragmentTests();
3778 const TQualifier& qualifier = publicType.qualifier;
3780 switch (qualifier.storage) {
3782 if (qualifier.hasMatrix())
3783 globalUniformDefaults.layoutMatrix = qualifier.layoutMatrix;
3784 if (qualifier.hasPacking())
3785 globalUniformDefaults.layoutPacking = qualifier.layoutPacking;
3788 if (qualifier.hasMatrix())
3789 globalBufferDefaults.layoutMatrix = qualifier.layoutMatrix;
3790 if (qualifier.hasPacking())
3791 globalBufferDefaults.layoutPacking = qualifier.layoutPacking;
3796 if (qualifier.hasStream())
3797 globalOutputDefaults.layoutStream = qualifier.layoutStream;
3798 if (qualifier.hasXfbBuffer())
3799 globalOutputDefaults.layoutXfbBuffer = qualifier.layoutXfbBuffer;
3800 if (globalOutputDefaults.hasXfbBuffer() && qualifier.hasXfbStride()) {
3801 if (! intermediate.setXfbBufferStride(globalOutputDefaults.layoutXfbBuffer, qualifier.layoutXfbStride))
3802 error(loc, "all stride settings must match for xfb buffer", "xfb_stride", "%d", qualifier.layoutXfbBuffer);
3806 error(loc, "default qualifier requires 'uniform', 'buffer', 'in', or 'out' storage qualification", "", "");
3812 // Take the sequence of statements that has been built up since the last case/default,
3813 // put it on the list of top-level nodes for the current (inner-most) switch statement,
3814 // and follow that by the case/default we are on now. (See switch topology comment on
3817 void HlslParseContext::wrapupSwitchSubsequence(TIntermAggregate* statements, TIntermNode* branchNode)
3819 TIntermSequence* switchSequence = switchSequenceStack.back();
3822 if (switchSequence->size() == 0)
3823 error(statements->getLoc(), "cannot have statements before first case/default label", "switch", "");
3824 statements->setOperator(EOpSequence);
3825 switchSequence->push_back(statements);
3828 // check all previous cases for the same label (or both are 'default')
3829 for (unsigned int s = 0; s < switchSequence->size(); ++s) {
3830 TIntermBranch* prevBranch = (*switchSequence)[s]->getAsBranchNode();
3832 TIntermTyped* prevExpression = prevBranch->getExpression();
3833 TIntermTyped* newExpression = branchNode->getAsBranchNode()->getExpression();
3834 if (prevExpression == nullptr && newExpression == nullptr)
3835 error(branchNode->getLoc(), "duplicate label", "default", "");
3836 else if (prevExpression != nullptr &&
3837 newExpression != nullptr &&
3838 prevExpression->getAsConstantUnion() &&
3839 newExpression->getAsConstantUnion() &&
3840 prevExpression->getAsConstantUnion()->getConstArray()[0].getIConst() ==
3841 newExpression->getAsConstantUnion()->getConstArray()[0].getIConst())
3842 error(branchNode->getLoc(), "duplicated value", "case", "");
3845 switchSequence->push_back(branchNode);
3850 // Turn the top-level node sequence built up of wrapupSwitchSubsequence
3851 // into a switch node.
3853 TIntermNode* HlslParseContext::addSwitch(const TSourceLoc& loc, TIntermTyped* expression, TIntermAggregate* lastStatements)
3855 wrapupSwitchSubsequence(lastStatements, nullptr);
3857 if (expression == nullptr ||
3858 (expression->getBasicType() != EbtInt && expression->getBasicType() != EbtUint) ||
3859 expression->getType().isArray() || expression->getType().isMatrix() || expression->getType().isVector())
3860 error(loc, "condition must be a scalar integer expression", "switch", "");
3862 // If there is nothing to do, drop the switch but still execute the expression
3863 TIntermSequence* switchSequence = switchSequenceStack.back();
3864 if (switchSequence->size() == 0)
3867 if (lastStatements == nullptr) {
3868 // emulate a break for error recovery
3869 lastStatements = intermediate.makeAggregate(intermediate.addBranch(EOpBreak, loc));
3870 lastStatements->setOperator(EOpSequence);
3871 switchSequence->push_back(lastStatements);
3874 TIntermAggregate* body = new TIntermAggregate(EOpSequence);
3875 body->getSequence() = *switchSequenceStack.back();
3878 TIntermSwitch* switchNode = new TIntermSwitch(expression, body);
3879 switchNode->setLoc(loc);
3884 } // end namespace glslang