2 // Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
3 // Copyright (C) 2012-2015 LunarG, Inc.
4 // Copyright (C) 2015-2018 Google, Inc.
5 // Copyright (C) 2017, 2019 ARM Limited.
6 // Modifications Copyright (C) 2020 Advanced Micro Devices, Inc. All rights reserved.
8 // All rights reserved.
10 // Redistribution and use in source and binary forms, with or without
11 // modification, are permitted provided that the following conditions
14 // Redistributions of source code must retain the above copyright
15 // notice, this list of conditions and the following disclaimer.
17 // Redistributions in binary form must reproduce the above
18 // copyright notice, this list of conditions and the following
19 // disclaimer in the documentation and/or other materials provided
20 // with the distribution.
22 // Neither the name of 3Dlabs Inc. Ltd. nor the names of its
23 // contributors may be used to endorse or promote products derived
24 // from this software without specific prior written permission.
26 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
27 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
28 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
29 // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
30 // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
31 // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
32 // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
33 // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
34 // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35 // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
36 // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
37 // POSSIBILITY OF SUCH DAMAGE.
40 #include "ParseHelper.h"
43 #include "../OSDependent/osinclude.h"
46 #include "preprocessor/PpContext.h"
48 extern int yyparse(glslang::TParseContext*);
52 TParseContext::TParseContext(TSymbolTable& symbolTable, TIntermediate& interm, bool parsingBuiltins,
53 int version, EProfile profile, const SpvVersion& spvVersion, EShLanguage language,
54 TInfoSink& infoSink, bool forwardCompatible, EShMessages messages,
55 const TString* entryPoint) :
56 TParseContextBase(symbolTable, interm, parsingBuiltins, version, profile, spvVersion, language,
57 infoSink, forwardCompatible, messages, entryPoint),
60 limits(resources.limits)
63 atomicUintOffsets(nullptr), anyIndexLimits(false)
66 // decide whether precision qualifiers should be ignored or respected
67 if (isEsProfile() || spvVersion.vulkan > 0) {
68 precisionManager.respectPrecisionQualifiers();
69 if (! parsingBuiltins && language == EShLangFragment && !isEsProfile() && spvVersion.vulkan > 0)
70 precisionManager.warnAboutDefaults();
73 setPrecisionDefaults();
75 globalUniformDefaults.clear();
76 globalUniformDefaults.layoutMatrix = ElmColumnMajor;
77 globalUniformDefaults.layoutPacking = spvVersion.spv != 0 ? ElpStd140 : ElpShared;
79 globalBufferDefaults.clear();
80 globalBufferDefaults.layoutMatrix = ElmColumnMajor;
81 globalBufferDefaults.layoutPacking = spvVersion.spv != 0 ? ElpStd430 : ElpShared;
83 // use storage buffer on SPIR-V 1.3 and up
84 if (spvVersion.spv >= EShTargetSpv_1_3)
85 intermediate.setUseStorageBuffer();
87 globalInputDefaults.clear();
88 globalOutputDefaults.clear();
90 globalSharedDefaults.clear();
91 globalSharedDefaults.layoutMatrix = ElmColumnMajor;
92 globalSharedDefaults.layoutPacking = ElpStd430;
95 // "Shaders in the transform
96 // feedback capturing mode have an initial global default of
97 // layout(xfb_buffer = 0) out;"
98 if (language == EShLangVertex ||
99 language == EShLangTessControl ||
100 language == EShLangTessEvaluation ||
101 language == EShLangGeometry)
102 globalOutputDefaults.layoutXfbBuffer = 0;
104 if (language == EShLangGeometry)
105 globalOutputDefaults.layoutStream = 0;
108 if (entryPoint != nullptr && entryPoint->size() > 0 && *entryPoint != "main")
109 infoSink.info.message(EPrefixError, "Source entry point must be \"main\"");
112 TParseContext::~TParseContext()
115 delete [] atomicUintOffsets;
119 // Set up all default precisions as needed by the current environment.
120 // Intended just as a TParseContext constructor helper.
121 void TParseContext::setPrecisionDefaults()
123 // Set all precision defaults to EpqNone, which is correct for all types
124 // when not obeying precision qualifiers, and correct for types that don't
125 // have defaults (thus getting an error on use) when obeying precision
128 for (int type = 0; type < EbtNumTypes; ++type)
129 defaultPrecision[type] = EpqNone;
131 for (int type = 0; type < maxSamplerIndex; ++type)
132 defaultSamplerPrecision[type] = EpqNone;
134 // replace with real precision defaults for those that have them
135 if (obeyPrecisionQualifiers()) {
137 // Most don't have defaults, a few default to lowp.
139 sampler.set(EbtFloat, Esd2D);
140 defaultSamplerPrecision[computeSamplerTypeIndex(sampler)] = EpqLow;
141 sampler.set(EbtFloat, EsdCube);
142 defaultSamplerPrecision[computeSamplerTypeIndex(sampler)] = EpqLow;
143 sampler.set(EbtFloat, Esd2D);
144 sampler.setExternal(true);
145 defaultSamplerPrecision[computeSamplerTypeIndex(sampler)] = EpqLow;
148 // If we are parsing built-in computational variables/functions, it is meaningful to record
149 // whether the built-in has no precision qualifier, as that ambiguity
150 // is used to resolve the precision from the supplied arguments/operands instead.
151 // So, we don't actually want to replace EpqNone with a default precision for built-ins.
152 if (! parsingBuiltins) {
153 if (isEsProfile() && language == EShLangFragment) {
154 defaultPrecision[EbtInt] = EpqMedium;
155 defaultPrecision[EbtUint] = EpqMedium;
157 defaultPrecision[EbtInt] = EpqHigh;
158 defaultPrecision[EbtUint] = EpqHigh;
159 defaultPrecision[EbtFloat] = EpqHigh;
162 if (!isEsProfile()) {
164 // All sampler precisions default to highp.
165 for (int type = 0; type < maxSamplerIndex; ++type)
166 defaultSamplerPrecision[type] = EpqHigh;
170 defaultPrecision[EbtSampler] = EpqLow;
171 defaultPrecision[EbtAtomicUint] = EpqHigh;
175 void TParseContext::setLimits(const TBuiltInResource& r)
178 intermediate.setLimits(r);
181 anyIndexLimits = ! limits.generalAttributeMatrixVectorIndexing ||
182 ! limits.generalConstantMatrixVectorIndexing ||
183 ! limits.generalSamplerIndexing ||
184 ! limits.generalUniformIndexing ||
185 ! limits.generalVariableIndexing ||
186 ! limits.generalVaryingIndexing;
189 // "Each binding point tracks its own current default offset for
190 // inheritance of subsequent variables using the same binding. The initial state of compilation is that all
191 // binding points have an offset of 0."
192 atomicUintOffsets = new int[resources.maxAtomicCounterBindings];
193 for (int b = 0; b < resources.maxAtomicCounterBindings; ++b)
194 atomicUintOffsets[b] = 0;
199 // Parse an array of strings using yyparse, going through the
200 // preprocessor to tokenize the shader strings, then through
203 // Returns true for successful acceptance of the shader, false if any errors.
205 bool TParseContext::parseShaderStrings(TPpContext& ppContext, TInputScanner& input, bool versionWillBeError)
207 currentScanner = &input;
208 ppContext.setInput(input, versionWillBeError);
213 return numErrors == 0;
216 // This is called from bison when it has a parse (syntax) error
217 // Note though that to stop cascading errors, we set EOF, which
218 // will usually cause a syntax error, so be more accurate that
219 // compilation is terminating.
220 void TParseContext::parserError(const char* s)
222 if (! getScanner()->atEndOfInput() || numErrors == 0)
223 error(getCurrentLoc(), "", "", s, "");
225 error(getCurrentLoc(), "compilation terminated", "", "");
228 void TParseContext::growGlobalUniformBlock(const TSourceLoc& loc, TType& memberType, const TString& memberName, TTypeList* typeList)
230 bool createBlock = globalUniformBlock == nullptr;
233 globalUniformBinding = intermediate.getGlobalUniformBinding();
234 globalUniformSet = intermediate.getGlobalUniformSet();
237 // use base class function to create/expand block
238 TParseContextBase::growGlobalUniformBlock(loc, memberType, memberName, typeList);
240 if (spvVersion.vulkan > 0 && spvVersion.vulkanRelaxed) {
241 // check for a block storage override
242 TBlockStorageClass storageOverride = intermediate.getBlockStorageOverride(getGlobalUniformBlockName());
243 TQualifier& qualifier = globalUniformBlock->getWritableType().getQualifier();
244 qualifier.defaultBlock = true;
246 if (storageOverride != EbsNone) {
248 // Remap block storage
249 qualifier.setBlockStorage(storageOverride);
251 // check that the change didn't create errors
252 blockQualifierCheck(loc, qualifier, false);
255 // remap meber storage as well
256 memberType.getQualifier().setBlockStorage(storageOverride);
261 void TParseContext::growAtomicCounterBlock(int binding, const TSourceLoc& loc, TType& memberType, const TString& memberName, TTypeList* typeList)
263 bool createBlock = atomicCounterBuffers.find(binding) == atomicCounterBuffers.end();
266 atomicCounterBlockSet = intermediate.getAtomicCounterBlockSet();
269 // use base class function to create/expand block
270 TParseContextBase::growAtomicCounterBlock(binding, loc, memberType, memberName, typeList);
271 TQualifier& qualifier = atomicCounterBuffers[binding]->getWritableType().getQualifier();
272 qualifier.defaultBlock = true;
274 if (spvVersion.vulkan > 0 && spvVersion.vulkanRelaxed) {
275 // check for a Block storage override
276 TBlockStorageClass storageOverride = intermediate.getBlockStorageOverride(getAtomicCounterBlockName());
278 if (storageOverride != EbsNone) {
280 // Remap block storage
282 qualifier.setBlockStorage(storageOverride);
284 // check that the change didn't create errors
285 blockQualifierCheck(loc, qualifier, false);
288 // remap meber storage as well
289 memberType.getQualifier().setBlockStorage(storageOverride);
294 const char* TParseContext::getGlobalUniformBlockName() const
296 const char* name = intermediate.getGlobalUniformBlockName();
297 if (std::string(name) == "")
298 return "gl_DefaultUniformBlock";
302 void TParseContext::finalizeGlobalUniformBlockLayout(TVariable&)
305 void TParseContext::setUniformBlockDefaults(TType& block) const
307 block.getQualifier().layoutPacking = ElpStd140;
308 block.getQualifier().layoutMatrix = ElmColumnMajor;
312 const char* TParseContext::getAtomicCounterBlockName() const
314 const char* name = intermediate.getAtomicCounterBlockName();
315 if (std::string(name) == "")
316 return "gl_AtomicCounterBlock";
320 void TParseContext::finalizeAtomicCounterBlockLayout(TVariable&)
324 void TParseContext::setAtomicCounterBlockDefaults(TType& block) const
326 block.getQualifier().layoutPacking = ElpStd430;
327 block.getQualifier().layoutMatrix = ElmRowMajor;
330 void TParseContext::setInvariant(const TSourceLoc& loc, const char* builtin) {
331 TSymbol* symbol = symbolTable.find(builtin);
332 if (symbol && symbol->getType().getQualifier().isPipeOutput()) {
333 if (intermediate.inIoAccessed(builtin))
334 warn(loc, "changing qualification after use", "invariant", builtin);
335 TSymbol* csymbol = symbolTable.copyUp(symbol);
336 csymbol->getWritableType().getQualifier().invariant = true;
340 void TParseContext::handlePragma(const TSourceLoc& loc, const TVector<TString>& tokens)
344 pragmaCallback(loc.line, tokens);
346 if (tokens.size() == 0)
349 if (tokens[0].compare("optimize") == 0) {
350 if (tokens.size() != 4) {
351 error(loc, "optimize pragma syntax is incorrect", "#pragma", "");
355 if (tokens[1].compare("(") != 0) {
356 error(loc, "\"(\" expected after 'optimize' keyword", "#pragma", "");
360 if (tokens[2].compare("on") == 0)
361 contextPragma.optimize = true;
362 else if (tokens[2].compare("off") == 0)
363 contextPragma.optimize = false;
366 // If an implementation does not recognize the tokens following #pragma, then it will ignore that pragma.
367 warn(loc, "\"on\" or \"off\" expected after '(' for 'optimize' pragma", "#pragma", "");
371 if (tokens[3].compare(")") != 0) {
372 error(loc, "\")\" expected to end 'optimize' pragma", "#pragma", "");
375 } else if (tokens[0].compare("debug") == 0) {
376 if (tokens.size() != 4) {
377 error(loc, "debug pragma syntax is incorrect", "#pragma", "");
381 if (tokens[1].compare("(") != 0) {
382 error(loc, "\"(\" expected after 'debug' keyword", "#pragma", "");
386 if (tokens[2].compare("on") == 0)
387 contextPragma.debug = true;
388 else if (tokens[2].compare("off") == 0)
389 contextPragma.debug = false;
392 // If an implementation does not recognize the tokens following #pragma, then it will ignore that pragma.
393 warn(loc, "\"on\" or \"off\" expected after '(' for 'debug' pragma", "#pragma", "");
397 if (tokens[3].compare(")") != 0) {
398 error(loc, "\")\" expected to end 'debug' pragma", "#pragma", "");
401 } else if (spvVersion.spv > 0 && tokens[0].compare("use_storage_buffer") == 0) {
402 if (tokens.size() != 1)
403 error(loc, "extra tokens", "#pragma", "");
404 intermediate.setUseStorageBuffer();
405 } else if (spvVersion.spv > 0 && tokens[0].compare("use_vulkan_memory_model") == 0) {
406 if (tokens.size() != 1)
407 error(loc, "extra tokens", "#pragma", "");
408 intermediate.setUseVulkanMemoryModel();
409 } else if (spvVersion.spv > 0 && tokens[0].compare("use_variable_pointers") == 0) {
410 if (tokens.size() != 1)
411 error(loc, "extra tokens", "#pragma", "");
412 if (spvVersion.spv < glslang::EShTargetSpv_1_3)
413 error(loc, "requires SPIR-V 1.3", "#pragma use_variable_pointers", "");
414 intermediate.setUseVariablePointers();
415 } else if (tokens[0].compare("once") == 0) {
416 warn(loc, "not implemented", "#pragma once", "");
417 } else if (tokens[0].compare("glslang_binary_double_output") == 0) {
418 intermediate.setBinaryDoubleOutput();
419 } else if (spvVersion.spv > 0 && tokens[0].compare("STDGL") == 0 &&
420 tokens[1].compare("invariant") == 0 && tokens[3].compare("all") == 0) {
421 intermediate.setInvariantAll();
422 // Set all builtin out variables invariant if declared
423 setInvariant(loc, "gl_Position");
424 setInvariant(loc, "gl_PointSize");
425 setInvariant(loc, "gl_ClipDistance");
426 setInvariant(loc, "gl_CullDistance");
427 setInvariant(loc, "gl_TessLevelOuter");
428 setInvariant(loc, "gl_TessLevelInner");
429 setInvariant(loc, "gl_PrimitiveID");
430 setInvariant(loc, "gl_Layer");
431 setInvariant(loc, "gl_ViewportIndex");
432 setInvariant(loc, "gl_FragDepth");
433 setInvariant(loc, "gl_SampleMask");
434 setInvariant(loc, "gl_ClipVertex");
435 setInvariant(loc, "gl_FrontColor");
436 setInvariant(loc, "gl_BackColor");
437 setInvariant(loc, "gl_FrontSecondaryColor");
438 setInvariant(loc, "gl_BackSecondaryColor");
439 setInvariant(loc, "gl_TexCoord");
440 setInvariant(loc, "gl_FogFragCoord");
441 setInvariant(loc, "gl_FragColor");
442 setInvariant(loc, "gl_FragData");
448 // Handle seeing a variable identifier in the grammar.
450 TIntermTyped* TParseContext::handleVariable(const TSourceLoc& loc, TSymbol* symbol, const TString* string)
452 TIntermTyped* node = nullptr;
454 // Error check for requiring specific extensions present.
455 if (symbol && symbol->getNumExtensions())
456 requireExtensions(loc, symbol->getNumExtensions(), symbol->getExtensions(), symbol->getName().c_str());
459 if (symbol && symbol->isReadOnly()) {
460 // All shared things containing an unsized array must be copied up
461 // on first use, so that all future references will share its array structure,
462 // so that editing the implicit size will effect all nodes consuming it,
463 // and so that editing the implicit size won't change the shared one.
465 // If this is a variable or a block, check it and all it contains, but if this
466 // is a member of an anonymous block, check the whole block, as the whole block
467 // will need to be copied up if it contains an unsized array.
469 // This check is being done before the block-name check further down, so guard
471 if (!symbol->getType().isUnusableName()) {
472 if (symbol->getType().containsUnsizedArray() ||
473 (symbol->getAsAnonMember() &&
474 symbol->getAsAnonMember()->getAnonContainer().getType().containsUnsizedArray()))
475 makeEditable(symbol);
480 const TVariable* variable;
481 const TAnonMember* anon = symbol ? symbol->getAsAnonMember() : nullptr;
483 // It was a member of an anonymous container.
485 // Create a subtree for its dereference.
486 variable = anon->getAnonContainer().getAsVariable();
487 TIntermTyped* container = intermediate.addSymbol(*variable, loc);
488 TIntermTyped* constNode = intermediate.addConstantUnion(anon->getMemberNumber(), loc);
489 node = intermediate.addIndex(EOpIndexDirectStruct, container, constNode, loc);
491 node->setType(*(*variable->getType().getStruct())[anon->getMemberNumber()].type);
492 if (node->getType().hiddenMember())
493 error(loc, "member of nameless block was not redeclared", string->c_str(), "");
495 // Not a member of an anonymous container.
497 // The symbol table search was done in the lexical phase.
498 // See if it was a variable.
499 variable = symbol ? symbol->getAsVariable() : nullptr;
501 if (variable->getType().isUnusableName()) {
502 error(loc, "cannot be used (maybe an instance name is needed)", string->c_str(), "");
507 error(loc, "variable name expected", string->c_str(), "");
510 // Recovery, if it wasn't found or was not a variable.
512 variable = new TVariable(string, TType(EbtVoid));
514 if (variable->getType().getQualifier().isFrontEndConstant())
515 node = intermediate.addConstantUnion(variable->getConstArray(), variable->getType(), loc);
517 node = intermediate.addSymbol(*variable, loc);
520 if (variable->getType().getQualifier().isIo())
521 intermediate.addIoAccessed(*string);
523 if (variable->getType().isReference() &&
524 variable->getType().getQualifier().bufferReferenceNeedsVulkanMemoryModel()) {
525 intermediate.setUseVulkanMemoryModel();
532 // Handle seeing a base[index] dereference in the grammar.
534 TIntermTyped* TParseContext::handleBracketDereference(const TSourceLoc& loc, TIntermTyped* base, TIntermTyped* index)
537 if (index->getQualifier().isFrontEndConstant())
538 indexValue = index->getAsConstantUnion()->getConstArray()[0].getIConst();
540 // basic type checks...
543 if (! base->isArray() && ! base->isMatrix() && ! base->isVector() && ! base->getType().isCoopMat() &&
544 ! base->isReference()) {
545 if (base->getAsSymbolNode())
546 error(loc, " left of '[' is not of type array, matrix, or vector ", base->getAsSymbolNode()->getName().c_str(), "");
548 error(loc, " left of '[' is not of type array, matrix, or vector ", "expression", "");
550 // Insert dummy error-recovery result
551 return intermediate.addConstantUnion(0.0, EbtFloat, loc);
554 if (!base->isArray() && base->isVector()) {
555 if (base->getType().contains16BitFloat())
556 requireFloat16Arithmetic(loc, "[", "does not operate on types containing float16");
557 if (base->getType().contains16BitInt())
558 requireInt16Arithmetic(loc, "[", "does not operate on types containing (u)int16");
559 if (base->getType().contains8BitInt())
560 requireInt8Arithmetic(loc, "[", "does not operate on types containing (u)int8");
563 // check for constant folding
564 if (base->getType().getQualifier().isFrontEndConstant() && index->getQualifier().isFrontEndConstant()) {
565 // both base and index are front-end constants
566 checkIndex(loc, base->getType(), indexValue);
567 return intermediate.foldDereference(base, indexValue, loc);
570 // at least one of base and index is not a front-end constant variable...
571 TIntermTyped* result = nullptr;
574 if (base->isReference() && ! base->isArray()) {
575 requireExtensions(loc, 1, &E_GL_EXT_buffer_reference2, "buffer reference indexing");
576 if (base->getType().getReferentType()->containsUnsizedArray()) {
577 error(loc, "cannot index reference to buffer containing an unsized array", "", "");
580 result = intermediate.addBinaryMath(EOpAdd, base, index, loc);
581 if (result != nullptr)
582 result->setType(base->getType());
584 if (result == nullptr) {
585 error(loc, "cannot index buffer reference", "", "");
586 result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
590 if (base->getAsSymbolNode() && isIoResizeArray(base->getType()))
591 handleIoResizeArrayAccess(loc, base);
594 if (index->getQualifier().isFrontEndConstant())
595 checkIndex(loc, base->getType(), indexValue);
597 if (index->getQualifier().isFrontEndConstant()) {
599 if (base->getType().isUnsizedArray()) {
600 base->getWritableType().updateImplicitArraySize(indexValue + 1);
601 // For 2D per-view builtin arrays, update the inner dimension size in parent type
602 if (base->getQualifier().isPerView() && base->getQualifier().builtIn != EbvNone) {
603 TIntermBinary* binaryNode = base->getAsBinaryNode();
605 TType& leftType = binaryNode->getLeft()->getWritableType();
606 TArraySizes& arraySizes = *leftType.getArraySizes();
607 assert(arraySizes.getNumDims() == 2);
608 arraySizes.setDimSize(1, std::max(arraySizes.getDimSize(1), indexValue + 1));
613 checkIndex(loc, base->getType(), indexValue);
614 result = intermediate.addIndex(EOpIndexDirect, base, index, loc);
617 if (base->getType().isUnsizedArray()) {
618 // we have a variable index into an unsized array, which is okay,
619 // depending on the situation
620 if (base->getAsSymbolNode() && isIoResizeArray(base->getType()))
621 error(loc, "", "[", "array must be sized by a redeclaration or layout qualifier before being indexed with a variable");
623 // it is okay for a run-time sized array
624 checkRuntimeSizable(loc, *base);
626 base->getWritableType().setArrayVariablyIndexed();
629 if (base->getBasicType() == EbtBlock) {
630 if (base->getQualifier().storage == EvqBuffer)
631 requireProfile(base->getLoc(), ~EEsProfile, "variable indexing buffer block array");
632 else if (base->getQualifier().storage == EvqUniform)
633 profileRequires(base->getLoc(), EEsProfile, 320, Num_AEP_gpu_shader5, AEP_gpu_shader5,
634 "variable indexing uniform block array");
636 // input/output blocks either don't exist or can't be variably indexed
638 } else if (language == EShLangFragment && base->getQualifier().isPipeOutput())
639 requireProfile(base->getLoc(), ~EEsProfile, "variable indexing fragment shader output array");
640 else if (base->getBasicType() == EbtSampler && version >= 130) {
641 const char* explanation = "variable indexing sampler array";
642 requireProfile(base->getLoc(), EEsProfile | ECoreProfile | ECompatibilityProfile, explanation);
643 profileRequires(base->getLoc(), EEsProfile, 320, Num_AEP_gpu_shader5, AEP_gpu_shader5, explanation);
644 profileRequires(base->getLoc(), ECoreProfile | ECompatibilityProfile, 400, nullptr, explanation);
647 result = intermediate.addIndex(EOpIndexIndirect, base, index, loc);
650 // Insert valid dereferenced result type
651 TType newType(base->getType(), 0);
652 if (base->getType().getQualifier().isConstant() && index->getQualifier().isConstant()) {
653 newType.getQualifier().storage = EvqConst;
654 // If base or index is a specialization constant, the result should also be a specialization constant.
655 if (base->getType().getQualifier().isSpecConstant() || index->getQualifier().isSpecConstant()) {
656 newType.getQualifier().makeSpecConstant();
659 newType.getQualifier().storage = EvqTemporary;
660 newType.getQualifier().specConstant = false;
662 result->setType(newType);
665 inheritMemoryQualifiers(base->getQualifier(), result->getWritableType().getQualifier());
667 // Propagate nonuniform
668 if (base->getQualifier().isNonUniform() || index->getQualifier().isNonUniform())
669 result->getWritableType().getQualifier().nonUniform = true;
672 handleIndexLimits(loc, base, index);
680 // for ES 2.0 (version 100) limitations for almost all index operations except vertex-shader uniforms
681 void TParseContext::handleIndexLimits(const TSourceLoc& /*loc*/, TIntermTyped* base, TIntermTyped* index)
683 if ((! limits.generalSamplerIndexing && base->getBasicType() == EbtSampler) ||
684 (! limits.generalUniformIndexing && base->getQualifier().isUniformOrBuffer() && language != EShLangVertex) ||
685 (! limits.generalAttributeMatrixVectorIndexing && base->getQualifier().isPipeInput() && language == EShLangVertex && (base->getType().isMatrix() || base->getType().isVector())) ||
686 (! limits.generalConstantMatrixVectorIndexing && base->getAsConstantUnion()) ||
687 (! limits.generalVariableIndexing && ! base->getType().getQualifier().isUniformOrBuffer() &&
688 ! base->getType().getQualifier().isPipeInput() &&
689 ! base->getType().getQualifier().isPipeOutput() &&
690 ! base->getType().getQualifier().isConstant()) ||
691 (! limits.generalVaryingIndexing && (base->getType().getQualifier().isPipeInput() ||
692 base->getType().getQualifier().isPipeOutput()))) {
693 // it's too early to know what the inductive variables are, save it for post processing
694 needsIndexLimitationChecking.push_back(index);
698 // Make a shared symbol have a non-shared version that can be edited by the current
699 // compile, such that editing its type will not change the shared version and will
700 // effect all nodes sharing it.
701 void TParseContext::makeEditable(TSymbol*& symbol)
703 TParseContextBase::makeEditable(symbol);
705 // See if it's tied to IO resizing
706 if (isIoResizeArray(symbol->getType()))
707 ioArraySymbolResizeList.push_back(symbol);
710 // Return true if this is a geometry shader input array or tessellation control output array
711 // or mesh shader output array.
712 bool TParseContext::isIoResizeArray(const TType& type) const
714 return type.isArray() &&
715 ((language == EShLangGeometry && type.getQualifier().storage == EvqVaryingIn) ||
716 (language == EShLangTessControl && type.getQualifier().storage == EvqVaryingOut &&
717 ! type.getQualifier().patch) ||
718 (language == EShLangFragment && type.getQualifier().storage == EvqVaryingIn &&
719 type.getQualifier().pervertexNV) ||
720 (language == EShLangMeshNV && type.getQualifier().storage == EvqVaryingOut &&
721 !type.getQualifier().perTaskNV));
724 // If an array is not isIoResizeArray() but is an io array, make sure it has the right size
725 void TParseContext::fixIoArraySize(const TSourceLoc& loc, TType& type)
727 if (! type.isArray() || type.getQualifier().patch || symbolTable.atBuiltInLevel())
730 assert(! isIoResizeArray(type));
732 if (type.getQualifier().storage != EvqVaryingIn || type.getQualifier().patch)
735 if (language == EShLangTessControl || language == EShLangTessEvaluation) {
736 if (type.getOuterArraySize() != resources.maxPatchVertices) {
737 if (type.isSizedArray())
738 error(loc, "tessellation input array size must be gl_MaxPatchVertices or implicitly sized", "[]", "");
739 type.changeOuterArraySize(resources.maxPatchVertices);
744 // Issue any errors if the non-array object is missing arrayness WRT
745 // shader I/O that has array requirements.
746 // All arrayness checking is handled in array paths, this is for
747 void TParseContext::ioArrayCheck(const TSourceLoc& loc, const TType& type, const TString& identifier)
749 if (! type.isArray() && ! symbolTable.atBuiltInLevel()) {
750 if (type.getQualifier().isArrayedIo(language) && !type.getQualifier().layoutPassthrough)
751 error(loc, "type must be an array:", type.getStorageQualifierString(), identifier.c_str());
755 // Handle a dereference of a geometry shader input array or tessellation control output array.
756 // See ioArraySymbolResizeList comment in ParseHelper.h.
758 void TParseContext::handleIoResizeArrayAccess(const TSourceLoc& /*loc*/, TIntermTyped* base)
760 TIntermSymbol* symbolNode = base->getAsSymbolNode();
765 // fix array size, if it can be fixed and needs to be fixed (will allow variable indexing)
766 if (symbolNode->getType().isUnsizedArray()) {
767 int newSize = getIoArrayImplicitSize(symbolNode->getType().getQualifier());
769 symbolNode->getWritableType().changeOuterArraySize(newSize);
773 // If there has been an input primitive declaration (geometry shader) or an output
774 // number of vertices declaration(tessellation shader), make sure all input array types
775 // match it in size. Types come either from nodes in the AST or symbols in the
778 // Types without an array size will be given one.
779 // Types already having a size that is wrong will get an error.
781 void TParseContext::checkIoArraysConsistency(const TSourceLoc &loc, bool tailOnly)
783 int requiredSize = 0;
784 TString featureString;
785 size_t listSize = ioArraySymbolResizeList.size();
788 // If tailOnly = true, only check the last array symbol in the list.
792 for (bool firstIteration = true; i < listSize; ++i) {
793 TType &type = ioArraySymbolResizeList[i]->getWritableType();
795 // As I/O array sizes don't change, fetch requiredSize only once,
796 // except for mesh shaders which could have different I/O array sizes based on type qualifiers.
797 if (firstIteration || (language == EShLangMeshNV)) {
798 requiredSize = getIoArrayImplicitSize(type.getQualifier(), &featureString);
799 if (requiredSize == 0)
801 firstIteration = false;
804 checkIoArrayConsistency(loc, requiredSize, featureString.c_str(), type,
805 ioArraySymbolResizeList[i]->getName());
809 int TParseContext::getIoArrayImplicitSize(const TQualifier &qualifier, TString *featureString) const
811 int expectedSize = 0;
812 TString str = "unknown";
813 unsigned int maxVertices = intermediate.getVertices() != TQualifier::layoutNotSet ? intermediate.getVertices() : 0;
815 if (language == EShLangGeometry) {
816 expectedSize = TQualifier::mapGeometryToSize(intermediate.getInputPrimitive());
817 str = TQualifier::getGeometryString(intermediate.getInputPrimitive());
819 else if (language == EShLangTessControl) {
820 expectedSize = maxVertices;
822 } else if (language == EShLangFragment) {
823 // Number of vertices for Fragment shader is always three.
826 } else if (language == EShLangMeshNV) {
827 unsigned int maxPrimitives =
828 intermediate.getPrimitives() != TQualifier::layoutNotSet ? intermediate.getPrimitives() : 0;
829 if (qualifier.builtIn == EbvPrimitiveIndicesNV) {
830 expectedSize = maxPrimitives * TQualifier::mapGeometryToSize(intermediate.getOutputPrimitive());
831 str = "max_primitives*";
832 str += TQualifier::getGeometryString(intermediate.getOutputPrimitive());
834 else if (qualifier.isPerPrimitive()) {
835 expectedSize = maxPrimitives;
836 str = "max_primitives";
839 expectedSize = maxVertices;
840 str = "max_vertices";
844 *featureString = str;
848 void TParseContext::checkIoArrayConsistency(const TSourceLoc& loc, int requiredSize, const char* feature, TType& type, const TString& name)
850 if (type.isUnsizedArray())
851 type.changeOuterArraySize(requiredSize);
852 else if (type.getOuterArraySize() != requiredSize) {
853 if (language == EShLangGeometry)
854 error(loc, "inconsistent input primitive for array size of", feature, name.c_str());
855 else if (language == EShLangTessControl)
856 error(loc, "inconsistent output number of vertices for array size of", feature, name.c_str());
857 else if (language == EShLangFragment) {
858 if (type.getOuterArraySize() > requiredSize)
859 error(loc, " cannot be greater than 3 for pervertexNV", feature, name.c_str());
861 else if (language == EShLangMeshNV)
862 error(loc, "inconsistent output array size of", feature, name.c_str());
868 #endif // GLSLANG_WEB
870 // Handle seeing a binary node with a math operation.
871 // Returns nullptr if not semantically allowed.
872 TIntermTyped* TParseContext::handleBinaryMath(const TSourceLoc& loc, const char* str, TOperator op, TIntermTyped* left, TIntermTyped* right)
874 rValueErrorCheck(loc, str, left->getAsTyped());
875 rValueErrorCheck(loc, str, right->getAsTyped());
879 // TODO: Bring more source language-specific checks up from intermediate.cpp
880 // to the specific parse helpers for that source language.
883 case EOpLessThanEqual:
884 case EOpGreaterThanEqual:
885 if (! left->isScalar() || ! right->isScalar())
892 if (((left->getType().contains16BitFloat() || right->getType().contains16BitFloat()) && !float16Arithmetic()) ||
893 ((left->getType().contains16BitInt() || right->getType().contains16BitInt()) && !int16Arithmetic()) ||
894 ((left->getType().contains8BitInt() || right->getType().contains8BitInt()) && !int8Arithmetic())) {
898 TIntermTyped* result = nullptr;
900 if ((left->isReference() || right->isReference()))
901 requireExtensions(loc, 1, &E_GL_EXT_buffer_reference2, "buffer reference math");
902 result = intermediate.addBinaryMath(op, left, right, loc);
905 if (result == nullptr)
906 binaryOpError(loc, str, left->getCompleteString(), right->getCompleteString());
911 // Handle seeing a unary node with a math operation.
912 TIntermTyped* TParseContext::handleUnaryMath(const TSourceLoc& loc, const char* str, TOperator op, TIntermTyped* childNode)
914 rValueErrorCheck(loc, str, childNode);
917 if ((childNode->getType().contains16BitFloat() && !float16Arithmetic()) ||
918 (childNode->getType().contains16BitInt() && !int16Arithmetic()) ||
919 (childNode->getType().contains8BitInt() && !int8Arithmetic())) {
923 TIntermTyped* result = nullptr;
925 result = intermediate.addUnaryMath(op, childNode, loc);
930 unaryOpError(loc, str, childNode->getCompleteString());
936 // Handle seeing a base.field dereference in the grammar.
938 TIntermTyped* TParseContext::handleDotDereference(const TSourceLoc& loc, TIntermTyped* base, const TString& field)
943 // .length() can't be resolved until we later see the function-calling syntax.
944 // Save away the name in the AST for now. Processing is completed in
945 // handleLengthMethod().
947 if (field == "length") {
948 if (base->isArray()) {
949 profileRequires(loc, ENoProfile, 120, E_GL_3DL_array_objects, ".length");
950 profileRequires(loc, EEsProfile, 300, nullptr, ".length");
951 } else if (base->isVector() || base->isMatrix()) {
952 const char* feature = ".length() on vectors and matrices";
953 requireProfile(loc, ~EEsProfile, feature);
954 profileRequires(loc, ~EEsProfile, 420, E_GL_ARB_shading_language_420pack, feature);
955 } else if (!base->getType().isCoopMat()) {
956 error(loc, "does not operate on this type:", field.c_str(), base->getType().getCompleteString().c_str());
961 return intermediate.addMethod(base, TType(EbtInt), &field, loc);
964 // It's not .length() if we get to here.
966 if (base->isArray()) {
967 error(loc, "cannot apply to an array:", ".", field.c_str());
972 if (base->getType().isCoopMat()) {
973 error(loc, "cannot apply to a cooperative matrix type:", ".", field.c_str());
977 // It's neither an array nor .length() if we get here,
978 // leaving swizzles and struct/block dereferences.
980 TIntermTyped* result = base;
981 if ((base->isVector() || base->isScalar()) &&
982 (base->isFloatingDomain() || base->isIntegerDomain() || base->getBasicType() == EbtBool)) {
983 result = handleDotSwizzle(loc, base, field);
984 } else if (base->isStruct() || base->isReference()) {
985 const TTypeList* fields = base->isReference() ?
986 base->getType().getReferentType()->getStruct() :
987 base->getType().getStruct();
988 bool fieldFound = false;
990 for (member = 0; member < (int)fields->size(); ++member) {
991 if ((*fields)[member].type->getFieldName() == field) {
997 if (base->getType().getQualifier().isFrontEndConstant())
998 result = intermediate.foldDereference(base, member, loc);
1000 blockMemberExtensionCheck(loc, base, member, field);
1001 TIntermTyped* index = intermediate.addConstantUnion(member, loc);
1002 result = intermediate.addIndex(EOpIndexDirectStruct, base, index, loc);
1003 result->setType(*(*fields)[member].type);
1004 if ((*fields)[member].type->getQualifier().isIo())
1005 intermediate.addIoAccessed(field);
1007 inheritMemoryQualifiers(base->getQualifier(), result->getWritableType().getQualifier());
1009 error(loc, "no such field in structure", field.c_str(), "");
1011 error(loc, "does not apply to this type:", field.c_str(), base->getType().getCompleteString().c_str());
1013 // Propagate noContraction up the dereference chain
1014 if (base->getQualifier().isNoContraction())
1015 result->getWritableType().getQualifier().setNoContraction();
1017 // Propagate nonuniform
1018 if (base->getQualifier().isNonUniform())
1019 result->getWritableType().getQualifier().nonUniform = true;
1025 // Handle seeing a base.swizzle, a subset of base.identifier in the grammar.
1027 TIntermTyped* TParseContext::handleDotSwizzle(const TSourceLoc& loc, TIntermTyped* base, const TString& field)
1029 TIntermTyped* result = base;
1030 if (base->isScalar()) {
1031 const char* dotFeature = "scalar swizzle";
1032 requireProfile(loc, ~EEsProfile, dotFeature);
1033 profileRequires(loc, ~EEsProfile, 420, E_GL_ARB_shading_language_420pack, dotFeature);
1036 TSwizzleSelectors<TVectorSelector> selectors;
1037 parseSwizzleSelector(loc, field, base->getVectorSize(), selectors);
1039 if (base->isVector() && selectors.size() != 1 && base->getType().contains16BitFloat())
1040 requireFloat16Arithmetic(loc, ".", "can't swizzle types containing float16");
1041 if (base->isVector() && selectors.size() != 1 && base->getType().contains16BitInt())
1042 requireInt16Arithmetic(loc, ".", "can't swizzle types containing (u)int16");
1043 if (base->isVector() && selectors.size() != 1 && base->getType().contains8BitInt())
1044 requireInt8Arithmetic(loc, ".", "can't swizzle types containing (u)int8");
1046 if (base->isScalar()) {
1047 if (selectors.size() == 1)
1050 TType type(base->getBasicType(), EvqTemporary, selectors.size());
1051 // Swizzle operations propagate specialization-constantness
1052 if (base->getQualifier().isSpecConstant())
1053 type.getQualifier().makeSpecConstant();
1054 return addConstructor(loc, base, type);
1058 if (base->getType().getQualifier().isFrontEndConstant())
1059 result = intermediate.foldSwizzle(base, selectors, loc);
1061 if (selectors.size() == 1) {
1062 TIntermTyped* index = intermediate.addConstantUnion(selectors[0], loc);
1063 result = intermediate.addIndex(EOpIndexDirect, base, index, loc);
1064 result->setType(TType(base->getBasicType(), EvqTemporary, base->getType().getQualifier().precision));
1066 TIntermTyped* index = intermediate.addSwizzle(selectors, loc);
1067 result = intermediate.addIndex(EOpVectorSwizzle, base, index, loc);
1068 result->setType(TType(base->getBasicType(), EvqTemporary, base->getType().getQualifier().precision, selectors.size()));
1070 // Swizzle operations propagate specialization-constantness
1071 if (base->getType().getQualifier().isSpecConstant())
1072 result->getWritableType().getQualifier().makeSpecConstant();
1078 void TParseContext::blockMemberExtensionCheck(const TSourceLoc& loc, const TIntermTyped* base, int member, const TString& memberName)
1080 // a block that needs extension checking is either 'base', or if arrayed,
1081 // one level removed to the left
1082 const TIntermSymbol* baseSymbol = nullptr;
1083 if (base->getAsBinaryNode() == nullptr)
1084 baseSymbol = base->getAsSymbolNode();
1086 baseSymbol = base->getAsBinaryNode()->getLeft()->getAsSymbolNode();
1087 if (baseSymbol == nullptr)
1089 const TSymbol* symbol = symbolTable.find(baseSymbol->getName());
1090 if (symbol == nullptr)
1092 const TVariable* variable = symbol->getAsVariable();
1093 if (variable == nullptr)
1095 if (!variable->hasMemberExtensions())
1098 // We now have a variable that is the base of a dot reference
1099 // with members that need extension checking.
1100 if (variable->getNumMemberExtensions(member) > 0)
1101 requireExtensions(loc, variable->getNumMemberExtensions(member), variable->getMemberExtensions(member), memberName.c_str());
1105 // Handle seeing a function declarator in the grammar. This is the precursor
1106 // to recognizing a function prototype or function definition.
1108 TFunction* TParseContext::handleFunctionDeclarator(const TSourceLoc& loc, TFunction& function, bool prototype)
1110 // ES can't declare prototypes inside functions
1111 if (! symbolTable.atGlobalLevel())
1112 requireProfile(loc, ~EEsProfile, "local function declaration");
1115 // Multiple declarations of the same function name are allowed.
1117 // If this is a definition, the definition production code will check for redefinitions
1118 // (we don't know at this point if it's a definition or not).
1120 // Redeclarations (full signature match) are allowed. But, return types and parameter qualifiers must also match.
1121 // - except ES 100, which only allows a single prototype
1123 // ES 100 does not allow redefining, but does allow overloading of built-in functions.
1124 // ES 300 does not allow redefining or overloading of built-in functions.
1127 TSymbol* symbol = symbolTable.find(function.getMangledName(), &builtIn);
1128 if (symbol && symbol->getAsFunction() && builtIn)
1129 requireProfile(loc, ~EEsProfile, "redefinition of built-in function");
1131 // Check the validity of using spirv_literal qualifier
1132 for (int i = 0; i < function.getParamCount(); ++i) {
1133 if (function[i].type->getQualifier().isSpirvLiteral() && function.getBuiltInOp() != EOpSpirvInst)
1134 error(loc, "'spirv_literal' can only be used on functions defined with 'spirv_instruction' for argument",
1135 function.getName().c_str(), "%d", i + 1);
1138 // For function declaration with SPIR-V instruction qualifier, always ignore the built-in function and
1139 // respect this redeclared one.
1140 if (symbol && builtIn && function.getBuiltInOp() == EOpSpirvInst)
1143 const TFunction* prevDec = symbol ? symbol->getAsFunction() : 0;
1145 if (prevDec->isPrototyped() && prototype)
1146 profileRequires(loc, EEsProfile, 300, nullptr, "multiple prototypes for same function");
1147 if (prevDec->getType() != function.getType())
1148 error(loc, "overloaded functions must have the same return type", function.getName().c_str(), "");
1150 if (prevDec->getSpirvInstruction() != function.getSpirvInstruction()) {
1151 error(loc, "overloaded functions must have the same qualifiers", function.getName().c_str(),
1152 "spirv_instruction");
1155 for (int i = 0; i < prevDec->getParamCount(); ++i) {
1156 if ((*prevDec)[i].type->getQualifier().storage != function[i].type->getQualifier().storage)
1157 error(loc, "overloaded functions must have the same parameter storage qualifiers for argument", function[i].type->getStorageQualifierString(), "%d", i+1);
1159 if ((*prevDec)[i].type->getQualifier().precision != function[i].type->getQualifier().precision)
1160 error(loc, "overloaded functions must have the same parameter precision qualifiers for argument", function[i].type->getPrecisionQualifierString(), "%d", i+1);
1164 arrayObjectCheck(loc, function.getType(), "array in function return type");
1167 // All built-in functions are defined, even though they don't have a body.
1168 // Count their prototype as a definition instead.
1169 if (symbolTable.atBuiltInLevel())
1170 function.setDefined();
1172 if (prevDec && ! builtIn)
1173 symbol->getAsFunction()->setPrototyped(); // need a writable one, but like having prevDec as a const
1174 function.setPrototyped();
1178 // This insert won't actually insert it if it's a duplicate signature, but it will still check for
1179 // other forms of name collisions.
1180 if (! symbolTable.insert(function))
1181 error(loc, "function name is redeclaration of existing name", function.getName().c_str(), "");
1184 // If this is a redeclaration, it could also be a definition,
1185 // in which case, we need to use the parameter names from this one, and not the one that's
1186 // being redeclared. So, pass back this declaration, not the one in the symbol table.
1192 // Handle seeing the function prototype in front of a function definition in the grammar.
1193 // The body is handled after this function returns.
1195 TIntermAggregate* TParseContext::handleFunctionDefinition(const TSourceLoc& loc, TFunction& function)
1197 currentCaller = function.getMangledName();
1198 TSymbol* symbol = symbolTable.find(function.getMangledName());
1199 TFunction* prevDec = symbol ? symbol->getAsFunction() : nullptr;
1202 error(loc, "can't find function", function.getName().c_str(), "");
1203 // Note: 'prevDec' could be 'function' if this is the first time we've seen function
1204 // as it would have just been put in the symbol table. Otherwise, we're looking up
1205 // an earlier occurrence.
1207 if (prevDec && prevDec->isDefined()) {
1208 // Then this function already has a body.
1209 error(loc, "function already has a body", function.getName().c_str(), "");
1211 if (prevDec && ! prevDec->isDefined()) {
1212 prevDec->setDefined();
1214 // Remember the return type for later checking for RETURN statements.
1215 currentFunctionType = &(prevDec->getType());
1217 currentFunctionType = new TType(EbtVoid);
1218 functionReturnsValue = false;
1220 // Check for entry point
1221 if (function.getName().compare(intermediate.getEntryPointName().c_str()) == 0) {
1222 intermediate.setEntryPointMangledName(function.getMangledName().c_str());
1223 intermediate.incrementEntryPointCount();
1229 // Raise error message if main function takes any parameters or returns anything other than void
1232 if (function.getParamCount() > 0)
1233 error(loc, "function cannot take any parameter(s)", function.getName().c_str(), "");
1234 if (function.getType().getBasicType() != EbtVoid)
1235 error(loc, "", function.getType().getBasicTypeString().c_str(), "entry point cannot return a value");
1239 // New symbol table scope for body of function plus its arguments
1244 // Insert parameters into the symbol table.
1245 // If the parameter has no name, it's not an error, just don't insert it
1246 // (could be used for unused args).
1248 // Also, accumulate the list of parameters into the HIL, so lower level code
1249 // knows where to find parameters.
1251 TIntermAggregate* paramNodes = new TIntermAggregate;
1252 for (int i = 0; i < function.getParamCount(); i++) {
1253 TParameter& param = function[i];
1254 if (param.name != nullptr) {
1255 TVariable *variable = new TVariable(param.name, *param.type);
1257 // Insert the parameters with name in the symbol table.
1258 if (! symbolTable.insert(*variable))
1259 error(loc, "redefinition", variable->getName().c_str(), "");
1261 // Transfer ownership of name pointer to symbol table.
1262 param.name = nullptr;
1264 // Add the parameter to the HIL
1265 paramNodes = intermediate.growAggregate(paramNodes,
1266 intermediate.addSymbol(*variable, loc),
1270 paramNodes = intermediate.growAggregate(paramNodes, intermediate.addSymbol(*param.type, loc), loc);
1272 intermediate.setAggregateOperator(paramNodes, EOpParameters, TType(EbtVoid), loc);
1273 loopNestingLevel = 0;
1274 statementNestingLevel = 0;
1275 controlFlowNestingLevel = 0;
1276 postEntryPointReturn = false;
1282 // Handle seeing function call syntax in the grammar, which could be any of
1283 // - .length() method
1285 // - a call to a built-in function mapped to an operator
1286 // - a call to a built-in function that will remain a function call (e.g., texturing)
1288 // - subroutine call (not implemented yet)
1290 TIntermTyped* TParseContext::handleFunctionCall(const TSourceLoc& loc, TFunction* function, TIntermNode* arguments)
1292 TIntermTyped* result = nullptr;
1294 if (spvVersion.vulkan != 0 && spvVersion.vulkanRelaxed) {
1295 // allow calls that are invalid in Vulkan Semantics to be invisibily
1296 // remapped to equivalent valid functions
1297 result = vkRelaxedRemapFunctionCall(loc, function, arguments);
1302 if (function->getBuiltInOp() == EOpArrayLength)
1303 result = handleLengthMethod(loc, function, arguments);
1304 else if (function->getBuiltInOp() != EOpNull) {
1306 // Then this should be a constructor.
1307 // Don't go through the symbol table for constructors.
1308 // Their parameters will be verified algorithmically.
1310 TType type(EbtVoid); // use this to get the type back
1311 if (! constructorError(loc, arguments, *function, function->getBuiltInOp(), type)) {
1313 // It's a constructor, of type 'type'.
1315 result = addConstructor(loc, arguments, type);
1316 if (result == nullptr)
1317 error(loc, "cannot construct with these arguments", type.getCompleteString().c_str(), "");
1321 // Find it in the symbol table.
1323 const TFunction* fnCandidate;
1325 fnCandidate = findFunction(loc, *function, builtIn);
1327 // This is a declared function that might map to
1328 // - a built-in operator,
1329 // - a built-in function not mapped to an operator, or
1330 // - a user function.
1332 // Error check for a function requiring specific extensions present.
1333 if (builtIn && fnCandidate->getNumExtensions())
1334 requireExtensions(loc, fnCandidate->getNumExtensions(), fnCandidate->getExtensions(), fnCandidate->getName().c_str());
1336 if (builtIn && fnCandidate->getType().contains16BitFloat())
1337 requireFloat16Arithmetic(loc, "built-in function", "float16 types can only be in uniform block or buffer storage");
1338 if (builtIn && fnCandidate->getType().contains16BitInt())
1339 requireInt16Arithmetic(loc, "built-in function", "(u)int16 types can only be in uniform block or buffer storage");
1340 if (builtIn && fnCandidate->getType().contains8BitInt())
1341 requireInt8Arithmetic(loc, "built-in function", "(u)int8 types can only be in uniform block or buffer storage");
1343 if (arguments != nullptr) {
1344 // Make sure qualifications work for these arguments.
1345 TIntermAggregate* aggregate = arguments->getAsAggregate();
1346 for (int i = 0; i < fnCandidate->getParamCount(); ++i) {
1347 // At this early point there is a slight ambiguity between whether an aggregate 'arguments'
1348 // is the single argument itself or its children are the arguments. Only one argument
1349 // means take 'arguments' itself as the one argument.
1350 TIntermNode* arg = fnCandidate->getParamCount() == 1 ? arguments : (aggregate ? aggregate->getSequence()[i] : arguments);
1351 TQualifier& formalQualifier = (*fnCandidate)[i].type->getQualifier();
1352 if (formalQualifier.isParamOutput()) {
1353 if (lValueErrorCheck(arguments->getLoc(), "assign", arg->getAsTyped()))
1354 error(arguments->getLoc(), "Non-L-value cannot be passed for 'out' or 'inout' parameters.", "out", "");
1357 if (formalQualifier.isSpirvLiteral()) {
1358 if (!arg->getAsTyped()->getQualifier().isFrontEndConstant()) {
1359 error(arguments->getLoc(),
1360 "Non front-end constant expressions cannot be passed for 'spirv_literal' parameters.",
1361 "spirv_literal", "");
1365 const TType& argType = arg->getAsTyped()->getType();
1366 const TQualifier& argQualifier = argType.getQualifier();
1367 if (argQualifier.isMemory() && (argType.containsOpaque() || argType.isReference())) {
1368 const char* message = "argument cannot drop memory qualifier when passed to formal parameter";
1370 if (argQualifier.volatil && ! formalQualifier.volatil)
1371 error(arguments->getLoc(), message, "volatile", "");
1372 if (argQualifier.coherent && ! (formalQualifier.devicecoherent || formalQualifier.coherent))
1373 error(arguments->getLoc(), message, "coherent", "");
1374 if (argQualifier.devicecoherent && ! (formalQualifier.devicecoherent || formalQualifier.coherent))
1375 error(arguments->getLoc(), message, "devicecoherent", "");
1376 if (argQualifier.queuefamilycoherent && ! (formalQualifier.queuefamilycoherent || formalQualifier.devicecoherent || formalQualifier.coherent))
1377 error(arguments->getLoc(), message, "queuefamilycoherent", "");
1378 if (argQualifier.workgroupcoherent && ! (formalQualifier.workgroupcoherent || formalQualifier.queuefamilycoherent || formalQualifier.devicecoherent || formalQualifier.coherent))
1379 error(arguments->getLoc(), message, "workgroupcoherent", "");
1380 if (argQualifier.subgroupcoherent && ! (formalQualifier.subgroupcoherent || formalQualifier.workgroupcoherent || formalQualifier.queuefamilycoherent || formalQualifier.devicecoherent || formalQualifier.coherent))
1381 error(arguments->getLoc(), message, "subgroupcoherent", "");
1382 if (argQualifier.readonly && ! formalQualifier.readonly)
1383 error(arguments->getLoc(), message, "readonly", "");
1384 if (argQualifier.writeonly && ! formalQualifier.writeonly)
1385 error(arguments->getLoc(), message, "writeonly", "");
1386 // Don't check 'restrict', it is different than the rest:
1387 // "...but only restrict can be taken away from a calling argument, by a formal parameter that
1388 // lacks the restrict qualifier..."
1391 if (!builtIn && argQualifier.getFormat() != formalQualifier.getFormat()) {
1392 // we have mismatched formats, which should only be allowed if writeonly
1393 // and at least one format is unknown
1394 if (!formalQualifier.isWriteOnly() || (formalQualifier.getFormat() != ElfNone &&
1395 argQualifier.getFormat() != ElfNone))
1396 error(arguments->getLoc(), "image formats must match", "format", "");
1398 if (builtIn && arg->getAsTyped()->getType().contains16BitFloat())
1399 requireFloat16Arithmetic(arguments->getLoc(), "built-in function", "float16 types can only be in uniform block or buffer storage");
1400 if (builtIn && arg->getAsTyped()->getType().contains16BitInt())
1401 requireInt16Arithmetic(arguments->getLoc(), "built-in function", "(u)int16 types can only be in uniform block or buffer storage");
1402 if (builtIn && arg->getAsTyped()->getType().contains8BitInt())
1403 requireInt8Arithmetic(arguments->getLoc(), "built-in function", "(u)int8 types can only be in uniform block or buffer storage");
1405 // TODO 4.5 functionality: A shader will fail to compile
1406 // if the value passed to the memargument of an atomic memory function does not correspond to a buffer or
1407 // shared variable. It is acceptable to pass an element of an array or a single component of a vector to the
1408 // memargument of an atomic memory function, as long as the underlying array or vector is a buffer or
1412 // Convert 'in' arguments
1413 addInputArgumentConversions(*fnCandidate, arguments); // arguments may be modified if it's just a single argument node
1416 if (builtIn && fnCandidate->getBuiltInOp() != EOpNull) {
1417 // A function call mapped to a built-in operation.
1418 result = handleBuiltInFunctionCall(loc, arguments, *fnCandidate);
1420 } else if (fnCandidate->getBuiltInOp() == EOpSpirvInst) {
1421 // When SPIR-V instruction qualifier is specified, the function call is still mapped to a built-in operation.
1422 result = handleBuiltInFunctionCall(loc, arguments, *fnCandidate);
1425 // This is a function call not mapped to built-in operator.
1426 // It could still be a built-in function, but only if PureOperatorBuiltins == false.
1427 result = intermediate.setAggregateOperator(arguments, EOpFunctionCall, fnCandidate->getType(), loc);
1428 TIntermAggregate* call = result->getAsAggregate();
1429 call->setName(fnCandidate->getMangledName());
1431 // this is how we know whether the given function is a built-in function or a user-defined function
1432 // if builtIn == false, it's a userDefined -> could be an overloaded built-in function also
1433 // if builtIn == true, it's definitely a built-in function with EOpNull
1435 call->setUserDefined();
1436 if (symbolTable.atGlobalLevel()) {
1437 requireProfile(loc, ~EEsProfile, "calling user function from global scope");
1438 intermediate.addToCallGraph(infoSink, "main(", fnCandidate->getMangledName());
1440 intermediate.addToCallGraph(infoSink, currentCaller, fnCandidate->getMangledName());
1445 nonOpBuiltInCheck(loc, *fnCandidate, *call);
1448 userFunctionCallCheck(loc, *call);
1451 // Convert 'out' arguments. If it was a constant folded built-in, it won't be an aggregate anymore.
1452 // Built-ins with a single argument aren't called with an aggregate, but they also don't have an output.
1453 // Also, build the qualifier list for user function calls, which are always called with an aggregate.
1454 if (result->getAsAggregate()) {
1455 TQualifierList& qualifierList = result->getAsAggregate()->getQualifierList();
1456 for (int i = 0; i < fnCandidate->getParamCount(); ++i) {
1457 TStorageQualifier qual = (*fnCandidate)[i].type->getQualifier().storage;
1458 qualifierList.push_back(qual);
1460 result = addOutputArgumentConversions(*fnCandidate, *result->getAsAggregate());
1463 if (result->getAsTyped()->getType().isCoopMat() &&
1464 !result->getAsTyped()->getType().isParameterized()) {
1465 assert(fnCandidate->getBuiltInOp() == EOpCooperativeMatrixMulAdd);
1467 result->setType(result->getAsAggregate()->getSequence()[2]->getAsTyped()->getType());
1472 // generic error recovery
1473 // TODO: simplification: localize all the error recoveries that look like this, and taking type into account to reduce cascades
1474 if (result == nullptr)
1475 result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
1480 TIntermTyped* TParseContext::handleBuiltInFunctionCall(TSourceLoc loc, TIntermNode* arguments,
1481 const TFunction& function)
1483 checkLocation(loc, function.getBuiltInOp());
1484 TIntermTyped *result = intermediate.addBuiltInFunctionCall(loc, function.getBuiltInOp(),
1485 function.getParamCount() == 1,
1486 arguments, function.getType());
1487 if (result != nullptr && obeyPrecisionQualifiers())
1488 computeBuiltinPrecisions(*result, function);
1490 if (result == nullptr) {
1491 if (arguments == nullptr)
1492 error(loc, " wrong operand type", "Internal Error",
1493 "built in unary operator function. Type: %s", "");
1495 error(arguments->getLoc(), " wrong operand type", "Internal Error",
1496 "built in unary operator function. Type: %s",
1497 static_cast<TIntermTyped*>(arguments)->getCompleteString().c_str());
1498 } else if (result->getAsOperator())
1499 builtInOpCheck(loc, function, *result->getAsOperator());
1502 // Special handling for function call with SPIR-V instruction qualifier specified
1503 if (function.getBuiltInOp() == EOpSpirvInst) {
1504 if (auto agg = result->getAsAggregate()) {
1505 // Propogate spirv_by_reference/spirv_literal from parameters to arguments
1506 auto& sequence = agg->getSequence();
1507 for (unsigned i = 0; i < sequence.size(); ++i) {
1508 if (function[i].type->getQualifier().isSpirvByReference())
1509 sequence[i]->getAsTyped()->getQualifier().setSpirvByReference();
1510 if (function[i].type->getQualifier().isSpirvLiteral())
1511 sequence[i]->getAsTyped()->getQualifier().setSpirvLiteral();
1514 // Attach the function call to SPIR-V intruction
1515 agg->setSpirvInstruction(function.getSpirvInstruction());
1516 } else if (auto unaryNode = result->getAsUnaryNode()) {
1517 // Propogate spirv_by_reference/spirv_literal from parameters to arguments
1518 if (function[0].type->getQualifier().isSpirvByReference())
1519 unaryNode->getOperand()->getQualifier().setSpirvByReference();
1520 if (function[0].type->getQualifier().isSpirvLiteral())
1521 unaryNode->getOperand()->getQualifier().setSpirvLiteral();
1523 // Attach the function call to SPIR-V intruction
1524 unaryNode->setSpirvInstruction(function.getSpirvInstruction());
1533 // "The operation of a built-in function can have a different precision
1534 // qualification than the precision qualification of the resulting value.
1535 // These two precision qualifications are established as follows.
1537 // The precision qualification of the operation of a built-in function is
1538 // based on the precision qualification of its input arguments and formal
1539 // parameters: When a formal parameter specifies a precision qualifier,
1540 // that is used, otherwise, the precision qualification of the calling
1541 // argument is used. The highest precision of these will be the precision
1542 // qualification of the operation of the built-in function. Generally,
1543 // this is applied across all arguments to a built-in function, with the
1544 // exceptions being:
1545 // - bitfieldExtract and bitfieldInsert ignore the 'offset' and 'bits'
1547 // - interpolateAt* functions only look at the 'interpolant' argument.
1549 // The precision qualification of the result of a built-in function is
1550 // determined in one of the following ways:
1552 // - For the texture sampling, image load, and image store functions,
1553 // the precision of the return type matches the precision of the
1558 // - For prototypes that do not specify a resulting precision qualifier,
1559 // the precision will be the same as the precision of the operation.
1561 // - For prototypes that do specify a resulting precision qualifier,
1562 // the specified precision qualifier is the precision qualification of
1565 void TParseContext::computeBuiltinPrecisions(TIntermTyped& node, const TFunction& function)
1567 TPrecisionQualifier operationPrecision = EpqNone;
1568 TPrecisionQualifier resultPrecision = EpqNone;
1570 TIntermOperator* opNode = node.getAsOperator();
1571 if (opNode == nullptr)
1574 if (TIntermUnary* unaryNode = node.getAsUnaryNode()) {
1575 operationPrecision = std::max(function[0].type->getQualifier().precision,
1576 unaryNode->getOperand()->getType().getQualifier().precision);
1577 if (function.getType().getBasicType() != EbtBool)
1578 resultPrecision = function.getType().getQualifier().precision == EpqNone ?
1579 operationPrecision :
1580 function.getType().getQualifier().precision;
1581 } else if (TIntermAggregate* agg = node.getAsAggregate()) {
1582 TIntermSequence& sequence = agg->getSequence();
1583 unsigned int numArgs = (unsigned int)sequence.size();
1584 switch (agg->getOp()) {
1585 case EOpBitfieldExtract:
1588 case EOpBitfieldInsert:
1591 case EOpInterpolateAtCentroid:
1592 case EOpInterpolateAtOffset:
1593 case EOpInterpolateAtSample:
1596 case EOpDebugPrintf:
1602 // find the maximum precision from the arguments and parameters
1603 for (unsigned int arg = 0; arg < numArgs; ++arg) {
1604 operationPrecision = std::max(operationPrecision, sequence[arg]->getAsTyped()->getQualifier().precision);
1605 operationPrecision = std::max(operationPrecision, function[arg].type->getQualifier().precision);
1607 // compute the result precision
1608 if (agg->isSampling() ||
1609 agg->getOp() == EOpImageLoad || agg->getOp() == EOpImageStore ||
1610 agg->getOp() == EOpImageLoadLod || agg->getOp() == EOpImageStoreLod)
1611 resultPrecision = sequence[0]->getAsTyped()->getQualifier().precision;
1612 else if (function.getType().getBasicType() != EbtBool)
1613 resultPrecision = function.getType().getQualifier().precision == EpqNone ?
1614 operationPrecision :
1615 function.getType().getQualifier().precision;
1618 // Propagate precision through this node and its children. That algorithm stops
1619 // when a precision is found, so start by clearing this subroot precision
1620 opNode->getQualifier().precision = EpqNone;
1621 if (operationPrecision != EpqNone) {
1622 opNode->propagatePrecision(operationPrecision);
1623 opNode->setOperationPrecision(operationPrecision);
1625 // Now, set the result precision, which might not match
1626 opNode->getQualifier().precision = resultPrecision;
1629 TIntermNode* TParseContext::handleReturnValue(const TSourceLoc& loc, TIntermTyped* value)
1632 storage16BitAssignmentCheck(loc, value->getType(), "return");
1635 functionReturnsValue = true;
1636 TIntermBranch* branch = nullptr;
1637 if (currentFunctionType->getBasicType() == EbtVoid) {
1638 error(loc, "void function cannot return a value", "return", "");
1639 branch = intermediate.addBranch(EOpReturn, loc);
1640 } else if (*currentFunctionType != value->getType()) {
1641 TIntermTyped* converted = intermediate.addConversion(EOpReturn, *currentFunctionType, value);
1643 if (*currentFunctionType != converted->getType())
1644 error(loc, "cannot convert return value to function return type", "return", "");
1646 warn(loc, "type conversion on return values was not explicitly allowed until version 420",
1648 branch = intermediate.addBranch(EOpReturn, converted, loc);
1650 error(loc, "type does not match, or is not convertible to, the function's return type", "return", "");
1651 branch = intermediate.addBranch(EOpReturn, value, loc);
1654 branch = intermediate.addBranch(EOpReturn, value, loc);
1656 branch->updatePrecision(currentFunctionType->getQualifier().precision);
1660 // See if the operation is being done in an illegal location.
1661 void TParseContext::checkLocation(const TSourceLoc& loc, TOperator op)
1666 if (language == EShLangTessControl) {
1667 if (controlFlowNestingLevel > 0)
1668 error(loc, "tessellation control barrier() cannot be placed within flow control", "", "");
1670 error(loc, "tessellation control barrier() must be in main()", "", "");
1671 else if (postEntryPointReturn)
1672 error(loc, "tessellation control barrier() cannot be placed after a return from main()", "", "");
1675 case EOpBeginInvocationInterlock:
1676 if (language != EShLangFragment)
1677 error(loc, "beginInvocationInterlockARB() must be in a fragment shader", "", "");
1679 error(loc, "beginInvocationInterlockARB() must be in main()", "", "");
1680 else if (postEntryPointReturn)
1681 error(loc, "beginInvocationInterlockARB() cannot be placed after a return from main()", "", "");
1682 if (controlFlowNestingLevel > 0)
1683 error(loc, "beginInvocationInterlockARB() cannot be placed within flow control", "", "");
1685 if (beginInvocationInterlockCount > 0)
1686 error(loc, "beginInvocationInterlockARB() must only be called once", "", "");
1687 if (endInvocationInterlockCount > 0)
1688 error(loc, "beginInvocationInterlockARB() must be called before endInvocationInterlockARB()", "", "");
1690 beginInvocationInterlockCount++;
1692 // default to pixel_interlock_ordered
1693 if (intermediate.getInterlockOrdering() == EioNone)
1694 intermediate.setInterlockOrdering(EioPixelInterlockOrdered);
1696 case EOpEndInvocationInterlock:
1697 if (language != EShLangFragment)
1698 error(loc, "endInvocationInterlockARB() must be in a fragment shader", "", "");
1700 error(loc, "endInvocationInterlockARB() must be in main()", "", "");
1701 else if (postEntryPointReturn)
1702 error(loc, "endInvocationInterlockARB() cannot be placed after a return from main()", "", "");
1703 if (controlFlowNestingLevel > 0)
1704 error(loc, "endInvocationInterlockARB() cannot be placed within flow control", "", "");
1706 if (endInvocationInterlockCount > 0)
1707 error(loc, "endInvocationInterlockARB() must only be called once", "", "");
1708 if (beginInvocationInterlockCount == 0)
1709 error(loc, "beginInvocationInterlockARB() must be called before endInvocationInterlockARB()", "", "");
1711 endInvocationInterlockCount++;
1719 // Finish processing object.length(). This started earlier in handleDotDereference(), where
1720 // the ".length" part was recognized and semantically checked, and finished here where the
1721 // function syntax "()" is recognized.
1723 // Return resulting tree node.
1724 TIntermTyped* TParseContext::handleLengthMethod(const TSourceLoc& loc, TFunction* function, TIntermNode* intermNode)
1728 if (function->getParamCount() > 0)
1729 error(loc, "method does not accept any arguments", function->getName().c_str(), "");
1731 const TType& type = intermNode->getAsTyped()->getType();
1732 if (type.isArray()) {
1733 if (type.isUnsizedArray()) {
1735 if (intermNode->getAsSymbolNode() && isIoResizeArray(type)) {
1736 // We could be between a layout declaration that gives a built-in io array implicit size and
1737 // a user redeclaration of that array, meaning we have to substitute its implicit size here
1738 // without actually redeclaring the array. (It is an error to use a member before the
1739 // redeclaration, but not an error to use the array name itself.)
1740 const TString& name = intermNode->getAsSymbolNode()->getName();
1741 if (name == "gl_in" || name == "gl_out" || name == "gl_MeshVerticesNV" ||
1742 name == "gl_MeshPrimitivesNV") {
1743 length = getIoArrayImplicitSize(type.getQualifier());
1749 if (intermNode->getAsSymbolNode() && isIoResizeArray(type))
1750 error(loc, "", function->getName().c_str(), "array must first be sized by a redeclaration or layout qualifier");
1751 else if (isRuntimeLength(*intermNode->getAsTyped())) {
1752 // Create a unary op and let the back end handle it
1753 return intermediate.addBuiltInFunctionCall(loc, EOpArrayLength, true, intermNode, TType(EbtInt));
1756 error(loc, "", function->getName().c_str(), "array must be declared with a size before using this method");
1758 } else if (type.getOuterArrayNode()) {
1759 // If the array's outer size is specified by an intermediate node, it means the array's length
1760 // was specified by a specialization constant. In such a case, we should return the node of the
1761 // specialization constants to represent the length.
1762 return type.getOuterArrayNode();
1764 length = type.getOuterArraySize();
1765 } else if (type.isMatrix())
1766 length = type.getMatrixCols();
1767 else if (type.isVector())
1768 length = type.getVectorSize();
1769 else if (type.isCoopMat())
1770 return intermediate.addBuiltInFunctionCall(loc, EOpArrayLength, true, intermNode, TType(EbtInt));
1772 // we should not get here, because earlier semantic checking should have prevented this path
1773 error(loc, ".length()", "unexpected use of .length()", "");
1780 return intermediate.addConstantUnion(length, loc);
1784 // Add any needed implicit conversions for function-call arguments to input parameters.
1786 void TParseContext::addInputArgumentConversions(const TFunction& function, TIntermNode*& arguments) const
1789 TIntermAggregate* aggregate = arguments->getAsAggregate();
1791 // Process each argument's conversion
1792 for (int i = 0; i < function.getParamCount(); ++i) {
1793 // At this early point there is a slight ambiguity between whether an aggregate 'arguments'
1794 // is the single argument itself or its children are the arguments. Only one argument
1795 // means take 'arguments' itself as the one argument.
1796 TIntermTyped* arg = function.getParamCount() == 1 ? arguments->getAsTyped() : (aggregate ? aggregate->getSequence()[i]->getAsTyped() : arguments->getAsTyped());
1797 if (*function[i].type != arg->getType()) {
1798 if (function[i].type->getQualifier().isParamInput() &&
1799 !function[i].type->isCoopMat()) {
1800 // In-qualified arguments just need an extra node added above the argument to
1801 // convert to the correct type.
1802 arg = intermediate.addConversion(EOpFunctionCall, *function[i].type, arg);
1804 if (function.getParamCount() == 1)
1808 aggregate->getSequence()[i] = arg;
1820 // Add any needed implicit output conversions for function-call arguments. This
1821 // can require a new tree topology, complicated further by whether the function
1822 // has a return value.
1824 // Returns a node of a subtree that evaluates to the return value of the function.
1826 TIntermTyped* TParseContext::addOutputArgumentConversions(const TFunction& function, TIntermAggregate& intermNode) const
1831 TIntermSequence& arguments = intermNode.getSequence();
1833 // Will there be any output conversions?
1834 bool outputConversions = false;
1835 for (int i = 0; i < function.getParamCount(); ++i) {
1836 if (*function[i].type != arguments[i]->getAsTyped()->getType() && function[i].type->getQualifier().isParamOutput()) {
1837 outputConversions = true;
1842 if (! outputConversions)
1845 // Setup for the new tree, if needed:
1847 // Output conversions need a different tree topology.
1848 // Out-qualified arguments need a temporary of the correct type, with the call
1849 // followed by an assignment of the temporary to the original argument:
1850 // void: function(arg, ...) -> ( function(tempArg, ...), arg = tempArg, ...)
1851 // ret = function(arg, ...) -> ret = (tempRet = function(tempArg, ...), arg = tempArg, ..., tempRet)
1852 // Where the "tempArg" type needs no conversion as an argument, but will convert on assignment.
1853 TIntermTyped* conversionTree = nullptr;
1854 TVariable* tempRet = nullptr;
1855 if (intermNode.getBasicType() != EbtVoid) {
1856 // do the "tempRet = function(...), " bit from above
1857 tempRet = makeInternalVariable("tempReturn", intermNode.getType());
1858 TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, intermNode.getLoc());
1859 conversionTree = intermediate.addAssign(EOpAssign, tempRetNode, &intermNode, intermNode.getLoc());
1861 conversionTree = &intermNode;
1863 conversionTree = intermediate.makeAggregate(conversionTree);
1865 // Process each argument's conversion
1866 for (int i = 0; i < function.getParamCount(); ++i) {
1867 if (*function[i].type != arguments[i]->getAsTyped()->getType()) {
1868 if (function[i].type->getQualifier().isParamOutput()) {
1869 // Out-qualified arguments need to use the topology set up above.
1870 // do the " ...(tempArg, ...), arg = tempArg" bit from above
1872 paramType.shallowCopy(*function[i].type);
1873 if (arguments[i]->getAsTyped()->getType().isParameterized() &&
1874 !paramType.isParameterized()) {
1875 paramType.shallowCopy(arguments[i]->getAsTyped()->getType());
1876 paramType.copyTypeParameters(*arguments[i]->getAsTyped()->getType().getTypeParameters());
1878 TVariable* tempArg = makeInternalVariable("tempArg", paramType);
1879 tempArg->getWritableType().getQualifier().makeTemporary();
1880 TIntermSymbol* tempArgNode = intermediate.addSymbol(*tempArg, intermNode.getLoc());
1881 TIntermTyped* tempAssign = intermediate.addAssign(EOpAssign, arguments[i]->getAsTyped(), tempArgNode, arguments[i]->getLoc());
1882 conversionTree = intermediate.growAggregate(conversionTree, tempAssign, arguments[i]->getLoc());
1883 // replace the argument with another node for the same tempArg variable
1884 arguments[i] = intermediate.addSymbol(*tempArg, intermNode.getLoc());
1889 // Finalize the tree topology (see bigger comment above).
1891 // do the "..., tempRet" bit from above
1892 TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, intermNode.getLoc());
1893 conversionTree = intermediate.growAggregate(conversionTree, tempRetNode, intermNode.getLoc());
1895 conversionTree = intermediate.setAggregateOperator(conversionTree, EOpComma, intermNode.getType(), intermNode.getLoc());
1897 return conversionTree;
1901 TIntermTyped* TParseContext::addAssign(const TSourceLoc& loc, TOperator op, TIntermTyped* left, TIntermTyped* right)
1903 if ((op == EOpAddAssign || op == EOpSubAssign) && left->isReference())
1904 requireExtensions(loc, 1, &E_GL_EXT_buffer_reference2, "+= and -= on a buffer reference");
1906 return intermediate.addAssign(op, left, right, loc);
1909 void TParseContext::memorySemanticsCheck(const TSourceLoc& loc, const TFunction& fnCandidate, const TIntermOperator& callNode)
1911 const TIntermSequence* argp = &callNode.getAsAggregate()->getSequence();
1913 //const int gl_SemanticsRelaxed = 0x0;
1914 const int gl_SemanticsAcquire = 0x2;
1915 const int gl_SemanticsRelease = 0x4;
1916 const int gl_SemanticsAcquireRelease = 0x8;
1917 const int gl_SemanticsMakeAvailable = 0x2000;
1918 const int gl_SemanticsMakeVisible = 0x4000;
1919 const int gl_SemanticsVolatile = 0x8000;
1921 //const int gl_StorageSemanticsNone = 0x0;
1922 const int gl_StorageSemanticsBuffer = 0x40;
1923 const int gl_StorageSemanticsShared = 0x100;
1924 const int gl_StorageSemanticsImage = 0x800;
1925 const int gl_StorageSemanticsOutput = 0x1000;
1928 unsigned int semantics = 0, storageClassSemantics = 0;
1929 unsigned int semantics2 = 0, storageClassSemantics2 = 0;
1931 const TIntermTyped* arg0 = (*argp)[0]->getAsTyped();
1932 const bool isMS = arg0->getBasicType() == EbtSampler && arg0->getType().getSampler().isMultiSample();
1934 // Grab the semantics and storage class semantics from the operands, based on opcode
1935 switch (callNode.getOp()) {
1937 case EOpAtomicSubtract:
1943 case EOpAtomicExchange:
1944 case EOpAtomicStore:
1945 storageClassSemantics = (*argp)[3]->getAsConstantUnion()->getConstArray()[0].getIConst();
1946 semantics = (*argp)[4]->getAsConstantUnion()->getConstArray()[0].getIConst();
1949 storageClassSemantics = (*argp)[2]->getAsConstantUnion()->getConstArray()[0].getIConst();
1950 semantics = (*argp)[3]->getAsConstantUnion()->getConstArray()[0].getIConst();
1952 case EOpAtomicCompSwap:
1953 storageClassSemantics = (*argp)[4]->getAsConstantUnion()->getConstArray()[0].getIConst();
1954 semantics = (*argp)[5]->getAsConstantUnion()->getConstArray()[0].getIConst();
1955 storageClassSemantics2 = (*argp)[6]->getAsConstantUnion()->getConstArray()[0].getIConst();
1956 semantics2 = (*argp)[7]->getAsConstantUnion()->getConstArray()[0].getIConst();
1959 case EOpImageAtomicAdd:
1960 case EOpImageAtomicMin:
1961 case EOpImageAtomicMax:
1962 case EOpImageAtomicAnd:
1963 case EOpImageAtomicOr:
1964 case EOpImageAtomicXor:
1965 case EOpImageAtomicExchange:
1966 case EOpImageAtomicStore:
1967 storageClassSemantics = (*argp)[isMS ? 5 : 4]->getAsConstantUnion()->getConstArray()[0].getIConst();
1968 semantics = (*argp)[isMS ? 6 : 5]->getAsConstantUnion()->getConstArray()[0].getIConst();
1970 case EOpImageAtomicLoad:
1971 storageClassSemantics = (*argp)[isMS ? 4 : 3]->getAsConstantUnion()->getConstArray()[0].getIConst();
1972 semantics = (*argp)[isMS ? 5 : 4]->getAsConstantUnion()->getConstArray()[0].getIConst();
1974 case EOpImageAtomicCompSwap:
1975 storageClassSemantics = (*argp)[isMS ? 6 : 5]->getAsConstantUnion()->getConstArray()[0].getIConst();
1976 semantics = (*argp)[isMS ? 7 : 6]->getAsConstantUnion()->getConstArray()[0].getIConst();
1977 storageClassSemantics2 = (*argp)[isMS ? 8 : 7]->getAsConstantUnion()->getConstArray()[0].getIConst();
1978 semantics2 = (*argp)[isMS ? 9 : 8]->getAsConstantUnion()->getConstArray()[0].getIConst();
1982 storageClassSemantics = (*argp)[2]->getAsConstantUnion()->getConstArray()[0].getIConst();
1983 semantics = (*argp)[3]->getAsConstantUnion()->getConstArray()[0].getIConst();
1985 case EOpMemoryBarrier:
1986 storageClassSemantics = (*argp)[1]->getAsConstantUnion()->getConstArray()[0].getIConst();
1987 semantics = (*argp)[2]->getAsConstantUnion()->getConstArray()[0].getIConst();
1993 if ((semantics & gl_SemanticsAcquire) &&
1994 (callNode.getOp() == EOpAtomicStore || callNode.getOp() == EOpImageAtomicStore)) {
1995 error(loc, "gl_SemanticsAcquire must not be used with (image) atomic store",
1996 fnCandidate.getName().c_str(), "");
1998 if ((semantics & gl_SemanticsRelease) &&
1999 (callNode.getOp() == EOpAtomicLoad || callNode.getOp() == EOpImageAtomicLoad)) {
2000 error(loc, "gl_SemanticsRelease must not be used with (image) atomic load",
2001 fnCandidate.getName().c_str(), "");
2003 if ((semantics & gl_SemanticsAcquireRelease) &&
2004 (callNode.getOp() == EOpAtomicStore || callNode.getOp() == EOpImageAtomicStore ||
2005 callNode.getOp() == EOpAtomicLoad || callNode.getOp() == EOpImageAtomicLoad)) {
2006 error(loc, "gl_SemanticsAcquireRelease must not be used with (image) atomic load/store",
2007 fnCandidate.getName().c_str(), "");
2009 if (((semantics | semantics2) & ~(gl_SemanticsAcquire |
2010 gl_SemanticsRelease |
2011 gl_SemanticsAcquireRelease |
2012 gl_SemanticsMakeAvailable |
2013 gl_SemanticsMakeVisible |
2014 gl_SemanticsVolatile))) {
2015 error(loc, "Invalid semantics value", fnCandidate.getName().c_str(), "");
2017 if (((storageClassSemantics | storageClassSemantics2) & ~(gl_StorageSemanticsBuffer |
2018 gl_StorageSemanticsShared |
2019 gl_StorageSemanticsImage |
2020 gl_StorageSemanticsOutput))) {
2021 error(loc, "Invalid storage class semantics value", fnCandidate.getName().c_str(), "");
2024 if (callNode.getOp() == EOpMemoryBarrier) {
2025 if (!IsPow2(semantics & (gl_SemanticsAcquire | gl_SemanticsRelease | gl_SemanticsAcquireRelease))) {
2026 error(loc, "Semantics must include exactly one of gl_SemanticsRelease, gl_SemanticsAcquire, or "
2027 "gl_SemanticsAcquireRelease", fnCandidate.getName().c_str(), "");
2030 if (semantics & (gl_SemanticsAcquire | gl_SemanticsRelease | gl_SemanticsAcquireRelease)) {
2031 if (!IsPow2(semantics & (gl_SemanticsAcquire | gl_SemanticsRelease | gl_SemanticsAcquireRelease))) {
2032 error(loc, "Semantics must not include multiple of gl_SemanticsRelease, gl_SemanticsAcquire, or "
2033 "gl_SemanticsAcquireRelease", fnCandidate.getName().c_str(), "");
2036 if (semantics2 & (gl_SemanticsAcquire | gl_SemanticsRelease | gl_SemanticsAcquireRelease)) {
2037 if (!IsPow2(semantics2 & (gl_SemanticsAcquire | gl_SemanticsRelease | gl_SemanticsAcquireRelease))) {
2038 error(loc, "semUnequal must not include multiple of gl_SemanticsRelease, gl_SemanticsAcquire, or "
2039 "gl_SemanticsAcquireRelease", fnCandidate.getName().c_str(), "");
2043 if (callNode.getOp() == EOpMemoryBarrier) {
2044 if (storageClassSemantics == 0) {
2045 error(loc, "Storage class semantics must not be zero", fnCandidate.getName().c_str(), "");
2048 if (callNode.getOp() == EOpBarrier && semantics != 0 && storageClassSemantics == 0) {
2049 error(loc, "Storage class semantics must not be zero", fnCandidate.getName().c_str(), "");
2051 if ((callNode.getOp() == EOpAtomicCompSwap || callNode.getOp() == EOpImageAtomicCompSwap) &&
2052 (semantics2 & (gl_SemanticsRelease | gl_SemanticsAcquireRelease))) {
2053 error(loc, "semUnequal must not be gl_SemanticsRelease or gl_SemanticsAcquireRelease",
2054 fnCandidate.getName().c_str(), "");
2056 if ((semantics & gl_SemanticsMakeAvailable) &&
2057 !(semantics & (gl_SemanticsRelease | gl_SemanticsAcquireRelease))) {
2058 error(loc, "gl_SemanticsMakeAvailable requires gl_SemanticsRelease or gl_SemanticsAcquireRelease",
2059 fnCandidate.getName().c_str(), "");
2061 if ((semantics & gl_SemanticsMakeVisible) &&
2062 !(semantics & (gl_SemanticsAcquire | gl_SemanticsAcquireRelease))) {
2063 error(loc, "gl_SemanticsMakeVisible requires gl_SemanticsAcquire or gl_SemanticsAcquireRelease",
2064 fnCandidate.getName().c_str(), "");
2066 if ((semantics & gl_SemanticsVolatile) &&
2067 (callNode.getOp() == EOpMemoryBarrier || callNode.getOp() == EOpBarrier)) {
2068 error(loc, "gl_SemanticsVolatile must not be used with memoryBarrier or controlBarrier",
2069 fnCandidate.getName().c_str(), "");
2071 if ((callNode.getOp() == EOpAtomicCompSwap || callNode.getOp() == EOpImageAtomicCompSwap) &&
2072 ((semantics ^ semantics2) & gl_SemanticsVolatile)) {
2073 error(loc, "semEqual and semUnequal must either both include gl_SemanticsVolatile or neither",
2074 fnCandidate.getName().c_str(), "");
2079 // Do additional checking of built-in function calls that is not caught
2080 // by normal semantic checks on argument type, extension tagging, etc.
2082 // Assumes there has been a semantically correct match to a built-in function prototype.
2084 void TParseContext::builtInOpCheck(const TSourceLoc& loc, const TFunction& fnCandidate, TIntermOperator& callNode)
2086 // Set up convenience accessors to the argument(s). There is almost always
2087 // multiple arguments for the cases below, but when there might be one,
2088 // check the unaryArg first.
2089 const TIntermSequence* argp = nullptr; // confusing to use [] syntax on a pointer, so this is to help get a reference
2090 const TIntermTyped* unaryArg = nullptr;
2091 const TIntermTyped* arg0 = nullptr;
2092 if (callNode.getAsAggregate()) {
2093 argp = &callNode.getAsAggregate()->getSequence();
2094 if (argp->size() > 0)
2095 arg0 = (*argp)[0]->getAsTyped();
2097 assert(callNode.getAsUnaryNode());
2098 unaryArg = callNode.getAsUnaryNode()->getOperand();
2102 TString featureString;
2103 const char* feature = nullptr;
2104 switch (callNode.getOp()) {
2106 case EOpTextureGather:
2107 case EOpTextureGatherOffset:
2108 case EOpTextureGatherOffsets:
2110 // Figure out which variants are allowed by what extensions,
2111 // and what arguments must be constant for which situations.
2113 featureString = fnCandidate.getName();
2114 featureString += "(...)";
2115 feature = featureString.c_str();
2116 profileRequires(loc, EEsProfile, 310, nullptr, feature);
2117 int compArg = -1; // track which argument, if any, is the constant component argument
2118 switch (callNode.getOp()) {
2119 case EOpTextureGather:
2120 // More than two arguments needs gpu_shader5, and rectangular or shadow needs gpu_shader5,
2121 // otherwise, need GL_ARB_texture_gather.
2122 if (fnCandidate.getParamCount() > 2 || fnCandidate[0].type->getSampler().dim == EsdRect || fnCandidate[0].type->getSampler().shadow) {
2123 profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_gpu_shader5, feature);
2124 if (! fnCandidate[0].type->getSampler().shadow)
2127 profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_texture_gather, feature);
2129 case EOpTextureGatherOffset:
2130 // GL_ARB_texture_gather is good enough for 2D non-shadow textures with no component argument
2131 if (fnCandidate[0].type->getSampler().dim == Esd2D && ! fnCandidate[0].type->getSampler().shadow && fnCandidate.getParamCount() == 3)
2132 profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_texture_gather, feature);
2134 profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_gpu_shader5, feature);
2135 if (! (*argp)[fnCandidate[0].type->getSampler().shadow ? 3 : 2]->getAsConstantUnion())
2136 profileRequires(loc, EEsProfile, 320, Num_AEP_gpu_shader5, AEP_gpu_shader5,
2137 "non-constant offset argument");
2138 if (! fnCandidate[0].type->getSampler().shadow)
2141 case EOpTextureGatherOffsets:
2142 profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_gpu_shader5, feature);
2143 if (! fnCandidate[0].type->getSampler().shadow)
2145 // check for constant offsets
2146 if (! (*argp)[fnCandidate[0].type->getSampler().shadow ? 3 : 2]->getAsConstantUnion())
2147 error(loc, "must be a compile-time constant:", feature, "offsets argument");
2153 if (compArg > 0 && compArg < fnCandidate.getParamCount()) {
2154 if ((*argp)[compArg]->getAsConstantUnion()) {
2155 int value = (*argp)[compArg]->getAsConstantUnion()->getConstArray()[0].getIConst();
2156 if (value < 0 || value > 3)
2157 error(loc, "must be 0, 1, 2, or 3:", feature, "component argument");
2159 error(loc, "must be a compile-time constant:", feature, "component argument");
2163 if (callNode.getOp() == EOpTextureGather)
2164 bias = fnCandidate.getParamCount() > 3;
2165 else if (callNode.getOp() == EOpTextureGatherOffset ||
2166 callNode.getOp() == EOpTextureGatherOffsets)
2167 bias = fnCandidate.getParamCount() > 4;
2170 featureString = fnCandidate.getName();
2171 featureString += "with bias argument";
2172 feature = featureString.c_str();
2173 profileRequires(loc, ~EEsProfile, 450, nullptr, feature);
2174 requireExtensions(loc, 1, &E_GL_AMD_texture_gather_bias_lod, feature);
2178 case EOpSparseTextureGather:
2179 case EOpSparseTextureGatherOffset:
2180 case EOpSparseTextureGatherOffsets:
2183 if (callNode.getOp() == EOpSparseTextureGather)
2184 bias = fnCandidate.getParamCount() > 4;
2185 else if (callNode.getOp() == EOpSparseTextureGatherOffset ||
2186 callNode.getOp() == EOpSparseTextureGatherOffsets)
2187 bias = fnCandidate.getParamCount() > 5;
2190 featureString = fnCandidate.getName();
2191 featureString += "with bias argument";
2192 feature = featureString.c_str();
2193 profileRequires(loc, ~EEsProfile, 450, nullptr, feature);
2194 requireExtensions(loc, 1, &E_GL_AMD_texture_gather_bias_lod, feature);
2196 // As per GL_ARB_sparse_texture2 extension "Offsets" parameter must be constant integral expression
2197 // for sparseTextureGatherOffsetsARB just as textureGatherOffsets
2198 if (callNode.getOp() == EOpSparseTextureGatherOffsets) {
2199 int offsetsArg = arg0->getType().getSampler().shadow ? 3 : 2;
2200 if (!(*argp)[offsetsArg]->getAsConstantUnion())
2201 error(loc, "argument must be compile-time constant", "offsets", "");
2206 case EOpSparseTextureGatherLod:
2207 case EOpSparseTextureGatherLodOffset:
2208 case EOpSparseTextureGatherLodOffsets:
2210 requireExtensions(loc, 1, &E_GL_ARB_sparse_texture2, fnCandidate.getName().c_str());
2214 case EOpSwizzleInvocations:
2216 if (! (*argp)[1]->getAsConstantUnion())
2217 error(loc, "argument must be compile-time constant", "offset", "");
2219 unsigned offset[4] = {};
2220 offset[0] = (*argp)[1]->getAsConstantUnion()->getConstArray()[0].getUConst();
2221 offset[1] = (*argp)[1]->getAsConstantUnion()->getConstArray()[1].getUConst();
2222 offset[2] = (*argp)[1]->getAsConstantUnion()->getConstArray()[2].getUConst();
2223 offset[3] = (*argp)[1]->getAsConstantUnion()->getConstArray()[3].getUConst();
2224 if (offset[0] > 3 || offset[1] > 3 || offset[2] > 3 || offset[3] > 3)
2225 error(loc, "components must be in the range [0, 3]", "offset", "");
2231 case EOpSwizzleInvocationsMasked:
2233 if (! (*argp)[1]->getAsConstantUnion())
2234 error(loc, "argument must be compile-time constant", "mask", "");
2236 unsigned mask[3] = {};
2237 mask[0] = (*argp)[1]->getAsConstantUnion()->getConstArray()[0].getUConst();
2238 mask[1] = (*argp)[1]->getAsConstantUnion()->getConstArray()[1].getUConst();
2239 mask[2] = (*argp)[1]->getAsConstantUnion()->getConstArray()[2].getUConst();
2240 if (mask[0] > 31 || mask[1] > 31 || mask[2] > 31)
2241 error(loc, "components must be in the range [0, 31]", "mask", "");
2248 case EOpTextureOffset:
2249 case EOpTextureFetchOffset:
2250 case EOpTextureProjOffset:
2251 case EOpTextureLodOffset:
2252 case EOpTextureProjLodOffset:
2253 case EOpTextureGradOffset:
2254 case EOpTextureProjGradOffset:
2256 // Handle texture-offset limits checking
2257 // Pick which argument has to hold constant offsets
2259 switch (callNode.getOp()) {
2260 case EOpTextureOffset: arg = 2; break;
2261 case EOpTextureFetchOffset: arg = (arg0->getType().getSampler().isRect()) ? 2 : 3; break;
2262 case EOpTextureProjOffset: arg = 2; break;
2263 case EOpTextureLodOffset: arg = 3; break;
2264 case EOpTextureProjLodOffset: arg = 3; break;
2265 case EOpTextureGradOffset: arg = 4; break;
2266 case EOpTextureProjGradOffset: arg = 4; break;
2275 bool f16ShadowCompare = (*argp)[1]->getAsTyped()->getBasicType() == EbtFloat16 &&
2276 arg0->getType().getSampler().shadow;
2277 if (f16ShadowCompare)
2280 if (! (*argp)[arg]->getAsTyped()->getQualifier().isConstant())
2281 error(loc, "argument must be compile-time constant", "texel offset", "");
2282 else if ((*argp)[arg]->getAsConstantUnion()) {
2283 const TType& type = (*argp)[arg]->getAsTyped()->getType();
2284 for (int c = 0; c < type.getVectorSize(); ++c) {
2285 int offset = (*argp)[arg]->getAsConstantUnion()->getConstArray()[c].getIConst();
2286 if (offset > resources.maxProgramTexelOffset || offset < resources.minProgramTexelOffset)
2287 error(loc, "value is out of range:", "texel offset",
2288 "[gl_MinProgramTexelOffset, gl_MaxProgramTexelOffset]");
2292 if (callNode.getOp() == EOpTextureOffset) {
2293 TSampler s = arg0->getType().getSampler();
2294 if (s.is2D() && s.isArrayed() && s.isShadow()) {
2296 error(loc, "TextureOffset does not support sampler2DArrayShadow : ", "sampler", "ES Profile");
2297 else if (version <= 420)
2298 error(loc, "TextureOffset does not support sampler2DArrayShadow : ", "sampler", "version <= 420");
2308 if (!(*argp)[10]->getAsConstantUnion())
2309 error(loc, "argument must be compile-time constant", "payload number", "a");
2311 case EOpTraceRayMotionNV:
2312 if (!(*argp)[11]->getAsConstantUnion())
2313 error(loc, "argument must be compile-time constant", "payload number", "a");
2316 if (!(*argp)[10]->getAsConstantUnion())
2317 error(loc, "argument must be compile-time constant", "payload number", "a");
2319 unsigned int location = (*argp)[10]->getAsConstantUnion()->getAsConstantUnion()->getConstArray()[0].getUConst();
2320 if (intermediate.checkLocationRT(0, location) < 0)
2321 error(loc, "with layout(location =", "no rayPayloadEXT/rayPayloadInEXT declared", "%d)", location);
2324 case EOpExecuteCallableNV:
2325 if (!(*argp)[1]->getAsConstantUnion())
2326 error(loc, "argument must be compile-time constant", "callable data number", "");
2328 case EOpExecuteCallableKHR:
2329 if (!(*argp)[1]->getAsConstantUnion())
2330 error(loc, "argument must be compile-time constant", "callable data number", "");
2332 unsigned int location = (*argp)[1]->getAsConstantUnion()->getAsConstantUnion()->getConstArray()[0].getUConst();
2333 if (intermediate.checkLocationRT(1, location) < 0)
2334 error(loc, "with layout(location =", "no callableDataEXT/callableDataInEXT declared", "%d)", location);
2338 case EOpRayQueryGetIntersectionType:
2339 case EOpRayQueryGetIntersectionT:
2340 case EOpRayQueryGetIntersectionInstanceCustomIndex:
2341 case EOpRayQueryGetIntersectionInstanceId:
2342 case EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2343 case EOpRayQueryGetIntersectionGeometryIndex:
2344 case EOpRayQueryGetIntersectionPrimitiveIndex:
2345 case EOpRayQueryGetIntersectionBarycentrics:
2346 case EOpRayQueryGetIntersectionFrontFace:
2347 case EOpRayQueryGetIntersectionObjectRayDirection:
2348 case EOpRayQueryGetIntersectionObjectRayOrigin:
2349 case EOpRayQueryGetIntersectionObjectToWorld:
2350 case EOpRayQueryGetIntersectionWorldToObject:
2351 if (!(*argp)[1]->getAsConstantUnion())
2352 error(loc, "argument must be compile-time constant", "committed", "");
2355 case EOpTextureQuerySamples:
2356 case EOpImageQuerySamples:
2357 // GL_ARB_shader_texture_image_samples
2358 profileRequires(loc, ~EEsProfile, 450, E_GL_ARB_shader_texture_image_samples, "textureSamples and imageSamples");
2361 case EOpImageAtomicAdd:
2362 case EOpImageAtomicMin:
2363 case EOpImageAtomicMax:
2364 case EOpImageAtomicAnd:
2365 case EOpImageAtomicOr:
2366 case EOpImageAtomicXor:
2367 case EOpImageAtomicExchange:
2368 case EOpImageAtomicCompSwap:
2369 case EOpImageAtomicLoad:
2370 case EOpImageAtomicStore:
2372 // Make sure the image types have the correct layout() format and correct argument types
2373 const TType& imageType = arg0->getType();
2374 if (imageType.getSampler().type == EbtInt || imageType.getSampler().type == EbtUint ||
2375 imageType.getSampler().type == EbtInt64 || imageType.getSampler().type == EbtUint64) {
2376 if (imageType.getQualifier().getFormat() != ElfR32i && imageType.getQualifier().getFormat() != ElfR32ui &&
2377 imageType.getQualifier().getFormat() != ElfR64i && imageType.getQualifier().getFormat() != ElfR64ui)
2378 error(loc, "only supported on image with format r32i or r32ui", fnCandidate.getName().c_str(), "");
2379 if (callNode.getType().getBasicType() == EbtInt64 && imageType.getQualifier().getFormat() != ElfR64i)
2380 error(loc, "only supported on image with format r64i", fnCandidate.getName().c_str(), "");
2381 else if (callNode.getType().getBasicType() == EbtUint64 && imageType.getQualifier().getFormat() != ElfR64ui)
2382 error(loc, "only supported on image with format r64ui", fnCandidate.getName().c_str(), "");
2383 } else if (imageType.getSampler().type == EbtFloat) {
2384 if (fnCandidate.getName().compare(0, 19, "imageAtomicExchange") == 0) {
2385 // imageAtomicExchange doesn't require an extension
2386 } else if ((fnCandidate.getName().compare(0, 14, "imageAtomicAdd") == 0) ||
2387 (fnCandidate.getName().compare(0, 15, "imageAtomicLoad") == 0) ||
2388 (fnCandidate.getName().compare(0, 16, "imageAtomicStore") == 0)) {
2389 requireExtensions(loc, 1, &E_GL_EXT_shader_atomic_float, fnCandidate.getName().c_str());
2390 } else if ((fnCandidate.getName().compare(0, 14, "imageAtomicMin") == 0) ||
2391 (fnCandidate.getName().compare(0, 14, "imageAtomicMax") == 0)) {
2392 requireExtensions(loc, 1, &E_GL_EXT_shader_atomic_float2, fnCandidate.getName().c_str());
2394 error(loc, "only supported on integer images", fnCandidate.getName().c_str(), "");
2396 if (imageType.getQualifier().getFormat() != ElfR32f && isEsProfile())
2397 error(loc, "only supported on image with format r32f", fnCandidate.getName().c_str(), "");
2399 error(loc, "not supported on this image type", fnCandidate.getName().c_str(), "");
2402 const size_t maxArgs = imageType.getSampler().isMultiSample() ? 5 : 4;
2403 if (argp->size() > maxArgs) {
2404 requireExtensions(loc, 1, &E_GL_KHR_memory_scope_semantics, fnCandidate.getName().c_str());
2405 memorySemanticsCheck(loc, fnCandidate, callNode);
2412 case EOpAtomicSubtract:
2418 case EOpAtomicExchange:
2419 case EOpAtomicCompSwap:
2421 case EOpAtomicStore:
2423 if (argp->size() > 3) {
2424 requireExtensions(loc, 1, &E_GL_KHR_memory_scope_semantics, fnCandidate.getName().c_str());
2425 memorySemanticsCheck(loc, fnCandidate, callNode);
2426 if ((callNode.getOp() == EOpAtomicAdd || callNode.getOp() == EOpAtomicExchange ||
2427 callNode.getOp() == EOpAtomicLoad || callNode.getOp() == EOpAtomicStore) &&
2428 (arg0->getType().getBasicType() == EbtFloat ||
2429 arg0->getType().getBasicType() == EbtDouble)) {
2430 requireExtensions(loc, 1, &E_GL_EXT_shader_atomic_float, fnCandidate.getName().c_str());
2431 } else if ((callNode.getOp() == EOpAtomicAdd || callNode.getOp() == EOpAtomicExchange ||
2432 callNode.getOp() == EOpAtomicLoad || callNode.getOp() == EOpAtomicStore ||
2433 callNode.getOp() == EOpAtomicMin || callNode.getOp() == EOpAtomicMax) &&
2434 arg0->getType().isFloatingDomain()) {
2435 requireExtensions(loc, 1, &E_GL_EXT_shader_atomic_float2, fnCandidate.getName().c_str());
2437 } else if (arg0->getType().getBasicType() == EbtInt64 || arg0->getType().getBasicType() == EbtUint64) {
2438 const char* const extensions[2] = { E_GL_NV_shader_atomic_int64,
2439 E_GL_EXT_shader_atomic_int64 };
2440 requireExtensions(loc, 2, extensions, fnCandidate.getName().c_str());
2441 } else if ((callNode.getOp() == EOpAtomicAdd || callNode.getOp() == EOpAtomicExchange) &&
2442 (arg0->getType().getBasicType() == EbtFloat ||
2443 arg0->getType().getBasicType() == EbtDouble)) {
2444 requireExtensions(loc, 1, &E_GL_EXT_shader_atomic_float, fnCandidate.getName().c_str());
2445 } else if ((callNode.getOp() == EOpAtomicAdd || callNode.getOp() == EOpAtomicExchange ||
2446 callNode.getOp() == EOpAtomicLoad || callNode.getOp() == EOpAtomicStore ||
2447 callNode.getOp() == EOpAtomicMin || callNode.getOp() == EOpAtomicMax) &&
2448 arg0->getType().isFloatingDomain()) {
2449 requireExtensions(loc, 1, &E_GL_EXT_shader_atomic_float2, fnCandidate.getName().c_str());
2452 const TIntermTyped* base = TIntermediate::findLValueBase(arg0, true , true);
2453 const TType* refType = (base->getType().isReference()) ? base->getType().getReferentType() : nullptr;
2454 const TQualifier& qualifier = (refType != nullptr) ? refType->getQualifier() : base->getType().getQualifier();
2455 if (qualifier.storage != EvqShared && qualifier.storage != EvqBuffer)
2456 error(loc,"Atomic memory function can only be used for shader storage block member or shared variable.",
2457 fnCandidate.getName().c_str(), "");
2462 case EOpInterpolateAtCentroid:
2463 case EOpInterpolateAtSample:
2464 case EOpInterpolateAtOffset:
2465 case EOpInterpolateAtVertex:
2466 // Make sure the first argument is an interpolant, or an array element of an interpolant
2467 if (arg0->getType().getQualifier().storage != EvqVaryingIn) {
2468 // It might still be an array element.
2470 // We could check more, but the semantics of the first argument are already met; the
2471 // only way to turn an array into a float/vec* is array dereference and swizzle.
2473 // ES and desktop 4.3 and earlier: swizzles may not be used
2474 // desktop 4.4 and later: swizzles may be used
2475 bool swizzleOkay = (!isEsProfile()) && (version >= 440);
2476 const TIntermTyped* base = TIntermediate::findLValueBase(arg0, swizzleOkay);
2477 if (base == nullptr || base->getType().getQualifier().storage != EvqVaryingIn)
2478 error(loc, "first argument must be an interpolant, or interpolant-array element", fnCandidate.getName().c_str(), "");
2481 if (callNode.getOp() == EOpInterpolateAtVertex) {
2482 if (!arg0->getType().getQualifier().isExplicitInterpolation())
2483 error(loc, "argument must be qualified as __explicitInterpAMD in", "interpolant", "");
2485 if (! (*argp)[1]->getAsConstantUnion())
2486 error(loc, "argument must be compile-time constant", "vertex index", "");
2488 unsigned vertexIdx = (*argp)[1]->getAsConstantUnion()->getConstArray()[0].getUConst();
2490 error(loc, "must be in the range [0, 2]", "vertex index", "");
2496 case EOpEmitStreamVertex:
2497 case EOpEndStreamPrimitive:
2498 intermediate.setMultiStream();
2501 case EOpSubgroupClusteredAdd:
2502 case EOpSubgroupClusteredMul:
2503 case EOpSubgroupClusteredMin:
2504 case EOpSubgroupClusteredMax:
2505 case EOpSubgroupClusteredAnd:
2506 case EOpSubgroupClusteredOr:
2507 case EOpSubgroupClusteredXor:
2508 // The <clusterSize> as used in the subgroupClustered<op>() operations must be:
2509 // - An integral constant expression.
2512 if ((*argp)[1]->getAsConstantUnion() == nullptr)
2513 error(loc, "argument must be compile-time constant", "cluster size", "");
2515 int size = (*argp)[1]->getAsConstantUnion()->getConstArray()[0].getIConst();
2517 error(loc, "argument must be at least 1", "cluster size", "");
2518 else if (!IsPow2(size))
2519 error(loc, "argument must be a power of 2", "cluster size", "");
2523 case EOpSubgroupBroadcast:
2524 case EOpSubgroupQuadBroadcast:
2525 if (spvVersion.spv < EShTargetSpv_1_5) {
2526 // <id> must be an integral constant expression.
2527 if ((*argp)[1]->getAsConstantUnion() == nullptr)
2528 error(loc, "argument must be compile-time constant", "id", "");
2533 case EOpMemoryBarrier:
2534 if (argp->size() > 0) {
2535 requireExtensions(loc, 1, &E_GL_KHR_memory_scope_semantics, fnCandidate.getName().c_str());
2536 memorySemanticsCheck(loc, fnCandidate, callNode);
2541 if (profile == EEsProfile && version < 310) {
2542 // Look for specific signatures
2543 if ((*argp)[0]->getAsTyped()->getBasicType() != EbtFloat &&
2544 (*argp)[1]->getAsTyped()->getBasicType() != EbtFloat &&
2545 (*argp)[2]->getAsTyped()->getBasicType() == EbtBool) {
2546 requireExtensions(loc, 1, &E_GL_EXT_shader_integer_mix, "specific signature of builtin mix");
2550 if (profile != EEsProfile && version < 450) {
2551 if ((*argp)[0]->getAsTyped()->getBasicType() != EbtFloat &&
2552 (*argp)[0]->getAsTyped()->getBasicType() != EbtDouble &&
2553 (*argp)[1]->getAsTyped()->getBasicType() != EbtFloat &&
2554 (*argp)[1]->getAsTyped()->getBasicType() != EbtDouble &&
2555 (*argp)[2]->getAsTyped()->getBasicType() == EbtBool) {
2556 requireExtensions(loc, 1, &E_GL_EXT_shader_integer_mix, fnCandidate.getName().c_str());
2567 // Texture operations on texture objects (aside from texelFetch on a
2568 // textureBuffer) require EXT_samplerless_texture_functions.
2569 switch (callNode.getOp()) {
2570 case EOpTextureQuerySize:
2571 case EOpTextureQueryLevels:
2572 case EOpTextureQuerySamples:
2573 case EOpTextureFetch:
2574 case EOpTextureFetchOffset:
2576 const TSampler& sampler = fnCandidate[0].type->getSampler();
2578 const bool isTexture = sampler.isTexture() && !sampler.isCombined();
2579 const bool isBuffer = sampler.isBuffer();
2580 const bool isFetch = callNode.getOp() == EOpTextureFetch || callNode.getOp() == EOpTextureFetchOffset;
2582 if (isTexture && (!isBuffer || !isFetch))
2583 requireExtensions(loc, 1, &E_GL_EXT_samplerless_texture_functions, fnCandidate.getName().c_str());
2592 if (callNode.isSubgroup()) {
2593 // these require SPIR-V 1.3
2594 if (spvVersion.spv > 0 && spvVersion.spv < EShTargetSpv_1_3)
2595 error(loc, "requires SPIR-V 1.3", "subgroup op", "");
2597 // Check that if extended types are being used that the correct extensions are enabled.
2598 if (arg0 != nullptr) {
2599 const TType& type = arg0->getType();
2600 switch (type.getBasicType()) {
2605 requireExtensions(loc, 1, &E_GL_EXT_shader_subgroup_extended_types_int8, type.getCompleteString().c_str());
2609 requireExtensions(loc, 1, &E_GL_EXT_shader_subgroup_extended_types_int16, type.getCompleteString().c_str());
2613 requireExtensions(loc, 1, &E_GL_EXT_shader_subgroup_extended_types_int64, type.getCompleteString().c_str());
2616 requireExtensions(loc, 1, &E_GL_EXT_shader_subgroup_extended_types_float16, type.getCompleteString().c_str());
2625 extern bool PureOperatorBuiltins;
2627 // Deprecated! Use PureOperatorBuiltins == true instead, in which case this
2628 // functionality is handled in builtInOpCheck() instead of here.
2630 // Do additional checking of built-in function calls that were not mapped
2631 // to built-in operations (e.g., texturing functions).
2633 // Assumes there has been a semantically correct match to a built-in function.
2635 void TParseContext::nonOpBuiltInCheck(const TSourceLoc& loc, const TFunction& fnCandidate, TIntermAggregate& callNode)
2637 // Further maintenance of this function is deprecated, because the "correct"
2638 // future-oriented design is to not have to do string compares on function names.
2640 // If PureOperatorBuiltins == true, then all built-ins should be mapped
2641 // to a TOperator, and this function would then never get called.
2643 assert(PureOperatorBuiltins == false);
2645 // built-in texturing functions get their return value precision from the precision of the sampler
2646 if (fnCandidate.getType().getQualifier().precision == EpqNone &&
2647 fnCandidate.getParamCount() > 0 && fnCandidate[0].type->getBasicType() == EbtSampler)
2648 callNode.getQualifier().precision = callNode.getSequence()[0]->getAsTyped()->getQualifier().precision;
2650 if (fnCandidate.getName().compare(0, 7, "texture") == 0) {
2651 if (fnCandidate.getName().compare(0, 13, "textureGather") == 0) {
2652 TString featureString = fnCandidate.getName() + "(...)";
2653 const char* feature = featureString.c_str();
2654 profileRequires(loc, EEsProfile, 310, nullptr, feature);
2656 int compArg = -1; // track which argument, if any, is the constant component argument
2657 if (fnCandidate.getName().compare("textureGatherOffset") == 0) {
2658 // GL_ARB_texture_gather is good enough for 2D non-shadow textures with no component argument
2659 if (fnCandidate[0].type->getSampler().dim == Esd2D && ! fnCandidate[0].type->getSampler().shadow && fnCandidate.getParamCount() == 3)
2660 profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_texture_gather, feature);
2662 profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_gpu_shader5, feature);
2663 int offsetArg = fnCandidate[0].type->getSampler().shadow ? 3 : 2;
2664 if (! callNode.getSequence()[offsetArg]->getAsConstantUnion())
2665 profileRequires(loc, EEsProfile, 320, Num_AEP_gpu_shader5, AEP_gpu_shader5,
2666 "non-constant offset argument");
2667 if (! fnCandidate[0].type->getSampler().shadow)
2669 } else if (fnCandidate.getName().compare("textureGatherOffsets") == 0) {
2670 profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_gpu_shader5, feature);
2671 if (! fnCandidate[0].type->getSampler().shadow)
2673 // check for constant offsets
2674 int offsetArg = fnCandidate[0].type->getSampler().shadow ? 3 : 2;
2675 if (! callNode.getSequence()[offsetArg]->getAsConstantUnion())
2676 error(loc, "must be a compile-time constant:", feature, "offsets argument");
2677 } else if (fnCandidate.getName().compare("textureGather") == 0) {
2678 // More than two arguments needs gpu_shader5, and rectangular or shadow needs gpu_shader5,
2679 // otherwise, need GL_ARB_texture_gather.
2680 if (fnCandidate.getParamCount() > 2 || fnCandidate[0].type->getSampler().dim == EsdRect || fnCandidate[0].type->getSampler().shadow) {
2681 profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_gpu_shader5, feature);
2682 if (! fnCandidate[0].type->getSampler().shadow)
2685 profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_texture_gather, feature);
2688 if (compArg > 0 && compArg < fnCandidate.getParamCount()) {
2689 if (callNode.getSequence()[compArg]->getAsConstantUnion()) {
2690 int value = callNode.getSequence()[compArg]->getAsConstantUnion()->getConstArray()[0].getIConst();
2691 if (value < 0 || value > 3)
2692 error(loc, "must be 0, 1, 2, or 3:", feature, "component argument");
2694 error(loc, "must be a compile-time constant:", feature, "component argument");
2697 // this is only for functions not starting "textureGather"...
2698 if (fnCandidate.getName().find("Offset") != TString::npos) {
2700 // Handle texture-offset limits checking
2702 if (fnCandidate.getName().compare("textureOffset") == 0)
2704 else if (fnCandidate.getName().compare("texelFetchOffset") == 0)
2706 else if (fnCandidate.getName().compare("textureProjOffset") == 0)
2708 else if (fnCandidate.getName().compare("textureLodOffset") == 0)
2710 else if (fnCandidate.getName().compare("textureProjLodOffset") == 0)
2712 else if (fnCandidate.getName().compare("textureGradOffset") == 0)
2714 else if (fnCandidate.getName().compare("textureProjGradOffset") == 0)
2718 if (! callNode.getSequence()[arg]->getAsConstantUnion())
2719 error(loc, "argument must be compile-time constant", "texel offset", "");
2721 const TType& type = callNode.getSequence()[arg]->getAsTyped()->getType();
2722 for (int c = 0; c < type.getVectorSize(); ++c) {
2723 int offset = callNode.getSequence()[arg]->getAsConstantUnion()->getConstArray()[c].getIConst();
2724 if (offset > resources.maxProgramTexelOffset || offset < resources.minProgramTexelOffset)
2725 error(loc, "value is out of range:", "texel offset", "[gl_MinProgramTexelOffset, gl_MaxProgramTexelOffset]");
2733 // GL_ARB_shader_texture_image_samples
2734 if (fnCandidate.getName().compare(0, 14, "textureSamples") == 0 || fnCandidate.getName().compare(0, 12, "imageSamples") == 0)
2735 profileRequires(loc, ~EEsProfile, 450, E_GL_ARB_shader_texture_image_samples, "textureSamples and imageSamples");
2737 if (fnCandidate.getName().compare(0, 11, "imageAtomic") == 0) {
2738 const TType& imageType = callNode.getSequence()[0]->getAsTyped()->getType();
2739 if (imageType.getSampler().type == EbtInt || imageType.getSampler().type == EbtUint) {
2740 if (imageType.getQualifier().getFormat() != ElfR32i && imageType.getQualifier().getFormat() != ElfR32ui)
2741 error(loc, "only supported on image with format r32i or r32ui", fnCandidate.getName().c_str(), "");
2743 if (fnCandidate.getName().compare(0, 19, "imageAtomicExchange") != 0)
2744 error(loc, "only supported on integer images", fnCandidate.getName().c_str(), "");
2745 else if (imageType.getQualifier().getFormat() != ElfR32f && isEsProfile())
2746 error(loc, "only supported on image with format r32f", fnCandidate.getName().c_str(), "");
2754 // Do any extra checking for a user function call.
2756 void TParseContext::userFunctionCallCheck(const TSourceLoc& loc, TIntermAggregate& callNode)
2758 TIntermSequence& arguments = callNode.getSequence();
2760 for (int i = 0; i < (int)arguments.size(); ++i)
2761 samplerConstructorLocationCheck(loc, "call argument", arguments[i]);
2765 // Emit an error if this is a sampler constructor
2767 void TParseContext::samplerConstructorLocationCheck(const TSourceLoc& loc, const char* token, TIntermNode* node)
2769 if (node->getAsOperator() && node->getAsOperator()->getOp() == EOpConstructTextureSampler)
2770 error(loc, "sampler constructor must appear at point of use", token, "");
2774 // Handle seeing a built-in constructor in a grammar production.
2776 TFunction* TParseContext::handleConstructorCall(const TSourceLoc& loc, const TPublicType& publicType)
2778 TType type(publicType);
2779 type.getQualifier().precision = EpqNone;
2781 if (type.isArray()) {
2782 profileRequires(loc, ENoProfile, 120, E_GL_3DL_array_objects, "arrayed constructor");
2783 profileRequires(loc, EEsProfile, 300, nullptr, "arrayed constructor");
2786 TOperator op = intermediate.mapTypeToConstructorOp(type);
2788 if (op == EOpNull) {
2789 error(loc, "cannot construct this type", type.getBasicString(), "");
2790 op = EOpConstructFloat;
2791 TType errorType(EbtFloat);
2792 type.shallowCopy(errorType);
2797 return new TFunction(&empty, type, op);
2800 // Handle seeing a precision qualifier in the grammar.
2801 void TParseContext::handlePrecisionQualifier(const TSourceLoc& /*loc*/, TQualifier& qualifier, TPrecisionQualifier precision)
2803 if (obeyPrecisionQualifiers())
2804 qualifier.precision = precision;
2807 // Check for messages to give on seeing a precision qualifier used in a
2808 // declaration in the grammar.
2809 void TParseContext::checkPrecisionQualifier(const TSourceLoc& loc, TPrecisionQualifier)
2811 if (precisionManager.shouldWarnAboutDefaults()) {
2812 warn(loc, "all default precisions are highp; use precision statements to quiet warning, e.g.:\n"
2813 " \"precision mediump int; precision highp float;\"", "", "");
2814 precisionManager.defaultWarningGiven();
2819 // Same error message for all places assignments don't work.
2821 void TParseContext::assignError(const TSourceLoc& loc, const char* op, TString left, TString right)
2823 error(loc, "", op, "cannot convert from '%s' to '%s'",
2824 right.c_str(), left.c_str());
2828 // Same error message for all places unary operations don't work.
2830 void TParseContext::unaryOpError(const TSourceLoc& loc, const char* op, TString operand)
2832 error(loc, " wrong operand type", op,
2833 "no operation '%s' exists that takes an operand of type %s (or there is no acceptable conversion)",
2834 op, operand.c_str());
2838 // Same error message for all binary operations don't work.
2840 void TParseContext::binaryOpError(const TSourceLoc& loc, const char* op, TString left, TString right)
2842 error(loc, " wrong operand types:", op,
2843 "no operation '%s' exists that takes a left-hand operand of type '%s' and "
2844 "a right operand of type '%s' (or there is no acceptable conversion)",
2845 op, left.c_str(), right.c_str());
2849 // A basic type of EbtVoid is a key that the name string was seen in the source, but
2850 // it was not found as a variable in the symbol table. If so, give the error
2851 // message and insert a dummy variable in the symbol table to prevent future errors.
2853 void TParseContext::variableCheck(TIntermTyped*& nodePtr)
2855 TIntermSymbol* symbol = nodePtr->getAsSymbolNode();
2859 if (symbol->getType().getBasicType() == EbtVoid) {
2860 const char *extraInfoFormat = "";
2861 if (spvVersion.vulkan != 0 && symbol->getName() == "gl_VertexID") {
2862 extraInfoFormat = "(Did you mean gl_VertexIndex?)";
2863 } else if (spvVersion.vulkan != 0 && symbol->getName() == "gl_InstanceID") {
2864 extraInfoFormat = "(Did you mean gl_InstanceIndex?)";
2866 error(symbol->getLoc(), "undeclared identifier", symbol->getName().c_str(), extraInfoFormat);
2868 // Add to symbol table to prevent future error messages on the same name
2869 if (symbol->getName().size() > 0) {
2870 TVariable* fakeVariable = new TVariable(&symbol->getName(), TType(EbtFloat));
2871 symbolTable.insert(*fakeVariable);
2873 // substitute a symbol node for this new variable
2874 nodePtr = intermediate.addSymbol(*fakeVariable, symbol->getLoc());
2877 switch (symbol->getQualifier().storage) {
2879 profileRequires(symbol->getLoc(), ENoProfile, 120, nullptr, "gl_PointCoord");
2881 default: break; // some compilers want this
2887 // Both test and if necessary, spit out an error, to see if the node is really
2888 // an l-value that can be operated on this way.
2890 // Returns true if there was an error.
2892 bool TParseContext::lValueErrorCheck(const TSourceLoc& loc, const char* op, TIntermTyped* node)
2894 TIntermBinary* binaryNode = node->getAsBinaryNode();
2897 bool errorReturn = false;
2899 switch(binaryNode->getOp()) {
2901 case EOpIndexDirect:
2902 case EOpIndexIndirect:
2903 // ... tessellation control shader ...
2904 // If a per-vertex output variable is used as an l-value, it is a
2905 // compile-time or link-time error if the expression indicating the
2906 // vertex index is not the identifier gl_InvocationID.
2907 if (language == EShLangTessControl) {
2908 const TType& leftType = binaryNode->getLeft()->getType();
2909 if (leftType.getQualifier().storage == EvqVaryingOut && ! leftType.getQualifier().patch && binaryNode->getLeft()->getAsSymbolNode()) {
2910 // we have a per-vertex output
2911 const TIntermSymbol* rightSymbol = binaryNode->getRight()->getAsSymbolNode();
2912 if (! rightSymbol || rightSymbol->getQualifier().builtIn != EbvInvocationId)
2913 error(loc, "tessellation-control per-vertex output l-value must be indexed with gl_InvocationID", "[]", "");
2916 break; // left node is checked by base class
2918 case EOpVectorSwizzle:
2919 errorReturn = lValueErrorCheck(loc, op, binaryNode->getLeft());
2921 int offset[4] = {0,0,0,0};
2923 TIntermTyped* rightNode = binaryNode->getRight();
2924 TIntermAggregate *aggrNode = rightNode->getAsAggregate();
2926 for (TIntermSequence::iterator p = aggrNode->getSequence().begin();
2927 p != aggrNode->getSequence().end(); p++) {
2928 int value = (*p)->getAsTyped()->getAsConstantUnion()->getConstArray()[0].getIConst();
2930 if (offset[value] > 1) {
2931 error(loc, " l-value of swizzle cannot have duplicate components", op, "", "");
2944 error(loc, " l-value required", op, "", "");
2949 if (binaryNode && binaryNode->getOp() == EOpIndexDirectStruct && binaryNode->getLeft()->isReference())
2952 // Let the base class check errors
2953 if (TParseContextBase::lValueErrorCheck(loc, op, node))
2956 const char* symbol = nullptr;
2957 TIntermSymbol* symNode = node->getAsSymbolNode();
2958 if (symNode != nullptr)
2959 symbol = symNode->getName().c_str();
2961 const char* message = nullptr;
2962 switch (node->getQualifier().storage) {
2963 case EvqVaryingIn: message = "can't modify shader input"; break;
2964 case EvqInstanceId: message = "can't modify gl_InstanceID"; break;
2965 case EvqVertexId: message = "can't modify gl_VertexID"; break;
2966 case EvqFace: message = "can't modify gl_FrontFace"; break;
2967 case EvqFragCoord: message = "can't modify gl_FragCoord"; break;
2968 case EvqPointCoord: message = "can't modify gl_PointCoord"; break;
2970 intermediate.setDepthReplacing();
2971 // "In addition, it is an error to statically write to gl_FragDepth in the fragment shader."
2972 if (isEsProfile() && intermediate.getEarlyFragmentTests())
2973 message = "can't modify gl_FragDepth if using early_fragment_tests";
2980 if (message == nullptr && binaryNode == nullptr && symNode == nullptr) {
2981 error(loc, " l-value required", op, "", "");
2987 // Everything else is okay, no error.
2989 if (message == nullptr)
2993 // If we get here, we have an error and a message.
2996 error(loc, " l-value required", op, "\"%s\" (%s)", symbol, message);
2998 error(loc, " l-value required", op, "(%s)", message);
3003 // Test for and give an error if the node can't be read from.
3004 void TParseContext::rValueErrorCheck(const TSourceLoc& loc, const char* op, TIntermTyped* node)
3006 // Let the base class check errors
3007 TParseContextBase::rValueErrorCheck(loc, op, node);
3009 TIntermSymbol* symNode = node->getAsSymbolNode();
3010 if (!(symNode && symNode->getQualifier().isWriteOnly())) // base class checks
3011 if (symNode && symNode->getQualifier().isExplicitInterpolation())
3012 error(loc, "can't read from explicitly-interpolated object: ", op, symNode->getName().c_str());
3014 // local_size_{xyz} must be assigned or specialized before gl_WorkGroupSize can be assigned.
3015 if(node->getQualifier().builtIn == EbvWorkGroupSize &&
3016 !(intermediate.isLocalSizeSet() || intermediate.isLocalSizeSpecialized()))
3017 error(loc, "can't read from gl_WorkGroupSize before a fixed workgroup size has been declared", op, "");
3021 // Both test, and if necessary spit out an error, to see if the node is really
3024 void TParseContext::constantValueCheck(TIntermTyped* node, const char* token)
3026 if (! node->getQualifier().isConstant())
3027 error(node->getLoc(), "constant expression required", token, "");
3031 // Both test, and if necessary spit out an error, to see if the node is really
3034 void TParseContext::integerCheck(const TIntermTyped* node, const char* token)
3036 if ((node->getBasicType() == EbtInt || node->getBasicType() == EbtUint) && node->isScalar())
3039 error(node->getLoc(), "scalar integer expression required", token, "");
3043 // Both test, and if necessary spit out an error, to see if we are currently
3046 void TParseContext::globalCheck(const TSourceLoc& loc, const char* token)
3048 if (! symbolTable.atGlobalLevel())
3049 error(loc, "not allowed in nested scope", token, "");
3053 // Reserved errors for GLSL.
3055 void TParseContext::reservedErrorCheck(const TSourceLoc& loc, const TString& identifier)
3057 // "Identifiers starting with "gl_" are reserved for use by OpenGL, and may not be
3058 // declared in a shader; this results in a compile-time error."
3059 if (! symbolTable.atBuiltInLevel()) {
3060 if (builtInName(identifier) && !extensionTurnedOn(E_GL_EXT_spirv_intrinsics))
3061 // The extension GL_EXT_spirv_intrinsics allows us to declare identifiers starting with "gl_".
3062 error(loc, "identifiers starting with \"gl_\" are reserved", identifier.c_str(), "");
3064 // "__" are not supposed to be an error. ES 300 (and desktop) added the clarification:
3065 // "In addition, all identifiers containing two consecutive underscores (__) are
3066 // reserved; using such a name does not itself result in an error, but may result
3067 // in undefined behavior."
3068 // however, before that, ES tests required an error.
3069 if (identifier.find("__") != TString::npos && !extensionTurnedOn(E_GL_EXT_spirv_intrinsics)) {
3070 // The extension GL_EXT_spirv_intrinsics allows us to declare identifiers starting with "__".
3071 if (isEsProfile() && version < 300)
3072 error(loc, "identifiers containing consecutive underscores (\"__\") are reserved, and an error if version < 300", identifier.c_str(), "");
3074 warn(loc, "identifiers containing consecutive underscores (\"__\") are reserved", identifier.c_str(), "");
3080 // Reserved errors for the preprocessor.
3082 void TParseContext::reservedPpErrorCheck(const TSourceLoc& loc, const char* identifier, const char* op)
3084 // "__" are not supposed to be an error. ES 300 (and desktop) added the clarification:
3085 // "All macro names containing two consecutive underscores ( __ ) are reserved;
3086 // defining such a name does not itself result in an error, but may result in
3087 // undefined behavior. All macro names prefixed with "GL_" ("GL" followed by a
3088 // single underscore) are also reserved, and defining such a name results in a
3089 // compile-time error."
3090 // however, before that, ES tests required an error.
3091 if (strncmp(identifier, "GL_", 3) == 0 && !extensionTurnedOn(E_GL_EXT_spirv_intrinsics))
3092 // The extension GL_EXT_spirv_intrinsics allows us to declare macros prefixed with "GL_".
3093 ppError(loc, "names beginning with \"GL_\" can't be (un)defined:", op, identifier);
3094 else if (strncmp(identifier, "defined", 8) == 0)
3095 if (relaxedErrors())
3096 ppWarn(loc, "\"defined\" is (un)defined:", op, identifier);
3098 ppError(loc, "\"defined\" can't be (un)defined:", op, identifier);
3099 else if (strstr(identifier, "__") != 0 && !extensionTurnedOn(E_GL_EXT_spirv_intrinsics)) {
3100 // The extension GL_EXT_spirv_intrinsics allows us to declare macros prefixed with "__".
3101 if (isEsProfile() && version >= 300 &&
3102 (strcmp(identifier, "__LINE__") == 0 ||
3103 strcmp(identifier, "__FILE__") == 0 ||
3104 strcmp(identifier, "__VERSION__") == 0))
3105 ppError(loc, "predefined names can't be (un)defined:", op, identifier);
3107 if (isEsProfile() && version < 300 && !relaxedErrors())
3108 ppError(loc, "names containing consecutive underscores are reserved, and an error if version < 300:", op, identifier);
3110 ppWarn(loc, "names containing consecutive underscores are reserved:", op, identifier);
3116 // See if this version/profile allows use of the line-continuation character '\'.
3118 // Returns true if a line continuation should be done.
3120 bool TParseContext::lineContinuationCheck(const TSourceLoc& loc, bool endOfComment)
3126 const char* message = "line continuation";
3128 bool lineContinuationAllowed = (isEsProfile() && version >= 300) ||
3129 (!isEsProfile() && (version >= 420 || extensionTurnedOn(E_GL_ARB_shading_language_420pack)));
3132 if (lineContinuationAllowed)
3133 warn(loc, "used at end of comment; the following line is still part of the comment", message, "");
3135 warn(loc, "used at end of comment, but this version does not provide line continuation", message, "");
3137 return lineContinuationAllowed;
3140 if (relaxedErrors()) {
3141 if (! lineContinuationAllowed)
3142 warn(loc, "not allowed in this version", message, "");
3145 profileRequires(loc, EEsProfile, 300, nullptr, message);
3146 profileRequires(loc, ~EEsProfile, 420, E_GL_ARB_shading_language_420pack, message);
3149 return lineContinuationAllowed;
3152 bool TParseContext::builtInName(const TString& identifier)
3154 return identifier.compare(0, 3, "gl_") == 0;
3158 // Make sure there is enough data and not too many arguments provided to the
3159 // constructor to build something of the type of the constructor. Also returns
3160 // the type of the constructor.
3162 // Part of establishing type is establishing specialization-constness.
3163 // We don't yet know "top down" whether type is a specialization constant,
3164 // but a const constructor can becomes a specialization constant if any of
3165 // its children are, subject to KHR_vulkan_glsl rules:
3167 // - int(), uint(), and bool() constructors for type conversions
3168 // from any of the following types to any of the following types:
3172 // - vector versions of the above conversion constructors
3174 // Returns true if there was an error in construction.
3176 bool TParseContext::constructorError(const TSourceLoc& loc, TIntermNode* node, TFunction& function, TOperator op, TType& type)
3178 // See if the constructor does not establish the main type, only requalifies
3179 // it, in which case the type comes from the argument instead of from the
3180 // constructor function.
3183 case EOpConstructNonuniform:
3184 if (node != nullptr && node->getAsTyped() != nullptr) {
3185 type.shallowCopy(node->getAsTyped()->getType());
3186 type.getQualifier().makeTemporary();
3187 type.getQualifier().nonUniform = true;
3192 type.shallowCopy(function.getType());
3196 // See if it's a matrix
3197 bool constructingMatrix = false;
3199 case EOpConstructTextureSampler:
3200 return constructorTextureSamplerError(loc, function);
3201 case EOpConstructMat2x2:
3202 case EOpConstructMat2x3:
3203 case EOpConstructMat2x4:
3204 case EOpConstructMat3x2:
3205 case EOpConstructMat3x3:
3206 case EOpConstructMat3x4:
3207 case EOpConstructMat4x2:
3208 case EOpConstructMat4x3:
3209 case EOpConstructMat4x4:
3211 case EOpConstructDMat2x2:
3212 case EOpConstructDMat2x3:
3213 case EOpConstructDMat2x4:
3214 case EOpConstructDMat3x2:
3215 case EOpConstructDMat3x3:
3216 case EOpConstructDMat3x4:
3217 case EOpConstructDMat4x2:
3218 case EOpConstructDMat4x3:
3219 case EOpConstructDMat4x4:
3220 case EOpConstructF16Mat2x2:
3221 case EOpConstructF16Mat2x3:
3222 case EOpConstructF16Mat2x4:
3223 case EOpConstructF16Mat3x2:
3224 case EOpConstructF16Mat3x3:
3225 case EOpConstructF16Mat3x4:
3226 case EOpConstructF16Mat4x2:
3227 case EOpConstructF16Mat4x3:
3228 case EOpConstructF16Mat4x4:
3230 constructingMatrix = true;
3237 // Walk the arguments for first-pass checks and collection of information.
3241 bool constType = true;
3242 bool specConstType = false; // value is only valid if constType is true
3244 bool overFull = false;
3245 bool matrixInMatrix = false;
3246 bool arrayArg = false;
3247 bool floatArgument = false;
3248 bool intArgument = false;
3249 for (int arg = 0; arg < function.getParamCount(); ++arg) {
3250 if (function[arg].type->isArray()) {
3251 if (function[arg].type->isUnsizedArray()) {
3252 // Can't construct from an unsized array.
3253 error(loc, "array argument must be sized", "constructor", "");
3258 if (constructingMatrix && function[arg].type->isMatrix())
3259 matrixInMatrix = true;
3261 // 'full' will go to true when enough args have been seen. If we loop
3262 // again, there is an extra argument.
3264 // For vectors and matrices, it's okay to have too many components
3265 // available, but not okay to have unused arguments.
3269 size += function[arg].type->computeNumComponents();
3270 if (op != EOpConstructStruct && ! type.isArray() && size >= type.computeNumComponents())
3273 if (! function[arg].type->getQualifier().isConstant())
3275 if (function[arg].type->getQualifier().isSpecConstant())
3276 specConstType = true;
3277 if (function[arg].type->isFloatingDomain())
3278 floatArgument = true;
3279 if (function[arg].type->isIntegerDomain())
3281 if (type.isStruct()) {
3282 if (function[arg].type->contains16BitFloat()) {
3283 requireFloat16Arithmetic(loc, "constructor", "can't construct structure containing 16-bit type");
3285 if (function[arg].type->contains16BitInt()) {
3286 requireInt16Arithmetic(loc, "constructor", "can't construct structure containing 16-bit type");
3288 if (function[arg].type->contains8BitInt()) {
3289 requireInt8Arithmetic(loc, "constructor", "can't construct structure containing 8-bit type");
3293 if (op == EOpConstructNonuniform)
3298 case EOpConstructFloat16:
3299 case EOpConstructF16Vec2:
3300 case EOpConstructF16Vec3:
3301 case EOpConstructF16Vec4:
3303 requireFloat16Arithmetic(loc, "constructor", "16-bit arrays not supported");
3304 if (type.isVector() && function.getParamCount() != 1)
3305 requireFloat16Arithmetic(loc, "constructor", "16-bit vectors only take vector types");
3307 case EOpConstructUint16:
3308 case EOpConstructU16Vec2:
3309 case EOpConstructU16Vec3:
3310 case EOpConstructU16Vec4:
3311 case EOpConstructInt16:
3312 case EOpConstructI16Vec2:
3313 case EOpConstructI16Vec3:
3314 case EOpConstructI16Vec4:
3316 requireInt16Arithmetic(loc, "constructor", "16-bit arrays not supported");
3317 if (type.isVector() && function.getParamCount() != 1)
3318 requireInt16Arithmetic(loc, "constructor", "16-bit vectors only take vector types");
3320 case EOpConstructUint8:
3321 case EOpConstructU8Vec2:
3322 case EOpConstructU8Vec3:
3323 case EOpConstructU8Vec4:
3324 case EOpConstructInt8:
3325 case EOpConstructI8Vec2:
3326 case EOpConstructI8Vec3:
3327 case EOpConstructI8Vec4:
3329 requireInt8Arithmetic(loc, "constructor", "8-bit arrays not supported");
3330 if (type.isVector() && function.getParamCount() != 1)
3331 requireInt8Arithmetic(loc, "constructor", "8-bit vectors only take vector types");
3338 // inherit constness from children
3341 // Finish pinning down spec-const semantics
3342 if (specConstType) {
3344 case EOpConstructInt8:
3345 case EOpConstructInt:
3346 case EOpConstructUint:
3347 case EOpConstructBool:
3348 case EOpConstructBVec2:
3349 case EOpConstructBVec3:
3350 case EOpConstructBVec4:
3351 case EOpConstructIVec2:
3352 case EOpConstructIVec3:
3353 case EOpConstructIVec4:
3354 case EOpConstructUVec2:
3355 case EOpConstructUVec3:
3356 case EOpConstructUVec4:
3358 case EOpConstructUint8:
3359 case EOpConstructInt16:
3360 case EOpConstructUint16:
3361 case EOpConstructInt64:
3362 case EOpConstructUint64:
3363 case EOpConstructI8Vec2:
3364 case EOpConstructI8Vec3:
3365 case EOpConstructI8Vec4:
3366 case EOpConstructU8Vec2:
3367 case EOpConstructU8Vec3:
3368 case EOpConstructU8Vec4:
3369 case EOpConstructI16Vec2:
3370 case EOpConstructI16Vec3:
3371 case EOpConstructI16Vec4:
3372 case EOpConstructU16Vec2:
3373 case EOpConstructU16Vec3:
3374 case EOpConstructU16Vec4:
3375 case EOpConstructI64Vec2:
3376 case EOpConstructI64Vec3:
3377 case EOpConstructI64Vec4:
3378 case EOpConstructU64Vec2:
3379 case EOpConstructU64Vec3:
3380 case EOpConstructU64Vec4:
3382 // This was the list of valid ones, if they aren't converting from float
3383 // and aren't making an array.
3384 makeSpecConst = ! floatArgument && ! type.isArray();
3387 case EOpConstructVec2:
3388 case EOpConstructVec3:
3389 case EOpConstructVec4:
3390 // This was the list of valid ones, if they aren't converting from int
3391 // and aren't making an array.
3392 makeSpecConst = ! intArgument && !type.isArray();
3396 // anything else wasn't white-listed in the spec as a conversion
3397 makeSpecConst = false;
3401 makeSpecConst = false;
3404 type.getQualifier().makeSpecConstant();
3405 else if (specConstType)
3406 type.getQualifier().makeTemporary();
3408 type.getQualifier().storage = EvqConst;
3411 if (type.isArray()) {
3412 if (function.getParamCount() == 0) {
3413 error(loc, "array constructor must have at least one argument", "constructor", "");
3417 if (type.isUnsizedArray()) {
3418 // auto adapt the constructor type to the number of arguments
3419 type.changeOuterArraySize(function.getParamCount());
3420 } else if (type.getOuterArraySize() != function.getParamCount()) {
3421 error(loc, "array constructor needs one argument per array element", "constructor", "");
3425 if (type.isArrayOfArrays()) {
3426 // Types have to match, but we're still making the type.
3427 // Finish making the type, and the comparison is done later
3428 // when checking for conversion.
3429 TArraySizes& arraySizes = *type.getArraySizes();
3431 // At least the dimensionalities have to match.
3432 if (! function[0].type->isArray() ||
3433 arraySizes.getNumDims() != function[0].type->getArraySizes()->getNumDims() + 1) {
3434 error(loc, "array constructor argument not correct type to construct array element", "constructor", "");
3438 if (arraySizes.isInnerUnsized()) {
3439 // "Arrays of arrays ..., and the size for any dimension is optional"
3440 // That means we need to adopt (from the first argument) the other array sizes into the type.
3441 for (int d = 1; d < arraySizes.getNumDims(); ++d) {
3442 if (arraySizes.getDimSize(d) == UnsizedArraySize) {
3443 arraySizes.setDimSize(d, function[0].type->getArraySizes()->getDimSize(d - 1));
3450 if (arrayArg && op != EOpConstructStruct && ! type.isArrayOfArrays()) {
3451 error(loc, "constructing non-array constituent from array argument", "constructor", "");
3455 if (matrixInMatrix && ! type.isArray()) {
3456 profileRequires(loc, ENoProfile, 120, nullptr, "constructing matrix from matrix");
3458 // "If a matrix argument is given to a matrix constructor,
3459 // it is a compile-time error to have any other arguments."
3460 if (function.getParamCount() != 1)
3461 error(loc, "matrix constructed from matrix can only have one argument", "constructor", "");
3466 error(loc, "too many arguments", "constructor", "");
3470 if (op == EOpConstructStruct && ! type.isArray() && (int)type.getStruct()->size() != function.getParamCount()) {
3471 error(loc, "Number of constructor parameters does not match the number of structure fields", "constructor", "");
3475 if ((op != EOpConstructStruct && size != 1 && size < type.computeNumComponents()) ||
3476 (op == EOpConstructStruct && size < type.computeNumComponents())) {
3477 error(loc, "not enough data provided for construction", "constructor", "");
3481 if (type.isCoopMat() && function.getParamCount() != 1) {
3482 error(loc, "wrong number of arguments", "constructor", "");
3485 if (type.isCoopMat() &&
3486 !(function[0].type->isScalar() || function[0].type->isCoopMat())) {
3487 error(loc, "Cooperative matrix constructor argument must be scalar or cooperative matrix", "constructor", "");
3491 TIntermTyped* typed = node->getAsTyped();
3492 if (typed == nullptr) {
3493 error(loc, "constructor argument does not have a type", "constructor", "");
3496 if (op != EOpConstructStruct && op != EOpConstructNonuniform && typed->getBasicType() == EbtSampler) {
3497 error(loc, "cannot convert a sampler", "constructor", "");
3500 if (op != EOpConstructStruct && typed->isAtomic()) {
3501 error(loc, "cannot convert an atomic_uint", "constructor", "");
3504 if (typed->getBasicType() == EbtVoid) {
3505 error(loc, "cannot convert a void", "constructor", "");
3512 // Verify all the correct semantics for constructing a combined texture/sampler.
3513 // Return true if the semantics are incorrect.
3514 bool TParseContext::constructorTextureSamplerError(const TSourceLoc& loc, const TFunction& function)
3516 TString constructorName = function.getType().getBasicTypeString(); // TODO: performance: should not be making copy; interface needs to change
3517 const char* token = constructorName.c_str();
3519 // exactly two arguments needed
3520 if (function.getParamCount() != 2) {
3521 error(loc, "sampler-constructor requires two arguments", token, "");
3525 // For now, not allowing arrayed constructors, the rest of this function
3526 // is set up to allow them, if this test is removed:
3527 if (function.getType().isArray()) {
3528 error(loc, "sampler-constructor cannot make an array of samplers", token, "");
3533 // * the constructor's first argument must be a texture type
3534 // * the dimensionality (1D, 2D, 3D, Cube, Rect, Buffer, MS, and Array)
3535 // of the texture type must match that of the constructed sampler type
3536 // (that is, the suffixes of the type of the first argument and the
3537 // type of the constructor will be spelled the same way)
3538 if (function[0].type->getBasicType() != EbtSampler ||
3539 ! function[0].type->getSampler().isTexture() ||
3540 function[0].type->isArray()) {
3541 error(loc, "sampler-constructor first argument must be a scalar *texture* type", token, "");
3544 // simulate the first argument's impact on the result type, so it can be compared with the encapsulated operator!=()
3545 TSampler texture = function.getType().getSampler();
3546 texture.setCombined(false);
3547 texture.shadow = false;
3548 if (texture != function[0].type->getSampler()) {
3549 error(loc, "sampler-constructor first argument must be a *texture* type"
3550 " matching the dimensionality and sampled type of the constructor", token, "");
3555 // * the constructor's second argument must be a scalar of type
3556 // *sampler* or *samplerShadow*
3557 if ( function[1].type->getBasicType() != EbtSampler ||
3558 ! function[1].type->getSampler().isPureSampler() ||
3559 function[1].type->isArray()) {
3560 error(loc, "sampler-constructor second argument must be a scalar sampler or samplerShadow", token, "");
3567 // Checks to see if a void variable has been declared and raise an error message for such a case
3569 // returns true in case of an error
3571 bool TParseContext::voidErrorCheck(const TSourceLoc& loc, const TString& identifier, const TBasicType basicType)
3573 if (basicType == EbtVoid) {
3574 error(loc, "illegal use of type 'void'", identifier.c_str(), "");
3581 // Checks to see if the node (for the expression) contains a scalar boolean expression or not
3582 void TParseContext::boolCheck(const TSourceLoc& loc, const TIntermTyped* type)
3584 if (type->getBasicType() != EbtBool || type->isArray() || type->isMatrix() || type->isVector())
3585 error(loc, "boolean expression expected", "", "");
3588 // This function checks to see if the node (for the expression) contains a scalar boolean expression or not
3589 void TParseContext::boolCheck(const TSourceLoc& loc, const TPublicType& pType)
3591 if (pType.basicType != EbtBool || pType.arraySizes || pType.matrixCols > 1 || (pType.vectorSize > 1))
3592 error(loc, "boolean expression expected", "", "");
3595 void TParseContext::samplerCheck(const TSourceLoc& loc, const TType& type, const TString& identifier, TIntermTyped* /*initializer*/)
3597 // Check that the appropriate extension is enabled if external sampler is used.
3598 // There are two extensions. The correct one must be used based on GLSL version.
3599 if (type.getBasicType() == EbtSampler && type.getSampler().isExternal()) {
3600 if (version < 300) {
3601 requireExtensions(loc, 1, &E_GL_OES_EGL_image_external, "samplerExternalOES");
3603 requireExtensions(loc, 1, &E_GL_OES_EGL_image_external_essl3, "samplerExternalOES");
3606 if (type.getSampler().isYuv()) {
3607 requireExtensions(loc, 1, &E_GL_EXT_YUV_target, "__samplerExternal2DY2YEXT");
3610 if (type.getQualifier().storage == EvqUniform)
3613 if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtSampler))
3614 error(loc, "non-uniform struct contains a sampler or image:", type.getBasicTypeString().c_str(), identifier.c_str());
3615 else if (type.getBasicType() == EbtSampler && type.getQualifier().storage != EvqUniform) {
3616 // non-uniform sampler
3617 // not yet: okay if it has an initializer
3618 // if (! initializer)
3619 error(loc, "sampler/image types can only be used in uniform variables or function parameters:", type.getBasicTypeString().c_str(), identifier.c_str());
3625 void TParseContext::atomicUintCheck(const TSourceLoc& loc, const TType& type, const TString& identifier)
3627 if (type.getQualifier().storage == EvqUniform)
3630 if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtAtomicUint))
3631 error(loc, "non-uniform struct contains an atomic_uint:", type.getBasicTypeString().c_str(), identifier.c_str());
3632 else if (type.getBasicType() == EbtAtomicUint && type.getQualifier().storage != EvqUniform)
3633 error(loc, "atomic_uints can only be used in uniform variables or function parameters:", type.getBasicTypeString().c_str(), identifier.c_str());
3636 void TParseContext::accStructCheck(const TSourceLoc& loc, const TType& type, const TString& identifier)
3638 if (type.getQualifier().storage == EvqUniform)
3641 if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtAccStruct))
3642 error(loc, "non-uniform struct contains an accelerationStructureNV:", type.getBasicTypeString().c_str(), identifier.c_str());
3643 else if (type.getBasicType() == EbtAccStruct && type.getQualifier().storage != EvqUniform)
3644 error(loc, "accelerationStructureNV can only be used in uniform variables or function parameters:",
3645 type.getBasicTypeString().c_str(), identifier.c_str());
3649 #endif // GLSLANG_WEB
3651 void TParseContext::transparentOpaqueCheck(const TSourceLoc& loc, const TType& type, const TString& identifier)
3653 if (parsingBuiltins)
3656 if (type.getQualifier().storage != EvqUniform)
3659 if (type.containsNonOpaque()) {
3660 // Vulkan doesn't allow transparent uniforms outside of blocks
3661 if (spvVersion.vulkan > 0 && !spvVersion.vulkanRelaxed)
3662 vulkanRemoved(loc, "non-opaque uniforms outside a block");
3663 // OpenGL wants locations on these (unless they are getting automapped)
3664 if (spvVersion.openGl > 0 && !type.getQualifier().hasLocation() && !intermediate.getAutoMapLocations())
3665 error(loc, "non-opaque uniform variables need a layout(location=L)", identifier.c_str(), "");
3670 // Qualifier checks knowing the qualifier and that it is a member of a struct/block.
3672 void TParseContext::memberQualifierCheck(glslang::TPublicType& publicType)
3674 globalQualifierFixCheck(publicType.loc, publicType.qualifier, true);
3675 checkNoShaderLayouts(publicType.loc, publicType.shaderQualifiers);
3676 if (publicType.qualifier.isNonUniform()) {
3677 error(publicType.loc, "not allowed on block or structure members", "nonuniformEXT", "");
3678 publicType.qualifier.nonUniform = false;
3683 // Check/fix just a full qualifier (no variables or types yet, but qualifier is complete) at global level.
3685 void TParseContext::globalQualifierFixCheck(const TSourceLoc& loc, TQualifier& qualifier, bool isMemberCheck)
3687 bool nonuniformOkay = false;
3689 // move from parameter/unknown qualifiers to pipeline in/out qualifiers
3690 switch (qualifier.storage) {
3692 profileRequires(loc, ENoProfile, 130, nullptr, "in for stage inputs");
3693 profileRequires(loc, EEsProfile, 300, nullptr, "in for stage inputs");
3694 qualifier.storage = EvqVaryingIn;
3695 nonuniformOkay = true;
3698 profileRequires(loc, ENoProfile, 130, nullptr, "out for stage outputs");
3699 profileRequires(loc, EEsProfile, 300, nullptr, "out for stage outputs");
3700 qualifier.storage = EvqVaryingOut;
3701 if (intermediate.isInvariantAll())
3702 qualifier.invariant = true;
3705 qualifier.storage = EvqVaryingIn;
3706 error(loc, "cannot use 'inout' at global scope", "", "");
3710 nonuniformOkay = true;
3713 // According to GLSL spec: The std430 qualifier is supported only for shader storage blocks; a shader using
3714 // the std430 qualifier on a uniform block will fail to compile.
3715 // Only check the global declaration: layout(std430) uniform;
3716 if (blockName == nullptr &&
3717 qualifier.layoutPacking == ElpStd430)
3719 requireExtensions(loc, 1, &E_GL_EXT_scalar_block_layout, "default std430 layout for uniform");
3726 if (!nonuniformOkay && qualifier.isNonUniform())
3727 error(loc, "for non-parameter, can only apply to 'in' or no storage qualifier", "nonuniformEXT", "");
3730 if (qualifier.isSpirvByReference())
3731 error(loc, "can only apply to parameter", "spirv_by_reference", "");
3733 if (qualifier.isSpirvLiteral())
3734 error(loc, "can only apply to parameter", "spirv_literal", "");
3737 // Storage qualifier isn't ready for memberQualifierCheck, we should skip invariantCheck for it.
3738 if (!isMemberCheck || structNestingLevel > 0)
3739 invariantCheck(loc, qualifier);
3743 // Check a full qualifier and type (no variable yet) at global level.
3745 void TParseContext::globalQualifierTypeCheck(const TSourceLoc& loc, const TQualifier& qualifier, const TPublicType& publicType)
3747 if (! symbolTable.atGlobalLevel())
3750 if (!(publicType.userDef && publicType.userDef->isReference()) && !parsingBuiltins) {
3751 if (qualifier.isMemoryQualifierImageAndSSBOOnly() && ! publicType.isImage() && publicType.qualifier.storage != EvqBuffer) {
3752 error(loc, "memory qualifiers cannot be used on this type", "", "");
3753 } else if (qualifier.isMemory() && (publicType.basicType != EbtSampler) && !publicType.qualifier.isUniformOrBuffer()) {
3754 error(loc, "memory qualifiers cannot be used on this type", "", "");
3758 if (qualifier.storage == EvqBuffer &&
3759 publicType.basicType != EbtBlock &&
3760 !qualifier.hasBufferReference())
3761 error(loc, "buffers can be declared only as blocks", "buffer", "");
3763 if (qualifier.storage != EvqVaryingIn && publicType.basicType == EbtDouble &&
3764 extensionTurnedOn(E_GL_ARB_vertex_attrib_64bit) && language == EShLangVertex &&
3766 profileRequires(loc, ECoreProfile | ECompatibilityProfile, 410, E_GL_ARB_gpu_shader_fp64, "vertex-shader `double` type");
3768 if (qualifier.storage != EvqVaryingIn && qualifier.storage != EvqVaryingOut)
3771 if (publicType.shaderQualifiers.hasBlendEquation())
3772 error(loc, "can only be applied to a standalone 'out'", "blend equation", "");
3774 // now, knowing it is a shader in/out, do all the in/out semantic checks
3776 if (publicType.basicType == EbtBool && !parsingBuiltins) {
3777 error(loc, "cannot be bool", GetStorageQualifierString(qualifier.storage), "");
3781 if (isTypeInt(publicType.basicType) || publicType.basicType == EbtDouble)
3782 profileRequires(loc, EEsProfile, 300, nullptr, "shader input/output");
3784 if (!qualifier.flat && !qualifier.isExplicitInterpolation() && !qualifier.isPervertexNV()) {
3785 if (isTypeInt(publicType.basicType) ||
3786 publicType.basicType == EbtDouble ||
3787 (publicType.userDef && ( publicType.userDef->containsBasicType(EbtInt)
3788 || publicType.userDef->containsBasicType(EbtUint)
3789 || publicType.userDef->contains16BitInt()
3790 || publicType.userDef->contains8BitInt()
3791 || publicType.userDef->contains64BitInt()
3792 || publicType.userDef->containsDouble()))) {
3793 if (qualifier.storage == EvqVaryingIn && language == EShLangFragment)
3794 error(loc, "must be qualified as flat", TType::getBasicString(publicType.basicType), GetStorageQualifierString(qualifier.storage));
3795 else if (qualifier.storage == EvqVaryingOut && language == EShLangVertex && version == 300)
3796 error(loc, "must be qualified as flat", TType::getBasicString(publicType.basicType), GetStorageQualifierString(qualifier.storage));
3800 if (qualifier.isPatch() && qualifier.isInterpolation())
3801 error(loc, "cannot use interpolation qualifiers with patch", "patch", "");
3803 if (qualifier.isTaskMemory() && publicType.basicType != EbtBlock)
3804 error(loc, "taskNV variables can be declared only as blocks", "taskNV", "");
3806 if (qualifier.storage == EvqVaryingIn) {
3809 if (publicType.basicType == EbtStruct) {
3810 error(loc, "cannot be a structure or array", GetStorageQualifierString(qualifier.storage), "");
3813 if (publicType.arraySizes) {
3814 requireProfile(loc, ~EEsProfile, "vertex input arrays");
3815 profileRequires(loc, ENoProfile, 150, nullptr, "vertex input arrays");
3817 if (publicType.basicType == EbtDouble)
3818 profileRequires(loc, ~EEsProfile, 410, E_GL_ARB_vertex_attrib_64bit, "vertex-shader `double` type input");
3819 if (qualifier.isAuxiliary() || qualifier.isInterpolation() || qualifier.isMemory() || qualifier.invariant)
3820 error(loc, "vertex input cannot be further qualified", "", "");
3822 case EShLangFragment:
3823 if (publicType.userDef) {
3824 profileRequires(loc, EEsProfile, 300, nullptr, "fragment-shader struct input");
3825 profileRequires(loc, ~EEsProfile, 150, nullptr, "fragment-shader struct input");
3826 if (publicType.userDef->containsStructure())
3827 requireProfile(loc, ~EEsProfile, "fragment-shader struct input containing structure");
3828 if (publicType.userDef->containsArray())
3829 requireProfile(loc, ~EEsProfile, "fragment-shader struct input containing an array");
3832 case EShLangCompute:
3833 if (! symbolTable.atBuiltInLevel())
3834 error(loc, "global storage input qualifier cannot be used in a compute shader", "in", "");
3837 case EShLangTessControl:
3838 if (qualifier.patch)
3839 error(loc, "can only use on output in tessellation-control shader", "patch", "");
3846 // qualifier.storage == EvqVaryingOut
3849 if (publicType.userDef) {
3850 profileRequires(loc, EEsProfile, 300, nullptr, "vertex-shader struct output");
3851 profileRequires(loc, ~EEsProfile, 150, nullptr, "vertex-shader struct output");
3852 if (publicType.userDef->containsStructure())
3853 requireProfile(loc, ~EEsProfile, "vertex-shader struct output containing structure");
3854 if (publicType.userDef->containsArray())
3855 requireProfile(loc, ~EEsProfile, "vertex-shader struct output containing an array");
3859 case EShLangFragment:
3860 profileRequires(loc, EEsProfile, 300, nullptr, "fragment shader output");
3861 if (publicType.basicType == EbtStruct) {
3862 error(loc, "cannot be a structure", GetStorageQualifierString(qualifier.storage), "");
3865 if (publicType.matrixRows > 0) {
3866 error(loc, "cannot be a matrix", GetStorageQualifierString(qualifier.storage), "");
3869 if (qualifier.isAuxiliary())
3870 error(loc, "can't use auxiliary qualifier on a fragment output", "centroid/sample/patch", "");
3871 if (qualifier.isInterpolation())
3872 error(loc, "can't use interpolation qualifier on a fragment output", "flat/smooth/noperspective", "");
3873 if (publicType.basicType == EbtDouble || publicType.basicType == EbtInt64 || publicType.basicType == EbtUint64)
3874 error(loc, "cannot contain a double, int64, or uint64", GetStorageQualifierString(qualifier.storage), "");
3877 case EShLangCompute:
3878 error(loc, "global storage output qualifier cannot be used in a compute shader", "out", "");
3881 case EShLangTessEvaluation:
3882 if (qualifier.patch)
3883 error(loc, "can only use on input in tessellation-evaluation shader", "patch", "");
3893 // Merge characteristics of the 'src' qualifier into the 'dst'.
3894 // If there is duplication, issue error messages, unless 'force'
3895 // is specified, which means to just override default settings.
3897 // Also, when force is false, it will be assumed that 'src' follows
3898 // 'dst', for the purpose of error checking order for versions
3899 // that require specific orderings of qualifiers.
3901 void TParseContext::mergeQualifiers(const TSourceLoc& loc, TQualifier& dst, const TQualifier& src, bool force)
3903 // Multiple auxiliary qualifiers (mostly done later by 'individual qualifiers')
3904 if (src.isAuxiliary() && dst.isAuxiliary())
3905 error(loc, "can only have one auxiliary qualifier (centroid, patch, and sample)", "", "");
3907 // Multiple interpolation qualifiers (mostly done later by 'individual qualifiers')
3908 if (src.isInterpolation() && dst.isInterpolation())
3909 error(loc, "can only have one interpolation qualifier (flat, smooth, noperspective, __explicitInterpAMD)", "", "");
3912 if (! force && ((!isEsProfile() && version < 420) ||
3913 (isEsProfile() && version < 310))
3914 && ! extensionTurnedOn(E_GL_ARB_shading_language_420pack)) {
3915 // non-function parameters
3916 if (src.isNoContraction() && (dst.invariant || dst.isInterpolation() || dst.isAuxiliary() || dst.storage != EvqTemporary || dst.precision != EpqNone))
3917 error(loc, "precise qualifier must appear first", "", "");
3918 if (src.invariant && (dst.isInterpolation() || dst.isAuxiliary() || dst.storage != EvqTemporary || dst.precision != EpqNone))
3919 error(loc, "invariant qualifier must appear before interpolation, storage, and precision qualifiers ", "", "");
3920 else if (src.isInterpolation() && (dst.isAuxiliary() || dst.storage != EvqTemporary || dst.precision != EpqNone))
3921 error(loc, "interpolation qualifiers must appear before storage and precision qualifiers", "", "");
3922 else if (src.isAuxiliary() && (dst.storage != EvqTemporary || dst.precision != EpqNone))
3923 error(loc, "Auxiliary qualifiers (centroid, patch, and sample) must appear before storage and precision qualifiers", "", "");
3924 else if (src.storage != EvqTemporary && (dst.precision != EpqNone))
3925 error(loc, "precision qualifier must appear as last qualifier", "", "");
3927 // function parameters
3928 if (src.isNoContraction() && (dst.storage == EvqConst || dst.storage == EvqIn || dst.storage == EvqOut))
3929 error(loc, "precise qualifier must appear first", "", "");
3930 if (src.storage == EvqConst && (dst.storage == EvqIn || dst.storage == EvqOut))
3931 error(loc, "in/out must appear before const", "", "");
3934 // Storage qualification
3935 if (dst.storage == EvqTemporary || dst.storage == EvqGlobal)
3936 dst.storage = src.storage;
3937 else if ((dst.storage == EvqIn && src.storage == EvqOut) ||
3938 (dst.storage == EvqOut && src.storage == EvqIn))
3939 dst.storage = EvqInOut;
3940 else if ((dst.storage == EvqIn && src.storage == EvqConst) ||
3941 (dst.storage == EvqConst && src.storage == EvqIn))
3942 dst.storage = EvqConstReadOnly;
3943 else if (src.storage != EvqTemporary &&
3944 src.storage != EvqGlobal)
3945 error(loc, "too many storage qualifiers", GetStorageQualifierString(src.storage), "");
3947 // Precision qualifiers
3948 if (! force && src.precision != EpqNone && dst.precision != EpqNone)
3949 error(loc, "only one precision qualifier allowed", GetPrecisionQualifierString(src.precision), "");
3950 if (dst.precision == EpqNone || (force && src.precision != EpqNone))
3951 dst.precision = src.precision;
3954 if (!force && ((src.coherent && (dst.devicecoherent || dst.queuefamilycoherent || dst.workgroupcoherent || dst.subgroupcoherent || dst.shadercallcoherent)) ||
3955 (src.devicecoherent && (dst.coherent || dst.queuefamilycoherent || dst.workgroupcoherent || dst.subgroupcoherent || dst.shadercallcoherent)) ||
3956 (src.queuefamilycoherent && (dst.coherent || dst.devicecoherent || dst.workgroupcoherent || dst.subgroupcoherent || dst.shadercallcoherent)) ||
3957 (src.workgroupcoherent && (dst.coherent || dst.devicecoherent || dst.queuefamilycoherent || dst.subgroupcoherent || dst.shadercallcoherent)) ||
3958 (src.subgroupcoherent && (dst.coherent || dst.devicecoherent || dst.queuefamilycoherent || dst.workgroupcoherent || dst.shadercallcoherent)) ||
3959 (src.shadercallcoherent && (dst.coherent || dst.devicecoherent || dst.queuefamilycoherent || dst.workgroupcoherent || dst.subgroupcoherent)))) {
3960 error(loc, "only one coherent/devicecoherent/queuefamilycoherent/workgroupcoherent/subgroupcoherent/shadercallcoherent qualifier allowed",
3961 GetPrecisionQualifierString(src.precision), "");
3964 // Layout qualifiers
3965 mergeObjectLayoutQualifiers(dst, src, false);
3967 // individual qualifiers
3968 bool repeated = false;
3969 #define MERGE_SINGLETON(field) repeated |= dst.field && src.field; dst.field |= src.field;
3970 MERGE_SINGLETON(invariant);
3971 MERGE_SINGLETON(centroid);
3972 MERGE_SINGLETON(smooth);
3973 MERGE_SINGLETON(flat);
3974 MERGE_SINGLETON(specConstant);
3976 MERGE_SINGLETON(noContraction);
3977 MERGE_SINGLETON(nopersp);
3978 MERGE_SINGLETON(explicitInterp);
3979 MERGE_SINGLETON(perPrimitiveNV);
3980 MERGE_SINGLETON(perViewNV);
3981 MERGE_SINGLETON(perTaskNV);
3982 MERGE_SINGLETON(patch);
3983 MERGE_SINGLETON(sample);
3984 MERGE_SINGLETON(coherent);
3985 MERGE_SINGLETON(devicecoherent);
3986 MERGE_SINGLETON(queuefamilycoherent);
3987 MERGE_SINGLETON(workgroupcoherent);
3988 MERGE_SINGLETON(subgroupcoherent);
3989 MERGE_SINGLETON(shadercallcoherent);
3990 MERGE_SINGLETON(nonprivate);
3991 MERGE_SINGLETON(volatil);
3992 MERGE_SINGLETON(restrict);
3993 MERGE_SINGLETON(readonly);
3994 MERGE_SINGLETON(writeonly);
3995 MERGE_SINGLETON(nonUniform);
3999 // SPIR-V storage class qualifier (GL_EXT_spirv_intrinsics)
4000 dst.spirvStorageClass = src.spirvStorageClass;
4002 // SPIR-V decorate qualifiers (GL_EXT_spirv_intrinsics)
4003 if (src.hasSprivDecorate()) {
4004 if (dst.hasSprivDecorate()) {
4005 const TSpirvDecorate& srcSpirvDecorate = src.getSpirvDecorate();
4006 TSpirvDecorate& dstSpirvDecorate = dst.getSpirvDecorate();
4007 for (auto& decorate : srcSpirvDecorate.decorates) {
4008 if (dstSpirvDecorate.decorates.find(decorate.first) != dstSpirvDecorate.decorates.end())
4009 error(loc, "too many SPIR-V decorate qualifiers", "spirv_decorate", "(decoration=%u)", decorate.first);
4011 dstSpirvDecorate.decorates.insert(decorate);
4014 for (auto& decorateId : srcSpirvDecorate.decorateIds) {
4015 if (dstSpirvDecorate.decorateIds.find(decorateId.first) != dstSpirvDecorate.decorateIds.end())
4016 error(loc, "too many SPIR-V decorate qualifiers", "spirv_decorate_id", "(decoration=%u)", decorateId.first);
4018 dstSpirvDecorate.decorateIds.insert(decorateId);
4021 for (auto& decorateString : srcSpirvDecorate.decorateStrings) {
4022 if (dstSpirvDecorate.decorates.find(decorateString.first) != dstSpirvDecorate.decorates.end())
4023 error(loc, "too many SPIR-V decorate qualifiers", "spirv_decorate_string", "(decoration=%u)", decorateString.first);
4025 dstSpirvDecorate.decorates.insert(decorateString);
4028 dst.spirvDecorate = src.spirvDecorate;
4034 error(loc, "replicated qualifiers", "", "");
4037 void TParseContext::setDefaultPrecision(const TSourceLoc& loc, TPublicType& publicType, TPrecisionQualifier qualifier)
4039 TBasicType basicType = publicType.basicType;
4041 if (basicType == EbtSampler) {
4042 defaultSamplerPrecision[computeSamplerTypeIndex(publicType.sampler)] = qualifier;
4044 return; // all is well
4047 if (basicType == EbtInt || basicType == EbtFloat) {
4048 if (publicType.isScalar()) {
4049 defaultPrecision[basicType] = qualifier;
4050 if (basicType == EbtInt) {
4051 defaultPrecision[EbtUint] = qualifier;
4052 precisionManager.explicitIntDefaultSeen();
4054 precisionManager.explicitFloatDefaultSeen();
4056 return; // all is well
4060 if (basicType == EbtAtomicUint) {
4061 if (qualifier != EpqHigh)
4062 error(loc, "can only apply highp to atomic_uint", "precision", "");
4067 error(loc, "cannot apply precision statement to this type; use 'float', 'int' or a sampler type", TType::getBasicString(basicType), "");
4070 // used to flatten the sampler type space into a single dimension
4071 // correlates with the declaration of defaultSamplerPrecision[]
4072 int TParseContext::computeSamplerTypeIndex(TSampler& sampler)
4074 int arrayIndex = sampler.arrayed ? 1 : 0;
4075 int shadowIndex = sampler.shadow ? 1 : 0;
4076 int externalIndex = sampler.isExternal() ? 1 : 0;
4077 int imageIndex = sampler.isImageClass() ? 1 : 0;
4078 int msIndex = sampler.isMultiSample() ? 1 : 0;
4080 int flattened = EsdNumDims * (EbtNumTypes * (2 * (2 * (2 * (2 * arrayIndex + msIndex) + imageIndex) + shadowIndex) +
4081 externalIndex) + sampler.type) + sampler.dim;
4082 assert(flattened < maxSamplerIndex);
4087 TPrecisionQualifier TParseContext::getDefaultPrecision(TPublicType& publicType)
4089 if (publicType.basicType == EbtSampler)
4090 return defaultSamplerPrecision[computeSamplerTypeIndex(publicType.sampler)];
4092 return defaultPrecision[publicType.basicType];
4095 void TParseContext::precisionQualifierCheck(const TSourceLoc& loc, TBasicType baseType, TQualifier& qualifier)
4097 // Built-in symbols are allowed some ambiguous precisions, to be pinned down
4098 // later by context.
4099 if (! obeyPrecisionQualifiers() || parsingBuiltins)
4103 if (baseType == EbtAtomicUint && qualifier.precision != EpqNone && qualifier.precision != EpqHigh)
4104 error(loc, "atomic counters can only be highp", "atomic_uint", "");
4107 if (baseType == EbtFloat || baseType == EbtUint || baseType == EbtInt || baseType == EbtSampler || baseType == EbtAtomicUint) {
4108 if (qualifier.precision == EpqNone) {
4109 if (relaxedErrors())
4110 warn(loc, "type requires declaration of default precision qualifier", TType::getBasicString(baseType), "substituting 'mediump'");
4112 error(loc, "type requires declaration of default precision qualifier", TType::getBasicString(baseType), "");
4113 qualifier.precision = EpqMedium;
4114 defaultPrecision[baseType] = EpqMedium;
4116 } else if (qualifier.precision != EpqNone)
4117 error(loc, "type cannot have precision qualifier", TType::getBasicString(baseType), "");
4120 void TParseContext::parameterTypeCheck(const TSourceLoc& loc, TStorageQualifier qualifier, const TType& type)
4122 if ((qualifier == EvqOut || qualifier == EvqInOut) && type.isOpaque())
4123 error(loc, "samplers and atomic_uints cannot be output parameters", type.getBasicTypeString().c_str(), "");
4124 if (!parsingBuiltins && type.contains16BitFloat())
4125 requireFloat16Arithmetic(loc, type.getBasicTypeString().c_str(), "float16 types can only be in uniform block or buffer storage");
4126 if (!parsingBuiltins && type.contains16BitInt())
4127 requireInt16Arithmetic(loc, type.getBasicTypeString().c_str(), "(u)int16 types can only be in uniform block or buffer storage");
4128 if (!parsingBuiltins && type.contains8BitInt())
4129 requireInt8Arithmetic(loc, type.getBasicTypeString().c_str(), "(u)int8 types can only be in uniform block or buffer storage");
4132 bool TParseContext::containsFieldWithBasicType(const TType& type, TBasicType basicType)
4134 if (type.getBasicType() == basicType)
4137 if (type.getBasicType() == EbtStruct) {
4138 const TTypeList& structure = *type.getStruct();
4139 for (unsigned int i = 0; i < structure.size(); ++i) {
4140 if (containsFieldWithBasicType(*structure[i].type, basicType))
4149 // Do size checking for an array type's size.
4151 void TParseContext::arraySizeCheck(const TSourceLoc& loc, TIntermTyped* expr, TArraySize& sizePair, const char *sizeType)
4153 bool isConst = false;
4154 sizePair.node = nullptr;
4158 TIntermConstantUnion* constant = expr->getAsConstantUnion();
4160 // handle true (non-specialization) constant
4161 size = constant->getConstArray()[0].getIConst();
4164 // see if it's a specialization constant instead
4165 if (expr->getQualifier().isSpecConstant()) {
4167 sizePair.node = expr;
4168 TIntermSymbol* symbol = expr->getAsSymbolNode();
4169 if (symbol && symbol->getConstArray().size() > 0)
4170 size = symbol->getConstArray()[0].getIConst();
4171 } else if (expr->getAsUnaryNode() &&
4172 expr->getAsUnaryNode()->getOp() == glslang::EOpArrayLength &&
4173 expr->getAsUnaryNode()->getOperand()->getType().isCoopMat()) {
4176 sizePair.node = expr->getAsUnaryNode();
4180 sizePair.size = size;
4182 if (! isConst || (expr->getBasicType() != EbtInt && expr->getBasicType() != EbtUint)) {
4183 error(loc, sizeType, "", "must be a constant integer expression");
4188 error(loc, sizeType, "", "must be a positive integer");
4194 // See if this qualifier can be an array.
4196 // Returns true if there is an error.
4198 bool TParseContext::arrayQualifierError(const TSourceLoc& loc, const TQualifier& qualifier)
4200 if (qualifier.storage == EvqConst) {
4201 profileRequires(loc, ENoProfile, 120, E_GL_3DL_array_objects, "const array");
4202 profileRequires(loc, EEsProfile, 300, nullptr, "const array");
4205 if (qualifier.storage == EvqVaryingIn && language == EShLangVertex) {
4206 requireProfile(loc, ~EEsProfile, "vertex input arrays");
4207 profileRequires(loc, ENoProfile, 150, nullptr, "vertex input arrays");
4214 // See if this qualifier and type combination can be an array.
4215 // Assumes arrayQualifierError() was also called to catch the type-invariant tests.
4217 // Returns true if there is an error.
4219 bool TParseContext::arrayError(const TSourceLoc& loc, const TType& type)
4221 if (type.getQualifier().storage == EvqVaryingOut && language == EShLangVertex) {
4222 if (type.isArrayOfArrays())
4223 requireProfile(loc, ~EEsProfile, "vertex-shader array-of-array output");
4224 else if (type.isStruct())
4225 requireProfile(loc, ~EEsProfile, "vertex-shader array-of-struct output");
4227 if (type.getQualifier().storage == EvqVaryingIn && language == EShLangFragment) {
4228 if (type.isArrayOfArrays())
4229 requireProfile(loc, ~EEsProfile, "fragment-shader array-of-array input");
4230 else if (type.isStruct())
4231 requireProfile(loc, ~EEsProfile, "fragment-shader array-of-struct input");
4233 if (type.getQualifier().storage == EvqVaryingOut && language == EShLangFragment) {
4234 if (type.isArrayOfArrays())
4235 requireProfile(loc, ~EEsProfile, "fragment-shader array-of-array output");
4242 // Require array to be completely sized
4244 void TParseContext::arraySizeRequiredCheck(const TSourceLoc& loc, const TArraySizes& arraySizes)
4246 if (!parsingBuiltins && arraySizes.hasUnsized())
4247 error(loc, "array size required", "", "");
4250 void TParseContext::structArrayCheck(const TSourceLoc& /*loc*/, const TType& type)
4252 const TTypeList& structure = *type.getStruct();
4253 for (int m = 0; m < (int)structure.size(); ++m) {
4254 const TType& member = *structure[m].type;
4255 if (member.isArray())
4256 arraySizeRequiredCheck(structure[m].loc, *member.getArraySizes());
4260 void TParseContext::arraySizesCheck(const TSourceLoc& loc, const TQualifier& qualifier, TArraySizes* arraySizes,
4261 const TIntermTyped* initializer, bool lastMember)
4265 // always allow special built-in ins/outs sized to topologies
4266 if (parsingBuiltins)
4269 // initializer must be a sized array, in which case
4270 // allow the initializer to set any unknown array sizes
4271 if (initializer != nullptr) {
4272 if (initializer->getType().isUnsizedArray())
4273 error(loc, "array initializer must be sized", "[]", "");
4277 // No environment allows any non-outer-dimension to be implicitly sized
4278 if (arraySizes->isInnerUnsized()) {
4279 error(loc, "only outermost dimension of an array of arrays can be implicitly sized", "[]", "");
4280 arraySizes->clearInnerUnsized();
4283 if (arraySizes->isInnerSpecialization() &&
4284 (qualifier.storage != EvqTemporary && qualifier.storage != EvqGlobal && qualifier.storage != EvqShared && qualifier.storage != EvqConst))
4285 error(loc, "only outermost dimension of an array of arrays can be a specialization constant", "[]", "");
4289 // desktop always allows outer-dimension-unsized variable arrays,
4293 // for ES, if size isn't coming from an initializer, it has to be explicitly declared now,
4294 // with very few exceptions
4296 // implicitly-sized io exceptions:
4298 case EShLangGeometry:
4299 if (qualifier.storage == EvqVaryingIn)
4300 if ((isEsProfile() && version >= 320) ||
4301 extensionsTurnedOn(Num_AEP_geometry_shader, AEP_geometry_shader))
4304 case EShLangTessControl:
4305 if ( qualifier.storage == EvqVaryingIn ||
4306 (qualifier.storage == EvqVaryingOut && ! qualifier.isPatch()))
4307 if ((isEsProfile() && version >= 320) ||
4308 extensionsTurnedOn(Num_AEP_tessellation_shader, AEP_tessellation_shader))
4311 case EShLangTessEvaluation:
4312 if ((qualifier.storage == EvqVaryingIn && ! qualifier.isPatch()) ||
4313 qualifier.storage == EvqVaryingOut)
4314 if ((isEsProfile() && version >= 320) ||
4315 extensionsTurnedOn(Num_AEP_tessellation_shader, AEP_tessellation_shader))
4319 if (qualifier.storage == EvqVaryingOut)
4320 if ((isEsProfile() && version >= 320) ||
4321 extensionTurnedOn(E_GL_NV_mesh_shader))
4330 // last member of ssbo block exception:
4331 if (qualifier.storage == EvqBuffer && lastMember)
4334 arraySizeRequiredCheck(loc, *arraySizes);
4337 void TParseContext::arrayOfArrayVersionCheck(const TSourceLoc& loc, const TArraySizes* sizes)
4339 if (sizes == nullptr || sizes->getNumDims() == 1)
4342 const char* feature = "arrays of arrays";
4344 requireProfile(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, feature);
4345 profileRequires(loc, EEsProfile, 310, nullptr, feature);
4346 profileRequires(loc, ECoreProfile | ECompatibilityProfile, 430, nullptr, feature);
4350 // Do all the semantic checking for declaring or redeclaring an array, with and
4351 // without a size, and make the right changes to the symbol table.
4353 void TParseContext::declareArray(const TSourceLoc& loc, const TString& identifier, const TType& type, TSymbol*& symbol)
4355 if (symbol == nullptr) {
4357 symbol = symbolTable.find(identifier, nullptr, ¤tScope);
4359 if (symbol && builtInName(identifier) && ! symbolTable.atBuiltInLevel()) {
4360 // bad shader (errors already reported) trying to redeclare a built-in name as an array
4364 if (symbol == nullptr || ! currentScope) {
4366 // Successfully process a new definition.
4367 // (Redeclarations have to take place at the same scope; otherwise they are hiding declarations)
4369 symbol = new TVariable(&identifier, type);
4370 symbolTable.insert(*symbol);
4371 if (symbolTable.atGlobalLevel())
4372 trackLinkage(*symbol);
4375 if (! symbolTable.atBuiltInLevel()) {
4376 if (isIoResizeArray(type)) {
4377 ioArraySymbolResizeList.push_back(symbol);
4378 checkIoArraysConsistency(loc, true);
4380 fixIoArraySize(loc, symbol->getWritableType());
4386 if (symbol->getAsAnonMember()) {
4387 error(loc, "cannot redeclare a user-block member array", identifier.c_str(), "");
4394 // Process a redeclaration.
4397 if (symbol == nullptr) {
4398 error(loc, "array variable name expected", identifier.c_str(), "");
4402 // redeclareBuiltinVariable() should have already done the copyUp()
4403 TType& existingType = symbol->getWritableType();
4405 if (! existingType.isArray()) {
4406 error(loc, "redeclaring non-array as array", identifier.c_str(), "");
4410 if (! existingType.sameElementType(type)) {
4411 error(loc, "redeclaration of array with a different element type", identifier.c_str(), "");
4415 if (! existingType.sameInnerArrayness(type)) {
4416 error(loc, "redeclaration of array with a different array dimensions or sizes", identifier.c_str(), "");
4421 if (existingType.isSizedArray()) {
4422 // be more leniant for input arrays to geometry shaders and tessellation control outputs, where the redeclaration is the same size
4423 if (! (isIoResizeArray(type) && existingType.getOuterArraySize() == type.getOuterArraySize()))
4424 error(loc, "redeclaration of array with size", identifier.c_str(), "");
4428 arrayLimitCheck(loc, identifier, type.getOuterArraySize());
4430 existingType.updateArraySizes(type);
4432 if (isIoResizeArray(type))
4433 checkIoArraysConsistency(loc);
4439 // Policy and error check for needing a runtime sized array.
4440 void TParseContext::checkRuntimeSizable(const TSourceLoc& loc, const TIntermTyped& base)
4442 // runtime length implies runtime sizeable, so no problem
4443 if (isRuntimeLength(base))
4446 if (base.getType().getQualifier().builtIn == EbvSampleMask)
4449 // Check for last member of a bufferreference type, which is runtime sizeable
4450 // but doesn't support runtime length
4451 if (base.getType().getQualifier().storage == EvqBuffer) {
4452 const TIntermBinary* binary = base.getAsBinaryNode();
4453 if (binary != nullptr &&
4454 binary->getOp() == EOpIndexDirectStruct &&
4455 binary->getLeft()->isReference()) {
4457 const int index = binary->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
4458 const int memberCount = (int)binary->getLeft()->getType().getReferentType()->getStruct()->size();
4459 if (index == memberCount - 1)
4464 // check for additional things allowed by GL_EXT_nonuniform_qualifier
4465 if (base.getBasicType() == EbtSampler || base.getBasicType() == EbtAccStruct || base.getBasicType() == EbtRayQuery ||
4466 (base.getBasicType() == EbtBlock && base.getType().getQualifier().isUniformOrBuffer()))
4467 requireExtensions(loc, 1, &E_GL_EXT_nonuniform_qualifier, "variable index");
4469 error(loc, "", "[", "array must be redeclared with a size before being indexed with a variable");
4472 // Policy decision for whether a run-time .length() is allowed.
4473 bool TParseContext::isRuntimeLength(const TIntermTyped& base) const
4475 if (base.getType().getQualifier().storage == EvqBuffer) {
4476 // in a buffer block
4477 const TIntermBinary* binary = base.getAsBinaryNode();
4478 if (binary != nullptr && binary->getOp() == EOpIndexDirectStruct) {
4479 // is it the last member?
4480 const int index = binary->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
4482 if (binary->getLeft()->isReference())
4485 const int memberCount = (int)binary->getLeft()->getType().getStruct()->size();
4486 if (index == memberCount - 1)
4494 // Check if mesh perviewNV attributes have a view dimension
4495 // and resize it to gl_MaxMeshViewCountNV when implicitly sized.
4496 void TParseContext::checkAndResizeMeshViewDim(const TSourceLoc& loc, TType& type, bool isBlockMember)
4498 // see if member is a per-view attribute
4499 if (!type.getQualifier().isPerView())
4502 if ((isBlockMember && type.isArray()) || (!isBlockMember && type.isArrayOfArrays())) {
4503 // since we don't have the maxMeshViewCountNV set during parsing builtins, we hardcode the value.
4504 int maxViewCount = parsingBuiltins ? 4 : resources.maxMeshViewCountNV;
4505 // For block members, outermost array dimension is the view dimension.
4506 // For non-block members, outermost array dimension is the vertex/primitive dimension
4507 // and 2nd outermost is the view dimension.
4508 int viewDim = isBlockMember ? 0 : 1;
4509 int viewDimSize = type.getArraySizes()->getDimSize(viewDim);
4511 if (viewDimSize != UnsizedArraySize && viewDimSize != maxViewCount)
4512 error(loc, "mesh view output array size must be gl_MaxMeshViewCountNV or implicitly sized", "[]", "");
4513 else if (viewDimSize == UnsizedArraySize)
4514 type.getArraySizes()->setDimSize(viewDim, maxViewCount);
4517 error(loc, "requires a view array dimension", "perviewNV", "");
4521 #endif // GLSLANG_WEB
4523 // Returns true if the first argument to the #line directive is the line number for the next line.
4525 // Desktop, pre-version 3.30: "After processing this directive
4526 // (including its new-line), the implementation will behave as if it is compiling at line number line+1 and
4527 // source string number source-string-number."
4529 // Desktop, version 3.30 and later, and ES: "After processing this directive
4530 // (including its new-line), the implementation will behave as if it is compiling at line number line and
4531 // source string number source-string-number.
4532 bool TParseContext::lineDirectiveShouldSetNextLine() const
4534 return isEsProfile() || version >= 330;
4538 // Enforce non-initializer type/qualifier rules.
4540 void TParseContext::nonInitConstCheck(const TSourceLoc& loc, TString& identifier, TType& type)
4543 // Make the qualifier make sense, given that there is not an initializer.
4545 if (type.getQualifier().storage == EvqConst ||
4546 type.getQualifier().storage == EvqConstReadOnly) {
4547 type.getQualifier().makeTemporary();
4548 error(loc, "variables with qualifier 'const' must be initialized", identifier.c_str(), "");
4553 // See if the identifier is a built-in symbol that can be redeclared, and if so,
4554 // copy the symbol table's read-only built-in variable to the current
4555 // global level, where it can be modified based on the passed in type.
4557 // Returns nullptr if no redeclaration took place; meaning a normal declaration still
4558 // needs to occur for it, not necessarily an error.
4560 // Returns a redeclared and type-modified variable if a redeclarated occurred.
4562 TSymbol* TParseContext::redeclareBuiltinVariable(const TSourceLoc& loc, const TString& identifier,
4563 const TQualifier& qualifier, const TShaderQualifiers& publicType)
4566 if (! builtInName(identifier) || symbolTable.atBuiltInLevel() || ! symbolTable.atGlobalLevel())
4569 bool nonEsRedecls = (!isEsProfile() && (version >= 130 || identifier == "gl_TexCoord"));
4570 bool esRedecls = (isEsProfile() &&
4571 (version >= 320 || extensionsTurnedOn(Num_AEP_shader_io_blocks, AEP_shader_io_blocks)));
4572 if (! esRedecls && ! nonEsRedecls)
4575 // Special case when using GL_ARB_separate_shader_objects
4576 bool ssoPre150 = false; // means the only reason this variable is redeclared is due to this combination
4577 if (!isEsProfile() && version <= 140 && extensionTurnedOn(E_GL_ARB_separate_shader_objects)) {
4578 if (identifier == "gl_Position" ||
4579 identifier == "gl_PointSize" ||
4580 identifier == "gl_ClipVertex" ||
4581 identifier == "gl_FogFragCoord")
4585 // Potentially redeclaring a built-in variable...
4588 (identifier == "gl_FragDepth" && ((nonEsRedecls && version >= 420) || esRedecls)) ||
4589 (identifier == "gl_FragCoord" && ((nonEsRedecls && version >= 150) || esRedecls)) ||
4590 identifier == "gl_ClipDistance" ||
4591 identifier == "gl_CullDistance" ||
4592 identifier == "gl_ShadingRateEXT" ||
4593 identifier == "gl_PrimitiveShadingRateEXT" ||
4594 identifier == "gl_FrontColor" ||
4595 identifier == "gl_BackColor" ||
4596 identifier == "gl_FrontSecondaryColor" ||
4597 identifier == "gl_BackSecondaryColor" ||
4598 identifier == "gl_SecondaryColor" ||
4599 (identifier == "gl_Color" && language == EShLangFragment) ||
4600 (identifier == "gl_FragStencilRefARB" && (nonEsRedecls && version >= 140)
4601 && language == EShLangFragment) ||
4602 identifier == "gl_SampleMask" ||
4603 identifier == "gl_Layer" ||
4604 identifier == "gl_PrimitiveIndicesNV" ||
4605 identifier == "gl_TexCoord") {
4607 // Find the existing symbol, if any.
4609 TSymbol* symbol = symbolTable.find(identifier, &builtIn);
4611 // If the symbol was not found, this must be a version/profile/stage
4612 // that doesn't have it.
4616 // If it wasn't at a built-in level, then it's already been redeclared;
4617 // that is, this is a redeclaration of a redeclaration; reuse that initial
4618 // redeclaration. Otherwise, make the new one.
4620 makeEditable(symbol);
4621 symbolTable.amendSymbolIdLevel(*symbol);
4624 // Now, modify the type of the copy, as per the type of the current redeclaration.
4626 TQualifier& symbolQualifier = symbol->getWritableType().getQualifier();
4628 if (intermediate.inIoAccessed(identifier))
4629 error(loc, "cannot redeclare after use", identifier.c_str(), "");
4630 if (qualifier.hasLayout())
4631 error(loc, "cannot apply layout qualifier to", "redeclaration", symbol->getName().c_str());
4632 if (qualifier.isMemory() || qualifier.isAuxiliary() || (language == EShLangVertex && qualifier.storage != EvqVaryingOut) ||
4633 (language == EShLangFragment && qualifier.storage != EvqVaryingIn))
4634 error(loc, "cannot change storage, memory, or auxiliary qualification of", "redeclaration", symbol->getName().c_str());
4635 if (! qualifier.smooth)
4636 error(loc, "cannot change interpolation qualification of", "redeclaration", symbol->getName().c_str());
4637 } else if (identifier == "gl_FrontColor" ||
4638 identifier == "gl_BackColor" ||
4639 identifier == "gl_FrontSecondaryColor" ||
4640 identifier == "gl_BackSecondaryColor" ||
4641 identifier == "gl_SecondaryColor" ||
4642 identifier == "gl_Color") {
4643 symbolQualifier.flat = qualifier.flat;
4644 symbolQualifier.smooth = qualifier.smooth;
4645 symbolQualifier.nopersp = qualifier.nopersp;
4646 if (qualifier.hasLayout())
4647 error(loc, "cannot apply layout qualifier to", "redeclaration", symbol->getName().c_str());
4648 if (qualifier.isMemory() || qualifier.isAuxiliary() || symbol->getType().getQualifier().storage != qualifier.storage)
4649 error(loc, "cannot change storage, memory, or auxiliary qualification of", "redeclaration", symbol->getName().c_str());
4650 } else if (identifier == "gl_TexCoord" ||
4651 identifier == "gl_ClipDistance" ||
4652 identifier == "gl_CullDistance") {
4653 if (qualifier.hasLayout() || qualifier.isMemory() || qualifier.isAuxiliary() ||
4654 qualifier.nopersp != symbolQualifier.nopersp || qualifier.flat != symbolQualifier.flat ||
4655 symbolQualifier.storage != qualifier.storage)
4656 error(loc, "cannot change qualification of", "redeclaration", symbol->getName().c_str());
4657 } else if (identifier == "gl_FragCoord") {
4658 if (intermediate.inIoAccessed("gl_FragCoord"))
4659 error(loc, "cannot redeclare after use", "gl_FragCoord", "");
4660 if (qualifier.nopersp != symbolQualifier.nopersp || qualifier.flat != symbolQualifier.flat ||
4661 qualifier.isMemory() || qualifier.isAuxiliary())
4662 error(loc, "can only change layout qualification of", "redeclaration", symbol->getName().c_str());
4663 if (qualifier.storage != EvqVaryingIn)
4664 error(loc, "cannot change input storage qualification of", "redeclaration", symbol->getName().c_str());
4665 if (! builtIn && (publicType.pixelCenterInteger != intermediate.getPixelCenterInteger() ||
4666 publicType.originUpperLeft != intermediate.getOriginUpperLeft()))
4667 error(loc, "cannot redeclare with different qualification:", "redeclaration", symbol->getName().c_str());
4668 if (publicType.pixelCenterInteger)
4669 intermediate.setPixelCenterInteger();
4670 if (publicType.originUpperLeft)
4671 intermediate.setOriginUpperLeft();
4672 } else if (identifier == "gl_FragDepth") {
4673 if (qualifier.nopersp != symbolQualifier.nopersp || qualifier.flat != symbolQualifier.flat ||
4674 qualifier.isMemory() || qualifier.isAuxiliary())
4675 error(loc, "can only change layout qualification of", "redeclaration", symbol->getName().c_str());
4676 if (qualifier.storage != EvqVaryingOut)
4677 error(loc, "cannot change output storage qualification of", "redeclaration", symbol->getName().c_str());
4678 if (publicType.layoutDepth != EldNone) {
4679 if (intermediate.inIoAccessed("gl_FragDepth"))
4680 error(loc, "cannot redeclare after use", "gl_FragDepth", "");
4681 if (! intermediate.setDepth(publicType.layoutDepth))
4682 error(loc, "all redeclarations must use the same depth layout on", "redeclaration", symbol->getName().c_str());
4686 identifier == "gl_PrimitiveIndicesNV" ||
4687 identifier == "gl_FragStencilRefARB") {
4688 if (qualifier.hasLayout())
4689 error(loc, "cannot apply layout qualifier to", "redeclaration", symbol->getName().c_str());
4690 if (qualifier.storage != EvqVaryingOut)
4691 error(loc, "cannot change output storage qualification of", "redeclaration", symbol->getName().c_str());
4693 else if (identifier == "gl_SampleMask") {
4694 if (!publicType.layoutOverrideCoverage) {
4695 error(loc, "redeclaration only allowed for override_coverage layout", "redeclaration", symbol->getName().c_str());
4697 intermediate.setLayoutOverrideCoverage();
4699 else if (identifier == "gl_Layer") {
4700 if (!qualifier.layoutViewportRelative && qualifier.layoutSecondaryViewportRelativeOffset == -2048)
4701 error(loc, "redeclaration only allowed for viewport_relative or secondary_view_offset layout", "redeclaration", symbol->getName().c_str());
4702 symbolQualifier.layoutViewportRelative = qualifier.layoutViewportRelative;
4703 symbolQualifier.layoutSecondaryViewportRelativeOffset = qualifier.layoutSecondaryViewportRelativeOffset;
4706 // TODO: semantics quality: separate smooth from nothing declared, then use IsInterpolation for several tests above
4716 // Either redeclare the requested block, or give an error message why it can't be done.
4718 // TODO: functionality: explicitly sizing members of redeclared blocks is not giving them an explicit size
4719 void TParseContext::redeclareBuiltinBlock(const TSourceLoc& loc, TTypeList& newTypeList, const TString& blockName,
4720 const TString* instanceName, TArraySizes* arraySizes)
4723 const char* feature = "built-in block redeclaration";
4724 profileRequires(loc, EEsProfile, 320, Num_AEP_shader_io_blocks, AEP_shader_io_blocks, feature);
4725 profileRequires(loc, ~EEsProfile, 410, E_GL_ARB_separate_shader_objects, feature);
4727 if (blockName != "gl_PerVertex" && blockName != "gl_PerFragment" &&
4728 blockName != "gl_MeshPerVertexNV" && blockName != "gl_MeshPerPrimitiveNV") {
4729 error(loc, "cannot redeclare block: ", "block declaration", blockName.c_str());
4733 // Redeclaring a built-in block...
4735 if (instanceName && ! builtInName(*instanceName)) {
4736 error(loc, "cannot redeclare a built-in block with a user name", instanceName->c_str(), "");
4740 // Blocks with instance names are easy to find, lookup the instance name,
4741 // Anonymous blocks need to be found via a member.
4745 block = symbolTable.find(*instanceName, &builtIn);
4747 block = symbolTable.find(newTypeList.front().type->getFieldName(), &builtIn);
4749 // If the block was not found, this must be a version/profile/stage
4750 // that doesn't have it, or the instance name is wrong.
4751 const char* errorName = instanceName ? instanceName->c_str() : newTypeList.front().type->getFieldName().c_str();
4753 error(loc, "no declaration found for redeclaration", errorName, "");
4756 // Built-in blocks cannot be redeclared more than once, which if happened,
4757 // we'd be finding the already redeclared one here, rather than the built in.
4759 error(loc, "can only redeclare a built-in block once, and before any use", blockName.c_str(), "");
4763 // Copy the block to make a writable version, to insert into the block table after editing.
4764 block = symbolTable.copyUpDeferredInsert(block);
4766 if (block->getType().getBasicType() != EbtBlock) {
4767 error(loc, "cannot redeclare a non block as a block", errorName, "");
4771 // Fix XFB stuff up, it applies to the order of the redeclaration, not
4772 // the order of the original members.
4773 if (currentBlockQualifier.storage == EvqVaryingOut && globalOutputDefaults.hasXfbBuffer()) {
4774 if (!currentBlockQualifier.hasXfbBuffer())
4775 currentBlockQualifier.layoutXfbBuffer = globalOutputDefaults.layoutXfbBuffer;
4776 if (!currentBlockQualifier.hasStream())
4777 currentBlockQualifier.layoutStream = globalOutputDefaults.layoutStream;
4778 fixXfbOffsets(currentBlockQualifier, newTypeList);
4781 // Edit and error check the container against the redeclaration
4782 // - remove unused members
4783 // - ensure remaining qualifiers/types match
4785 TType& type = block->getWritableType();
4787 // if gl_PerVertex is redeclared for the purpose of passing through "gl_Position"
4788 // for passthrough purpose, the redeclared block should have the same qualifers as
4790 if (currentBlockQualifier.layoutPassthrough) {
4791 type.getQualifier().layoutPassthrough = currentBlockQualifier.layoutPassthrough;
4792 type.getQualifier().storage = currentBlockQualifier.storage;
4793 type.getQualifier().layoutStream = currentBlockQualifier.layoutStream;
4794 type.getQualifier().layoutXfbBuffer = currentBlockQualifier.layoutXfbBuffer;
4797 TTypeList::iterator member = type.getWritableStruct()->begin();
4798 size_t numOriginalMembersFound = 0;
4799 while (member != type.getStruct()->end()) {
4802 TTypeList::const_iterator newMember;
4803 TSourceLoc memberLoc;
4805 for (newMember = newTypeList.begin(); newMember != newTypeList.end(); ++newMember) {
4806 if (member->type->getFieldName() == newMember->type->getFieldName()) {
4808 memberLoc = newMember->loc;
4814 ++numOriginalMembersFound;
4815 // - ensure match between redeclared members' types
4816 // - check for things that can't be changed
4817 // - update things that can be changed
4818 TType& oldType = *member->type;
4819 const TType& newType = *newMember->type;
4820 if (! newType.sameElementType(oldType))
4821 error(memberLoc, "cannot redeclare block member with a different type", member->type->getFieldName().c_str(), "");
4822 if (oldType.isArray() != newType.isArray())
4823 error(memberLoc, "cannot change arrayness of redeclared block member", member->type->getFieldName().c_str(), "");
4824 else if (! oldType.getQualifier().isPerView() && ! oldType.sameArrayness(newType) && oldType.isSizedArray())
4825 error(memberLoc, "cannot change array size of redeclared block member", member->type->getFieldName().c_str(), "");
4826 else if (! oldType.getQualifier().isPerView() && newType.isArray())
4827 arrayLimitCheck(loc, member->type->getFieldName(), newType.getOuterArraySize());
4828 if (oldType.getQualifier().isPerView() && ! newType.getQualifier().isPerView())
4829 error(memberLoc, "missing perviewNV qualifier to redeclared block member", member->type->getFieldName().c_str(), "");
4830 else if (! oldType.getQualifier().isPerView() && newType.getQualifier().isPerView())
4831 error(memberLoc, "cannot add perviewNV qualifier to redeclared block member", member->type->getFieldName().c_str(), "");
4832 else if (newType.getQualifier().isPerView()) {
4833 if (oldType.getArraySizes()->getNumDims() != newType.getArraySizes()->getNumDims())
4834 error(memberLoc, "cannot change arrayness of redeclared block member", member->type->getFieldName().c_str(), "");
4835 else if (! newType.isUnsizedArray() && newType.getOuterArraySize() != resources.maxMeshViewCountNV)
4836 error(loc, "mesh view output array size must be gl_MaxMeshViewCountNV or implicitly sized", "[]", "");
4837 else if (newType.getArraySizes()->getNumDims() == 2) {
4838 int innerDimSize = newType.getArraySizes()->getDimSize(1);
4839 arrayLimitCheck(memberLoc, member->type->getFieldName(), innerDimSize);
4840 oldType.getArraySizes()->setDimSize(1, innerDimSize);
4843 if (oldType.getQualifier().isPerPrimitive() && ! newType.getQualifier().isPerPrimitive())
4844 error(memberLoc, "missing perprimitiveNV qualifier to redeclared block member", member->type->getFieldName().c_str(), "");
4845 else if (! oldType.getQualifier().isPerPrimitive() && newType.getQualifier().isPerPrimitive())
4846 error(memberLoc, "cannot add perprimitiveNV qualifier to redeclared block member", member->type->getFieldName().c_str(), "");
4847 if (newType.getQualifier().isMemory())
4848 error(memberLoc, "cannot add memory qualifier to redeclared block member", member->type->getFieldName().c_str(), "");
4849 if (newType.getQualifier().hasNonXfbLayout())
4850 error(memberLoc, "cannot add non-XFB layout to redeclared block member", member->type->getFieldName().c_str(), "");
4851 if (newType.getQualifier().patch)
4852 error(memberLoc, "cannot add patch to redeclared block member", member->type->getFieldName().c_str(), "");
4853 if (newType.getQualifier().hasXfbBuffer() &&
4854 newType.getQualifier().layoutXfbBuffer != currentBlockQualifier.layoutXfbBuffer)
4855 error(memberLoc, "member cannot contradict block (or what block inherited from global)", "xfb_buffer", "");
4856 if (newType.getQualifier().hasStream() &&
4857 newType.getQualifier().layoutStream != currentBlockQualifier.layoutStream)
4858 error(memberLoc, "member cannot contradict block (or what block inherited from global)", "xfb_stream", "");
4859 oldType.getQualifier().centroid = newType.getQualifier().centroid;
4860 oldType.getQualifier().sample = newType.getQualifier().sample;
4861 oldType.getQualifier().invariant = newType.getQualifier().invariant;
4862 oldType.getQualifier().noContraction = newType.getQualifier().noContraction;
4863 oldType.getQualifier().smooth = newType.getQualifier().smooth;
4864 oldType.getQualifier().flat = newType.getQualifier().flat;
4865 oldType.getQualifier().nopersp = newType.getQualifier().nopersp;
4866 oldType.getQualifier().layoutXfbOffset = newType.getQualifier().layoutXfbOffset;
4867 oldType.getQualifier().layoutXfbBuffer = newType.getQualifier().layoutXfbBuffer;
4868 oldType.getQualifier().layoutXfbStride = newType.getQualifier().layoutXfbStride;
4869 if (oldType.getQualifier().layoutXfbOffset != TQualifier::layoutXfbBufferEnd) {
4870 // If any member has an xfb_offset, then the block's xfb_buffer inherents current xfb_buffer,
4871 // and for xfb processing, the member needs it as well, along with xfb_stride.
4872 type.getQualifier().layoutXfbBuffer = currentBlockQualifier.layoutXfbBuffer;
4873 oldType.getQualifier().layoutXfbBuffer = currentBlockQualifier.layoutXfbBuffer;
4875 if (oldType.isUnsizedArray() && newType.isSizedArray())
4876 oldType.changeOuterArraySize(newType.getOuterArraySize());
4878 // check and process the member's type, which will include managing xfb information
4879 layoutTypeCheck(loc, oldType);
4881 // go to next member
4884 // For missing members of anonymous blocks that have been redeclared,
4885 // hide the original (shared) declaration.
4886 // Instance-named blocks can just have the member removed.
4888 member = type.getWritableStruct()->erase(member);
4890 member->type->hideMember();
4896 if (spvVersion.vulkan > 0) {
4897 // ...then streams apply to built-in blocks, instead of them being only on stream 0
4898 type.getQualifier().layoutStream = currentBlockQualifier.layoutStream;
4901 if (numOriginalMembersFound < newTypeList.size())
4902 error(loc, "block redeclaration has extra members", blockName.c_str(), "");
4903 if (type.isArray() != (arraySizes != nullptr) ||
4904 (type.isArray() && arraySizes != nullptr && type.getArraySizes()->getNumDims() != arraySizes->getNumDims()))
4905 error(loc, "cannot change arrayness of redeclared block", blockName.c_str(), "");
4906 else if (type.isArray()) {
4907 // At this point, we know both are arrays and both have the same number of dimensions.
4909 // It is okay for a built-in block redeclaration to be unsized, and keep the size of the
4910 // original block declaration.
4911 if (!arraySizes->isSized() && type.isSizedArray())
4912 arraySizes->changeOuterSize(type.getOuterArraySize());
4914 // And, okay to be giving a size to the array, by the redeclaration
4915 if (!type.isSizedArray() && arraySizes->isSized())
4916 type.changeOuterArraySize(arraySizes->getOuterSize());
4918 // Now, they must match in all dimensions.
4919 if (type.isSizedArray() && *type.getArraySizes() != *arraySizes)
4920 error(loc, "cannot change array size of redeclared block", blockName.c_str(), "");
4923 symbolTable.insert(*block);
4925 // Check for general layout qualifier errors
4926 layoutObjectCheck(loc, *block);
4928 // Tracking for implicit sizing of array
4929 if (isIoResizeArray(block->getType())) {
4930 ioArraySymbolResizeList.push_back(block);
4931 checkIoArraysConsistency(loc, true);
4932 } else if (block->getType().isArray())
4933 fixIoArraySize(loc, block->getWritableType());
4935 // Save it in the AST for linker use.
4936 trackLinkage(*block);
4937 #endif // GLSLANG_WEB
4940 void TParseContext::paramCheckFixStorage(const TSourceLoc& loc, const TStorageQualifier& qualifier, TType& type)
4942 switch (qualifier) {
4944 case EvqConstReadOnly:
4945 type.getQualifier().storage = EvqConstReadOnly;
4950 type.getQualifier().storage = qualifier;
4954 type.getQualifier().storage = EvqIn;
4957 type.getQualifier().storage = EvqIn;
4958 error(loc, "storage qualifier not allowed on function parameter", GetStorageQualifierString(qualifier), "");
4963 void TParseContext::paramCheckFix(const TSourceLoc& loc, const TQualifier& qualifier, TType& type)
4966 if (qualifier.isMemory()) {
4967 type.getQualifier().volatil = qualifier.volatil;
4968 type.getQualifier().coherent = qualifier.coherent;
4969 type.getQualifier().devicecoherent = qualifier.devicecoherent ;
4970 type.getQualifier().queuefamilycoherent = qualifier.queuefamilycoherent;
4971 type.getQualifier().workgroupcoherent = qualifier.workgroupcoherent;
4972 type.getQualifier().subgroupcoherent = qualifier.subgroupcoherent;
4973 type.getQualifier().shadercallcoherent = qualifier.shadercallcoherent;
4974 type.getQualifier().nonprivate = qualifier.nonprivate;
4975 type.getQualifier().readonly = qualifier.readonly;
4976 type.getQualifier().writeonly = qualifier.writeonly;
4977 type.getQualifier().restrict = qualifier.restrict;
4981 if (qualifier.isAuxiliary() ||
4982 qualifier.isInterpolation())
4983 error(loc, "cannot use auxiliary or interpolation qualifiers on a function parameter", "", "");
4984 if (qualifier.hasLayout())
4985 error(loc, "cannot use layout qualifiers on a function parameter", "", "");
4986 if (qualifier.invariant)
4987 error(loc, "cannot use invariant qualifier on a function parameter", "", "");
4988 if (qualifier.isNoContraction()) {
4989 if (qualifier.isParamOutput())
4990 type.getQualifier().setNoContraction();
4992 warn(loc, "qualifier has no effect on non-output parameters", "precise", "");
4994 if (qualifier.isNonUniform())
4995 type.getQualifier().nonUniform = qualifier.nonUniform;
4997 if (qualifier.isSpirvByReference())
4998 type.getQualifier().setSpirvByReference();
4999 if (qualifier.isSpirvLiteral()) {
5000 if (type.getBasicType() == EbtFloat || type.getBasicType() == EbtInt || type.getBasicType() == EbtUint ||
5001 type.getBasicType() == EbtBool)
5002 type.getQualifier().setSpirvLiteral();
5004 error(loc, "cannot use spirv_literal qualifier", type.getBasicTypeString().c_str(), "");
5008 paramCheckFixStorage(loc, qualifier.storage, type);
5011 void TParseContext::nestedBlockCheck(const TSourceLoc& loc)
5013 if (structNestingLevel > 0 || blockNestingLevel > 0)
5014 error(loc, "cannot nest a block definition inside a structure or block", "", "");
5015 ++blockNestingLevel;
5018 void TParseContext::nestedStructCheck(const TSourceLoc& loc)
5020 if (structNestingLevel > 0 || blockNestingLevel > 0)
5021 error(loc, "cannot nest a structure definition inside a structure or block", "", "");
5022 ++structNestingLevel;
5025 void TParseContext::arrayObjectCheck(const TSourceLoc& loc, const TType& type, const char* op)
5027 // Some versions don't allow comparing arrays or structures containing arrays
5028 if (type.containsArray()) {
5029 profileRequires(loc, ENoProfile, 120, E_GL_3DL_array_objects, op);
5030 profileRequires(loc, EEsProfile, 300, nullptr, op);
5034 void TParseContext::opaqueCheck(const TSourceLoc& loc, const TType& type, const char* op)
5036 if (containsFieldWithBasicType(type, EbtSampler))
5037 error(loc, "can't use with samplers or structs containing samplers", op, "");
5040 void TParseContext::referenceCheck(const TSourceLoc& loc, const TType& type, const char* op)
5043 if (containsFieldWithBasicType(type, EbtReference))
5044 error(loc, "can't use with reference types", op, "");
5048 void TParseContext::storage16BitAssignmentCheck(const TSourceLoc& loc, const TType& type, const char* op)
5051 if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtFloat16))
5052 requireFloat16Arithmetic(loc, op, "can't use with structs containing float16");
5054 if (type.isArray() && type.getBasicType() == EbtFloat16)
5055 requireFloat16Arithmetic(loc, op, "can't use with arrays containing float16");
5057 if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtInt16))
5058 requireInt16Arithmetic(loc, op, "can't use with structs containing int16");
5060 if (type.isArray() && type.getBasicType() == EbtInt16)
5061 requireInt16Arithmetic(loc, op, "can't use with arrays containing int16");
5063 if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtUint16))
5064 requireInt16Arithmetic(loc, op, "can't use with structs containing uint16");
5066 if (type.isArray() && type.getBasicType() == EbtUint16)
5067 requireInt16Arithmetic(loc, op, "can't use with arrays containing uint16");
5069 if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtInt8))
5070 requireInt8Arithmetic(loc, op, "can't use with structs containing int8");
5072 if (type.isArray() && type.getBasicType() == EbtInt8)
5073 requireInt8Arithmetic(loc, op, "can't use with arrays containing int8");
5075 if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtUint8))
5076 requireInt8Arithmetic(loc, op, "can't use with structs containing uint8");
5078 if (type.isArray() && type.getBasicType() == EbtUint8)
5079 requireInt8Arithmetic(loc, op, "can't use with arrays containing uint8");
5083 void TParseContext::specializationCheck(const TSourceLoc& loc, const TType& type, const char* op)
5085 if (type.containsSpecializationSize())
5086 error(loc, "can't use with types containing arrays sized with a specialization constant", op, "");
5089 void TParseContext::structTypeCheck(const TSourceLoc& /*loc*/, TPublicType& publicType)
5091 const TTypeList& typeList = *publicType.userDef->getStruct();
5093 // fix and check for member storage qualifiers and types that don't belong within a structure
5094 for (unsigned int member = 0; member < typeList.size(); ++member) {
5095 TQualifier& memberQualifier = typeList[member].type->getQualifier();
5096 const TSourceLoc& memberLoc = typeList[member].loc;
5097 if (memberQualifier.isAuxiliary() ||
5098 memberQualifier.isInterpolation() ||
5099 (memberQualifier.storage != EvqTemporary && memberQualifier.storage != EvqGlobal))
5100 error(memberLoc, "cannot use storage or interpolation qualifiers on structure members", typeList[member].type->getFieldName().c_str(), "");
5101 if (memberQualifier.isMemory())
5102 error(memberLoc, "cannot use memory qualifiers on structure members", typeList[member].type->getFieldName().c_str(), "");
5103 if (memberQualifier.hasLayout()) {
5104 error(memberLoc, "cannot use layout qualifiers on structure members", typeList[member].type->getFieldName().c_str(), "");
5105 memberQualifier.clearLayout();
5107 if (memberQualifier.invariant)
5108 error(memberLoc, "cannot use invariant qualifier on structure members", typeList[member].type->getFieldName().c_str(), "");
5113 // See if this loop satisfies the limitations for ES 2.0 (version 100) for loops in Appendex A:
5115 // "The loop index has type int or float.
5117 // "The for statement has the form:
5118 // for ( init-declaration ; condition ; expression )
5119 // init-declaration has the form: type-specifier identifier = constant-expression
5120 // condition has the form: loop-index relational_operator constant-expression
5121 // where relational_operator is one of: > >= < <= == or !=
5122 // expression [sic] has one of the following forms:
5125 // loop-index += constant-expression
5126 // loop-index -= constant-expression
5128 // The body is handled in an AST traversal.
5130 void TParseContext::inductiveLoopCheck(const TSourceLoc& loc, TIntermNode* init, TIntermLoop* loop)
5133 // loop index init must exist and be a declaration, which shows up in the AST as an aggregate of size 1 of the declaration
5134 bool badInit = false;
5135 if (! init || ! init->getAsAggregate() || init->getAsAggregate()->getSequence().size() != 1)
5137 TIntermBinary* binaryInit = 0;
5139 // get the declaration assignment
5140 binaryInit = init->getAsAggregate()->getSequence()[0]->getAsBinaryNode();
5145 error(loc, "inductive-loop init-declaration requires the form \"type-specifier loop-index = constant-expression\"", "limitations", "");
5149 // loop index must be type int or float
5150 if (! binaryInit->getType().isScalar() || (binaryInit->getBasicType() != EbtInt && binaryInit->getBasicType() != EbtFloat)) {
5151 error(loc, "inductive loop requires a scalar 'int' or 'float' loop index", "limitations", "");
5155 // init is the form "loop-index = constant"
5156 if (binaryInit->getOp() != EOpAssign || ! binaryInit->getLeft()->getAsSymbolNode() || ! binaryInit->getRight()->getAsConstantUnion()) {
5157 error(loc, "inductive-loop init-declaration requires the form \"type-specifier loop-index = constant-expression\"", "limitations", "");
5161 // get the unique id of the loop index
5162 long long loopIndex = binaryInit->getLeft()->getAsSymbolNode()->getId();
5163 inductiveLoopIds.insert(loopIndex);
5165 // condition's form must be "loop-index relational-operator constant-expression"
5166 bool badCond = ! loop->getTest();
5168 TIntermBinary* binaryCond = loop->getTest()->getAsBinaryNode();
5169 badCond = ! binaryCond;
5171 switch (binaryCond->getOp()) {
5172 case EOpGreaterThan:
5173 case EOpGreaterThanEqual:
5175 case EOpLessThanEqual:
5183 if (binaryCond && (! binaryCond->getLeft()->getAsSymbolNode() ||
5184 binaryCond->getLeft()->getAsSymbolNode()->getId() != loopIndex ||
5185 ! binaryCond->getRight()->getAsConstantUnion()))
5189 error(loc, "inductive-loop condition requires the form \"loop-index <comparison-op> constant-expression\"", "limitations", "");
5195 // loop-index += constant-expression
5196 // loop-index -= constant-expression
5197 bool badTerminal = ! loop->getTerminal();
5198 if (! badTerminal) {
5199 TIntermUnary* unaryTerminal = loop->getTerminal()->getAsUnaryNode();
5200 TIntermBinary* binaryTerminal = loop->getTerminal()->getAsBinaryNode();
5201 if (unaryTerminal || binaryTerminal) {
5202 switch(loop->getTerminal()->getAsOperator()->getOp()) {
5203 case EOpPostDecrement:
5204 case EOpPostIncrement:
5213 if (binaryTerminal && (! binaryTerminal->getLeft()->getAsSymbolNode() ||
5214 binaryTerminal->getLeft()->getAsSymbolNode()->getId() != loopIndex ||
5215 ! binaryTerminal->getRight()->getAsConstantUnion()))
5217 if (unaryTerminal && (! unaryTerminal->getOperand()->getAsSymbolNode() ||
5218 unaryTerminal->getOperand()->getAsSymbolNode()->getId() != loopIndex))
5222 error(loc, "inductive-loop termination requires the form \"loop-index++, loop-index--, loop-index += constant-expression, or loop-index -= constant-expression\"", "limitations", "");
5227 inductiveLoopBodyCheck(loop->getBody(), loopIndex, symbolTable);
5232 // Do limit checks for built-in arrays.
5233 void TParseContext::arrayLimitCheck(const TSourceLoc& loc, const TString& identifier, int size)
5235 if (identifier.compare("gl_TexCoord") == 0)
5236 limitCheck(loc, size, "gl_MaxTextureCoords", "gl_TexCoord array size");
5237 else if (identifier.compare("gl_ClipDistance") == 0)
5238 limitCheck(loc, size, "gl_MaxClipDistances", "gl_ClipDistance array size");
5239 else if (identifier.compare("gl_CullDistance") == 0)
5240 limitCheck(loc, size, "gl_MaxCullDistances", "gl_CullDistance array size");
5241 else if (identifier.compare("gl_ClipDistancePerViewNV") == 0)
5242 limitCheck(loc, size, "gl_MaxClipDistances", "gl_ClipDistancePerViewNV array size");
5243 else if (identifier.compare("gl_CullDistancePerViewNV") == 0)
5244 limitCheck(loc, size, "gl_MaxCullDistances", "gl_CullDistancePerViewNV array size");
5246 #endif // GLSLANG_WEB
5248 // See if the provided value is less than or equal to the symbol indicated by limit,
5249 // which should be a constant in the symbol table.
5250 void TParseContext::limitCheck(const TSourceLoc& loc, int value, const char* limit, const char* feature)
5252 TSymbol* symbol = symbolTable.find(limit);
5253 assert(symbol->getAsVariable());
5254 const TConstUnionArray& constArray = symbol->getAsVariable()->getConstArray();
5255 assert(! constArray.empty());
5256 if (value > constArray[0].getIConst())
5257 error(loc, "must be less than or equal to", feature, "%s (%d)", limit, constArray[0].getIConst());
5263 // Do any additional error checking, etc., once we know the parsing is done.
5265 void TParseContext::finish()
5267 TParseContextBase::finish();
5269 if (parsingBuiltins)
5272 // Check on array indexes for ES 2.0 (version 100) limitations.
5273 for (size_t i = 0; i < needsIndexLimitationChecking.size(); ++i)
5274 constantIndexExpressionCheck(needsIndexLimitationChecking[i]);
5276 // Check for stages that are enabled by extension.
5277 // Can't do this at the beginning, it is chicken and egg to add a stage by
5279 // Stage-specific features were correctly tested for already, this is just
5280 // about the stage itself.
5282 case EShLangGeometry:
5283 if (isEsProfile() && version == 310)
5284 requireExtensions(getCurrentLoc(), Num_AEP_geometry_shader, AEP_geometry_shader, "geometry shaders");
5286 case EShLangTessControl:
5287 case EShLangTessEvaluation:
5288 if (isEsProfile() && version == 310)
5289 requireExtensions(getCurrentLoc(), Num_AEP_tessellation_shader, AEP_tessellation_shader, "tessellation shaders");
5290 else if (!isEsProfile() && version < 400)
5291 requireExtensions(getCurrentLoc(), 1, &E_GL_ARB_tessellation_shader, "tessellation shaders");
5293 case EShLangCompute:
5294 if (!isEsProfile() && version < 430)
5295 requireExtensions(getCurrentLoc(), 1, &E_GL_ARB_compute_shader, "compute shaders");
5298 requireExtensions(getCurrentLoc(), 1, &E_GL_NV_mesh_shader, "task shaders");
5301 requireExtensions(getCurrentLoc(), 1, &E_GL_NV_mesh_shader, "mesh shaders");
5307 // Set default outputs for GL_NV_geometry_shader_passthrough
5308 if (language == EShLangGeometry && extensionTurnedOn(E_SPV_NV_geometry_shader_passthrough)) {
5309 if (intermediate.getOutputPrimitive() == ElgNone) {
5310 switch (intermediate.getInputPrimitive()) {
5311 case ElgPoints: intermediate.setOutputPrimitive(ElgPoints); break;
5312 case ElgLines: intermediate.setOutputPrimitive(ElgLineStrip); break;
5313 case ElgTriangles: intermediate.setOutputPrimitive(ElgTriangleStrip); break;
5317 if (intermediate.getVertices() == TQualifier::layoutNotSet) {
5318 switch (intermediate.getInputPrimitive()) {
5319 case ElgPoints: intermediate.setVertices(1); break;
5320 case ElgLines: intermediate.setVertices(2); break;
5321 case ElgTriangles: intermediate.setVertices(3); break;
5327 #endif // GLSLANG_WEB
5330 // Layout qualifier stuff.
5333 // Put the id's layout qualification into the public type, for qualifiers not having a number set.
5334 // This is before we know any type information for error checking.
5335 void TParseContext::setLayoutQualifier(const TSourceLoc& loc, TPublicType& publicType, TString& id)
5337 std::transform(id.begin(), id.end(), id.begin(), ::tolower);
5339 if (id == TQualifier::getLayoutMatrixString(ElmColumnMajor)) {
5340 publicType.qualifier.layoutMatrix = ElmColumnMajor;
5343 if (id == TQualifier::getLayoutMatrixString(ElmRowMajor)) {
5344 publicType.qualifier.layoutMatrix = ElmRowMajor;
5347 if (id == TQualifier::getLayoutPackingString(ElpPacked)) {
5348 if (spvVersion.spv != 0) {
5349 if (spvVersion.vulkanRelaxed)
5350 return; // silently ignore qualifier
5352 spvRemoved(loc, "packed");
5354 publicType.qualifier.layoutPacking = ElpPacked;
5357 if (id == TQualifier::getLayoutPackingString(ElpShared)) {
5358 if (spvVersion.spv != 0) {
5359 if (spvVersion.vulkanRelaxed)
5360 return; // silently ignore qualifier
5362 spvRemoved(loc, "shared");
5364 publicType.qualifier.layoutPacking = ElpShared;
5367 if (id == TQualifier::getLayoutPackingString(ElpStd140)) {
5368 publicType.qualifier.layoutPacking = ElpStd140;
5372 if (id == TQualifier::getLayoutPackingString(ElpStd430)) {
5373 requireProfile(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, "std430");
5374 profileRequires(loc, ECoreProfile | ECompatibilityProfile, 430, E_GL_ARB_shader_storage_buffer_object, "std430");
5375 profileRequires(loc, EEsProfile, 310, nullptr, "std430");
5376 publicType.qualifier.layoutPacking = ElpStd430;
5379 if (id == TQualifier::getLayoutPackingString(ElpScalar)) {
5380 requireVulkan(loc, "scalar");
5381 requireExtensions(loc, 1, &E_GL_EXT_scalar_block_layout, "scalar block layout");
5382 publicType.qualifier.layoutPacking = ElpScalar;
5385 // TODO: compile-time performance: may need to stop doing linear searches
5386 for (TLayoutFormat format = (TLayoutFormat)(ElfNone + 1); format < ElfCount; format = (TLayoutFormat)(format + 1)) {
5387 if (id == TQualifier::getLayoutFormatString(format)) {
5388 if ((format > ElfEsFloatGuard && format < ElfFloatGuard) ||
5389 (format > ElfEsIntGuard && format < ElfIntGuard) ||
5390 (format > ElfEsUintGuard && format < ElfCount))
5391 requireProfile(loc, ENoProfile | ECoreProfile | ECompatibilityProfile, "image load-store format");
5392 profileRequires(loc, ENoProfile | ECoreProfile | ECompatibilityProfile, 420, E_GL_ARB_shader_image_load_store, "image load store");
5393 profileRequires(loc, EEsProfile, 310, E_GL_ARB_shader_image_load_store, "image load store");
5394 publicType.qualifier.layoutFormat = format;
5398 if (id == "push_constant") {
5399 requireVulkan(loc, "push_constant");
5400 publicType.qualifier.layoutPushConstant = true;
5403 if (id == "buffer_reference") {
5404 requireVulkan(loc, "buffer_reference");
5405 requireExtensions(loc, 1, &E_GL_EXT_buffer_reference, "buffer_reference");
5406 publicType.qualifier.layoutBufferReference = true;
5407 intermediate.setUseStorageBuffer();
5408 intermediate.setUsePhysicalStorageBuffer();
5411 if (language == EShLangGeometry || language == EShLangTessEvaluation || language == EShLangMeshNV) {
5412 if (id == TQualifier::getGeometryString(ElgTriangles)) {
5413 publicType.shaderQualifiers.geometry = ElgTriangles;
5416 if (language == EShLangGeometry || language == EShLangMeshNV) {
5417 if (id == TQualifier::getGeometryString(ElgPoints)) {
5418 publicType.shaderQualifiers.geometry = ElgPoints;
5421 if (id == TQualifier::getGeometryString(ElgLines)) {
5422 publicType.shaderQualifiers.geometry = ElgLines;
5425 if (language == EShLangGeometry) {
5426 if (id == TQualifier::getGeometryString(ElgLineStrip)) {
5427 publicType.shaderQualifiers.geometry = ElgLineStrip;
5430 if (id == TQualifier::getGeometryString(ElgLinesAdjacency)) {
5431 publicType.shaderQualifiers.geometry = ElgLinesAdjacency;
5434 if (id == TQualifier::getGeometryString(ElgTrianglesAdjacency)) {
5435 publicType.shaderQualifiers.geometry = ElgTrianglesAdjacency;
5438 if (id == TQualifier::getGeometryString(ElgTriangleStrip)) {
5439 publicType.shaderQualifiers.geometry = ElgTriangleStrip;
5442 if (id == "passthrough") {
5443 requireExtensions(loc, 1, &E_SPV_NV_geometry_shader_passthrough, "geometry shader passthrough");
5444 publicType.qualifier.layoutPassthrough = true;
5445 intermediate.setGeoPassthroughEXT();
5450 assert(language == EShLangTessEvaluation);
5453 if (id == TQualifier::getGeometryString(ElgTriangles)) {
5454 publicType.shaderQualifiers.geometry = ElgTriangles;
5457 if (id == TQualifier::getGeometryString(ElgQuads)) {
5458 publicType.shaderQualifiers.geometry = ElgQuads;
5461 if (id == TQualifier::getGeometryString(ElgIsolines)) {
5462 publicType.shaderQualifiers.geometry = ElgIsolines;
5467 if (id == TQualifier::getVertexSpacingString(EvsEqual)) {
5468 publicType.shaderQualifiers.spacing = EvsEqual;
5471 if (id == TQualifier::getVertexSpacingString(EvsFractionalEven)) {
5472 publicType.shaderQualifiers.spacing = EvsFractionalEven;
5475 if (id == TQualifier::getVertexSpacingString(EvsFractionalOdd)) {
5476 publicType.shaderQualifiers.spacing = EvsFractionalOdd;
5481 if (id == TQualifier::getVertexOrderString(EvoCw)) {
5482 publicType.shaderQualifiers.order = EvoCw;
5485 if (id == TQualifier::getVertexOrderString(EvoCcw)) {
5486 publicType.shaderQualifiers.order = EvoCcw;
5491 if (id == "point_mode") {
5492 publicType.shaderQualifiers.pointMode = true;
5497 if (language == EShLangFragment) {
5498 if (id == "origin_upper_left") {
5499 requireProfile(loc, ECoreProfile | ECompatibilityProfile, "origin_upper_left");
5500 publicType.shaderQualifiers.originUpperLeft = true;
5503 if (id == "pixel_center_integer") {
5504 requireProfile(loc, ECoreProfile | ECompatibilityProfile, "pixel_center_integer");
5505 publicType.shaderQualifiers.pixelCenterInteger = true;
5508 if (id == "early_fragment_tests") {
5509 profileRequires(loc, ENoProfile | ECoreProfile | ECompatibilityProfile, 420, E_GL_ARB_shader_image_load_store, "early_fragment_tests");
5510 profileRequires(loc, EEsProfile, 310, nullptr, "early_fragment_tests");
5511 publicType.shaderQualifiers.earlyFragmentTests = true;
5514 if (id == "post_depth_coverage") {
5515 requireExtensions(loc, Num_post_depth_coverageEXTs, post_depth_coverageEXTs, "post depth coverage");
5516 if (extensionTurnedOn(E_GL_ARB_post_depth_coverage)) {
5517 publicType.shaderQualifiers.earlyFragmentTests = true;
5519 publicType.shaderQualifiers.postDepthCoverage = true;
5522 for (TLayoutDepth depth = (TLayoutDepth)(EldNone + 1); depth < EldCount; depth = (TLayoutDepth)(depth+1)) {
5523 if (id == TQualifier::getLayoutDepthString(depth)) {
5524 requireProfile(loc, ECoreProfile | ECompatibilityProfile, "depth layout qualifier");
5525 profileRequires(loc, ECoreProfile | ECompatibilityProfile, 420, nullptr, "depth layout qualifier");
5526 publicType.shaderQualifiers.layoutDepth = depth;
5530 for (TInterlockOrdering order = (TInterlockOrdering)(EioNone + 1); order < EioCount; order = (TInterlockOrdering)(order+1)) {
5531 if (id == TQualifier::getInterlockOrderingString(order)) {
5532 requireProfile(loc, ECoreProfile | ECompatibilityProfile, "fragment shader interlock layout qualifier");
5533 profileRequires(loc, ECoreProfile | ECompatibilityProfile, 450, nullptr, "fragment shader interlock layout qualifier");
5534 requireExtensions(loc, 1, &E_GL_ARB_fragment_shader_interlock, TQualifier::getInterlockOrderingString(order));
5535 if (order == EioShadingRateInterlockOrdered || order == EioShadingRateInterlockUnordered)
5536 requireExtensions(loc, 1, &E_GL_NV_shading_rate_image, TQualifier::getInterlockOrderingString(order));
5537 publicType.shaderQualifiers.interlockOrdering = order;
5541 if (id.compare(0, 13, "blend_support") == 0) {
5543 for (TBlendEquationShift be = (TBlendEquationShift)0; be < EBlendCount; be = (TBlendEquationShift)(be + 1)) {
5544 if (id == TQualifier::getBlendEquationString(be)) {
5545 profileRequires(loc, EEsProfile, 320, E_GL_KHR_blend_equation_advanced, "blend equation");
5546 profileRequires(loc, ~EEsProfile, 0, E_GL_KHR_blend_equation_advanced, "blend equation");
5547 intermediate.addBlendEquation(be);
5548 publicType.shaderQualifiers.blendEquation = true;
5554 error(loc, "unknown blend equation", "blend_support", "");
5557 if (id == "override_coverage") {
5558 requireExtensions(loc, 1, &E_GL_NV_sample_mask_override_coverage, "sample mask override coverage");
5559 publicType.shaderQualifiers.layoutOverrideCoverage = true;
5563 if (language == EShLangVertex ||
5564 language == EShLangTessControl ||
5565 language == EShLangTessEvaluation ||
5566 language == EShLangGeometry ) {
5567 if (id == "viewport_relative") {
5568 requireExtensions(loc, 1, &E_GL_NV_viewport_array2, "view port array2");
5569 publicType.qualifier.layoutViewportRelative = true;
5573 if (language == EShLangRayGen || language == EShLangIntersect ||
5574 language == EShLangAnyHit || language == EShLangClosestHit ||
5575 language == EShLangMiss || language == EShLangCallable) {
5576 if (id == "shaderrecordnv" || id == "shaderrecordext") {
5577 if (id == "shaderrecordnv") {
5578 requireExtensions(loc, 1, &E_GL_NV_ray_tracing, "shader record NV");
5580 requireExtensions(loc, 1, &E_GL_EXT_ray_tracing, "shader record EXT");
5582 publicType.qualifier.layoutShaderRecord = true;
5588 if (language == EShLangCompute) {
5589 if (id.compare(0, 17, "derivative_group_") == 0) {
5590 requireExtensions(loc, 1, &E_GL_NV_compute_shader_derivatives, "compute shader derivatives");
5591 if (id == "derivative_group_quadsnv") {
5592 publicType.shaderQualifiers.layoutDerivativeGroupQuads = true;
5594 } else if (id == "derivative_group_linearnv") {
5595 publicType.shaderQualifiers.layoutDerivativeGroupLinear = true;
5601 if (id == "primitive_culling") {
5602 requireExtensions(loc, 1, &E_GL_EXT_ray_flags_primitive_culling, "primitive culling");
5603 publicType.shaderQualifiers.layoutPrimitiveCulling = true;
5608 error(loc, "unrecognized layout identifier, or qualifier requires assignment (e.g., binding = 4)", id.c_str(), "");
5611 // Put the id's layout qualifier value into the public type, for qualifiers having a number set.
5612 // This is before we know any type information for error checking.
5613 void TParseContext::setLayoutQualifier(const TSourceLoc& loc, TPublicType& publicType, TString& id, const TIntermTyped* node)
5615 const char* feature = "layout-id value";
5616 const char* nonLiteralFeature = "non-literal layout-id value";
5618 integerCheck(node, feature);
5619 const TIntermConstantUnion* constUnion = node->getAsConstantUnion();
5621 bool nonLiteral = false;
5623 value = constUnion->getConstArray()[0].getIConst();
5624 if (! constUnion->isLiteral()) {
5625 requireProfile(loc, ECoreProfile | ECompatibilityProfile, nonLiteralFeature);
5626 profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, E_GL_ARB_enhanced_layouts, nonLiteralFeature);
5629 // grammar should have give out the error message
5635 error(loc, "cannot be negative", feature, "");
5639 std::transform(id.begin(), id.end(), id.begin(), ::tolower);
5641 if (id == "offset") {
5642 // "offset" can be for either
5643 // - uniform offsets
5644 // - atomic_uint offsets
5645 const char* feature = "offset";
5646 if (spvVersion.spv == 0) {
5647 requireProfile(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, feature);
5648 const char* exts[2] = { E_GL_ARB_enhanced_layouts, E_GL_ARB_shader_atomic_counters };
5649 profileRequires(loc, ECoreProfile | ECompatibilityProfile, 420, 2, exts, feature);
5650 profileRequires(loc, EEsProfile, 310, nullptr, feature);
5652 publicType.qualifier.layoutOffset = value;
5653 publicType.qualifier.explicitOffset = true;
5655 error(loc, "needs a literal integer", "offset", "");
5657 } else if (id == "align") {
5658 const char* feature = "uniform buffer-member align";
5659 if (spvVersion.spv == 0) {
5660 requireProfile(loc, ECoreProfile | ECompatibilityProfile, feature);
5661 profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, E_GL_ARB_enhanced_layouts, feature);
5663 // "The specified alignment must be a power of 2, or a compile-time error results."
5664 if (! IsPow2(value))
5665 error(loc, "must be a power of 2", "align", "");
5667 publicType.qualifier.layoutAlign = value;
5669 error(loc, "needs a literal integer", "align", "");
5671 } else if (id == "location") {
5672 profileRequires(loc, EEsProfile, 300, nullptr, "location");
5673 const char* exts[2] = { E_GL_ARB_separate_shader_objects, E_GL_ARB_explicit_attrib_location };
5674 // GL_ARB_explicit_uniform_location requires 330 or GL_ARB_explicit_attrib_location we do not need to add it here
5675 profileRequires(loc, ~EEsProfile, 330, 2, exts, "location");
5676 if ((unsigned int)value >= TQualifier::layoutLocationEnd)
5677 error(loc, "location is too large", id.c_str(), "");
5679 publicType.qualifier.layoutLocation = value;
5681 error(loc, "needs a literal integer", "location", "");
5683 } else if (id == "set") {
5684 if ((unsigned int)value >= TQualifier::layoutSetEnd)
5685 error(loc, "set is too large", id.c_str(), "");
5687 publicType.qualifier.layoutSet = value;
5689 requireVulkan(loc, "descriptor set");
5691 error(loc, "needs a literal integer", "set", "");
5693 } else if (id == "binding") {
5695 profileRequires(loc, ~EEsProfile, 420, E_GL_ARB_shading_language_420pack, "binding");
5696 profileRequires(loc, EEsProfile, 310, nullptr, "binding");
5698 if ((unsigned int)value >= TQualifier::layoutBindingEnd)
5699 error(loc, "binding is too large", id.c_str(), "");
5701 publicType.qualifier.layoutBinding = value;
5703 error(loc, "needs a literal integer", "binding", "");
5706 if (id == "constant_id") {
5707 requireSpv(loc, "constant_id");
5708 if (value >= (int)TQualifier::layoutSpecConstantIdEnd) {
5709 error(loc, "specialization-constant id is too large", id.c_str(), "");
5711 publicType.qualifier.layoutSpecConstantId = value;
5712 publicType.qualifier.specConstant = true;
5713 if (! intermediate.addUsedConstantId(value))
5714 error(loc, "specialization-constant id already used", id.c_str(), "");
5717 error(loc, "needs a literal integer", "constant_id", "");
5721 if (id == "component") {
5722 requireProfile(loc, ECoreProfile | ECompatibilityProfile, "component");
5723 profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, E_GL_ARB_enhanced_layouts, "component");
5724 if ((unsigned)value >= TQualifier::layoutComponentEnd)
5725 error(loc, "component is too large", id.c_str(), "");
5727 publicType.qualifier.layoutComponent = value;
5729 error(loc, "needs a literal integer", "component", "");
5732 if (id.compare(0, 4, "xfb_") == 0) {
5733 // "Any shader making any static use (after preprocessing) of any of these
5734 // *xfb_* qualifiers will cause the shader to be in a transform feedback
5735 // capturing mode and hence responsible for describing the transform feedback
5737 intermediate.setXfbMode();
5738 const char* feature = "transform feedback qualifier";
5739 requireStage(loc, (EShLanguageMask)(EShLangVertexMask | EShLangGeometryMask | EShLangTessControlMask | EShLangTessEvaluationMask), feature);
5740 requireProfile(loc, ECoreProfile | ECompatibilityProfile, feature);
5741 profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, E_GL_ARB_enhanced_layouts, feature);
5742 if (id == "xfb_buffer") {
5743 // "It is a compile-time error to specify an *xfb_buffer* that is greater than
5744 // the implementation-dependent constant gl_MaxTransformFeedbackBuffers."
5745 if (value >= resources.maxTransformFeedbackBuffers)
5746 error(loc, "buffer is too large:", id.c_str(), "gl_MaxTransformFeedbackBuffers is %d", resources.maxTransformFeedbackBuffers);
5747 if (value >= (int)TQualifier::layoutXfbBufferEnd)
5748 error(loc, "buffer is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbBufferEnd-1);
5750 publicType.qualifier.layoutXfbBuffer = value;
5752 error(loc, "needs a literal integer", "xfb_buffer", "");
5754 } else if (id == "xfb_offset") {
5755 if (value >= (int)TQualifier::layoutXfbOffsetEnd)
5756 error(loc, "offset is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbOffsetEnd-1);
5758 publicType.qualifier.layoutXfbOffset = value;
5760 error(loc, "needs a literal integer", "xfb_offset", "");
5762 } else if (id == "xfb_stride") {
5763 // "The resulting stride (implicit or explicit), when divided by 4, must be less than or equal to the
5764 // implementation-dependent constant gl_MaxTransformFeedbackInterleavedComponents."
5765 if (value > 4 * resources.maxTransformFeedbackInterleavedComponents) {
5766 error(loc, "1/4 stride is too large:", id.c_str(), "gl_MaxTransformFeedbackInterleavedComponents is %d",
5767 resources.maxTransformFeedbackInterleavedComponents);
5769 if (value >= (int)TQualifier::layoutXfbStrideEnd)
5770 error(loc, "stride is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbStrideEnd-1);
5772 publicType.qualifier.layoutXfbStride = value;
5774 error(loc, "needs a literal integer", "xfb_stride", "");
5778 if (id == "input_attachment_index") {
5779 requireVulkan(loc, "input_attachment_index");
5780 if (value >= (int)TQualifier::layoutAttachmentEnd)
5781 error(loc, "attachment index is too large", id.c_str(), "");
5783 publicType.qualifier.layoutAttachment = value;
5785 error(loc, "needs a literal integer", "input_attachment_index", "");
5788 if (id == "num_views") {
5789 requireExtensions(loc, Num_OVR_multiview_EXTs, OVR_multiview_EXTs, "num_views");
5790 publicType.shaderQualifiers.numViews = value;
5792 error(loc, "needs a literal integer", "num_views", "");
5795 if (language == EShLangVertex ||
5796 language == EShLangTessControl ||
5797 language == EShLangTessEvaluation ||
5798 language == EShLangGeometry) {
5799 if (id == "secondary_view_offset") {
5800 requireExtensions(loc, 1, &E_GL_NV_stereo_view_rendering, "stereo view rendering");
5801 publicType.qualifier.layoutSecondaryViewportRelativeOffset = value;
5803 error(loc, "needs a literal integer", "secondary_view_offset", "");
5808 if (id == "buffer_reference_align") {
5809 requireExtensions(loc, 1, &E_GL_EXT_buffer_reference, "buffer_reference_align");
5810 if (! IsPow2(value))
5811 error(loc, "must be a power of 2", "buffer_reference_align", "");
5813 publicType.qualifier.layoutBufferReferenceAlign = IntLog2(value);
5815 error(loc, "needs a literal integer", "buffer_reference_align", "");
5822 case EShLangTessControl:
5823 if (id == "vertices") {
5825 error(loc, "must be greater than 0", "vertices", "");
5827 publicType.shaderQualifiers.vertices = value;
5829 error(loc, "needs a literal integer", "vertices", "");
5834 case EShLangGeometry:
5835 if (id == "invocations") {
5836 profileRequires(loc, ECompatibilityProfile | ECoreProfile, 400, nullptr, "invocations");
5838 error(loc, "must be at least 1", "invocations", "");
5840 publicType.shaderQualifiers.invocations = value;
5842 error(loc, "needs a literal integer", "invocations", "");
5845 if (id == "max_vertices") {
5846 publicType.shaderQualifiers.vertices = value;
5847 if (value > resources.maxGeometryOutputVertices)
5848 error(loc, "too large, must be less than gl_MaxGeometryOutputVertices", "max_vertices", "");
5850 error(loc, "needs a literal integer", "max_vertices", "");
5853 if (id == "stream") {
5854 requireProfile(loc, ~EEsProfile, "selecting output stream");
5855 publicType.qualifier.layoutStream = value;
5857 intermediate.setMultiStream();
5859 error(loc, "needs a literal integer", "stream", "");
5864 case EShLangFragment:
5865 if (id == "index") {
5866 requireProfile(loc, ECompatibilityProfile | ECoreProfile | EEsProfile, "index layout qualifier on fragment output");
5867 const char* exts[2] = { E_GL_ARB_separate_shader_objects, E_GL_ARB_explicit_attrib_location };
5868 profileRequires(loc, ECompatibilityProfile | ECoreProfile, 330, 2, exts, "index layout qualifier on fragment output");
5869 profileRequires(loc, EEsProfile ,310, E_GL_EXT_blend_func_extended, "index layout qualifier on fragment output");
5870 // "It is also a compile-time error if a fragment shader sets a layout index to less than 0 or greater than 1."
5871 if (value < 0 || value > 1) {
5873 error(loc, "value must be 0 or 1", "index", "");
5876 publicType.qualifier.layoutIndex = value;
5878 error(loc, "needs a literal integer", "index", "");
5884 if (id == "max_vertices") {
5885 requireExtensions(loc, 1, &E_GL_NV_mesh_shader, "max_vertices");
5886 publicType.shaderQualifiers.vertices = value;
5887 if (value > resources.maxMeshOutputVerticesNV)
5888 error(loc, "too large, must be less than gl_MaxMeshOutputVerticesNV", "max_vertices", "");
5890 error(loc, "needs a literal integer", "max_vertices", "");
5893 if (id == "max_primitives") {
5894 requireExtensions(loc, 1, &E_GL_NV_mesh_shader, "max_primitives");
5895 publicType.shaderQualifiers.primitives = value;
5896 if (value > resources.maxMeshOutputPrimitivesNV)
5897 error(loc, "too large, must be less than gl_MaxMeshOutputPrimitivesNV", "max_primitives", "");
5899 error(loc, "needs a literal integer", "max_primitives", "");
5907 case EShLangCompute:
5908 if (id.compare(0, 11, "local_size_") == 0) {
5910 if (language == EShLangMeshNV || language == EShLangTaskNV) {
5911 requireExtensions(loc, 1, &E_GL_NV_mesh_shader, "gl_WorkGroupSize");
5913 profileRequires(loc, EEsProfile, 310, 0, "gl_WorkGroupSize");
5914 profileRequires(loc, ~EEsProfile, 430, E_GL_ARB_compute_shader, "gl_WorkGroupSize");
5918 error(loc, "needs a literal integer", "local_size", "");
5919 if (id.size() == 12 && value == 0) {
5920 error(loc, "must be at least 1", id.c_str(), "");
5923 if (id == "local_size_x") {
5924 publicType.shaderQualifiers.localSize[0] = value;
5925 publicType.shaderQualifiers.localSizeNotDefault[0] = true;
5928 if (id == "local_size_y") {
5929 publicType.shaderQualifiers.localSize[1] = value;
5930 publicType.shaderQualifiers.localSizeNotDefault[1] = true;
5933 if (id == "local_size_z") {
5934 publicType.shaderQualifiers.localSize[2] = value;
5935 publicType.shaderQualifiers.localSizeNotDefault[2] = true;
5938 if (spvVersion.spv != 0) {
5939 if (id == "local_size_x_id") {
5940 publicType.shaderQualifiers.localSizeSpecId[0] = value;
5943 if (id == "local_size_y_id") {
5944 publicType.shaderQualifiers.localSizeSpecId[1] = value;
5947 if (id == "local_size_z_id") {
5948 publicType.shaderQualifiers.localSizeSpecId[2] = value;
5959 error(loc, "there is no such layout identifier for this stage taking an assigned value", id.c_str(), "");
5962 // Merge any layout qualifier information from src into dst, leaving everything else in dst alone
5964 // "More than one layout qualifier may appear in a single declaration.
5965 // Additionally, the same layout-qualifier-name can occur multiple times
5966 // within a layout qualifier or across multiple layout qualifiers in the
5967 // same declaration. When the same layout-qualifier-name occurs
5968 // multiple times, in a single declaration, the last occurrence overrides
5969 // the former occurrence(s). Further, if such a layout-qualifier-name
5970 // will effect subsequent declarations or other observable behavior, it
5971 // is only the last occurrence that will have any effect, behaving as if
5972 // the earlier occurrence(s) within the declaration are not present.
5973 // This is also true for overriding layout-qualifier-names, where one
5974 // overrides the other (e.g., row_major vs. column_major); only the last
5975 // occurrence has any effect."
5976 void TParseContext::mergeObjectLayoutQualifiers(TQualifier& dst, const TQualifier& src, bool inheritOnly)
5978 if (src.hasMatrix())
5979 dst.layoutMatrix = src.layoutMatrix;
5980 if (src.hasPacking())
5981 dst.layoutPacking = src.layoutPacking;
5984 if (src.hasStream())
5985 dst.layoutStream = src.layoutStream;
5986 if (src.hasFormat())
5987 dst.layoutFormat = src.layoutFormat;
5988 if (src.hasXfbBuffer())
5989 dst.layoutXfbBuffer = src.layoutXfbBuffer;
5990 if (src.hasBufferReferenceAlign())
5991 dst.layoutBufferReferenceAlign = src.layoutBufferReferenceAlign;
5995 dst.layoutAlign = src.layoutAlign;
5997 if (! inheritOnly) {
5998 if (src.hasLocation())
5999 dst.layoutLocation = src.layoutLocation;
6000 if (src.hasOffset())
6001 dst.layoutOffset = src.layoutOffset;
6003 dst.layoutSet = src.layoutSet;
6004 if (src.layoutBinding != TQualifier::layoutBindingEnd)
6005 dst.layoutBinding = src.layoutBinding;
6007 if (src.hasSpecConstantId())
6008 dst.layoutSpecConstantId = src.layoutSpecConstantId;
6011 if (src.hasComponent())
6012 dst.layoutComponent = src.layoutComponent;
6014 dst.layoutIndex = src.layoutIndex;
6015 if (src.hasXfbStride())
6016 dst.layoutXfbStride = src.layoutXfbStride;
6017 if (src.hasXfbOffset())
6018 dst.layoutXfbOffset = src.layoutXfbOffset;
6019 if (src.hasAttachment())
6020 dst.layoutAttachment = src.layoutAttachment;
6021 if (src.layoutPushConstant)
6022 dst.layoutPushConstant = true;
6024 if (src.layoutBufferReference)
6025 dst.layoutBufferReference = true;
6027 if (src.layoutPassthrough)
6028 dst.layoutPassthrough = true;
6029 if (src.layoutViewportRelative)
6030 dst.layoutViewportRelative = true;
6031 if (src.layoutSecondaryViewportRelativeOffset != -2048)
6032 dst.layoutSecondaryViewportRelativeOffset = src.layoutSecondaryViewportRelativeOffset;
6033 if (src.layoutShaderRecord)
6034 dst.layoutShaderRecord = true;
6035 if (src.pervertexNV)
6036 dst.pervertexNV = true;
6041 // Do error layout error checking given a full variable/block declaration.
6042 void TParseContext::layoutObjectCheck(const TSourceLoc& loc, const TSymbol& symbol)
6044 const TType& type = symbol.getType();
6045 const TQualifier& qualifier = type.getQualifier();
6047 // first, cross check WRT to just the type
6048 layoutTypeCheck(loc, type);
6050 // now, any remaining error checking based on the object itself
6052 if (qualifier.hasAnyLocation()) {
6053 switch (qualifier.storage) {
6056 if (symbol.getAsVariable() == nullptr)
6057 error(loc, "can only be used on variable declaration", "location", "");
6064 // user-variable location check, which are required for SPIR-V in/out:
6065 // - variables have it directly,
6066 // - blocks have it on each member (already enforced), so check first one
6067 if (spvVersion.spv > 0 && !parsingBuiltins && qualifier.builtIn == EbvNone &&
6068 !qualifier.hasLocation() && !intermediate.getAutoMapLocations()) {
6070 switch (qualifier.storage) {
6073 if (!type.getQualifier().isTaskMemory() &&
6075 !type.getQualifier().hasSprivDecorate() &&
6077 (type.getBasicType() != EbtBlock ||
6078 (!(*type.getStruct())[0].type->getQualifier().hasLocation() &&
6079 (*type.getStruct())[0].type->getQualifier().builtIn == EbvNone)))
6080 error(loc, "SPIR-V requires location for user input/output", "location", "");
6087 // Check packing and matrix
6088 if (qualifier.hasUniformLayout()) {
6089 switch (qualifier.storage) {
6092 if (type.getBasicType() != EbtBlock) {
6093 if (qualifier.hasMatrix())
6094 error(loc, "cannot specify matrix layout on a variable declaration", "layout", "");
6095 if (qualifier.hasPacking())
6096 error(loc, "cannot specify packing on a variable declaration", "layout", "");
6097 // "The offset qualifier can only be used on block members of blocks..."
6098 if (qualifier.hasOffset() && !type.isAtomic())
6099 error(loc, "cannot specify on a variable declaration", "offset", "");
6100 // "The align qualifier can only be used on blocks or block members..."
6101 if (qualifier.hasAlign())
6102 error(loc, "cannot specify on a variable declaration", "align", "");
6103 if (qualifier.isPushConstant())
6104 error(loc, "can only specify on a uniform block", "push_constant", "");
6105 if (qualifier.isShaderRecord())
6106 error(loc, "can only specify on a buffer block", "shaderRecordNV", "");
6107 if (qualifier.hasLocation() && type.isAtomic())
6108 error(loc, "cannot specify on atomic counter", "location", "");
6112 // these were already filtered by layoutTypeCheck() (or its callees)
6118 // "For some blocks declared as arrays, the location can only be applied at the block level:
6119 // When a block is declared as an array where additional locations are needed for each member
6120 // for each block array element, it is a compile-time error to specify locations on the block
6121 // members. That is, when locations would be under specified by applying them on block members,
6122 // they are not allowed on block members. For arrayed interfaces (those generally having an
6123 // extra level of arrayness due to interface expansion), the outer array is stripped before
6124 // applying this rule."
6125 void TParseContext::layoutMemberLocationArrayCheck(const TSourceLoc& loc, bool memberWithLocation,
6126 TArraySizes* arraySizes)
6128 if (memberWithLocation && arraySizes != nullptr) {
6129 if (arraySizes->getNumDims() > (currentBlockQualifier.isArrayedIo(language) ? 1 : 0))
6130 error(loc, "cannot use in a block array where new locations are needed for each block element",
6135 // Do layout error checking with respect to a type.
6136 void TParseContext::layoutTypeCheck(const TSourceLoc& loc, const TType& type)
6139 if (extensionTurnedOn(E_GL_EXT_spirv_intrinsics))
6140 return; // Skip any check if GL_EXT_spirv_intrinsics is turned on
6143 const TQualifier& qualifier = type.getQualifier();
6145 // first, intra-layout qualifier-only error checking
6146 layoutQualifierCheck(loc, qualifier);
6148 // now, error checking combining type and qualifier
6150 if (qualifier.hasAnyLocation()) {
6151 if (qualifier.hasLocation()) {
6152 if (qualifier.storage == EvqVaryingOut && language == EShLangFragment) {
6153 if (qualifier.layoutLocation >= (unsigned int)resources.maxDrawBuffers)
6154 error(loc, "too large for fragment output", "location", "");
6157 if (qualifier.hasComponent()) {
6158 // "It is a compile-time error if this sequence of components gets larger than 3."
6159 if (qualifier.layoutComponent + type.getVectorSize() * (type.getBasicType() == EbtDouble ? 2 : 1) > 4)
6160 error(loc, "type overflows the available 4 components", "component", "");
6162 // "It is a compile-time error to apply the component qualifier to a matrix, a structure, a block, or an array containing any of these."
6163 if (type.isMatrix() || type.getBasicType() == EbtBlock || type.getBasicType() == EbtStruct)
6164 error(loc, "cannot apply to a matrix, structure, or block", "component", "");
6166 // " It is a compile-time error to use component 1 or 3 as the beginning of a double or dvec2."
6167 if (type.getBasicType() == EbtDouble)
6168 if (qualifier.layoutComponent & 1)
6169 error(loc, "doubles cannot start on an odd-numbered component", "component", "");
6172 switch (qualifier.storage) {
6175 if (type.getBasicType() == EbtBlock)
6176 profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, E_GL_ARB_enhanced_layouts, "location qualifier on in/out block");
6177 if (type.getQualifier().isTaskMemory())
6178 error(loc, "cannot apply to taskNV in/out blocks", "location", "");
6182 if (type.getBasicType() == EbtBlock)
6183 error(loc, "cannot apply to uniform or buffer block", "location", "");
6189 case EvqCallableData:
6190 case EvqCallableDataIn:
6194 error(loc, "can only apply to uniform, buffer, in, or out storage qualifiers", "location", "");
6199 int repeated = intermediate.addUsedLocation(qualifier, type, typeCollision);
6200 if (repeated >= 0 && ! typeCollision)
6201 error(loc, "overlapping use of location", "location", "%d", repeated);
6202 // "fragment-shader outputs ... if two variables are placed within the same
6203 // location, they must have the same underlying type (floating-point or integer)"
6204 if (typeCollision && language == EShLangFragment && qualifier.isPipeOutput())
6205 error(loc, "fragment outputs sharing the same location must be the same basic type", "location", "%d", repeated);
6209 if (qualifier.hasXfbOffset() && qualifier.hasXfbBuffer()) {
6210 int repeated = intermediate.addXfbBufferOffset(type);
6212 error(loc, "overlapping offsets at", "xfb_offset", "offset %d in buffer %d", repeated, qualifier.layoutXfbBuffer);
6213 if (type.isUnsizedArray())
6214 error(loc, "unsized array", "xfb_offset", "in buffer %d", qualifier.layoutXfbBuffer);
6216 // "The offset must be a multiple of the size of the first component of the first
6217 // qualified variable or block member, or a compile-time error results. Further, if applied to an aggregate
6218 // containing a double or 64-bit integer, the offset must also be a multiple of 8..."
6219 if ((type.containsBasicType(EbtDouble) || type.containsBasicType(EbtInt64) || type.containsBasicType(EbtUint64)) &&
6220 ! IsMultipleOfPow2(qualifier.layoutXfbOffset, 8))
6221 error(loc, "type contains double or 64-bit integer; xfb_offset must be a multiple of 8", "xfb_offset", "");
6222 else if ((type.containsBasicType(EbtBool) || type.containsBasicType(EbtFloat) ||
6223 type.containsBasicType(EbtInt) || type.containsBasicType(EbtUint)) &&
6224 ! IsMultipleOfPow2(qualifier.layoutXfbOffset, 4))
6225 error(loc, "must be a multiple of size of first component", "xfb_offset", "");
6226 // ..., if applied to an aggregate containing a half float or 16-bit integer, the offset must also be a multiple of 2..."
6227 else if ((type.contains16BitFloat() || type.containsBasicType(EbtInt16) || type.containsBasicType(EbtUint16)) &&
6228 !IsMultipleOfPow2(qualifier.layoutXfbOffset, 2))
6229 error(loc, "type contains half float or 16-bit integer; xfb_offset must be a multiple of 2", "xfb_offset", "");
6231 if (qualifier.hasXfbStride() && qualifier.hasXfbBuffer()) {
6232 if (! intermediate.setXfbBufferStride(qualifier.layoutXfbBuffer, qualifier.layoutXfbStride))
6233 error(loc, "all stride settings must match for xfb buffer", "xfb_stride", "%d", qualifier.layoutXfbBuffer);
6237 if (qualifier.hasBinding()) {
6238 // Binding checking, from the spec:
6240 // "If the binding point for any uniform or shader storage block instance is less than zero, or greater than or
6241 // equal to the implementation-dependent maximum number of uniform buffer bindings, a compile-time
6242 // error will occur. When the binding identifier is used with a uniform or shader storage block instanced as
6243 // an array of size N, all elements of the array from binding through binding + N - 1 must be within this
6246 if (! type.isOpaque() && type.getBasicType() != EbtBlock)
6247 error(loc, "requires block, or sampler/image, or atomic-counter type", "binding", "");
6248 if (type.getBasicType() == EbtSampler) {
6249 int lastBinding = qualifier.layoutBinding;
6250 if (type.isArray()) {
6251 if (spvVersion.vulkan == 0) {
6252 if (type.isSizedArray())
6253 lastBinding += (type.getCumulativeArraySize() - 1);
6256 warn(loc, "assuming binding count of one for compile-time checking of binding numbers for unsized array", "[]", "");
6262 if (spvVersion.vulkan == 0 && lastBinding >= resources.maxCombinedTextureImageUnits)
6263 error(loc, "sampler binding not less than gl_MaxCombinedTextureImageUnits", "binding", type.isArray() ? "(using array)" : "");
6266 if (type.isAtomic() && !spvVersion.vulkanRelaxed) {
6267 if (qualifier.layoutBinding >= (unsigned int)resources.maxAtomicCounterBindings) {
6268 error(loc, "atomic_uint binding is too large; see gl_MaxAtomicCounterBindings", "binding", "");
6272 } else if (!intermediate.getAutoMapBindings()) {
6273 // some types require bindings
6276 if (type.isAtomic())
6277 error(loc, "layout(binding=X) is required", "atomic_uint", "");
6280 if (spvVersion.spv > 0) {
6281 if (qualifier.isUniformOrBuffer()) {
6282 if (type.getBasicType() == EbtBlock && !qualifier.isPushConstant() &&
6283 !qualifier.isShaderRecord() &&
6284 !qualifier.hasAttachment() &&
6285 !qualifier.hasBufferReference())
6286 error(loc, "uniform/buffer blocks require layout(binding=X)", "binding", "");
6287 else if (spvVersion.vulkan > 0 && type.getBasicType() == EbtSampler)
6288 error(loc, "sampler/texture/image requires layout(binding=X)", "binding", "");
6293 // some things can't have arrays of arrays
6294 if (type.isArrayOfArrays()) {
6295 if (spvVersion.vulkan > 0) {
6296 if (type.isOpaque() || (type.getQualifier().isUniformOrBuffer() && type.getBasicType() == EbtBlock))
6297 warn(loc, "Generating SPIR-V array-of-arrays, but Vulkan only supports single array level for this resource", "[][]", "");
6301 // "The offset qualifier can only be used on block members of blocks..."
6302 if (qualifier.hasOffset()) {
6303 if (type.getBasicType() == EbtBlock)
6304 error(loc, "only applies to block members, not blocks", "offset", "");
6308 if (qualifier.hasFormat()) {
6309 if (! type.isImage())
6310 error(loc, "only apply to images", TQualifier::getLayoutFormatString(qualifier.getFormat()), "");
6312 if (type.getSampler().type == EbtFloat && qualifier.getFormat() > ElfFloatGuard)
6313 error(loc, "does not apply to floating point images", TQualifier::getLayoutFormatString(qualifier.getFormat()), "");
6314 if (type.getSampler().type == EbtInt && (qualifier.getFormat() < ElfFloatGuard || qualifier.getFormat() > ElfIntGuard))
6315 error(loc, "does not apply to signed integer images", TQualifier::getLayoutFormatString(qualifier.getFormat()), "");
6316 if (type.getSampler().type == EbtUint && qualifier.getFormat() < ElfIntGuard)
6317 error(loc, "does not apply to unsigned integer images", TQualifier::getLayoutFormatString(qualifier.getFormat()), "");
6319 if (isEsProfile()) {
6320 // "Except for image variables qualified with the format qualifiers r32f, r32i, and r32ui, image variables must
6321 // specify either memory qualifier readonly or the memory qualifier writeonly."
6322 if (! (qualifier.getFormat() == ElfR32f || qualifier.getFormat() == ElfR32i || qualifier.getFormat() == ElfR32ui)) {
6323 if (! qualifier.isReadOnly() && ! qualifier.isWriteOnly())
6324 error(loc, "format requires readonly or writeonly memory qualifier", TQualifier::getLayoutFormatString(qualifier.getFormat()), "");
6328 } else if (type.isImage() && ! qualifier.isWriteOnly()) {
6329 const char *explanation = "image variables not declared 'writeonly' and without a format layout qualifier";
6330 requireProfile(loc, ECoreProfile | ECompatibilityProfile, explanation);
6331 profileRequires(loc, ECoreProfile | ECompatibilityProfile, 0, E_GL_EXT_shader_image_load_formatted, explanation);
6334 if (qualifier.isPushConstant() && type.getBasicType() != EbtBlock)
6335 error(loc, "can only be used with a block", "push_constant", "");
6337 if (qualifier.hasBufferReference() && type.getBasicType() != EbtBlock)
6338 error(loc, "can only be used with a block", "buffer_reference", "");
6340 if (qualifier.isShaderRecord() && type.getBasicType() != EbtBlock)
6341 error(loc, "can only be used with a block", "shaderRecordNV", "");
6344 if (type.isSubpass()) {
6345 if (! qualifier.hasAttachment())
6346 error(loc, "requires an input_attachment_index layout qualifier", "subpass", "");
6348 if (qualifier.hasAttachment())
6349 error(loc, "can only be used with a subpass", "input_attachment_index", "");
6352 // specialization-constant id
6353 if (qualifier.hasSpecConstantId()) {
6354 if (type.getQualifier().storage != EvqConst)
6355 error(loc, "can only be applied to 'const'-qualified scalar", "constant_id", "");
6356 if (! type.isScalar())
6357 error(loc, "can only be applied to a scalar", "constant_id", "");
6358 switch (type.getBasicType())
6374 error(loc, "cannot be applied to this type", "constant_id", "");
6380 static bool storageCanHaveLayoutInBlock(const enum TStorageQualifier storage)
6392 // Do layout error checking that can be done within a layout qualifier proper, not needing to know
6393 // if there are blocks, atomic counters, variables, etc.
6394 void TParseContext::layoutQualifierCheck(const TSourceLoc& loc, const TQualifier& qualifier)
6396 if (qualifier.storage == EvqShared && qualifier.hasLayout()) {
6397 if (spvVersion.spv > 0 && spvVersion.spv < EShTargetSpv_1_4) {
6398 error(loc, "shared block requires at least SPIR-V 1.4", "shared block", "");
6400 profileRequires(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, 0, E_GL_EXT_shared_memory_block, "shared block");
6403 // "It is a compile-time error to use *component* without also specifying the location qualifier (order does not matter)."
6404 if (qualifier.hasComponent() && ! qualifier.hasLocation())
6405 error(loc, "must specify 'location' to use 'component'", "component", "");
6407 if (qualifier.hasAnyLocation()) {
6409 // "As with input layout qualifiers, all shaders except compute shaders
6410 // allow *location* layout qualifiers on output variable declarations,
6411 // output block declarations, and output block member declarations."
6413 switch (qualifier.storage) {
6417 const char* feature = "location qualifier on input";
6418 if (isEsProfile() && version < 310)
6419 requireStage(loc, EShLangVertex, feature);
6421 requireStage(loc, (EShLanguageMask)~EShLangComputeMask, feature);
6422 if (language == EShLangVertex) {
6423 const char* exts[2] = { E_GL_ARB_separate_shader_objects, E_GL_ARB_explicit_attrib_location };
6424 profileRequires(loc, ~EEsProfile, 330, 2, exts, feature);
6425 profileRequires(loc, EEsProfile, 300, nullptr, feature);
6427 profileRequires(loc, ~EEsProfile, 410, E_GL_ARB_separate_shader_objects, feature);
6428 profileRequires(loc, EEsProfile, 310, nullptr, feature);
6434 const char* feature = "location qualifier on output";
6435 if (isEsProfile() && version < 310)
6436 requireStage(loc, EShLangFragment, feature);
6438 requireStage(loc, (EShLanguageMask)~EShLangComputeMask, feature);
6439 if (language == EShLangFragment) {
6440 const char* exts[2] = { E_GL_ARB_separate_shader_objects, E_GL_ARB_explicit_attrib_location };
6441 profileRequires(loc, ~EEsProfile, 330, 2, exts, feature);
6442 profileRequires(loc, EEsProfile, 300, nullptr, feature);
6444 profileRequires(loc, ~EEsProfile, 410, E_GL_ARB_separate_shader_objects, feature);
6445 profileRequires(loc, EEsProfile, 310, nullptr, feature);
6453 const char* feature = "location qualifier on uniform or buffer";
6454 requireProfile(loc, EEsProfile | ECoreProfile | ECompatibilityProfile | ENoProfile, feature);
6455 profileRequires(loc, ~EEsProfile, 330, E_GL_ARB_explicit_attrib_location, feature);
6456 profileRequires(loc, ~EEsProfile, 430, E_GL_ARB_explicit_uniform_location, feature);
6457 profileRequires(loc, EEsProfile, 310, nullptr, feature);
6463 if (qualifier.hasIndex()) {
6464 if (qualifier.storage != EvqVaryingOut)
6465 error(loc, "can only be used on an output", "index", "");
6466 if (! qualifier.hasLocation())
6467 error(loc, "can only be used with an explicit location", "index", "");
6471 if (qualifier.hasBinding()) {
6472 if (! qualifier.isUniformOrBuffer() && !qualifier.isTaskMemory())
6473 error(loc, "requires uniform or buffer storage qualifier", "binding", "");
6475 if (qualifier.hasStream()) {
6476 if (!qualifier.isPipeOutput())
6477 error(loc, "can only be used on an output", "stream", "");
6479 if (qualifier.hasXfb()) {
6480 if (!qualifier.isPipeOutput())
6481 error(loc, "can only be used on an output", "xfb layout qualifier", "");
6483 if (qualifier.hasUniformLayout()) {
6484 if (!storageCanHaveLayoutInBlock(qualifier.storage) && !qualifier.isTaskMemory()) {
6485 if (qualifier.hasMatrix() || qualifier.hasPacking())
6486 error(loc, "matrix or packing qualifiers can only be used on a uniform or buffer", "layout", "");
6487 if (qualifier.hasOffset() || qualifier.hasAlign())
6488 error(loc, "offset/align can only be used on a uniform or buffer", "layout", "");
6491 if (qualifier.isPushConstant()) {
6492 if (qualifier.storage != EvqUniform)
6493 error(loc, "can only be used with a uniform", "push_constant", "");
6494 if (qualifier.hasSet())
6495 error(loc, "cannot be used with push_constant", "set", "");
6497 if (qualifier.hasBufferReference()) {
6498 if (qualifier.storage != EvqBuffer)
6499 error(loc, "can only be used with buffer", "buffer_reference", "");
6501 if (qualifier.isShaderRecord()) {
6502 if (qualifier.storage != EvqBuffer)
6503 error(loc, "can only be used with a buffer", "shaderRecordNV", "");
6504 if (qualifier.hasBinding())
6505 error(loc, "cannot be used with shaderRecordNV", "binding", "");
6506 if (qualifier.hasSet())
6507 error(loc, "cannot be used with shaderRecordNV", "set", "");
6510 if (qualifier.storage == EvqHitAttr && qualifier.hasLayout()) {
6511 error(loc, "cannot apply layout qualifiers to hitAttributeNV variable", "hitAttributeNV", "");
6515 // For places that can't have shader-level layout qualifiers
6516 void TParseContext::checkNoShaderLayouts(const TSourceLoc& loc, const TShaderQualifiers& shaderQualifiers)
6519 const char* message = "can only apply to a standalone qualifier";
6521 if (shaderQualifiers.geometry != ElgNone)
6522 error(loc, message, TQualifier::getGeometryString(shaderQualifiers.geometry), "");
6523 if (shaderQualifiers.spacing != EvsNone)
6524 error(loc, message, TQualifier::getVertexSpacingString(shaderQualifiers.spacing), "");
6525 if (shaderQualifiers.order != EvoNone)
6526 error(loc, message, TQualifier::getVertexOrderString(shaderQualifiers.order), "");
6527 if (shaderQualifiers.pointMode)
6528 error(loc, message, "point_mode", "");
6529 if (shaderQualifiers.invocations != TQualifier::layoutNotSet)
6530 error(loc, message, "invocations", "");
6531 for (int i = 0; i < 3; ++i) {
6532 if (shaderQualifiers.localSize[i] > 1)
6533 error(loc, message, "local_size", "");
6534 if (shaderQualifiers.localSizeSpecId[i] != TQualifier::layoutNotSet)
6535 error(loc, message, "local_size id", "");
6537 if (shaderQualifiers.vertices != TQualifier::layoutNotSet) {
6538 if (language == EShLangGeometry || language == EShLangMeshNV)
6539 error(loc, message, "max_vertices", "");
6540 else if (language == EShLangTessControl)
6541 error(loc, message, "vertices", "");
6545 if (shaderQualifiers.earlyFragmentTests)
6546 error(loc, message, "early_fragment_tests", "");
6547 if (shaderQualifiers.postDepthCoverage)
6548 error(loc, message, "post_depth_coverage", "");
6549 if (shaderQualifiers.primitives != TQualifier::layoutNotSet) {
6550 if (language == EShLangMeshNV)
6551 error(loc, message, "max_primitives", "");
6555 if (shaderQualifiers.hasBlendEquation())
6556 error(loc, message, "blend equation", "");
6557 if (shaderQualifiers.numViews != TQualifier::layoutNotSet)
6558 error(loc, message, "num_views", "");
6559 if (shaderQualifiers.interlockOrdering != EioNone)
6560 error(loc, message, TQualifier::getInterlockOrderingString(shaderQualifiers.interlockOrdering), "");
6561 if (shaderQualifiers.layoutPrimitiveCulling)
6562 error(loc, "can only be applied as standalone", "primitive_culling", "");
6566 // Correct and/or advance an object's offset layout qualifier.
6567 void TParseContext::fixOffset(const TSourceLoc& loc, TSymbol& symbol)
6569 const TQualifier& qualifier = symbol.getType().getQualifier();
6571 if (symbol.getType().isAtomic()) {
6572 if (qualifier.hasBinding() && (int)qualifier.layoutBinding < resources.maxAtomicCounterBindings) {
6576 if (qualifier.hasOffset())
6577 offset = qualifier.layoutOffset;
6579 offset = atomicUintOffsets[qualifier.layoutBinding];
6581 if (offset % 4 != 0)
6582 error(loc, "atomic counters offset should align based on 4:", "offset", "%d", offset);
6584 symbol.getWritableType().getQualifier().layoutOffset = offset;
6586 // Check for overlap
6588 if (symbol.getType().isArray()) {
6589 if (symbol.getType().isSizedArray() && !symbol.getType().getArraySizes()->isInnerUnsized())
6590 numOffsets *= symbol.getType().getCumulativeArraySize();
6592 // "It is a compile-time error to declare an unsized array of atomic_uint."
6593 error(loc, "array must be explicitly sized", "atomic_uint", "");
6596 int repeated = intermediate.addUsedOffsets(qualifier.layoutBinding, offset, numOffsets);
6598 error(loc, "atomic counters sharing the same offset:", "offset", "%d", repeated);
6600 // Bump the default offset
6601 atomicUintOffsets[qualifier.layoutBinding] = offset + numOffsets;
6608 // Look up a function name in the symbol table, and make sure it is a function.
6610 // Return the function symbol if found, otherwise nullptr.
6612 const TFunction* TParseContext::findFunction(const TSourceLoc& loc, const TFunction& call, bool& builtIn)
6614 if (symbolTable.isFunctionNameVariable(call.getName())) {
6615 error(loc, "can't use function syntax on variable", call.getName().c_str(), "");
6620 return findFunctionExact(loc, call, builtIn);
6623 const TFunction* function = nullptr;
6625 // debugPrintfEXT has var args and is in the symbol table as "debugPrintfEXT()",
6626 // mangled to "debugPrintfEXT("
6627 if (call.getName() == "debugPrintfEXT") {
6628 TSymbol* symbol = symbolTable.find("debugPrintfEXT(", &builtIn);
6630 return symbol->getAsFunction();
6633 bool explicitTypesEnabled = extensionTurnedOn(E_GL_EXT_shader_explicit_arithmetic_types) ||
6634 extensionTurnedOn(E_GL_EXT_shader_explicit_arithmetic_types_int8) ||
6635 extensionTurnedOn(E_GL_EXT_shader_explicit_arithmetic_types_int16) ||
6636 extensionTurnedOn(E_GL_EXT_shader_explicit_arithmetic_types_int32) ||
6637 extensionTurnedOn(E_GL_EXT_shader_explicit_arithmetic_types_int64) ||
6638 extensionTurnedOn(E_GL_EXT_shader_explicit_arithmetic_types_float16) ||
6639 extensionTurnedOn(E_GL_EXT_shader_explicit_arithmetic_types_float32) ||
6640 extensionTurnedOn(E_GL_EXT_shader_explicit_arithmetic_types_float64);
6643 function = (explicitTypesEnabled && version >= 310)
6644 ? findFunctionExplicitTypes(loc, call, builtIn)
6645 : ((extensionTurnedOn(E_GL_EXT_shader_implicit_conversions) && version >= 310)
6646 ? findFunction120(loc, call, builtIn)
6647 : findFunctionExact(loc, call, builtIn));
6648 else if (version < 120)
6649 function = findFunctionExact(loc, call, builtIn);
6650 else if (version < 400)
6651 function = extensionTurnedOn(E_GL_ARB_gpu_shader_fp64) ? findFunction400(loc, call, builtIn) : findFunction120(loc, call, builtIn);
6652 else if (explicitTypesEnabled)
6653 function = findFunctionExplicitTypes(loc, call, builtIn);
6655 function = findFunction400(loc, call, builtIn);
6660 // Function finding algorithm for ES and desktop 110.
6661 const TFunction* TParseContext::findFunctionExact(const TSourceLoc& loc, const TFunction& call, bool& builtIn)
6663 TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn);
6664 if (symbol == nullptr) {
6665 error(loc, "no matching overloaded function found", call.getName().c_str(), "");
6670 return symbol->getAsFunction();
6673 // Function finding algorithm for desktop versions 120 through 330.
6674 const TFunction* TParseContext::findFunction120(const TSourceLoc& loc, const TFunction& call, bool& builtIn)
6676 // first, look for an exact match
6677 TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn);
6679 return symbol->getAsFunction();
6681 // exact match not found, look through a list of overloaded functions of the same name
6683 // "If no exact match is found, then [implicit conversions] will be applied to find a match. Mismatched types
6684 // on input parameters (in or inout or default) must have a conversion from the calling argument type to the
6685 // formal parameter type. Mismatched types on output parameters (out or inout) must have a conversion
6686 // from the formal parameter type to the calling argument type. When argument conversions are used to find
6687 // a match, it is a semantic error if there are multiple ways to apply these conversions to make the call match
6688 // more than one function."
6690 const TFunction* candidate = nullptr;
6691 TVector<const TFunction*> candidateList;
6692 symbolTable.findFunctionNameList(call.getMangledName(), candidateList, builtIn);
6694 for (auto it = candidateList.begin(); it != candidateList.end(); ++it) {
6695 const TFunction& function = *(*it);
6697 // to even be a potential match, number of arguments has to match
6698 if (call.getParamCount() != function.getParamCount())
6701 bool possibleMatch = true;
6702 for (int i = 0; i < function.getParamCount(); ++i) {
6703 // same types is easy
6704 if (*function[i].type == *call[i].type)
6707 // We have a mismatch in type, see if it is implicitly convertible
6709 if (function[i].type->isArray() || call[i].type->isArray() ||
6710 ! function[i].type->sameElementShape(*call[i].type))
6711 possibleMatch = false;
6713 // do direction-specific checks for conversion of basic type
6714 if (function[i].type->getQualifier().isParamInput()) {
6715 if (! intermediate.canImplicitlyPromote(call[i].type->getBasicType(), function[i].type->getBasicType()))
6716 possibleMatch = false;
6718 if (function[i].type->getQualifier().isParamOutput()) {
6719 if (! intermediate.canImplicitlyPromote(function[i].type->getBasicType(), call[i].type->getBasicType()))
6720 possibleMatch = false;
6723 if (! possibleMatch)
6726 if (possibleMatch) {
6728 // our second match, meaning ambiguity
6729 error(loc, "ambiguous function signature match: multiple signatures match under implicit type conversion", call.getName().c_str(), "");
6731 candidate = &function;
6735 if (candidate == nullptr)
6736 error(loc, "no matching overloaded function found", call.getName().c_str(), "");
6741 // Function finding algorithm for desktop version 400 and above.
6743 // "When function calls are resolved, an exact type match for all the arguments
6744 // is sought. If an exact match is found, all other functions are ignored, and
6745 // the exact match is used. If no exact match is found, then the implicit
6746 // conversions in section 4.1.10 Implicit Conversions will be applied to find
6747 // a match. Mismatched types on input parameters (in or inout or default) must
6748 // have a conversion from the calling argument type to the formal parameter type.
6749 // Mismatched types on output parameters (out or inout) must have a conversion
6750 // from the formal parameter type to the calling argument type.
6752 // "If implicit conversions can be used to find more than one matching function,
6753 // a single best-matching function is sought. To determine a best match, the
6754 // conversions between calling argument and formal parameter types are compared
6755 // for each function argument and pair of matching functions. After these
6756 // comparisons are performed, each pair of matching functions are compared.
6757 // A function declaration A is considered a better match than function
6760 // * for at least one function argument, the conversion for that argument in A
6761 // is better than the corresponding conversion in B; and
6762 // * there is no function argument for which the conversion in B is better than
6763 // the corresponding conversion in A.
6765 // "If a single function declaration is considered a better match than every
6766 // other matching function declaration, it will be used. Otherwise, a
6767 // compile-time semantic error for an ambiguous overloaded function call occurs.
6769 // "To determine whether the conversion for a single argument in one match is
6770 // better than that for another match, the following rules are applied, in order:
6772 // 1. An exact match is better than a match involving any implicit conversion.
6773 // 2. A match involving an implicit conversion from float to double is better
6774 // than a match involving any other implicit conversion.
6775 // 3. A match involving an implicit conversion from either int or uint to float
6776 // is better than a match involving an implicit conversion from either int
6777 // or uint to double.
6779 // "If none of the rules above apply to a particular pair of conversions, neither
6780 // conversion is considered better than the other."
6782 const TFunction* TParseContext::findFunction400(const TSourceLoc& loc, const TFunction& call, bool& builtIn)
6784 // first, look for an exact match
6785 TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn);
6787 return symbol->getAsFunction();
6789 // no exact match, use the generic selector, parameterized by the GLSL rules
6791 // create list of candidates to send
6792 TVector<const TFunction*> candidateList;
6793 symbolTable.findFunctionNameList(call.getMangledName(), candidateList, builtIn);
6795 // can 'from' convert to 'to'?
6796 const auto convertible = [this,builtIn](const TType& from, const TType& to, TOperator, int) -> bool {
6799 if (from.coopMatParameterOK(to))
6801 // Allow a sized array to be passed through an unsized array parameter, for coopMatLoad/Store functions
6802 if (builtIn && from.isArray() && to.isUnsizedArray()) {
6803 TType fromElementType(from, 0);
6804 TType toElementType(to, 0);
6805 if (fromElementType == toElementType)
6808 if (from.isArray() || to.isArray() || ! from.sameElementShape(to))
6810 if (from.isCoopMat() && to.isCoopMat())
6811 return from.sameCoopMatBaseType(to);
6812 return intermediate.canImplicitlyPromote(from.getBasicType(), to.getBasicType());
6815 // Is 'to2' a better conversion than 'to1'?
6816 // Ties should not be considered as better.
6817 // Assumes 'convertible' already said true.
6818 const auto better = [](const TType& from, const TType& to1, const TType& to2) -> bool {
6825 // 2. float -> double is better
6826 if (from.getBasicType() == EbtFloat) {
6827 if (to2.getBasicType() == EbtDouble && to1.getBasicType() != EbtDouble)
6831 // 3. -> float is better than -> double
6832 return to2.getBasicType() == EbtFloat && to1.getBasicType() == EbtDouble;
6835 // for ambiguity reporting
6838 // send to the generic selector
6839 const TFunction* bestMatch = selectFunction(candidateList, call, convertible, better, tie);
6841 if (bestMatch == nullptr)
6842 error(loc, "no matching overloaded function found", call.getName().c_str(), "");
6844 error(loc, "ambiguous best function under implicit type conversion", call.getName().c_str(), "");
6849 // "To determine whether the conversion for a single argument in one match
6850 // is better than that for another match, the conversion is assigned of the
6851 // three ranks ordered from best to worst:
6852 // 1. Exact match: no conversion.
6853 // 2. Promotion: integral or floating-point promotion.
6854 // 3. Conversion: integral conversion, floating-point conversion,
6855 // floating-integral conversion.
6856 // A conversion C1 is better than a conversion C2 if the rank of C1 is
6857 // better than the rank of C2."
6858 const TFunction* TParseContext::findFunctionExplicitTypes(const TSourceLoc& loc, const TFunction& call, bool& builtIn)
6860 // first, look for an exact match
6861 TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn);
6863 return symbol->getAsFunction();
6865 // no exact match, use the generic selector, parameterized by the GLSL rules
6867 // create list of candidates to send
6868 TVector<const TFunction*> candidateList;
6869 symbolTable.findFunctionNameList(call.getMangledName(), candidateList, builtIn);
6871 // can 'from' convert to 'to'?
6872 const auto convertible = [this,builtIn](const TType& from, const TType& to, TOperator, int) -> bool {
6875 if (from.coopMatParameterOK(to))
6877 // Allow a sized array to be passed through an unsized array parameter, for coopMatLoad/Store functions
6878 if (builtIn && from.isArray() && to.isUnsizedArray()) {
6879 TType fromElementType(from, 0);
6880 TType toElementType(to, 0);
6881 if (fromElementType == toElementType)
6884 if (from.isArray() || to.isArray() || ! from.sameElementShape(to))
6886 if (from.isCoopMat() && to.isCoopMat())
6887 return from.sameCoopMatBaseType(to);
6888 return intermediate.canImplicitlyPromote(from.getBasicType(), to.getBasicType());
6891 // Is 'to2' a better conversion than 'to1'?
6892 // Ties should not be considered as better.
6893 // Assumes 'convertible' already said true.
6894 const auto better = [this](const TType& from, const TType& to1, const TType& to2) -> bool {
6901 // 2. Promotion (integral, floating-point) is better
6902 TBasicType from_type = from.getBasicType();
6903 TBasicType to1_type = to1.getBasicType();
6904 TBasicType to2_type = to2.getBasicType();
6905 bool isPromotion1 = (intermediate.isIntegralPromotion(from_type, to1_type) ||
6906 intermediate.isFPPromotion(from_type, to1_type));
6907 bool isPromotion2 = (intermediate.isIntegralPromotion(from_type, to2_type) ||
6908 intermediate.isFPPromotion(from_type, to2_type));
6910 return !isPromotion1;
6914 // 3. Conversion (integral, floating-point , floating-integral)
6915 bool isConversion1 = (intermediate.isIntegralConversion(from_type, to1_type) ||
6916 intermediate.isFPConversion(from_type, to1_type) ||
6917 intermediate.isFPIntegralConversion(from_type, to1_type));
6918 bool isConversion2 = (intermediate.isIntegralConversion(from_type, to2_type) ||
6919 intermediate.isFPConversion(from_type, to2_type) ||
6920 intermediate.isFPIntegralConversion(from_type, to2_type));
6922 return isConversion2 && !isConversion1;
6925 // for ambiguity reporting
6928 // send to the generic selector
6929 const TFunction* bestMatch = selectFunction(candidateList, call, convertible, better, tie);
6931 if (bestMatch == nullptr)
6932 error(loc, "no matching overloaded function found", call.getName().c_str(), "");
6934 error(loc, "ambiguous best function under implicit type conversion", call.getName().c_str(), "");
6940 // Adjust function calls that aren't declared in Vulkan to a
6941 // calls with equivalent effects
6943 TIntermTyped* TParseContext::vkRelaxedRemapFunctionCall(const TSourceLoc& loc, TFunction* function, TIntermNode* arguments)
6945 TIntermTyped* result = nullptr;
6948 if (function->getBuiltInOp() != EOpNull) {
6952 if (function->getName() == "atomicCounterIncrement") {
6953 // change atomicCounterIncrement into an atomicAdd of 1
6954 TString name("atomicAdd");
6955 TType uintType(EbtUint);
6957 TFunction realFunc(&name, function->getType());
6959 for (int i = 0; i < function->getParamCount(); ++i) {
6960 realFunc.addParameter((*function)[i]);
6963 TParameter tmpP = { 0, &uintType };
6964 realFunc.addParameter(tmpP);
6965 arguments = intermediate.growAggregate(arguments, intermediate.addConstantUnion(1, loc, true));
6967 result = handleFunctionCall(loc, &realFunc, arguments);
6968 } else if (function->getName() == "atomicCounterDecrement") {
6969 // change atomicCounterDecrement into an atomicAdd with -1
6970 // and subtract 1 from result, to return post-decrement value
6971 TString name("atomicAdd");
6972 TType uintType(EbtUint);
6974 TFunction realFunc(&name, function->getType());
6976 for (int i = 0; i < function->getParamCount(); ++i) {
6977 realFunc.addParameter((*function)[i]);
6980 TParameter tmpP = { 0, &uintType };
6981 realFunc.addParameter(tmpP);
6982 arguments = intermediate.growAggregate(arguments, intermediate.addConstantUnion(-1, loc, true));
6984 result = handleFunctionCall(loc, &realFunc, arguments);
6986 // post decrement, so that it matches AtomicCounterDecrement semantics
6988 result = handleBinaryMath(loc, "-", EOpSub, result, intermediate.addConstantUnion(1, loc, true));
6990 } else if (function->getName() == "atomicCounter") {
6991 // change atomicCounter into a direct read of the variable
6992 if (arguments->getAsTyped()) {
6993 result = arguments->getAsTyped();
7001 // When a declaration includes a type, but not a variable name, it can be used
7002 // to establish defaults.
7003 void TParseContext::declareTypeDefaults(const TSourceLoc& loc, const TPublicType& publicType)
7006 if (publicType.basicType == EbtAtomicUint && publicType.qualifier.hasBinding()) {
7007 if (publicType.qualifier.layoutBinding >= (unsigned int)resources.maxAtomicCounterBindings) {
7008 error(loc, "atomic_uint binding is too large", "binding", "");
7011 if (publicType.qualifier.hasOffset())
7012 atomicUintOffsets[publicType.qualifier.layoutBinding] = publicType.qualifier.layoutOffset;
7016 if (publicType.arraySizes) {
7017 error(loc, "expect an array name", "", "");
7020 if (publicType.qualifier.hasLayout() && !publicType.qualifier.hasBufferReference())
7021 warn(loc, "useless application of layout qualifier", "layout", "");
7025 bool TParseContext::vkRelaxedRemapUniformVariable(const TSourceLoc& loc, TString& identifier, const TPublicType&,
7026 TArraySizes*, TIntermTyped* initializer, TType& type)
7028 if (parsingBuiltins || symbolTable.atBuiltInLevel() || !symbolTable.atGlobalLevel() ||
7029 type.getQualifier().storage != EvqUniform ||
7030 !(type.containsNonOpaque()
7032 || type.getBasicType() == EbtAtomicUint
7038 if (type.getQualifier().hasLocation()) {
7039 warn(loc, "ignoring layout qualifier for uniform", identifier.c_str(), "location");
7040 type.getQualifier().layoutLocation = TQualifier::layoutLocationEnd;
7044 warn(loc, "Ignoring initializer for uniform", identifier.c_str(), "");
7045 initializer = nullptr;
7048 if (type.isArray()) {
7049 // do array size checks here
7050 arraySizesCheck(loc, type.getQualifier(), type.getArraySizes(), initializer, false);
7052 if (arrayQualifierError(loc, type.getQualifier()) || arrayError(loc, type)) {
7053 error(loc, "array param error", identifier.c_str(), "");
7057 // do some checking on the type as it was declared
7058 layoutTypeCheck(loc, type);
7060 int bufferBinding = TQualifier::layoutBindingEnd;
7061 TVariable* updatedBlock = nullptr;
7064 // Convert atomic_uint into members of a buffer block
7065 if (type.isAtomic()) {
7066 type.setBasicType(EbtUint);
7067 type.getQualifier().storage = EvqBuffer;
7069 type.getQualifier().volatil = true;
7070 type.getQualifier().coherent = true;
7072 // xxTODO: use logic from fixOffset() to apply explicit member offset
7073 bufferBinding = type.getQualifier().layoutBinding;
7074 type.getQualifier().layoutBinding = TQualifier::layoutBindingEnd;
7075 type.getQualifier().explicitOffset = false;
7076 growAtomicCounterBlock(bufferBinding, loc, type, identifier, nullptr);
7077 updatedBlock = atomicCounterBuffers[bufferBinding];
7081 if (!updatedBlock) {
7082 growGlobalUniformBlock(loc, type, identifier, nullptr);
7083 updatedBlock = globalUniformBlock;
7087 // don't assign explicit member offsets here
7088 // if any are assigned, need to be updated here and in the merge/link step
7089 // fixBlockUniformOffsets(updatedBlock->getWritableType().getQualifier(), *updatedBlock->getWritableType().getWritableStruct());
7091 // checks on update buffer object
7092 layoutObjectCheck(loc, *updatedBlock);
7094 TSymbol* symbol = symbolTable.find(identifier);
7097 if (updatedBlock == globalUniformBlock)
7098 error(loc, "error adding uniform to default uniform block", identifier.c_str(), "");
7100 error(loc, "error adding atomic counter to atomic counter block", identifier.c_str(), "");
7105 mergeObjectLayoutQualifiers(updatedBlock->getWritableType().getQualifier(), type.getQualifier(), true);
7111 // Do everything necessary to handle a variable (non-block) declaration.
7112 // Either redeclaring a variable, or making a new one, updating the symbol
7113 // table, and all error checking.
7115 // Returns a subtree node that computes an initializer, if needed.
7116 // Returns nullptr if there is no code to execute for initialization.
7118 // 'publicType' is the type part of the declaration (to the left)
7119 // 'arraySizes' is the arrayness tagged on the identifier (to the right)
7121 TIntermNode* TParseContext::declareVariable(const TSourceLoc& loc, TString& identifier, const TPublicType& publicType,
7122 TArraySizes* arraySizes, TIntermTyped* initializer)
7124 // Make a fresh type that combines the characteristics from the individual
7125 // identifier syntax and the declaration-type syntax.
7126 TType type(publicType);
7127 type.transferArraySizes(arraySizes);
7128 type.copyArrayInnerSizes(publicType.arraySizes);
7129 arrayOfArrayVersionCheck(loc, type.getArraySizes());
7132 if (type.getBasicType() == EbtRayQuery) {
7133 error(loc, "ray queries can only be initialized by using the rayQueryInitializeEXT intrinsic:", "=", identifier.c_str());
7137 if (type.isCoopMat()) {
7138 intermediate.setUseVulkanMemoryModel();
7139 intermediate.setUseStorageBuffer();
7141 if (!publicType.typeParameters || publicType.typeParameters->getNumDims() != 4) {
7142 error(loc, "expected four type parameters", identifier.c_str(), "");
7144 if (publicType.typeParameters) {
7145 if (isTypeFloat(publicType.basicType) &&
7146 publicType.typeParameters->getDimSize(0) != 16 &&
7147 publicType.typeParameters->getDimSize(0) != 32 &&
7148 publicType.typeParameters->getDimSize(0) != 64) {
7149 error(loc, "expected 16, 32, or 64 bits for first type parameter", identifier.c_str(), "");
7151 if (isTypeInt(publicType.basicType) &&
7152 publicType.typeParameters->getDimSize(0) != 8 &&
7153 publicType.typeParameters->getDimSize(0) != 32) {
7154 error(loc, "expected 8 or 32 bits for first type parameter", identifier.c_str(), "");
7159 if (publicType.typeParameters && publicType.typeParameters->getNumDims() != 0) {
7160 error(loc, "unexpected type parameters", identifier.c_str(), "");
7164 if (voidErrorCheck(loc, identifier, type.getBasicType()))
7168 rValueErrorCheck(loc, "initializer", initializer);
7170 nonInitConstCheck(loc, identifier, type);
7172 samplerCheck(loc, type, identifier, initializer);
7173 transparentOpaqueCheck(loc, type, identifier);
7175 atomicUintCheck(loc, type, identifier);
7176 accStructCheck(loc, type, identifier);
7177 checkAndResizeMeshViewDim(loc, type, /*isBlockMember*/ false);
7179 if (type.getQualifier().storage == EvqConst && type.containsReference()) {
7180 error(loc, "variables with reference type can't have qualifier 'const'", "qualifier", "");
7183 if (type.getQualifier().storage != EvqUniform && type.getQualifier().storage != EvqBuffer) {
7184 if (type.contains16BitFloat())
7185 requireFloat16Arithmetic(loc, "qualifier", "float16 types can only be in uniform block or buffer storage");
7186 if (type.contains16BitInt())
7187 requireInt16Arithmetic(loc, "qualifier", "(u)int16 types can only be in uniform block or buffer storage");
7188 if (type.contains8BitInt())
7189 requireInt8Arithmetic(loc, "qualifier", "(u)int8 types can only be in uniform block or buffer storage");
7192 if (type.getQualifier().storage == EvqShared && type.containsCoopMat())
7193 error(loc, "qualifier", "Cooperative matrix types must not be used in shared memory", "");
7195 if (profile == EEsProfile) {
7196 if (type.getQualifier().isPipeInput() && type.getBasicType() == EbtStruct) {
7197 if (type.getQualifier().isArrayedIo(language)) {
7198 TType perVertexType(type, 0);
7199 if (perVertexType.containsArray() && perVertexType.containsBuiltIn() == false) {
7200 error(loc, "A per vertex structure containing an array is not allowed as input in ES", type.getTypeName().c_str(), "");
7203 else if (type.containsArray() && type.containsBuiltIn() == false) {
7204 error(loc, "A structure containing an array is not allowed as input in ES", type.getTypeName().c_str(), "");
7206 if (type.containsStructure())
7207 error(loc, "A structure containing an struct is not allowed as input in ES", type.getTypeName().c_str(), "");
7211 if (identifier != "gl_FragCoord" && (publicType.shaderQualifiers.originUpperLeft || publicType.shaderQualifiers.pixelCenterInteger))
7212 error(loc, "can only apply origin_upper_left and pixel_center_origin to gl_FragCoord", "layout qualifier", "");
7213 if (identifier != "gl_FragDepth" && publicType.shaderQualifiers.getDepth() != EldNone)
7214 error(loc, "can only apply depth layout to gl_FragDepth", "layout qualifier", "");
7216 // Check for redeclaration of built-ins and/or attempting to declare a reserved name
7217 TSymbol* symbol = redeclareBuiltinVariable(loc, identifier, type.getQualifier(), publicType.shaderQualifiers);
7218 if (symbol == nullptr)
7219 reservedErrorCheck(loc, identifier);
7221 if (symbol == nullptr && spvVersion.vulkan > 0 && spvVersion.vulkanRelaxed) {
7222 bool remapped = vkRelaxedRemapUniformVariable(loc, identifier, publicType, arraySizes, initializer, type);
7229 inheritGlobalDefaults(type.getQualifier());
7231 // Declare the variable
7232 if (type.isArray()) {
7233 // Check that implicit sizing is only where allowed.
7234 arraySizesCheck(loc, type.getQualifier(), type.getArraySizes(), initializer, false);
7236 if (! arrayQualifierError(loc, type.getQualifier()) && ! arrayError(loc, type))
7237 declareArray(loc, identifier, type, symbol);
7240 profileRequires(loc, ENoProfile, 120, E_GL_3DL_array_objects, "initializer");
7241 profileRequires(loc, EEsProfile, 300, nullptr, "initializer");
7245 if (symbol == nullptr)
7246 symbol = declareNonArray(loc, identifier, type);
7247 else if (type != symbol->getType())
7248 error(loc, "cannot change the type of", "redeclaration", symbol->getName().c_str());
7251 if (symbol == nullptr)
7254 // Deal with initializer
7255 TIntermNode* initNode = nullptr;
7256 if (symbol != nullptr && initializer) {
7257 TVariable* variable = symbol->getAsVariable();
7259 error(loc, "initializer requires a variable, not a member", identifier.c_str(), "");
7262 initNode = executeInitializer(loc, initializer, variable);
7265 // look for errors in layout qualifier use
7266 layoutObjectCheck(loc, *symbol);
7269 fixOffset(loc, *symbol);
7274 // Pick up global defaults from the provide global defaults into dst.
7275 void TParseContext::inheritGlobalDefaults(TQualifier& dst) const
7278 if (dst.storage == EvqVaryingOut) {
7279 if (! dst.hasStream() && language == EShLangGeometry)
7280 dst.layoutStream = globalOutputDefaults.layoutStream;
7281 if (! dst.hasXfbBuffer())
7282 dst.layoutXfbBuffer = globalOutputDefaults.layoutXfbBuffer;
7288 // Make an internal-only variable whose name is for debug purposes only
7289 // and won't be searched for. Callers will only use the return value to use
7290 // the variable, not the name to look it up. It is okay if the name
7291 // is the same as other names; there won't be any conflict.
7293 TVariable* TParseContext::makeInternalVariable(const char* name, const TType& type) const
7295 TString* nameString = NewPoolTString(name);
7296 TVariable* variable = new TVariable(nameString, type);
7297 symbolTable.makeInternalVariable(*variable);
7303 // Declare a non-array variable, the main point being there is no redeclaration
7304 // for resizing allowed.
7306 // Return the successfully declared variable.
7308 TVariable* TParseContext::declareNonArray(const TSourceLoc& loc, const TString& identifier, const TType& type)
7310 // make a new variable
7311 TVariable* variable = new TVariable(&identifier, type);
7314 ioArrayCheck(loc, type, identifier);
7317 // add variable to symbol table
7318 if (symbolTable.insert(*variable)) {
7319 if (symbolTable.atGlobalLevel())
7320 trackLinkage(*variable);
7324 error(loc, "redefinition", variable->getName().c_str(), "");
7329 // Handle all types of initializers from the grammar.
7331 // Returning nullptr just means there is no code to execute to handle the
7332 // initializer, which will, for example, be the case for constant initializers.
7334 TIntermNode* TParseContext::executeInitializer(const TSourceLoc& loc, TIntermTyped* initializer, TVariable* variable)
7336 // A null initializer is an aggregate that hasn't had an op assigned yet
7337 // (still EOpNull, no relation to nullInit), and has no children.
7338 bool nullInit = initializer->getAsAggregate() && initializer->getAsAggregate()->getOp() == EOpNull &&
7339 initializer->getAsAggregate()->getSequence().size() == 0;
7342 // Identifier must be of type constant, a global, or a temporary, and
7343 // starting at version 120, desktop allows uniforms to have initializers.
7345 TStorageQualifier qualifier = variable->getType().getQualifier().storage;
7346 if (! (qualifier == EvqTemporary || qualifier == EvqGlobal || qualifier == EvqConst ||
7347 (qualifier == EvqUniform && !isEsProfile() && version >= 120))) {
7348 if (qualifier == EvqShared) {
7349 // GL_EXT_null_initializer allows this for shared, if it's a null initializer
7351 const char* feature = "initialization with shared qualifier";
7352 profileRequires(loc, EEsProfile, 0, E_GL_EXT_null_initializer, feature);
7353 profileRequires(loc, ~EEsProfile, 0, E_GL_EXT_null_initializer, feature);
7355 error(loc, "initializer can only be a null initializer ('{}')", "shared", "");
7358 error(loc, " cannot initialize this type of qualifier ",
7359 variable->getType().getStorageQualifierString(), "");
7365 // only some types can be null initialized
7366 if (variable->getType().containsUnsizedArray()) {
7367 error(loc, "null initializers can't size unsized arrays", "{}", "");
7370 if (variable->getType().containsOpaque()) {
7371 error(loc, "null initializers can't be used on opaque values", "{}", "");
7374 variable->getWritableType().getQualifier().setNullInit();
7378 arrayObjectCheck(loc, variable->getType(), "array initializer");
7381 // If the initializer was from braces { ... }, we convert the whole subtree to a
7382 // constructor-style subtree, allowing the rest of the code to operate
7383 // identically for both kinds of initializers.
7385 // Type can't be deduced from the initializer list, so a skeletal type to
7386 // follow has to be passed in. Constness and specialization-constness
7387 // should be deduced bottom up, not dictated by the skeletal type.
7390 skeletalType.shallowCopy(variable->getType());
7391 skeletalType.getQualifier().makeTemporary();
7393 initializer = convertInitializerList(loc, skeletalType, initializer);
7395 if (! initializer) {
7396 // error recovery; don't leave const without constant values
7397 if (qualifier == EvqConst)
7398 variable->getWritableType().getQualifier().makeTemporary();
7402 // Fix outer arrayness if variable is unsized, getting size from the initializer
7403 if (initializer->getType().isSizedArray() && variable->getType().isUnsizedArray())
7404 variable->getWritableType().changeOuterArraySize(initializer->getType().getOuterArraySize());
7406 // Inner arrayness can also get set by an initializer
7407 if (initializer->getType().isArrayOfArrays() && variable->getType().isArrayOfArrays() &&
7408 initializer->getType().getArraySizes()->getNumDims() ==
7409 variable->getType().getArraySizes()->getNumDims()) {
7410 // adopt unsized sizes from the initializer's sizes
7411 for (int d = 1; d < variable->getType().getArraySizes()->getNumDims(); ++d) {
7412 if (variable->getType().getArraySizes()->getDimSize(d) == UnsizedArraySize) {
7413 variable->getWritableType().getArraySizes()->setDimSize(d,
7414 initializer->getType().getArraySizes()->getDimSize(d));
7419 // Uniforms require a compile-time constant initializer
7420 if (qualifier == EvqUniform && ! initializer->getType().getQualifier().isFrontEndConstant()) {
7421 error(loc, "uniform initializers must be constant", "=", "'%s'",
7422 variable->getType().getCompleteString().c_str());
7423 variable->getWritableType().getQualifier().makeTemporary();
7426 // Global consts require a constant initializer (specialization constant is okay)
7427 if (qualifier == EvqConst && symbolTable.atGlobalLevel() && ! initializer->getType().getQualifier().isConstant()) {
7428 error(loc, "global const initializers must be constant", "=", "'%s'",
7429 variable->getType().getCompleteString().c_str());
7430 variable->getWritableType().getQualifier().makeTemporary();
7434 // Const variables require a constant initializer, depending on version
7435 if (qualifier == EvqConst) {
7436 if (! initializer->getType().getQualifier().isConstant()) {
7437 const char* initFeature = "non-constant initializer";
7438 requireProfile(loc, ~EEsProfile, initFeature);
7439 profileRequires(loc, ~EEsProfile, 420, E_GL_ARB_shading_language_420pack, initFeature);
7440 variable->getWritableType().getQualifier().storage = EvqConstReadOnly;
7441 qualifier = EvqConstReadOnly;
7444 // Non-const global variables in ES need a const initializer.
7446 // "In declarations of global variables with no storage qualifier or with a const
7447 // qualifier any initializer must be a constant expression."
7448 if (symbolTable.atGlobalLevel() && ! initializer->getType().getQualifier().isConstant()) {
7449 const char* initFeature =
7450 "non-constant global initializer (needs GL_EXT_shader_non_constant_global_initializers)";
7451 if (isEsProfile()) {
7452 if (relaxedErrors() && ! extensionTurnedOn(E_GL_EXT_shader_non_constant_global_initializers))
7453 warn(loc, "not allowed in this version", initFeature, "");
7455 profileRequires(loc, EEsProfile, 0, E_GL_EXT_shader_non_constant_global_initializers, initFeature);
7460 if (qualifier == EvqConst || qualifier == EvqUniform) {
7461 // Compile-time tagging of the variable with its constant value...
7463 initializer = intermediate.addConversion(EOpAssign, variable->getType(), initializer);
7464 if (! initializer || ! initializer->getType().getQualifier().isConstant() ||
7465 variable->getType() != initializer->getType()) {
7466 error(loc, "non-matching or non-convertible constant type for const initializer",
7467 variable->getType().getStorageQualifierString(), "");
7468 variable->getWritableType().getQualifier().makeTemporary();
7472 // We either have a folded constant in getAsConstantUnion, or we have to use
7473 // the initializer's subtree in the AST to represent the computation of a
7474 // specialization constant.
7475 assert(initializer->getAsConstantUnion() || initializer->getType().getQualifier().isSpecConstant());
7476 if (initializer->getAsConstantUnion())
7477 variable->setConstArray(initializer->getAsConstantUnion()->getConstArray());
7479 // It's a specialization constant.
7480 variable->getWritableType().getQualifier().makeSpecConstant();
7482 // Keep the subtree that computes the specialization constant with the variable.
7483 // Later, a symbol node will adopt the subtree from the variable.
7484 variable->setConstSubtree(initializer);
7487 // normal assigning of a value to a variable...
7488 specializationCheck(loc, initializer->getType(), "initializer");
7489 TIntermSymbol* intermSymbol = intermediate.addSymbol(*variable, loc);
7490 TIntermTyped* initNode = intermediate.addAssign(EOpAssign, intermSymbol, initializer, loc);
7492 assignError(loc, "=", intermSymbol->getCompleteString(), initializer->getCompleteString());
7501 // Reprocess any initializer-list (the "{ ... }" syntax) parts of the
7504 // Need to hierarchically assign correct types and implicit
7505 // conversions. Will do this mimicking the same process used for
7506 // creating a constructor-style initializer, ensuring we get the
7507 // same form. However, it has to in parallel walk the 'type'
7508 // passed in, as type cannot be deduced from an initializer list.
7510 TIntermTyped* TParseContext::convertInitializerList(const TSourceLoc& loc, const TType& type, TIntermTyped* initializer)
7512 // Will operate recursively. Once a subtree is found that is constructor style,
7513 // everything below it is already good: Only the "top part" of the initializer
7514 // can be an initializer list, where "top part" can extend for several (or all) levels.
7516 // see if we have bottomed out in the tree within the initializer-list part
7517 TIntermAggregate* initList = initializer->getAsAggregate();
7518 if (! initList || initList->getOp() != EOpNull)
7521 // Of the initializer-list set of nodes, need to process bottom up,
7522 // so recurse deep, then process on the way up.
7524 // Go down the tree here...
7525 if (type.isArray()) {
7526 // The type's array might be unsized, which could be okay, so base sizes on the size of the aggregate.
7527 // Later on, initializer execution code will deal with array size logic.
7529 arrayType.shallowCopy(type); // sharing struct stuff is fine
7530 arrayType.copyArraySizes(*type.getArraySizes()); // but get a fresh copy of the array information, to edit below
7532 // edit array sizes to fill in unsized dimensions
7533 arrayType.changeOuterArraySize((int)initList->getSequence().size());
7534 TIntermTyped* firstInit = initList->getSequence()[0]->getAsTyped();
7535 if (arrayType.isArrayOfArrays() && firstInit->getType().isArray() &&
7536 arrayType.getArraySizes()->getNumDims() == firstInit->getType().getArraySizes()->getNumDims() + 1) {
7537 for (int d = 1; d < arrayType.getArraySizes()->getNumDims(); ++d) {
7538 if (arrayType.getArraySizes()->getDimSize(d) == UnsizedArraySize)
7539 arrayType.getArraySizes()->setDimSize(d, firstInit->getType().getArraySizes()->getDimSize(d - 1));
7543 TType elementType(arrayType, 0); // dereferenced type
7544 for (size_t i = 0; i < initList->getSequence().size(); ++i) {
7545 initList->getSequence()[i] = convertInitializerList(loc, elementType, initList->getSequence()[i]->getAsTyped());
7546 if (initList->getSequence()[i] == nullptr)
7550 return addConstructor(loc, initList, arrayType);
7551 } else if (type.isStruct()) {
7552 if (type.getStruct()->size() != initList->getSequence().size()) {
7553 error(loc, "wrong number of structure members", "initializer list", "");
7556 for (size_t i = 0; i < type.getStruct()->size(); ++i) {
7557 initList->getSequence()[i] = convertInitializerList(loc, *(*type.getStruct())[i].type, initList->getSequence()[i]->getAsTyped());
7558 if (initList->getSequence()[i] == nullptr)
7561 } else if (type.isMatrix()) {
7562 if (type.getMatrixCols() != (int)initList->getSequence().size()) {
7563 error(loc, "wrong number of matrix columns:", "initializer list", type.getCompleteString().c_str());
7566 TType vectorType(type, 0); // dereferenced type
7567 for (int i = 0; i < type.getMatrixCols(); ++i) {
7568 initList->getSequence()[i] = convertInitializerList(loc, vectorType, initList->getSequence()[i]->getAsTyped());
7569 if (initList->getSequence()[i] == nullptr)
7572 } else if (type.isVector()) {
7573 if (type.getVectorSize() != (int)initList->getSequence().size()) {
7574 error(loc, "wrong vector size (or rows in a matrix column):", "initializer list", type.getCompleteString().c_str());
7577 TBasicType destType = type.getBasicType();
7578 for (int i = 0; i < type.getVectorSize(); ++i) {
7579 TBasicType initType = initList->getSequence()[i]->getAsTyped()->getBasicType();
7580 if (destType != initType && !intermediate.canImplicitlyPromote(initType, destType)) {
7581 error(loc, "type mismatch in initializer list", "initializer list", type.getCompleteString().c_str());
7587 error(loc, "unexpected initializer-list type:", "initializer list", type.getCompleteString().c_str());
7591 // Now that the subtree is processed, process this node as if the
7592 // initializer list is a set of arguments to a constructor.
7593 TIntermNode* emulatedConstructorArguments;
7594 if (initList->getSequence().size() == 1)
7595 emulatedConstructorArguments = initList->getSequence()[0];
7597 emulatedConstructorArguments = initList;
7598 return addConstructor(loc, emulatedConstructorArguments, type);
7602 // Test for the correctness of the parameters passed to various constructor functions
7603 // and also convert them to the right data type, if allowed and required.
7605 // 'node' is what to construct from.
7606 // 'type' is what type to construct.
7608 // Returns nullptr for an error or the constructed node (aggregate or typed) for no error.
7610 TIntermTyped* TParseContext::addConstructor(const TSourceLoc& loc, TIntermNode* node, const TType& type)
7612 if (node == nullptr || node->getAsTyped() == nullptr)
7614 rValueErrorCheck(loc, "constructor", node->getAsTyped());
7616 TIntermAggregate* aggrNode = node->getAsAggregate();
7617 TOperator op = intermediate.mapTypeToConstructorOp(type);
7619 // Combined texture-sampler constructors are completely semantic checked
7620 // in constructorTextureSamplerError()
7621 if (op == EOpConstructTextureSampler) {
7622 if (aggrNode->getSequence()[1]->getAsTyped()->getType().getSampler().shadow) {
7623 // Transfer depth into the texture (SPIR-V image) type, as a hint
7624 // for tools to know this texture/image is a depth image.
7625 aggrNode->getSequence()[0]->getAsTyped()->getWritableType().getSampler().shadow = true;
7627 return intermediate.setAggregateOperator(aggrNode, op, type, loc);
7630 TTypeList::const_iterator memberTypes;
7631 if (op == EOpConstructStruct)
7632 memberTypes = type.getStruct()->begin();
7635 if (type.isArray()) {
7636 TType dereferenced(type, 0);
7637 elementType.shallowCopy(dereferenced);
7639 elementType.shallowCopy(type);
7643 if (aggrNode->getOp() != EOpNull)
7650 TIntermTyped *newNode;
7652 // If structure constructor or array constructor is being called
7653 // for only one parameter inside the structure, we need to call constructAggregate function once.
7655 newNode = constructAggregate(node, elementType, 1, node->getLoc());
7656 else if (op == EOpConstructStruct)
7657 newNode = constructAggregate(node, *(*memberTypes).type, 1, node->getLoc());
7659 newNode = constructBuiltIn(type, op, node->getAsTyped(), node->getLoc(), false);
7661 if (newNode && (type.isArray() || op == EOpConstructStruct))
7662 newNode = intermediate.setAggregateOperator(newNode, EOpConstructStruct, type, loc);
7668 // Handle list of arguments.
7670 TIntermSequence &sequenceVector = aggrNode->getSequence(); // Stores the information about the parameter to the constructor
7671 // if the structure constructor contains more than one parameter, then construct
7674 int paramCount = 0; // keeps track of the constructor parameter number being checked
7676 // for each parameter to the constructor call, check to see if the right type is passed or convert them
7677 // to the right type if possible (and allowed).
7678 // for structure constructors, just check if the right type is passed, no conversion is allowed.
7679 for (TIntermSequence::iterator p = sequenceVector.begin();
7680 p != sequenceVector.end(); p++, paramCount++) {
7682 newNode = constructAggregate(*p, elementType, paramCount+1, node->getLoc());
7683 else if (op == EOpConstructStruct)
7684 newNode = constructAggregate(*p, *(memberTypes[paramCount]).type, paramCount+1, node->getLoc());
7686 newNode = constructBuiltIn(type, op, (*p)->getAsTyped(), node->getLoc(), true);
7694 TIntermTyped *ret_node = intermediate.setAggregateOperator(aggrNode, op, type, loc);
7696 TIntermAggregate *agg_node = ret_node->getAsAggregate();
7697 if (agg_node && (agg_node->isVector() || agg_node->isArray() || agg_node->isMatrix()))
7698 agg_node->updatePrecision();
7703 // Function for constructor implementation. Calls addUnaryMath with appropriate EOp value
7704 // for the parameter to the constructor (passed to this function). Essentially, it converts
7705 // the parameter types correctly. If a constructor expects an int (like ivec2) and is passed a
7706 // float, then float is converted to int.
7708 // Returns nullptr for an error or the constructed node.
7710 TIntermTyped* TParseContext::constructBuiltIn(const TType& type, TOperator op, TIntermTyped* node, const TSourceLoc& loc,
7713 // If we are changing a matrix in both domain of basic type and to a non matrix,
7714 // do the shape change first (by default, below, basic type is changed before shape).
7715 // This avoids requesting a matrix of a new type that is going to be discarded anyway.
7716 // TODO: This could be generalized to more type combinations, but that would require
7717 // more extensive testing and full algorithm rework. For now, the need to do two changes makes
7718 // the recursive call work, and avoids the most egregious case of creating integer matrices.
7719 if (node->getType().isMatrix() && (type.isScalar() || type.isVector()) &&
7720 type.isFloatingDomain() != node->getType().isFloatingDomain()) {
7721 TType transitionType(node->getBasicType(), glslang::EvqTemporary, type.getVectorSize(), 0, 0, node->isVector());
7722 TOperator transitionOp = intermediate.mapTypeToConstructorOp(transitionType);
7723 node = constructBuiltIn(transitionType, transitionOp, node, loc, false);
7726 TIntermTyped* newNode;
7730 // First, convert types as needed.
7733 case EOpConstructVec2:
7734 case EOpConstructVec3:
7735 case EOpConstructVec4:
7736 case EOpConstructMat2x2:
7737 case EOpConstructMat2x3:
7738 case EOpConstructMat2x4:
7739 case EOpConstructMat3x2:
7740 case EOpConstructMat3x3:
7741 case EOpConstructMat3x4:
7742 case EOpConstructMat4x2:
7743 case EOpConstructMat4x3:
7744 case EOpConstructMat4x4:
7745 case EOpConstructFloat:
7746 basicOp = EOpConstructFloat;
7749 case EOpConstructIVec2:
7750 case EOpConstructIVec3:
7751 case EOpConstructIVec4:
7752 case EOpConstructInt:
7753 basicOp = EOpConstructInt;
7756 case EOpConstructUVec2:
7757 if (node->getType().getBasicType() == EbtReference) {
7758 requireExtensions(loc, 1, &E_GL_EXT_buffer_reference_uvec2, "reference conversion to uvec2");
7759 TIntermTyped* newNode = intermediate.addBuiltInFunctionCall(node->getLoc(), EOpConvPtrToUvec2, true, node,
7763 case EOpConstructUVec3:
7764 case EOpConstructUVec4:
7765 case EOpConstructUint:
7766 basicOp = EOpConstructUint;
7769 case EOpConstructBVec2:
7770 case EOpConstructBVec3:
7771 case EOpConstructBVec4:
7772 case EOpConstructBool:
7773 basicOp = EOpConstructBool;
7778 case EOpConstructDVec2:
7779 case EOpConstructDVec3:
7780 case EOpConstructDVec4:
7781 case EOpConstructDMat2x2:
7782 case EOpConstructDMat2x3:
7783 case EOpConstructDMat2x4:
7784 case EOpConstructDMat3x2:
7785 case EOpConstructDMat3x3:
7786 case EOpConstructDMat3x4:
7787 case EOpConstructDMat4x2:
7788 case EOpConstructDMat4x3:
7789 case EOpConstructDMat4x4:
7790 case EOpConstructDouble:
7791 basicOp = EOpConstructDouble;
7794 case EOpConstructF16Vec2:
7795 case EOpConstructF16Vec3:
7796 case EOpConstructF16Vec4:
7797 case EOpConstructF16Mat2x2:
7798 case EOpConstructF16Mat2x3:
7799 case EOpConstructF16Mat2x4:
7800 case EOpConstructF16Mat3x2:
7801 case EOpConstructF16Mat3x3:
7802 case EOpConstructF16Mat3x4:
7803 case EOpConstructF16Mat4x2:
7804 case EOpConstructF16Mat4x3:
7805 case EOpConstructF16Mat4x4:
7806 case EOpConstructFloat16:
7807 basicOp = EOpConstructFloat16;
7808 // 8/16-bit storage extensions don't support constructing composites of 8/16-bit types,
7809 // so construct a 32-bit type and convert
7810 if (!intermediate.getArithemeticFloat16Enabled()) {
7811 TType tempType(EbtFloat, EvqTemporary, type.getVectorSize());
7813 if (tempType != newNode->getType()) {
7814 TOperator aggregateOp;
7815 if (op == EOpConstructFloat16)
7816 aggregateOp = EOpConstructFloat;
7818 aggregateOp = (TOperator)(EOpConstructVec2 + op - EOpConstructF16Vec2);
7819 newNode = intermediate.setAggregateOperator(newNode, aggregateOp, tempType, node->getLoc());
7821 newNode = intermediate.addConversion(EbtFloat16, newNode);
7826 case EOpConstructI8Vec2:
7827 case EOpConstructI8Vec3:
7828 case EOpConstructI8Vec4:
7829 case EOpConstructInt8:
7830 basicOp = EOpConstructInt8;
7831 // 8/16-bit storage extensions don't support constructing composites of 8/16-bit types,
7832 // so construct a 32-bit type and convert
7833 if (!intermediate.getArithemeticInt8Enabled()) {
7834 TType tempType(EbtInt, EvqTemporary, type.getVectorSize());
7836 if (tempType != newNode->getType()) {
7837 TOperator aggregateOp;
7838 if (op == EOpConstructInt8)
7839 aggregateOp = EOpConstructInt;
7841 aggregateOp = (TOperator)(EOpConstructIVec2 + op - EOpConstructI8Vec2);
7842 newNode = intermediate.setAggregateOperator(newNode, aggregateOp, tempType, node->getLoc());
7844 newNode = intermediate.addConversion(EbtInt8, newNode);
7849 case EOpConstructU8Vec2:
7850 case EOpConstructU8Vec3:
7851 case EOpConstructU8Vec4:
7852 case EOpConstructUint8:
7853 basicOp = EOpConstructUint8;
7854 // 8/16-bit storage extensions don't support constructing composites of 8/16-bit types,
7855 // so construct a 32-bit type and convert
7856 if (!intermediate.getArithemeticInt8Enabled()) {
7857 TType tempType(EbtUint, EvqTemporary, type.getVectorSize());
7859 if (tempType != newNode->getType()) {
7860 TOperator aggregateOp;
7861 if (op == EOpConstructUint8)
7862 aggregateOp = EOpConstructUint;
7864 aggregateOp = (TOperator)(EOpConstructUVec2 + op - EOpConstructU8Vec2);
7865 newNode = intermediate.setAggregateOperator(newNode, aggregateOp, tempType, node->getLoc());
7867 newNode = intermediate.addConversion(EbtUint8, newNode);
7872 case EOpConstructI16Vec2:
7873 case EOpConstructI16Vec3:
7874 case EOpConstructI16Vec4:
7875 case EOpConstructInt16:
7876 basicOp = EOpConstructInt16;
7877 // 8/16-bit storage extensions don't support constructing composites of 8/16-bit types,
7878 // so construct a 32-bit type and convert
7879 if (!intermediate.getArithemeticInt16Enabled()) {
7880 TType tempType(EbtInt, EvqTemporary, type.getVectorSize());
7882 if (tempType != newNode->getType()) {
7883 TOperator aggregateOp;
7884 if (op == EOpConstructInt16)
7885 aggregateOp = EOpConstructInt;
7887 aggregateOp = (TOperator)(EOpConstructIVec2 + op - EOpConstructI16Vec2);
7888 newNode = intermediate.setAggregateOperator(newNode, aggregateOp, tempType, node->getLoc());
7890 newNode = intermediate.addConversion(EbtInt16, newNode);
7895 case EOpConstructU16Vec2:
7896 case EOpConstructU16Vec3:
7897 case EOpConstructU16Vec4:
7898 case EOpConstructUint16:
7899 basicOp = EOpConstructUint16;
7900 // 8/16-bit storage extensions don't support constructing composites of 8/16-bit types,
7901 // so construct a 32-bit type and convert
7902 if (!intermediate.getArithemeticInt16Enabled()) {
7903 TType tempType(EbtUint, EvqTemporary, type.getVectorSize());
7905 if (tempType != newNode->getType()) {
7906 TOperator aggregateOp;
7907 if (op == EOpConstructUint16)
7908 aggregateOp = EOpConstructUint;
7910 aggregateOp = (TOperator)(EOpConstructUVec2 + op - EOpConstructU16Vec2);
7911 newNode = intermediate.setAggregateOperator(newNode, aggregateOp, tempType, node->getLoc());
7913 newNode = intermediate.addConversion(EbtUint16, newNode);
7918 case EOpConstructI64Vec2:
7919 case EOpConstructI64Vec3:
7920 case EOpConstructI64Vec4:
7921 case EOpConstructInt64:
7922 basicOp = EOpConstructInt64;
7925 case EOpConstructUint64:
7926 if (type.isScalar() && node->getType().isReference()) {
7927 TIntermTyped* newNode = intermediate.addBuiltInFunctionCall(node->getLoc(), EOpConvPtrToUint64, true, node, type);
7931 case EOpConstructU64Vec2:
7932 case EOpConstructU64Vec3:
7933 case EOpConstructU64Vec4:
7934 basicOp = EOpConstructUint64;
7937 case EOpConstructNonuniform:
7938 // Make a nonuniform copy of node
7939 newNode = intermediate.addBuiltInFunctionCall(node->getLoc(), EOpCopyObject, true, node, type);
7942 case EOpConstructReference:
7943 // construct reference from reference
7944 if (node->getType().isReference()) {
7945 newNode = intermediate.addBuiltInFunctionCall(node->getLoc(), EOpConstructReference, true, node, type);
7947 // construct reference from uint64
7948 } else if (node->getType().isScalar() && node->getType().getBasicType() == EbtUint64) {
7949 TIntermTyped* newNode = intermediate.addBuiltInFunctionCall(node->getLoc(), EOpConvUint64ToPtr, true, node,
7952 // construct reference from uvec2
7953 } else if (node->getType().isVector() && node->getType().getBasicType() == EbtUint &&
7954 node->getVectorSize() == 2) {
7955 requireExtensions(loc, 1, &E_GL_EXT_buffer_reference_uvec2, "uvec2 conversion to reference");
7956 TIntermTyped* newNode = intermediate.addBuiltInFunctionCall(node->getLoc(), EOpConvUvec2ToPtr, true, node,
7963 case EOpConstructCooperativeMatrix:
7964 if (!node->getType().isCoopMat()) {
7965 if (type.getBasicType() != node->getType().getBasicType()) {
7966 node = intermediate.addConversion(type.getBasicType(), node);
7967 if (node == nullptr)
7970 node = intermediate.setAggregateOperator(node, EOpConstructCooperativeMatrix, type, node->getLoc());
7972 TOperator op = EOpNull;
7973 switch (type.getBasicType()) {
7978 switch (node->getType().getBasicType()) {
7979 case EbtFloat: op = EOpConvFloatToInt; break;
7980 case EbtFloat16: op = EOpConvFloat16ToInt; break;
7981 case EbtUint8: op = EOpConvUint8ToInt; break;
7982 case EbtInt8: op = EOpConvInt8ToInt; break;
7983 case EbtUint: op = EOpConvUintToInt; break;
7988 switch (node->getType().getBasicType()) {
7989 case EbtFloat: op = EOpConvFloatToUint; break;
7990 case EbtFloat16: op = EOpConvFloat16ToUint; break;
7991 case EbtUint8: op = EOpConvUint8ToUint; break;
7992 case EbtInt8: op = EOpConvInt8ToUint; break;
7993 case EbtInt: op = EOpConvIntToUint; break;
7994 case EbtUint: op = EOpConvUintToInt8; break;
7999 switch (node->getType().getBasicType()) {
8000 case EbtFloat: op = EOpConvFloatToInt8; break;
8001 case EbtFloat16: op = EOpConvFloat16ToInt8; break;
8002 case EbtUint8: op = EOpConvUint8ToInt8; break;
8003 case EbtInt: op = EOpConvIntToInt8; break;
8004 case EbtUint: op = EOpConvUintToInt8; break;
8009 switch (node->getType().getBasicType()) {
8010 case EbtFloat: op = EOpConvFloatToUint8; break;
8011 case EbtFloat16: op = EOpConvFloat16ToUint8; break;
8012 case EbtInt8: op = EOpConvInt8ToUint8; break;
8013 case EbtInt: op = EOpConvIntToUint8; break;
8014 case EbtUint: op = EOpConvUintToUint8; break;
8019 switch (node->getType().getBasicType()) {
8020 case EbtFloat16: op = EOpConvFloat16ToFloat; break;
8021 case EbtInt8: op = EOpConvInt8ToFloat; break;
8022 case EbtUint8: op = EOpConvUint8ToFloat; break;
8023 case EbtInt: op = EOpConvIntToFloat; break;
8024 case EbtUint: op = EOpConvUintToFloat; break;
8029 switch (node->getType().getBasicType()) {
8030 case EbtFloat: op = EOpConvFloatToFloat16; break;
8031 case EbtInt8: op = EOpConvInt8ToFloat16; break;
8032 case EbtUint8: op = EOpConvUint8ToFloat16; break;
8033 case EbtInt: op = EOpConvIntToFloat16; break;
8034 case EbtUint: op = EOpConvUintToFloat16; break;
8040 node = intermediate.addUnaryNode(op, node, node->getLoc(), type);
8041 // If it's a (non-specialization) constant, it must be folded.
8042 if (node->getAsUnaryNode()->getOperand()->getAsConstantUnion())
8043 return node->getAsUnaryNode()->getOperand()->getAsConstantUnion()->fold(op, node->getType());
8048 case EOpConstructAccStruct:
8049 if ((node->getType().isScalar() && node->getType().getBasicType() == EbtUint64)) {
8050 // construct acceleration structure from uint64
8051 requireExtensions(loc, 1, &E_GL_EXT_ray_tracing, "uint64_t conversion to acclerationStructureEXT");
8052 return intermediate.addBuiltInFunctionCall(node->getLoc(), EOpConvUint64ToAccStruct, true, node,
8054 } else if (node->getType().isVector() && node->getType().getBasicType() == EbtUint && node->getVectorSize() == 2) {
8055 // construct acceleration structure from uint64
8056 requireExtensions(loc, 1, &E_GL_EXT_ray_tracing, "uvec2 conversion to accelerationStructureEXT");
8057 return intermediate.addBuiltInFunctionCall(node->getLoc(), EOpConvUvec2ToAccStruct, true, node,
8061 #endif // GLSLANG_WEB
8064 error(loc, "unsupported construction", "", "");
8068 newNode = intermediate.addUnaryMath(basicOp, node, node->getLoc());
8069 if (newNode == nullptr) {
8070 error(loc, "can't convert", "constructor", "");
8075 // Now, if there still isn't an operation to do the construction, and we need one, add one.
8078 // Otherwise, skip out early.
8079 if (subset || (newNode != node && newNode->getType() == type))
8082 // setAggregateOperator will insert a new node for the constructor, as needed.
8083 return intermediate.setAggregateOperator(newNode, op, type, loc);
8086 // This function tests for the type of the parameters to the structure or array constructor. Raises
8087 // an error message if the expected type does not match the parameter passed to the constructor.
8089 // Returns nullptr for an error or the input node itself if the expected and the given parameter types match.
8091 TIntermTyped* TParseContext::constructAggregate(TIntermNode* node, const TType& type, int paramCount, const TSourceLoc& loc)
8093 TIntermTyped* converted = intermediate.addConversion(EOpConstructStruct, type, node->getAsTyped());
8094 if (! converted || converted->getType() != type) {
8095 error(loc, "", "constructor", "cannot convert parameter %d from '%s' to '%s'", paramCount,
8096 node->getAsTyped()->getType().getCompleteString().c_str(), type.getCompleteString().c_str());
8104 // If a memory qualifier is present in 'to', also make it present in 'from'.
8105 void TParseContext::inheritMemoryQualifiers(const TQualifier& from, TQualifier& to)
8108 if (from.isReadOnly())
8109 to.readonly = from.readonly;
8110 if (from.isWriteOnly())
8111 to.writeonly = from.writeonly;
8113 to.coherent = from.coherent;
8115 to.volatil = from.volatil;
8117 to.restrict = from.restrict;
8122 // Do everything needed to add an interface block.
8124 void TParseContext::declareBlock(const TSourceLoc& loc, TTypeList& typeList, const TString* instanceName,
8125 TArraySizes* arraySizes)
8127 if (spvVersion.vulkan > 0 && spvVersion.vulkanRelaxed)
8128 blockStorageRemap(loc, blockName, currentBlockQualifier);
8129 blockStageIoCheck(loc, currentBlockQualifier);
8130 blockQualifierCheck(loc, currentBlockQualifier, instanceName != nullptr);
8131 if (arraySizes != nullptr) {
8132 arraySizesCheck(loc, currentBlockQualifier, arraySizes, nullptr, false);
8133 arrayOfArrayVersionCheck(loc, arraySizes);
8134 if (arraySizes->getNumDims() > 1)
8135 requireProfile(loc, ~EEsProfile, "array-of-array of block");
8138 // Inherit and check member storage qualifiers WRT to the block-level qualifier.
8139 for (unsigned int member = 0; member < typeList.size(); ++member) {
8140 TType& memberType = *typeList[member].type;
8141 TQualifier& memberQualifier = memberType.getQualifier();
8142 const TSourceLoc& memberLoc = typeList[member].loc;
8143 if (memberQualifier.storage != EvqTemporary && memberQualifier.storage != EvqGlobal && memberQualifier.storage != currentBlockQualifier.storage)
8144 error(memberLoc, "member storage qualifier cannot contradict block storage qualifier", memberType.getFieldName().c_str(), "");
8145 memberQualifier.storage = currentBlockQualifier.storage;
8146 globalQualifierFixCheck(memberLoc, memberQualifier);
8148 inheritMemoryQualifiers(currentBlockQualifier, memberQualifier);
8149 if (currentBlockQualifier.perPrimitiveNV)
8150 memberQualifier.perPrimitiveNV = currentBlockQualifier.perPrimitiveNV;
8151 if (currentBlockQualifier.perViewNV)
8152 memberQualifier.perViewNV = currentBlockQualifier.perViewNV;
8153 if (currentBlockQualifier.perTaskNV)
8154 memberQualifier.perTaskNV = currentBlockQualifier.perTaskNV;
8155 if (memberQualifier.storage == EvqSpirvStorageClass)
8156 error(memberLoc, "member cannot have a spirv_storage_class qualifier", memberType.getFieldName().c_str(), "");
8157 if (memberQualifier.hasSprivDecorate() && !memberQualifier.getSpirvDecorate().decorateIds.empty())
8158 error(memberLoc, "member cannot have a spirv_decorate_id qualifier", memberType.getFieldName().c_str(), "");
8160 if ((currentBlockQualifier.storage == EvqUniform || currentBlockQualifier.storage == EvqBuffer) && (memberQualifier.isInterpolation() || memberQualifier.isAuxiliary()))
8161 error(memberLoc, "member of uniform or buffer block cannot have an auxiliary or interpolation qualifier", memberType.getFieldName().c_str(), "");
8162 if (memberType.isArray())
8163 arraySizesCheck(memberLoc, currentBlockQualifier, memberType.getArraySizes(), nullptr, member == typeList.size() - 1);
8164 if (memberQualifier.hasOffset()) {
8165 if (spvVersion.spv == 0) {
8166 profileRequires(memberLoc, ~EEsProfile, 440, E_GL_ARB_enhanced_layouts, "\"offset\" on block member");
8167 profileRequires(memberLoc, EEsProfile, 300, E_GL_ARB_enhanced_layouts, "\"offset\" on block member");
8171 if (memberType.containsOpaque())
8172 error(memberLoc, "member of block cannot be or contain a sampler, image, or atomic_uint type", typeList[member].type->getFieldName().c_str(), "");
8174 if (memberType.containsCoopMat())
8175 error(memberLoc, "member of block cannot be or contain a cooperative matrix type", typeList[member].type->getFieldName().c_str(), "");
8178 // This might be a redeclaration of a built-in block. If so, redeclareBuiltinBlock() will
8180 if (! symbolTable.atBuiltInLevel() && builtInName(*blockName)) {
8181 redeclareBuiltinBlock(loc, typeList, *blockName, instanceName, arraySizes);
8185 // Not a redeclaration of a built-in; check that all names are user names.
8186 reservedErrorCheck(loc, *blockName);
8188 reservedErrorCheck(loc, *instanceName);
8189 for (unsigned int member = 0; member < typeList.size(); ++member)
8190 reservedErrorCheck(typeList[member].loc, typeList[member].type->getFieldName());
8192 // Make default block qualification, and adjust the member qualifications
8194 TQualifier defaultQualification;
8195 switch (currentBlockQualifier.storage) {
8196 case EvqUniform: defaultQualification = globalUniformDefaults; break;
8197 case EvqBuffer: defaultQualification = globalBufferDefaults; break;
8198 case EvqVaryingIn: defaultQualification = globalInputDefaults; break;
8199 case EvqVaryingOut: defaultQualification = globalOutputDefaults; break;
8200 case EvqShared: defaultQualification = globalSharedDefaults; break;
8201 default: defaultQualification.clear(); break;
8204 // Special case for "push_constant uniform", which has a default of std430,
8205 // contrary to normal uniform defaults, and can't have a default tracked for it.
8206 if ((currentBlockQualifier.isPushConstant() && !currentBlockQualifier.hasPacking()) ||
8207 (currentBlockQualifier.isShaderRecord() && !currentBlockQualifier.hasPacking()))
8208 currentBlockQualifier.layoutPacking = ElpStd430;
8210 // Special case for "taskNV in/out", which has a default of std430,
8211 if (currentBlockQualifier.isTaskMemory() && !currentBlockQualifier.hasPacking())
8212 currentBlockQualifier.layoutPacking = ElpStd430;
8214 // fix and check for member layout qualifiers
8216 mergeObjectLayoutQualifiers(defaultQualification, currentBlockQualifier, true);
8218 // "The align qualifier can only be used on blocks or block members, and only for blocks declared with std140 or std430 layouts."
8219 if (currentBlockQualifier.hasAlign()) {
8220 if (defaultQualification.layoutPacking != ElpStd140 &&
8221 defaultQualification.layoutPacking != ElpStd430 &&
8222 defaultQualification.layoutPacking != ElpScalar) {
8223 error(loc, "can only be used with std140, std430, or scalar layout packing", "align", "");
8224 defaultQualification.layoutAlign = -1;
8228 bool memberWithLocation = false;
8229 bool memberWithoutLocation = false;
8230 bool memberWithPerViewQualifier = false;
8231 for (unsigned int member = 0; member < typeList.size(); ++member) {
8232 TQualifier& memberQualifier = typeList[member].type->getQualifier();
8233 const TSourceLoc& memberLoc = typeList[member].loc;
8235 if (memberQualifier.hasStream()) {
8236 if (defaultQualification.layoutStream != memberQualifier.layoutStream)
8237 error(memberLoc, "member cannot contradict block", "stream", "");
8240 // "This includes a block's inheritance of the
8241 // current global default buffer, a block member's inheritance of the block's
8242 // buffer, and the requirement that any *xfb_buffer* declared on a block
8243 // member must match the buffer inherited from the block."
8244 if (memberQualifier.hasXfbBuffer()) {
8245 if (defaultQualification.layoutXfbBuffer != memberQualifier.layoutXfbBuffer)
8246 error(memberLoc, "member cannot contradict block (or what block inherited from global)", "xfb_buffer", "");
8250 if (memberQualifier.hasPacking())
8251 error(memberLoc, "member of block cannot have a packing layout qualifier", typeList[member].type->getFieldName().c_str(), "");
8252 if (memberQualifier.hasLocation()) {
8253 const char* feature = "location on block member";
8254 switch (currentBlockQualifier.storage) {
8258 requireProfile(memberLoc, ECoreProfile | ECompatibilityProfile | EEsProfile, feature);
8259 profileRequires(memberLoc, ECoreProfile | ECompatibilityProfile, 440, E_GL_ARB_enhanced_layouts, feature);
8260 profileRequires(memberLoc, EEsProfile, 320, Num_AEP_shader_io_blocks, AEP_shader_io_blocks, feature);
8261 memberWithLocation = true;
8265 error(memberLoc, "can only use in an in/out block", feature, "");
8269 memberWithoutLocation = true;
8271 // "The offset qualifier can only be used on block members of blocks declared with std140 or std430 layouts."
8272 // "The align qualifier can only be used on blocks or block members, and only for blocks declared with std140 or std430 layouts."
8273 if (memberQualifier.hasAlign() || memberQualifier.hasOffset()) {
8274 if (defaultQualification.layoutPacking != ElpStd140 &&
8275 defaultQualification.layoutPacking != ElpStd430 &&
8276 defaultQualification.layoutPacking != ElpScalar)
8277 error(memberLoc, "can only be used with std140, std430, or scalar layout packing", "offset/align", "");
8280 if (memberQualifier.isPerView()) {
8281 memberWithPerViewQualifier = true;
8284 TQualifier newMemberQualification = defaultQualification;
8285 mergeQualifiers(memberLoc, newMemberQualification, memberQualifier, false);
8286 memberQualifier = newMemberQualification;
8289 layoutMemberLocationArrayCheck(loc, memberWithLocation, arraySizes);
8292 // Ensure that the block has an XfbBuffer assigned. This is needed
8293 // because if the block has a XfbOffset assigned, then it is
8294 // assumed that it has implicitly assigned the current global
8295 // XfbBuffer, and because it's members need to be assigned a
8296 // XfbOffset if they lack it.
8297 if (currentBlockQualifier.storage == EvqVaryingOut && globalOutputDefaults.hasXfbBuffer()) {
8298 if (!currentBlockQualifier.hasXfbBuffer() && currentBlockQualifier.hasXfbOffset())
8299 currentBlockQualifier.layoutXfbBuffer = globalOutputDefaults.layoutXfbBuffer;
8303 // Process the members
8304 fixBlockLocations(loc, currentBlockQualifier, typeList, memberWithLocation, memberWithoutLocation);
8305 fixXfbOffsets(currentBlockQualifier, typeList);
8306 fixBlockUniformOffsets(currentBlockQualifier, typeList);
8307 fixBlockUniformLayoutMatrix(currentBlockQualifier, &typeList, nullptr);
8308 fixBlockUniformLayoutPacking(currentBlockQualifier, &typeList, nullptr);
8309 for (unsigned int member = 0; member < typeList.size(); ++member)
8310 layoutTypeCheck(typeList[member].loc, *typeList[member].type);
8313 if (memberWithPerViewQualifier) {
8314 for (unsigned int member = 0; member < typeList.size(); ++member) {
8315 checkAndResizeMeshViewDim(typeList[member].loc, *typeList[member].type, /*isBlockMember*/ true);
8320 // reverse merge, so that currentBlockQualifier now has all layout information
8321 // (can't use defaultQualification directly, it's missing other non-layout-default-class qualifiers)
8322 mergeObjectLayoutQualifiers(currentBlockQualifier, defaultQualification, true);
8325 // Build and add the interface block as a new type named 'blockName'
8328 TType blockType(&typeList, *blockName, currentBlockQualifier);
8329 if (arraySizes != nullptr)
8330 blockType.transferArraySizes(arraySizes);
8333 if (arraySizes == nullptr)
8334 ioArrayCheck(loc, blockType, instanceName ? *instanceName : *blockName);
8335 if (currentBlockQualifier.hasBufferReference()) {
8337 if (currentBlockQualifier.storage != EvqBuffer)
8338 error(loc, "can only be used with buffer", "buffer_reference", "");
8340 // Create the block reference type. If it was forward-declared, detect that
8341 // as a referent struct type with no members. Replace the referent type with
8343 TType blockNameType(EbtReference, blockType, *blockName);
8344 TVariable* blockNameVar = new TVariable(blockName, blockNameType, true);
8345 if (! symbolTable.insert(*blockNameVar)) {
8346 TSymbol* existingName = symbolTable.find(*blockName);
8347 if (existingName->getType().isReference() &&
8348 existingName->getType().getReferentType()->getStruct() &&
8349 existingName->getType().getReferentType()->getStruct()->size() == 0 &&
8350 existingName->getType().getQualifier().storage == blockType.getQualifier().storage) {
8351 existingName->getType().getReferentType()->deepCopy(blockType);
8353 error(loc, "block name cannot be redefined", blockName->c_str(), "");
8356 if (!instanceName) {
8363 // Don't make a user-defined type out of block name; that will cause an error
8364 // if the same block name gets reused in a different interface.
8366 // "Block names have no other use within a shader
8367 // beyond interface matching; it is a compile-time error to use a block name at global scope for anything
8368 // other than as a block name (e.g., use of a block name for a global variable name or function name is
8369 // currently reserved)."
8371 // Use the symbol table to prevent normal reuse of the block's name, as a variable entry,
8372 // whose type is EbtBlock, but without all the structure; that will come from the type
8373 // the instances point to.
8375 TType blockNameType(EbtBlock, blockType.getQualifier().storage);
8376 TVariable* blockNameVar = new TVariable(blockName, blockNameType);
8377 if (! symbolTable.insert(*blockNameVar)) {
8378 TSymbol* existingName = symbolTable.find(*blockName);
8379 if (existingName->getType().getBasicType() == EbtBlock) {
8380 if (existingName->getType().getQualifier().storage == blockType.getQualifier().storage) {
8381 error(loc, "Cannot reuse block name within the same interface:", blockName->c_str(), blockType.getStorageQualifierString());
8385 error(loc, "block name cannot redefine a non-block name", blockName->c_str(), "");
8391 // Add the variable, as anonymous or named instanceName.
8392 // Make an anonymous variable if no name was provided.
8394 instanceName = NewPoolTString("");
8396 TVariable& variable = *new TVariable(instanceName, blockType);
8397 if (! symbolTable.insert(variable)) {
8398 if (*instanceName == "")
8399 error(loc, "nameless block contains a member that already has a name at global scope", blockName->c_str(), "");
8401 error(loc, "block instance name redefinition", variable.getName().c_str(), "");
8406 // Check for general layout qualifier errors
8407 layoutObjectCheck(loc, variable);
8411 if (isIoResizeArray(blockType)) {
8412 ioArraySymbolResizeList.push_back(&variable);
8413 checkIoArraysConsistency(loc, true);
8415 fixIoArraySize(loc, variable.getWritableType());
8418 // Save it in the AST for linker use.
8419 trackLinkage(variable);
8423 // allow storage type of block to be remapped at compile time
8425 void TParseContext::blockStorageRemap(const TSourceLoc&, const TString* instanceName, TQualifier& qualifier)
8427 TBlockStorageClass type = intermediate.getBlockStorageOverride(instanceName->c_str());
8428 if (type != EbsNone) {
8429 qualifier.setBlockStorage(type);
8433 // Do all block-declaration checking regarding the combination of in/out/uniform/buffer
8434 // with a particular stage.
8435 void TParseContext::blockStageIoCheck(const TSourceLoc& loc, const TQualifier& qualifier)
8437 const char *extsrt[2] = { E_GL_NV_ray_tracing, E_GL_EXT_ray_tracing };
8438 switch (qualifier.storage) {
8440 profileRequires(loc, EEsProfile, 300, nullptr, "uniform block");
8441 profileRequires(loc, ENoProfile, 140, E_GL_ARB_uniform_buffer_object, "uniform block");
8442 if (currentBlockQualifier.layoutPacking == ElpStd430 && ! currentBlockQualifier.isPushConstant())
8443 requireExtensions(loc, 1, &E_GL_EXT_scalar_block_layout, "std430 requires the buffer storage qualifier");
8446 requireProfile(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, "buffer block");
8447 profileRequires(loc, ECoreProfile | ECompatibilityProfile, 430, E_GL_ARB_shader_storage_buffer_object, "buffer block");
8448 profileRequires(loc, EEsProfile, 310, nullptr, "buffer block");
8451 profileRequires(loc, ~EEsProfile, 150, E_GL_ARB_separate_shader_objects, "input block");
8452 // It is a compile-time error to have an input block in a vertex shader or an output block in a fragment shader
8453 // "Compute shaders do not permit user-defined input variables..."
8454 requireStage(loc, (EShLanguageMask)(EShLangTessControlMask|EShLangTessEvaluationMask|EShLangGeometryMask|
8455 EShLangFragmentMask|EShLangMeshNVMask), "input block");
8456 if (language == EShLangFragment) {
8457 profileRequires(loc, EEsProfile, 320, Num_AEP_shader_io_blocks, AEP_shader_io_blocks, "fragment input block");
8458 } else if (language == EShLangMeshNV && ! qualifier.isTaskMemory()) {
8459 error(loc, "input blocks cannot be used in a mesh shader", "out", "");
8463 profileRequires(loc, ~EEsProfile, 150, E_GL_ARB_separate_shader_objects, "output block");
8464 requireStage(loc, (EShLanguageMask)(EShLangVertexMask|EShLangTessControlMask|EShLangTessEvaluationMask|
8465 EShLangGeometryMask|EShLangMeshNVMask|EShLangTaskNVMask), "output block");
8466 // ES 310 can have a block before shader_io is turned on, so skip this test for built-ins
8467 if (language == EShLangVertex && ! parsingBuiltins) {
8468 profileRequires(loc, EEsProfile, 320, Num_AEP_shader_io_blocks, AEP_shader_io_blocks, "vertex output block");
8469 } else if (language == EShLangMeshNV && qualifier.isTaskMemory()) {
8470 error(loc, "can only use on input blocks in mesh shader", "taskNV", "");
8471 } else if (language == EShLangTaskNV && ! qualifier.isTaskMemory()) {
8472 error(loc, "output blocks cannot be used in a task shader", "out", "");
8476 if (spvVersion.spv > 0 && spvVersion.spv < EShTargetSpv_1_4) {
8477 error(loc, "shared block requires at least SPIR-V 1.4", "shared block", "");
8479 profileRequires(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, 0, E_GL_EXT_shared_memory_block, "shared block");
8483 profileRequires(loc, ~EEsProfile, 460, 2, extsrt, "rayPayloadNV block");
8484 requireStage(loc, (EShLanguageMask)(EShLangRayGenMask | EShLangAnyHitMask | EShLangClosestHitMask | EShLangMissMask),
8485 "rayPayloadNV block");
8488 profileRequires(loc, ~EEsProfile, 460, 2, extsrt, "rayPayloadInNV block");
8489 requireStage(loc, (EShLanguageMask)(EShLangAnyHitMask | EShLangClosestHitMask | EShLangMissMask),
8490 "rayPayloadInNV block");
8493 profileRequires(loc, ~EEsProfile, 460, 2, extsrt, "hitAttributeNV block");
8494 requireStage(loc, (EShLanguageMask)(EShLangIntersectMask | EShLangAnyHitMask | EShLangClosestHitMask), "hitAttributeNV block");
8496 case EvqCallableData:
8497 profileRequires(loc, ~EEsProfile, 460, 2, extsrt, "callableDataNV block");
8498 requireStage(loc, (EShLanguageMask)(EShLangRayGenMask | EShLangClosestHitMask | EShLangMissMask | EShLangCallableMask),
8499 "callableDataNV block");
8501 case EvqCallableDataIn:
8502 profileRequires(loc, ~EEsProfile, 460, 2, extsrt, "callableDataInNV block");
8503 requireStage(loc, (EShLanguageMask)(EShLangCallableMask), "callableDataInNV block");
8507 error(loc, "only uniform, buffer, in, or out blocks are supported", blockName->c_str(), "");
8512 // Do all block-declaration checking regarding its qualifiers.
8513 void TParseContext::blockQualifierCheck(const TSourceLoc& loc, const TQualifier& qualifier, bool /*instanceName*/)
8515 // The 4.5 specification says:
8517 // interface-block :
8518 // layout-qualifieropt interface-qualifier block-name { member-list } instance-nameopt ;
8520 // interface-qualifier :
8528 // Note however memory qualifiers aren't included, yet the specification also says
8530 // "...memory qualifiers may also be used in the declaration of shader storage blocks..."
8532 if (qualifier.isInterpolation())
8533 error(loc, "cannot use interpolation qualifiers on an interface block", "flat/smooth/noperspective", "");
8534 if (qualifier.centroid)
8535 error(loc, "cannot use centroid qualifier on an interface block", "centroid", "");
8536 if (qualifier.isSample())
8537 error(loc, "cannot use sample qualifier on an interface block", "sample", "");
8538 if (qualifier.invariant)
8539 error(loc, "cannot use invariant qualifier on an interface block", "invariant", "");
8540 if (qualifier.isPushConstant())
8541 intermediate.addPushConstantCount();
8542 if (qualifier.isShaderRecord())
8543 intermediate.addShaderRecordCount();
8544 if (qualifier.isTaskMemory())
8545 intermediate.addTaskNVCount();
8549 // "For a block, this process applies to the entire block, or until the first member
8550 // is reached that has a location layout qualifier. When a block member is declared with a location
8551 // qualifier, its location comes from that qualifier: The member's location qualifier overrides the block-level
8552 // declaration. Subsequent members are again assigned consecutive locations, based on the newest location,
8553 // until the next member declared with a location qualifier. The values used for locations do not have to be
8554 // declared in increasing order."
8555 void TParseContext::fixBlockLocations(const TSourceLoc& loc, TQualifier& qualifier, TTypeList& typeList, bool memberWithLocation, bool memberWithoutLocation)
8557 // "If a block has no block-level location layout qualifier, it is required that either all or none of its members
8558 // have a location layout qualifier, or a compile-time error results."
8559 if (! qualifier.hasLocation() && memberWithLocation && memberWithoutLocation)
8560 error(loc, "either the block needs a location, or all members need a location, or no members have a location", "location", "");
8562 if (memberWithLocation) {
8563 // remove any block-level location and make it per *every* member
8564 int nextLocation = 0; // by the rule above, initial value is not relevant
8565 if (qualifier.hasAnyLocation()) {
8566 nextLocation = qualifier.layoutLocation;
8567 qualifier.layoutLocation = TQualifier::layoutLocationEnd;
8568 if (qualifier.hasComponent()) {
8569 // "It is a compile-time error to apply the *component* qualifier to a ... block"
8570 error(loc, "cannot apply to a block", "component", "");
8572 if (qualifier.hasIndex()) {
8573 error(loc, "cannot apply to a block", "index", "");
8576 for (unsigned int member = 0; member < typeList.size(); ++member) {
8577 TQualifier& memberQualifier = typeList[member].type->getQualifier();
8578 const TSourceLoc& memberLoc = typeList[member].loc;
8579 if (! memberQualifier.hasLocation()) {
8580 if (nextLocation >= (int)TQualifier::layoutLocationEnd)
8581 error(memberLoc, "location is too large", "location", "");
8582 memberQualifier.layoutLocation = nextLocation;
8583 memberQualifier.layoutComponent = TQualifier::layoutComponentEnd;
8585 nextLocation = memberQualifier.layoutLocation + intermediate.computeTypeLocationSize(
8586 *typeList[member].type, language);
8592 void TParseContext::fixXfbOffsets(TQualifier& qualifier, TTypeList& typeList)
8595 // "If a block is qualified with xfb_offset, all its
8596 // members are assigned transform feedback buffer offsets. If a block is not qualified with xfb_offset, any
8597 // members of that block not qualified with an xfb_offset will not be assigned transform feedback buffer
8600 if (! qualifier.hasXfbBuffer() || ! qualifier.hasXfbOffset())
8603 int nextOffset = qualifier.layoutXfbOffset;
8604 for (unsigned int member = 0; member < typeList.size(); ++member) {
8605 TQualifier& memberQualifier = typeList[member].type->getQualifier();
8606 bool contains64BitType = false;
8607 bool contains32BitType = false;
8608 bool contains16BitType = false;
8609 int memberSize = intermediate.computeTypeXfbSize(*typeList[member].type, contains64BitType, contains32BitType, contains16BitType);
8610 // see if we need to auto-assign an offset to this member
8611 if (! memberQualifier.hasXfbOffset()) {
8612 // "if applied to an aggregate containing a double or 64-bit integer, the offset must also be a multiple of 8"
8613 if (contains64BitType)
8614 RoundToPow2(nextOffset, 8);
8615 else if (contains32BitType)
8616 RoundToPow2(nextOffset, 4);
8617 else if (contains16BitType)
8618 RoundToPow2(nextOffset, 2);
8619 memberQualifier.layoutXfbOffset = nextOffset;
8621 nextOffset = memberQualifier.layoutXfbOffset;
8622 nextOffset += memberSize;
8625 // The above gave all block members an offset, so we can take it off the block now,
8626 // which will avoid double counting the offset usage.
8627 qualifier.layoutXfbOffset = TQualifier::layoutXfbOffsetEnd;
8631 // Calculate and save the offset of each block member, using the recursively
8632 // defined block offset rules and the user-provided offset and align.
8634 // Also, compute and save the total size of the block. For the block's size, arrayness
8635 // is not taken into account, as each element is backed by a separate buffer.
8637 void TParseContext::fixBlockUniformOffsets(TQualifier& qualifier, TTypeList& typeList)
8639 if (!storageCanHaveLayoutInBlock(qualifier.storage) && !qualifier.isTaskMemory())
8641 if (qualifier.layoutPacking != ElpStd140 && qualifier.layoutPacking != ElpStd430 && qualifier.layoutPacking != ElpScalar)
8646 for (unsigned int member = 0; member < typeList.size(); ++member) {
8647 TQualifier& memberQualifier = typeList[member].type->getQualifier();
8648 const TSourceLoc& memberLoc = typeList[member].loc;
8650 // "When align is applied to an array, it effects only the start of the array, not the array's internal stride."
8652 // modify just the children's view of matrix layout, if there is one for this member
8653 TLayoutMatrix subMatrixLayout = typeList[member].type->getQualifier().layoutMatrix;
8655 int memberAlignment = intermediate.getMemberAlignment(*typeList[member].type, memberSize, dummyStride, qualifier.layoutPacking,
8656 subMatrixLayout != ElmNone ? subMatrixLayout == ElmRowMajor : qualifier.layoutMatrix == ElmRowMajor);
8657 if (memberQualifier.hasOffset()) {
8658 // "The specified offset must be a multiple
8659 // of the base alignment of the type of the block member it qualifies, or a compile-time error results."
8660 if (! IsMultipleOfPow2(memberQualifier.layoutOffset, memberAlignment))
8661 error(memberLoc, "must be a multiple of the member's alignment", "offset", "");
8663 // GLSL: "It is a compile-time error to specify an offset that is smaller than the offset of the previous
8664 // member in the block or that lies within the previous member of the block"
8665 if (spvVersion.spv == 0) {
8666 if (memberQualifier.layoutOffset < offset)
8667 error(memberLoc, "cannot lie in previous members", "offset", "");
8669 // "The offset qualifier forces the qualified member to start at or after the specified
8670 // integral-constant expression, which will be its byte offset from the beginning of the buffer.
8671 // "The actual offset of a member is computed as
8672 // follows: If offset was declared, start with that offset, otherwise start with the next available offset."
8673 offset = std::max(offset, memberQualifier.layoutOffset);
8675 // TODO: Vulkan: "It is a compile-time error to have any offset, explicit or assigned,
8676 // that lies within another member of the block."
8678 offset = memberQualifier.layoutOffset;
8682 // "The actual alignment of a member will be the greater of the specified align alignment and the standard
8683 // (e.g., std140) base alignment for the member's type."
8684 if (memberQualifier.hasAlign())
8685 memberAlignment = std::max(memberAlignment, memberQualifier.layoutAlign);
8687 // "If the resulting offset is not a multiple of the actual alignment,
8688 // increase it to the first offset that is a multiple of
8689 // the actual alignment."
8690 RoundToPow2(offset, memberAlignment);
8691 typeList[member].type->getQualifier().layoutOffset = offset;
8692 offset += memberSize;
8697 // Spread LayoutMatrix to uniform block member, if a uniform block member is a struct,
8698 // we need spread LayoutMatrix to this struct member too. and keep this rule for recursive.
8700 void TParseContext::fixBlockUniformLayoutMatrix(TQualifier& qualifier, TTypeList* originTypeList,
8701 TTypeList* tmpTypeList)
8703 assert(tmpTypeList == nullptr || originTypeList->size() == tmpTypeList->size());
8704 for (unsigned int member = 0; member < originTypeList->size(); ++member) {
8705 if (qualifier.layoutPacking != ElpNone) {
8706 if (tmpTypeList == nullptr) {
8707 if (((*originTypeList)[member].type->isMatrix() ||
8708 (*originTypeList)[member].type->getBasicType() == EbtStruct) &&
8709 (*originTypeList)[member].type->getQualifier().layoutMatrix == ElmNone) {
8710 (*originTypeList)[member].type->getQualifier().layoutMatrix = qualifier.layoutMatrix;
8713 if (((*tmpTypeList)[member].type->isMatrix() ||
8714 (*tmpTypeList)[member].type->getBasicType() == EbtStruct) &&
8715 (*tmpTypeList)[member].type->getQualifier().layoutMatrix == ElmNone) {
8716 (*tmpTypeList)[member].type->getQualifier().layoutMatrix = qualifier.layoutMatrix;
8721 if ((*originTypeList)[member].type->getBasicType() == EbtStruct) {
8722 TQualifier* memberQualifier = nullptr;
8723 // block member can be declare a matrix style, so it should be update to the member's style
8724 if ((*originTypeList)[member].type->getQualifier().layoutMatrix == ElmNone) {
8725 memberQualifier = &qualifier;
8727 memberQualifier = &((*originTypeList)[member].type->getQualifier());
8730 const TType* tmpType = tmpTypeList == nullptr ?
8731 (*originTypeList)[member].type->clone() : (*tmpTypeList)[member].type;
8733 fixBlockUniformLayoutMatrix(*memberQualifier, (*originTypeList)[member].type->getWritableStruct(),
8734 tmpType->getWritableStruct());
8736 const TTypeList* structure = recordStructCopy(matrixFixRecord, (*originTypeList)[member].type, tmpType);
8738 if (tmpTypeList == nullptr) {
8739 (*originTypeList)[member].type->setStruct(const_cast<TTypeList*>(structure));
8741 if (tmpTypeList != nullptr) {
8742 (*tmpTypeList)[member].type->setStruct(const_cast<TTypeList*>(structure));
8749 // Spread LayoutPacking to matrix or aggregate block members. If a block member is a struct or
8750 // array of struct, spread LayoutPacking recursively to its matrix or aggregate members.
8752 void TParseContext::fixBlockUniformLayoutPacking(TQualifier& qualifier, TTypeList* originTypeList,
8753 TTypeList* tmpTypeList)
8755 assert(tmpTypeList == nullptr || originTypeList->size() == tmpTypeList->size());
8756 for (unsigned int member = 0; member < originTypeList->size(); ++member) {
8757 if (qualifier.layoutPacking != ElpNone) {
8758 if (tmpTypeList == nullptr) {
8759 if ((*originTypeList)[member].type->getQualifier().layoutPacking == ElpNone &&
8760 !(*originTypeList)[member].type->isScalarOrVector()) {
8761 (*originTypeList)[member].type->getQualifier().layoutPacking = qualifier.layoutPacking;
8764 if ((*tmpTypeList)[member].type->getQualifier().layoutPacking == ElpNone &&
8765 !(*tmpTypeList)[member].type->isScalarOrVector()) {
8766 (*tmpTypeList)[member].type->getQualifier().layoutPacking = qualifier.layoutPacking;
8771 if ((*originTypeList)[member].type->getBasicType() == EbtStruct) {
8772 // Deep copy the type in pool.
8773 // Because, struct use in different block may have different layout qualifier.
8774 // We have to new a object to distinguish between them.
8775 const TType* tmpType = tmpTypeList == nullptr ?
8776 (*originTypeList)[member].type->clone() : (*tmpTypeList)[member].type;
8778 fixBlockUniformLayoutPacking(qualifier, (*originTypeList)[member].type->getWritableStruct(),
8779 tmpType->getWritableStruct());
8781 const TTypeList* structure = recordStructCopy(packingFixRecord, (*originTypeList)[member].type, tmpType);
8783 if (tmpTypeList == nullptr) {
8784 (*originTypeList)[member].type->setStruct(const_cast<TTypeList*>(structure));
8786 if (tmpTypeList != nullptr) {
8787 (*tmpTypeList)[member].type->setStruct(const_cast<TTypeList*>(structure));
8793 // For an identifier that is already declared, add more qualification to it.
8794 void TParseContext::addQualifierToExisting(const TSourceLoc& loc, TQualifier qualifier, const TString& identifier)
8796 TSymbol* symbol = symbolTable.find(identifier);
8798 // A forward declaration of a block reference looks to the grammar like adding
8799 // a qualifier to an existing symbol. Detect this and create the block reference
8800 // type with an empty type list, which will be filled in later in
8801 // TParseContext::declareBlock.
8802 if (!symbol && qualifier.hasBufferReference()) {
8804 TType blockType(&typeList, identifier, qualifier);;
8805 TType blockNameType(EbtReference, blockType, identifier);
8806 TVariable* blockNameVar = new TVariable(&identifier, blockNameType, true);
8807 if (! symbolTable.insert(*blockNameVar)) {
8808 error(loc, "block name cannot redefine a non-block name", blockName->c_str(), "");
8814 error(loc, "identifier not previously declared", identifier.c_str(), "");
8817 if (symbol->getAsFunction()) {
8818 error(loc, "cannot re-qualify a function name", identifier.c_str(), "");
8822 if (qualifier.isAuxiliary() ||
8823 qualifier.isMemory() ||
8824 qualifier.isInterpolation() ||
8825 qualifier.hasLayout() ||
8826 qualifier.storage != EvqTemporary ||
8827 qualifier.precision != EpqNone) {
8828 error(loc, "cannot add storage, auxiliary, memory, interpolation, layout, or precision qualifier to an existing variable", identifier.c_str(), "");
8832 // For read-only built-ins, add a new symbol for holding the modified qualifier.
8833 // This will bring up an entire block, if a block type has to be modified (e.g., gl_Position inside a block)
8834 if (symbol->isReadOnly())
8835 symbol = symbolTable.copyUp(symbol);
8837 if (qualifier.invariant) {
8838 if (intermediate.inIoAccessed(identifier))
8839 error(loc, "cannot change qualification after use", "invariant", "");
8840 symbol->getWritableType().getQualifier().invariant = true;
8841 invariantCheck(loc, symbol->getType().getQualifier());
8842 } else if (qualifier.isNoContraction()) {
8843 if (intermediate.inIoAccessed(identifier))
8844 error(loc, "cannot change qualification after use", "precise", "");
8845 symbol->getWritableType().getQualifier().setNoContraction();
8846 } else if (qualifier.specConstant) {
8847 symbol->getWritableType().getQualifier().makeSpecConstant();
8848 if (qualifier.hasSpecConstantId())
8849 symbol->getWritableType().getQualifier().layoutSpecConstantId = qualifier.layoutSpecConstantId;
8851 warn(loc, "unknown requalification", "", "");
8854 void TParseContext::addQualifierToExisting(const TSourceLoc& loc, TQualifier qualifier, TIdentifierList& identifiers)
8856 for (unsigned int i = 0; i < identifiers.size(); ++i)
8857 addQualifierToExisting(loc, qualifier, *identifiers[i]);
8860 // Make sure 'invariant' isn't being applied to a non-allowed object.
8861 void TParseContext::invariantCheck(const TSourceLoc& loc, const TQualifier& qualifier)
8863 if (! qualifier.invariant)
8866 bool pipeOut = qualifier.isPipeOutput();
8867 bool pipeIn = qualifier.isPipeInput();
8868 if ((version >= 300 && isEsProfile()) || (!isEsProfile() && version >= 420)) {
8870 error(loc, "can only apply to an output", "invariant", "");
8872 if ((language == EShLangVertex && pipeIn) || (! pipeOut && ! pipeIn))
8873 error(loc, "can only apply to an output, or to an input in a non-vertex stage\n", "invariant", "");
8878 // Updating default qualifier for the case of a declaration with just a qualifier,
8879 // no type, block, or identifier.
8881 void TParseContext::updateStandaloneQualifierDefaults(const TSourceLoc& loc, const TPublicType& publicType)
8884 if (publicType.shaderQualifiers.vertices != TQualifier::layoutNotSet) {
8885 assert(language == EShLangTessControl || language == EShLangGeometry || language == EShLangMeshNV);
8886 const char* id = (language == EShLangTessControl) ? "vertices" : "max_vertices";
8888 if (publicType.qualifier.storage != EvqVaryingOut)
8889 error(loc, "can only apply to 'out'", id, "");
8890 if (! intermediate.setVertices(publicType.shaderQualifiers.vertices))
8891 error(loc, "cannot change previously set layout value", id, "");
8893 if (language == EShLangTessControl)
8894 checkIoArraysConsistency(loc);
8896 if (publicType.shaderQualifiers.primitives != TQualifier::layoutNotSet) {
8897 assert(language == EShLangMeshNV);
8898 const char* id = "max_primitives";
8900 if (publicType.qualifier.storage != EvqVaryingOut)
8901 error(loc, "can only apply to 'out'", id, "");
8902 if (! intermediate.setPrimitives(publicType.shaderQualifiers.primitives))
8903 error(loc, "cannot change previously set layout value", id, "");
8905 if (publicType.shaderQualifiers.invocations != TQualifier::layoutNotSet) {
8906 if (publicType.qualifier.storage != EvqVaryingIn)
8907 error(loc, "can only apply to 'in'", "invocations", "");
8908 if (! intermediate.setInvocations(publicType.shaderQualifiers.invocations))
8909 error(loc, "cannot change previously set layout value", "invocations", "");
8911 if (publicType.shaderQualifiers.geometry != ElgNone) {
8912 if (publicType.qualifier.storage == EvqVaryingIn) {
8913 switch (publicType.shaderQualifiers.geometry) {
8916 case ElgLinesAdjacency:
8918 case ElgTrianglesAdjacency:
8921 if (language == EShLangMeshNV) {
8922 error(loc, "cannot apply to input", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
8925 if (intermediate.setInputPrimitive(publicType.shaderQualifiers.geometry)) {
8926 if (language == EShLangGeometry)
8927 checkIoArraysConsistency(loc);
8929 error(loc, "cannot change previously set input primitive", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
8932 error(loc, "cannot apply to input", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
8934 } else if (publicType.qualifier.storage == EvqVaryingOut) {
8935 switch (publicType.shaderQualifiers.geometry) {
8938 if (language != EShLangMeshNV) {
8939 error(loc, "cannot apply to 'out'", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
8945 case ElgTriangleStrip:
8946 if (! intermediate.setOutputPrimitive(publicType.shaderQualifiers.geometry))
8947 error(loc, "cannot change previously set output primitive", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
8950 error(loc, "cannot apply to 'out'", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
8953 error(loc, "cannot apply to:", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), GetStorageQualifierString(publicType.qualifier.storage));
8955 if (publicType.shaderQualifiers.spacing != EvsNone) {
8956 if (publicType.qualifier.storage == EvqVaryingIn) {
8957 if (! intermediate.setVertexSpacing(publicType.shaderQualifiers.spacing))
8958 error(loc, "cannot change previously set vertex spacing", TQualifier::getVertexSpacingString(publicType.shaderQualifiers.spacing), "");
8960 error(loc, "can only apply to 'in'", TQualifier::getVertexSpacingString(publicType.shaderQualifiers.spacing), "");
8962 if (publicType.shaderQualifiers.order != EvoNone) {
8963 if (publicType.qualifier.storage == EvqVaryingIn) {
8964 if (! intermediate.setVertexOrder(publicType.shaderQualifiers.order))
8965 error(loc, "cannot change previously set vertex order", TQualifier::getVertexOrderString(publicType.shaderQualifiers.order), "");
8967 error(loc, "can only apply to 'in'", TQualifier::getVertexOrderString(publicType.shaderQualifiers.order), "");
8969 if (publicType.shaderQualifiers.pointMode) {
8970 if (publicType.qualifier.storage == EvqVaryingIn)
8971 intermediate.setPointMode();
8973 error(loc, "can only apply to 'in'", "point_mode", "");
8976 for (int i = 0; i < 3; ++i) {
8977 if (publicType.shaderQualifiers.localSizeNotDefault[i]) {
8978 if (publicType.qualifier.storage == EvqVaryingIn) {
8979 if (! intermediate.setLocalSize(i, publicType.shaderQualifiers.localSize[i]))
8980 error(loc, "cannot change previously set size", "local_size", "");
8983 if (language == EShLangCompute) {
8985 case 0: max = resources.maxComputeWorkGroupSizeX; break;
8986 case 1: max = resources.maxComputeWorkGroupSizeY; break;
8987 case 2: max = resources.maxComputeWorkGroupSizeZ; break;
8990 if (intermediate.getLocalSize(i) > (unsigned int)max)
8991 error(loc, "too large; see gl_MaxComputeWorkGroupSize", "local_size", "");
8994 else if (language == EShLangMeshNV) {
8996 case 0: max = resources.maxMeshWorkGroupSizeX_NV; break;
8997 case 1: max = resources.maxMeshWorkGroupSizeY_NV; break;
8998 case 2: max = resources.maxMeshWorkGroupSizeZ_NV; break;
9001 if (intermediate.getLocalSize(i) > (unsigned int)max)
9002 error(loc, "too large; see gl_MaxMeshWorkGroupSizeNV", "local_size", "");
9003 } else if (language == EShLangTaskNV) {
9005 case 0: max = resources.maxTaskWorkGroupSizeX_NV; break;
9006 case 1: max = resources.maxTaskWorkGroupSizeY_NV; break;
9007 case 2: max = resources.maxTaskWorkGroupSizeZ_NV; break;
9010 if (intermediate.getLocalSize(i) > (unsigned int)max)
9011 error(loc, "too large; see gl_MaxTaskWorkGroupSizeNV", "local_size", "");
9018 // Fix the existing constant gl_WorkGroupSize with this new information.
9019 TVariable* workGroupSize = getEditableVariable("gl_WorkGroupSize");
9020 if (workGroupSize != nullptr)
9021 workGroupSize->getWritableConstArray()[i].setUConst(intermediate.getLocalSize(i));
9024 error(loc, "can only apply to 'in'", "local_size", "");
9026 if (publicType.shaderQualifiers.localSizeSpecId[i] != TQualifier::layoutNotSet) {
9027 if (publicType.qualifier.storage == EvqVaryingIn) {
9028 if (! intermediate.setLocalSizeSpecId(i, publicType.shaderQualifiers.localSizeSpecId[i]))
9029 error(loc, "cannot change previously set size", "local_size", "");
9031 error(loc, "can only apply to 'in'", "local_size id", "");
9032 // Set the workgroup built-in variable as a specialization constant
9033 TVariable* workGroupSize = getEditableVariable("gl_WorkGroupSize");
9034 if (workGroupSize != nullptr)
9035 workGroupSize->getWritableType().getQualifier().specConstant = true;
9040 if (publicType.shaderQualifiers.earlyFragmentTests) {
9041 if (publicType.qualifier.storage == EvqVaryingIn)
9042 intermediate.setEarlyFragmentTests();
9044 error(loc, "can only apply to 'in'", "early_fragment_tests", "");
9046 if (publicType.shaderQualifiers.postDepthCoverage) {
9047 if (publicType.qualifier.storage == EvqVaryingIn)
9048 intermediate.setPostDepthCoverage();
9050 error(loc, "can only apply to 'in'", "post_coverage_coverage", "");
9052 if (publicType.shaderQualifiers.hasBlendEquation()) {
9053 if (publicType.qualifier.storage != EvqVaryingOut)
9054 error(loc, "can only apply to 'out'", "blend equation", "");
9056 if (publicType.shaderQualifiers.interlockOrdering) {
9057 if (publicType.qualifier.storage == EvqVaryingIn) {
9058 if (!intermediate.setInterlockOrdering(publicType.shaderQualifiers.interlockOrdering))
9059 error(loc, "cannot change previously set fragment shader interlock ordering", TQualifier::getInterlockOrderingString(publicType.shaderQualifiers.interlockOrdering), "");
9062 error(loc, "can only apply to 'in'", TQualifier::getInterlockOrderingString(publicType.shaderQualifiers.interlockOrdering), "");
9065 if (publicType.shaderQualifiers.layoutDerivativeGroupQuads &&
9066 publicType.shaderQualifiers.layoutDerivativeGroupLinear) {
9067 error(loc, "cannot be both specified", "derivative_group_quadsNV and derivative_group_linearNV", "");
9070 if (publicType.shaderQualifiers.layoutDerivativeGroupQuads) {
9071 if (publicType.qualifier.storage == EvqVaryingIn) {
9072 if ((intermediate.getLocalSize(0) & 1) ||
9073 (intermediate.getLocalSize(1) & 1))
9074 error(loc, "requires local_size_x and local_size_y to be multiple of two", "derivative_group_quadsNV", "");
9076 intermediate.setLayoutDerivativeMode(LayoutDerivativeGroupQuads);
9079 error(loc, "can only apply to 'in'", "derivative_group_quadsNV", "");
9081 if (publicType.shaderQualifiers.layoutDerivativeGroupLinear) {
9082 if (publicType.qualifier.storage == EvqVaryingIn) {
9083 if((intermediate.getLocalSize(0) *
9084 intermediate.getLocalSize(1) *
9085 intermediate.getLocalSize(2)) % 4 != 0)
9086 error(loc, "requires total group size to be multiple of four", "derivative_group_linearNV", "");
9088 intermediate.setLayoutDerivativeMode(LayoutDerivativeGroupLinear);
9091 error(loc, "can only apply to 'in'", "derivative_group_linearNV", "");
9093 // Check mesh out array sizes, once all the necessary out qualifiers are defined.
9094 if ((language == EShLangMeshNV) &&
9095 (intermediate.getVertices() != TQualifier::layoutNotSet) &&
9096 (intermediate.getPrimitives() != TQualifier::layoutNotSet) &&
9097 (intermediate.getOutputPrimitive() != ElgNone))
9099 checkIoArraysConsistency(loc);
9102 if (publicType.shaderQualifiers.layoutPrimitiveCulling) {
9103 if (publicType.qualifier.storage != EvqTemporary)
9104 error(loc, "layout qualifier can not have storage qualifiers", "primitive_culling","", "");
9106 intermediate.setLayoutPrimitiveCulling();
9108 // Exit early as further checks are not valid
9112 const TQualifier& qualifier = publicType.qualifier;
9114 if (qualifier.isAuxiliary() ||
9115 qualifier.isMemory() ||
9116 qualifier.isInterpolation() ||
9117 qualifier.precision != EpqNone)
9118 error(loc, "cannot use auxiliary, memory, interpolation, or precision qualifier in a default qualifier declaration (declaration with no type)", "qualifier", "");
9120 // "The offset qualifier can only be used on block members of blocks..."
9121 // "The align qualifier can only be used on blocks or block members..."
9122 if (qualifier.hasOffset() ||
9123 qualifier.hasAlign())
9124 error(loc, "cannot use offset or align qualifiers in a default qualifier declaration (declaration with no type)", "layout qualifier", "");
9126 layoutQualifierCheck(loc, qualifier);
9128 switch (qualifier.storage) {
9130 if (qualifier.hasMatrix())
9131 globalUniformDefaults.layoutMatrix = qualifier.layoutMatrix;
9132 if (qualifier.hasPacking())
9133 globalUniformDefaults.layoutPacking = qualifier.layoutPacking;
9136 if (qualifier.hasMatrix())
9137 globalBufferDefaults.layoutMatrix = qualifier.layoutMatrix;
9138 if (qualifier.hasPacking())
9139 globalBufferDefaults.layoutPacking = qualifier.layoutPacking;
9145 if (qualifier.hasStream())
9146 globalOutputDefaults.layoutStream = qualifier.layoutStream;
9147 if (qualifier.hasXfbBuffer())
9148 globalOutputDefaults.layoutXfbBuffer = qualifier.layoutXfbBuffer;
9149 if (globalOutputDefaults.hasXfbBuffer() && qualifier.hasXfbStride()) {
9150 if (! intermediate.setXfbBufferStride(globalOutputDefaults.layoutXfbBuffer, qualifier.layoutXfbStride))
9151 error(loc, "all stride settings must match for xfb buffer", "xfb_stride", "%d", qualifier.layoutXfbBuffer);
9156 if (qualifier.hasMatrix())
9157 globalSharedDefaults.layoutMatrix = qualifier.layoutMatrix;
9158 if (qualifier.hasPacking())
9159 globalSharedDefaults.layoutPacking = qualifier.layoutPacking;
9162 error(loc, "default qualifier requires 'uniform', 'buffer', 'in', 'out' or 'shared' storage qualification", "", "");
9166 if (qualifier.hasBinding())
9167 error(loc, "cannot declare a default, include a type or full declaration", "binding", "");
9168 if (qualifier.hasAnyLocation())
9169 error(loc, "cannot declare a default, use a full declaration", "location/component/index", "");
9170 if (qualifier.hasXfbOffset())
9171 error(loc, "cannot declare a default, use a full declaration", "xfb_offset", "");
9172 if (qualifier.isPushConstant())
9173 error(loc, "cannot declare a default, can only be used on a block", "push_constant", "");
9174 if (qualifier.hasBufferReference())
9175 error(loc, "cannot declare a default, can only be used on a block", "buffer_reference", "");
9176 if (qualifier.hasSpecConstantId())
9177 error(loc, "cannot declare a default, can only be used on a scalar", "constant_id", "");
9178 if (qualifier.isShaderRecord())
9179 error(loc, "cannot declare a default, can only be used on a block", "shaderRecordNV", "");
9183 // Take the sequence of statements that has been built up since the last case/default,
9184 // put it on the list of top-level nodes for the current (inner-most) switch statement,
9185 // and follow that by the case/default we are on now. (See switch topology comment on
9188 void TParseContext::wrapupSwitchSubsequence(TIntermAggregate* statements, TIntermNode* branchNode)
9190 TIntermSequence* switchSequence = switchSequenceStack.back();
9193 if (switchSequence->size() == 0)
9194 error(statements->getLoc(), "cannot have statements before first case/default label", "switch", "");
9195 statements->setOperator(EOpSequence);
9196 switchSequence->push_back(statements);
9199 // check all previous cases for the same label (or both are 'default')
9200 for (unsigned int s = 0; s < switchSequence->size(); ++s) {
9201 TIntermBranch* prevBranch = (*switchSequence)[s]->getAsBranchNode();
9203 TIntermTyped* prevExpression = prevBranch->getExpression();
9204 TIntermTyped* newExpression = branchNode->getAsBranchNode()->getExpression();
9205 if (prevExpression == nullptr && newExpression == nullptr)
9206 error(branchNode->getLoc(), "duplicate label", "default", "");
9207 else if (prevExpression != nullptr &&
9208 newExpression != nullptr &&
9209 prevExpression->getAsConstantUnion() &&
9210 newExpression->getAsConstantUnion() &&
9211 prevExpression->getAsConstantUnion()->getConstArray()[0].getIConst() ==
9212 newExpression->getAsConstantUnion()->getConstArray()[0].getIConst())
9213 error(branchNode->getLoc(), "duplicated value", "case", "");
9216 switchSequence->push_back(branchNode);
9221 // Turn the top-level node sequence built up of wrapupSwitchSubsequence9)
9222 // into a switch node.
9224 TIntermNode* TParseContext::addSwitch(const TSourceLoc& loc, TIntermTyped* expression, TIntermAggregate* lastStatements)
9226 profileRequires(loc, EEsProfile, 300, nullptr, "switch statements");
9227 profileRequires(loc, ENoProfile, 130, nullptr, "switch statements");
9229 wrapupSwitchSubsequence(lastStatements, nullptr);
9231 if (expression == nullptr ||
9232 (expression->getBasicType() != EbtInt && expression->getBasicType() != EbtUint) ||
9233 expression->getType().isArray() || expression->getType().isMatrix() || expression->getType().isVector())
9234 error(loc, "condition must be a scalar integer expression", "switch", "");
9236 // If there is nothing to do, drop the switch but still execute the expression
9237 TIntermSequence* switchSequence = switchSequenceStack.back();
9238 if (switchSequence->size() == 0)
9241 if (lastStatements == nullptr) {
9242 // This was originally an ERRROR, because early versions of the specification said
9243 // "it is an error to have no statement between a label and the end of the switch statement."
9244 // The specifications were updated to remove this (being ill-defined what a "statement" was),
9245 // so, this became a warning. However, 3.0 tests still check for the error.
9246 if (isEsProfile() && version <= 300 && ! relaxedErrors())
9247 error(loc, "last case/default label not followed by statements", "switch", "");
9249 warn(loc, "last case/default label not followed by statements", "switch", "");
9251 // emulate a break for error recovery
9252 lastStatements = intermediate.makeAggregate(intermediate.addBranch(EOpBreak, loc));
9253 lastStatements->setOperator(EOpSequence);
9254 switchSequence->push_back(lastStatements);
9257 TIntermAggregate* body = new TIntermAggregate(EOpSequence);
9258 body->getSequence() = *switchSequenceStack.back();
9261 TIntermSwitch* switchNode = new TIntermSwitch(expression, body);
9262 switchNode->setLoc(loc);
9268 // When a struct used in block, and has it's own layout packing, layout matrix,
9269 // record the origin structure of a struct to map, and Record the structure copy to the copy table,
9271 const TTypeList* TParseContext::recordStructCopy(TStructRecord& record, const TType* originType, const TType* tmpType)
9273 size_t memberCount = tmpType->getStruct()->size();
9274 size_t originHash = 0, tmpHash = 0;
9275 std::hash<size_t> hasher;
9276 for (size_t i = 0; i < memberCount; i++) {
9277 size_t originMemberHash = hasher(originType->getStruct()->at(i).type->getQualifier().layoutPacking +
9278 originType->getStruct()->at(i).type->getQualifier().layoutMatrix);
9279 size_t tmpMemberHash = hasher(tmpType->getStruct()->at(i).type->getQualifier().layoutPacking +
9280 tmpType->getStruct()->at(i).type->getQualifier().layoutMatrix);
9281 originHash = hasher((originHash ^ originMemberHash) << 1);
9282 tmpHash = hasher((tmpHash ^ tmpMemberHash) << 1);
9284 const TTypeList* originStruct = originType->getStruct();
9285 const TTypeList* tmpStruct = tmpType->getStruct();
9286 if (originHash != tmpHash) {
9287 auto fixRecords = record.find(originStruct);
9288 if (fixRecords != record.end()) {
9289 auto fixRecord = fixRecords->second.find(tmpHash);
9290 if (fixRecord != fixRecords->second.end()) {
9291 return fixRecord->second;
9293 record[originStruct][tmpHash] = tmpStruct;
9297 record[originStruct] = std::map<size_t, const TTypeList*>();
9298 record[originStruct][tmpHash] = tmpStruct;
9302 return originStruct;
9305 } // end namespace glslang