• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //
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.
7 //
8 // All rights reserved.
9 //
10 // Redistribution and use in source and binary forms, with or without
11 // modification, are permitted provided that the following conditions
12 // are met:
13 //
14 //    Redistributions of source code must retain the above copyright
15 //    notice, this list of conditions and the following disclaimer.
16 //
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.
21 //
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.
25 //
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.
38 //
39 
40 #include "ParseHelper.h"
41 #include "Initialize.h"
42 #include "Scan.h"
43 
44 #include "../OSDependent/osinclude.h"
45 #include <algorithm>
46 
47 #include "preprocessor/PpContext.h"
48 
49 extern int yyparse(glslang::TParseContext*);
50 
51 namespace glslang {
52 
TParseContext(TSymbolTable & symbolTable,TIntermediate & interm,bool parsingBuiltins,int version,EProfile profile,const SpvVersion & spvVersion,EShLanguage language,TInfoSink & infoSink,bool forwardCompatible,EShMessages messages,const TString * entryPoint)53 TParseContext::TParseContext(TSymbolTable& symbolTable, TIntermediate& interm, bool parsingBuiltins,
54                              int version, EProfile profile, const SpvVersion& spvVersion, EShLanguage language,
55                              TInfoSink& infoSink, bool forwardCompatible, EShMessages messages,
56                              const TString* entryPoint) :
57             TParseContextBase(symbolTable, interm, parsingBuiltins, version, profile, spvVersion, language,
58                               infoSink, forwardCompatible, messages, entryPoint),
59             inMain(false),
60             blockName(nullptr),
61             limits(resources.limits),
62             atomicUintOffsets(nullptr), anyIndexLimits(false)
63 {
64     // decide whether precision qualifiers should be ignored or respected
65     if (isEsProfile() || spvVersion.vulkan > 0) {
66         precisionManager.respectPrecisionQualifiers();
67         if (! parsingBuiltins && language == EShLangFragment && !isEsProfile() && spvVersion.vulkan > 0)
68             precisionManager.warnAboutDefaults();
69     }
70 
71     setPrecisionDefaults();
72 
73     globalUniformDefaults.clear();
74     globalUniformDefaults.layoutMatrix = ElmColumnMajor;
75     globalUniformDefaults.layoutPacking = spvVersion.spv != 0 ? ElpStd140 : ElpShared;
76 
77     globalBufferDefaults.clear();
78     globalBufferDefaults.layoutMatrix = ElmColumnMajor;
79     globalBufferDefaults.layoutPacking = spvVersion.spv != 0 ? ElpStd430 : ElpShared;
80 
81     globalInputDefaults.clear();
82     globalOutputDefaults.clear();
83 
84     globalSharedDefaults.clear();
85     globalSharedDefaults.layoutMatrix = ElmColumnMajor;
86     globalSharedDefaults.layoutPacking = ElpStd430;
87 
88     // "Shaders in the transform
89     // feedback capturing mode have an initial global default of
90     //     layout(xfb_buffer = 0) out;"
91     if (language == EShLangVertex ||
92         language == EShLangTessControl ||
93         language == EShLangTessEvaluation ||
94         language == EShLangGeometry)
95         globalOutputDefaults.layoutXfbBuffer = 0;
96 
97     if (language == EShLangGeometry)
98         globalOutputDefaults.layoutStream = 0;
99 
100     if (entryPoint != nullptr && entryPoint->size() > 0 && *entryPoint != "main")
101         infoSink.info.message(EPrefixError, "Source entry point must be \"main\"");
102 }
103 
~TParseContext()104 TParseContext::~TParseContext()
105 {
106     delete [] atomicUintOffsets;
107 }
108 
109 // Set up all default precisions as needed by the current environment.
110 // Intended just as a TParseContext constructor helper.
setPrecisionDefaults()111 void TParseContext::setPrecisionDefaults()
112 {
113     // Set all precision defaults to EpqNone, which is correct for all types
114     // when not obeying precision qualifiers, and correct for types that don't
115     // have defaults (thus getting an error on use) when obeying precision
116     // qualifiers.
117 
118     for (int type = 0; type < EbtNumTypes; ++type)
119         defaultPrecision[type] = EpqNone;
120 
121     for (int type = 0; type < maxSamplerIndex; ++type)
122         defaultSamplerPrecision[type] = EpqNone;
123 
124     // replace with real precision defaults for those that have them
125     if (obeyPrecisionQualifiers()) {
126         if (isEsProfile()) {
127             // Most don't have defaults, a few default to lowp.
128             TSampler sampler;
129             sampler.set(EbtFloat, Esd2D);
130             defaultSamplerPrecision[computeSamplerTypeIndex(sampler)] = EpqLow;
131             sampler.set(EbtFloat, EsdCube);
132             defaultSamplerPrecision[computeSamplerTypeIndex(sampler)] = EpqLow;
133             sampler.set(EbtFloat, Esd2D);
134             sampler.setExternal(true);
135             defaultSamplerPrecision[computeSamplerTypeIndex(sampler)] = EpqLow;
136         }
137 
138         // If we are parsing built-in computational variables/functions, it is meaningful to record
139         // whether the built-in has no precision qualifier, as that ambiguity
140         // is used to resolve the precision from the supplied arguments/operands instead.
141         // So, we don't actually want to replace EpqNone with a default precision for built-ins.
142         if (! parsingBuiltins) {
143             if (isEsProfile() && language == EShLangFragment) {
144                 defaultPrecision[EbtInt] = EpqMedium;
145                 defaultPrecision[EbtUint] = EpqMedium;
146             } else {
147                 defaultPrecision[EbtInt] = EpqHigh;
148                 defaultPrecision[EbtUint] = EpqHigh;
149                 defaultPrecision[EbtFloat] = EpqHigh;
150             }
151 
152             if (!isEsProfile()) {
153                 // Non-ES profile
154                 // All sampler precisions default to highp.
155                 for (int type = 0; type < maxSamplerIndex; ++type)
156                     defaultSamplerPrecision[type] = EpqHigh;
157             }
158         }
159 
160         defaultPrecision[EbtSampler] = EpqLow;
161         defaultPrecision[EbtAtomicUint] = EpqHigh;
162     }
163 }
164 
setLimits(const TBuiltInResource & r)165 void TParseContext::setLimits(const TBuiltInResource& r)
166 {
167     resources = r;
168     intermediate.setLimits(r);
169 
170     anyIndexLimits = ! limits.generalAttributeMatrixVectorIndexing ||
171                      ! limits.generalConstantMatrixVectorIndexing ||
172                      ! limits.generalSamplerIndexing ||
173                      ! limits.generalUniformIndexing ||
174                      ! limits.generalVariableIndexing ||
175                      ! limits.generalVaryingIndexing;
176 
177 
178     // "Each binding point tracks its own current default offset for
179     // inheritance of subsequent variables using the same binding. The initial state of compilation is that all
180     // binding points have an offset of 0."
181     atomicUintOffsets = new int[resources.maxAtomicCounterBindings];
182     for (int b = 0; b < resources.maxAtomicCounterBindings; ++b)
183         atomicUintOffsets[b] = 0;
184 }
185 
186 //
187 // Parse an array of strings using yyparse, going through the
188 // preprocessor to tokenize the shader strings, then through
189 // the GLSL scanner.
190 //
191 // Returns true for successful acceptance of the shader, false if any errors.
192 //
parseShaderStrings(TPpContext & ppContext,TInputScanner & input,bool versionWillBeError)193 bool TParseContext::parseShaderStrings(TPpContext& ppContext, TInputScanner& input, bool versionWillBeError)
194 {
195     currentScanner = &input;
196     ppContext.setInput(input, versionWillBeError);
197     yyparse(this);
198 
199     finish();
200 
201     return numErrors == 0;
202 }
203 
204 // This is called from bison when it has a parse (syntax) error
205 // Note though that to stop cascading errors, we set EOF, which
206 // will usually cause a syntax error, so be more accurate that
207 // compilation is terminating.
parserError(const char * s)208 void TParseContext::parserError(const char* s)
209 {
210     if (! getScanner()->atEndOfInput() || numErrors == 0)
211         error(getCurrentLoc(), "", "", s, "");
212     else
213         error(getCurrentLoc(), "compilation terminated", "", "");
214 }
215 
growGlobalUniformBlock(const TSourceLoc & loc,TType & memberType,const TString & memberName,TTypeList * typeList)216 void TParseContext::growGlobalUniformBlock(const TSourceLoc& loc, TType& memberType, const TString& memberName, TTypeList* typeList)
217 {
218     bool createBlock = globalUniformBlock == nullptr;
219 
220     if (createBlock) {
221         globalUniformBinding = intermediate.getGlobalUniformBinding();
222         globalUniformSet = intermediate.getGlobalUniformSet();
223     }
224 
225     // use base class function to create/expand block
226     TParseContextBase::growGlobalUniformBlock(loc, memberType, memberName, typeList);
227 
228     if (spvVersion.vulkan > 0 && spvVersion.vulkanRelaxed) {
229         // check for a block storage override
230         TBlockStorageClass storageOverride = intermediate.getBlockStorageOverride(getGlobalUniformBlockName());
231         TQualifier& qualifier = globalUniformBlock->getWritableType().getQualifier();
232         qualifier.defaultBlock = true;
233 
234         if (storageOverride != EbsNone) {
235             if (createBlock) {
236                 // Remap block storage
237                 qualifier.setBlockStorage(storageOverride);
238 
239                 // check that the change didn't create errors
240                 blockQualifierCheck(loc, qualifier, false);
241             }
242 
243             // remap meber storage as well
244             memberType.getQualifier().setBlockStorage(storageOverride);
245         }
246     }
247 }
248 
growAtomicCounterBlock(int binding,const TSourceLoc & loc,TType & memberType,const TString & memberName,TTypeList * typeList)249 void TParseContext::growAtomicCounterBlock(int binding, const TSourceLoc& loc, TType& memberType, const TString& memberName, TTypeList* typeList)
250 {
251     bool createBlock = atomicCounterBuffers.find(binding) == atomicCounterBuffers.end();
252 
253     if (createBlock) {
254         atomicCounterBlockSet = intermediate.getAtomicCounterBlockSet();
255     }
256 
257     // use base class function to create/expand block
258     TParseContextBase::growAtomicCounterBlock(binding, loc, memberType, memberName, typeList);
259     TQualifier& qualifier = atomicCounterBuffers[binding]->getWritableType().getQualifier();
260     qualifier.defaultBlock = true;
261 
262     if (spvVersion.vulkan > 0 && spvVersion.vulkanRelaxed) {
263         // check for a Block storage override
264         TBlockStorageClass storageOverride = intermediate.getBlockStorageOverride(getAtomicCounterBlockName());
265 
266         if (storageOverride != EbsNone) {
267             if (createBlock) {
268                 // Remap block storage
269 
270                 qualifier.setBlockStorage(storageOverride);
271 
272                 // check that the change didn't create errors
273                 blockQualifierCheck(loc, qualifier, false);
274             }
275 
276             // remap meber storage as well
277             memberType.getQualifier().setBlockStorage(storageOverride);
278         }
279     }
280 }
281 
getGlobalUniformBlockName() const282 const char* TParseContext::getGlobalUniformBlockName() const
283 {
284     const char* name = intermediate.getGlobalUniformBlockName();
285     if (std::string(name) == "")
286         return "gl_DefaultUniformBlock";
287     else
288         return name;
289 }
finalizeGlobalUniformBlockLayout(TVariable &)290 void TParseContext::finalizeGlobalUniformBlockLayout(TVariable&)
291 {
292 }
setUniformBlockDefaults(TType & block) const293 void TParseContext::setUniformBlockDefaults(TType& block) const
294 {
295     block.getQualifier().layoutPacking = ElpStd140;
296     block.getQualifier().layoutMatrix = ElmColumnMajor;
297 }
298 
299 
getAtomicCounterBlockName() const300 const char* TParseContext::getAtomicCounterBlockName() const
301 {
302     const char* name = intermediate.getAtomicCounterBlockName();
303     if (std::string(name) == "")
304         return "gl_AtomicCounterBlock";
305     else
306         return name;
307 }
finalizeAtomicCounterBlockLayout(TVariable &)308 void TParseContext::finalizeAtomicCounterBlockLayout(TVariable&)
309 {
310 }
311 
setAtomicCounterBlockDefaults(TType & block) const312 void TParseContext::setAtomicCounterBlockDefaults(TType& block) const
313 {
314     block.getQualifier().layoutPacking = ElpStd430;
315     block.getQualifier().layoutMatrix = ElmRowMajor;
316 }
317 
setInvariant(const TSourceLoc & loc,const char * builtin)318 void TParseContext::setInvariant(const TSourceLoc& loc, const char* builtin) {
319     TSymbol* symbol = symbolTable.find(builtin);
320     if (symbol && symbol->getType().getQualifier().isPipeOutput()) {
321         if (intermediate.inIoAccessed(builtin))
322             warn(loc, "changing qualification after use", "invariant", builtin);
323         TSymbol* csymbol = symbolTable.copyUp(symbol);
324         csymbol->getWritableType().getQualifier().invariant = true;
325     }
326 }
327 
handlePragma(const TSourceLoc & loc,const TVector<TString> & tokens)328 void TParseContext::handlePragma(const TSourceLoc& loc, const TVector<TString>& tokens)
329 {
330     if (pragmaCallback)
331         pragmaCallback(loc.line, tokens);
332 
333     if (tokens.size() == 0)
334         return;
335 
336     if (tokens[0].compare("optimize") == 0) {
337         if (tokens.size() != 4) {
338             error(loc, "optimize pragma syntax is incorrect", "#pragma", "");
339             return;
340         }
341 
342         if (tokens[1].compare("(") != 0) {
343             error(loc, "\"(\" expected after 'optimize' keyword", "#pragma", "");
344             return;
345         }
346 
347         if (tokens[2].compare("on") == 0)
348             contextPragma.optimize = true;
349         else if (tokens[2].compare("off") == 0)
350             contextPragma.optimize = false;
351         else {
352             if(relaxedErrors())
353                 //  If an implementation does not recognize the tokens following #pragma, then it will ignore that pragma.
354                 warn(loc, "\"on\" or \"off\" expected after '(' for 'optimize' pragma", "#pragma", "");
355             return;
356         }
357 
358         if (tokens[3].compare(")") != 0) {
359             error(loc, "\")\" expected to end 'optimize' pragma", "#pragma", "");
360             return;
361         }
362     } else if (tokens[0].compare("debug") == 0) {
363         if (tokens.size() != 4) {
364             error(loc, "debug pragma syntax is incorrect", "#pragma", "");
365             return;
366         }
367 
368         if (tokens[1].compare("(") != 0) {
369             error(loc, "\"(\" expected after 'debug' keyword", "#pragma", "");
370             return;
371         }
372 
373         if (tokens[2].compare("on") == 0)
374             contextPragma.debug = true;
375         else if (tokens[2].compare("off") == 0)
376             contextPragma.debug = false;
377         else {
378             if(relaxedErrors())
379                 //  If an implementation does not recognize the tokens following #pragma, then it will ignore that pragma.
380                 warn(loc, "\"on\" or \"off\" expected after '(' for 'debug' pragma", "#pragma", "");
381             return;
382         }
383 
384         if (tokens[3].compare(")") != 0) {
385             error(loc, "\")\" expected to end 'debug' pragma", "#pragma", "");
386             return;
387         }
388     } else if (spvVersion.spv > 0 && tokens[0].compare("use_storage_buffer") == 0) {
389         if (tokens.size() != 1)
390             error(loc, "extra tokens", "#pragma", "");
391         intermediate.setUseStorageBuffer();
392     } else if (spvVersion.spv > 0 && tokens[0].compare("use_vulkan_memory_model") == 0) {
393         if (tokens.size() != 1)
394             error(loc, "extra tokens", "#pragma", "");
395         intermediate.setUseVulkanMemoryModel();
396     } else if (spvVersion.spv > 0 && tokens[0].compare("use_variable_pointers") == 0) {
397         if (tokens.size() != 1)
398             error(loc, "extra tokens", "#pragma", "");
399         if (spvVersion.spv < glslang::EShTargetSpv_1_3)
400             error(loc, "requires SPIR-V 1.3", "#pragma use_variable_pointers", "");
401         intermediate.setUseVariablePointers();
402     } else if (tokens[0].compare("once") == 0) {
403         warn(loc, "not implemented", "#pragma once", "");
404     } else if (tokens[0].compare("glslang_binary_double_output") == 0) {
405         intermediate.setBinaryDoubleOutput();
406     } else if (spvVersion.spv > 0 && tokens[0].compare("STDGL") == 0 &&
407                tokens[1].compare("invariant") == 0 && tokens[3].compare("all") == 0) {
408         intermediate.setInvariantAll();
409         // Set all builtin out variables invariant if declared
410         setInvariant(loc, "gl_Position");
411         setInvariant(loc, "gl_PointSize");
412         setInvariant(loc, "gl_ClipDistance");
413         setInvariant(loc, "gl_CullDistance");
414         setInvariant(loc, "gl_TessLevelOuter");
415         setInvariant(loc, "gl_TessLevelInner");
416         setInvariant(loc, "gl_PrimitiveID");
417         setInvariant(loc, "gl_Layer");
418         setInvariant(loc, "gl_ViewportIndex");
419         setInvariant(loc, "gl_FragDepth");
420         setInvariant(loc, "gl_SampleMask");
421         setInvariant(loc, "gl_ClipVertex");
422         setInvariant(loc, "gl_FrontColor");
423         setInvariant(loc, "gl_BackColor");
424         setInvariant(loc, "gl_FrontSecondaryColor");
425         setInvariant(loc, "gl_BackSecondaryColor");
426         setInvariant(loc, "gl_TexCoord");
427         setInvariant(loc, "gl_FogFragCoord");
428         setInvariant(loc, "gl_FragColor");
429         setInvariant(loc, "gl_FragData");
430     }
431 }
432 
433 //
434 // Handle seeing a variable identifier in the grammar.
435 //
handleVariable(const TSourceLoc & loc,TSymbol * symbol,const TString * string)436 TIntermTyped* TParseContext::handleVariable(const TSourceLoc& loc, TSymbol* symbol, const TString* string)
437 {
438     TIntermTyped* node = nullptr;
439 
440     // Error check for requiring specific extensions present.
441     if (symbol && symbol->getNumExtensions())
442         requireExtensions(loc, symbol->getNumExtensions(), symbol->getExtensions(), symbol->getName().c_str());
443 
444     if (symbol && symbol->isReadOnly()) {
445         // All shared things containing an unsized array must be copied up
446         // on first use, so that all future references will share its array structure,
447         // so that editing the implicit size will effect all nodes consuming it,
448         // and so that editing the implicit size won't change the shared one.
449         //
450         // If this is a variable or a block, check it and all it contains, but if this
451         // is a member of an anonymous block, check the whole block, as the whole block
452         // will need to be copied up if it contains an unsized array.
453         //
454         // This check is being done before the block-name check further down, so guard
455         // for that too.
456         if (!symbol->getType().isUnusableName()) {
457             if (symbol->getType().containsUnsizedArray() ||
458                 (symbol->getAsAnonMember() &&
459                  symbol->getAsAnonMember()->getAnonContainer().getType().containsUnsizedArray()))
460                 makeEditable(symbol);
461         }
462     }
463 
464     const TVariable* variable;
465     const TAnonMember* anon = symbol ? symbol->getAsAnonMember() : nullptr;
466     if (anon) {
467         // It was a member of an anonymous container.
468 
469         // Create a subtree for its dereference.
470         variable = anon->getAnonContainer().getAsVariable();
471         TIntermTyped* container = intermediate.addSymbol(*variable, loc);
472         TIntermTyped* constNode = intermediate.addConstantUnion(anon->getMemberNumber(), loc);
473         node = intermediate.addIndex(EOpIndexDirectStruct, container, constNode, loc);
474 
475         node->setType(*(*variable->getType().getStruct())[anon->getMemberNumber()].type);
476         if (node->getType().hiddenMember())
477             error(loc, "member of nameless block was not redeclared", string->c_str(), "");
478     } else {
479         // Not a member of an anonymous container.
480 
481         // The symbol table search was done in the lexical phase.
482         // See if it was a variable.
483         variable = symbol ? symbol->getAsVariable() : nullptr;
484         if (variable) {
485             if (variable->getType().isUnusableName()) {
486                 error(loc, "cannot be used (maybe an instance name is needed)", string->c_str(), "");
487                 variable = nullptr;
488             }
489 
490             if (language == EShLangMesh && variable) {
491                 TLayoutGeometry primitiveType = intermediate.getOutputPrimitive();
492                 if ((variable->getMangledName() == "gl_PrimitiveTriangleIndicesEXT" && primitiveType != ElgTriangles) ||
493                     (variable->getMangledName() == "gl_PrimitiveLineIndicesEXT" && primitiveType != ElgLines) ||
494                     (variable->getMangledName() == "gl_PrimitivePointIndicesEXT" && primitiveType != ElgPoints)) {
495                     error(loc, "cannot be used (ouput primitive type mismatch)", string->c_str(), "");
496                     variable = nullptr;
497                 }
498             }
499         } else {
500             if (symbol)
501                 error(loc, "variable name expected", string->c_str(), "");
502         }
503 
504         // Recovery, if it wasn't found or was not a variable.
505         if (! variable)
506             variable = new TVariable(string, TType(EbtVoid));
507 
508         if (variable->getType().getQualifier().isFrontEndConstant())
509             node = intermediate.addConstantUnion(variable->getConstArray(), variable->getType(), loc);
510         else
511             node = intermediate.addSymbol(*variable, loc);
512     }
513 
514     if (variable->getType().getQualifier().isIo())
515         intermediate.addIoAccessed(*string);
516 
517     if (variable->getType().isReference() &&
518         variable->getType().getQualifier().bufferReferenceNeedsVulkanMemoryModel()) {
519         intermediate.setUseVulkanMemoryModel();
520     }
521 
522     return node;
523 }
524 
525 //
526 // Handle seeing a base[index] dereference in the grammar.
527 //
handleBracketDereference(const TSourceLoc & loc,TIntermTyped * base,TIntermTyped * index)528 TIntermTyped* TParseContext::handleBracketDereference(const TSourceLoc& loc, TIntermTyped* base, TIntermTyped* index)
529 {
530     int indexValue = 0;
531     if (index->getQualifier().isFrontEndConstant())
532         indexValue = index->getAsConstantUnion()->getConstArray()[0].getIConst();
533 
534     // basic type checks...
535     variableCheck(base);
536 
537     if (! base->isArray() && ! base->isMatrix() && ! base->isVector() && ! base->getType().isCoopMat() &&
538         ! base->isReference()) {
539         if (base->getAsSymbolNode())
540             error(loc, " left of '[' is not of type array, matrix, or vector ", base->getAsSymbolNode()->getName().c_str(), "");
541         else
542             error(loc, " left of '[' is not of type array, matrix, or vector ", "expression", "");
543 
544         // Insert dummy error-recovery result
545         return intermediate.addConstantUnion(0.0, EbtFloat, loc);
546     }
547 
548     if (!base->isArray() && base->isVector()) {
549         if (base->getType().contains16BitFloat())
550             requireFloat16Arithmetic(loc, "[", "does not operate on types containing float16");
551         if (base->getType().contains16BitInt())
552             requireInt16Arithmetic(loc, "[", "does not operate on types containing (u)int16");
553         if (base->getType().contains8BitInt())
554             requireInt8Arithmetic(loc, "[", "does not operate on types containing (u)int8");
555     }
556 
557     // check for constant folding
558     if (base->getType().getQualifier().isFrontEndConstant() && index->getQualifier().isFrontEndConstant()) {
559         // both base and index are front-end constants
560         checkIndex(loc, base->getType(), indexValue);
561         return intermediate.foldDereference(base, indexValue, loc);
562     }
563 
564     // at least one of base and index is not a front-end constant variable...
565     TIntermTyped* result = nullptr;
566 
567     if (base->isReference() && ! base->isArray()) {
568         requireExtensions(loc, 1, &E_GL_EXT_buffer_reference2, "buffer reference indexing");
569         if (base->getType().getReferentType()->containsUnsizedArray()) {
570             error(loc, "cannot index reference to buffer containing an unsized array", "", "");
571             result = nullptr;
572         } else {
573             result = intermediate.addBinaryMath(EOpAdd, base, index, loc);
574             if (result != nullptr)
575                 result->setType(base->getType());
576         }
577         if (result == nullptr) {
578             error(loc, "cannot index buffer reference", "", "");
579             result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
580         }
581         return result;
582     }
583     if (base->getAsSymbolNode() && isIoResizeArray(base->getType()))
584         handleIoResizeArrayAccess(loc, base);
585 
586     if (index->getQualifier().isFrontEndConstant())
587         checkIndex(loc, base->getType(), indexValue);
588 
589     if (index->getQualifier().isFrontEndConstant()) {
590         if (base->getType().isUnsizedArray()) {
591             base->getWritableType().updateImplicitArraySize(indexValue + 1);
592             base->getWritableType().setImplicitlySized(true);
593             if (base->getQualifier().builtIn == EbvClipDistance &&
594                 indexValue >= resources.maxClipDistances) {
595                 error(loc, "gl_ClipDistance", "[", "array index out of range '%d'", indexValue);
596             }
597             else if (base->getQualifier().builtIn == EbvCullDistance &&
598                 indexValue >= resources.maxCullDistances) {
599                 error(loc, "gl_CullDistance", "[", "array index out of range '%d'", indexValue);
600             }
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();
604                 if (binaryNode) {
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));
609                 }
610             }
611         } else
612             checkIndex(loc, base->getType(), indexValue);
613         result = intermediate.addIndex(EOpIndexDirect, base, index, loc);
614     } else {
615         if (base->getType().isUnsizedArray()) {
616             // we have a variable index into an unsized array, which is okay,
617             // depending on the situation
618             if (base->getAsSymbolNode() && isIoResizeArray(base->getType()))
619                 error(loc, "", "[", "array must be sized by a redeclaration or layout qualifier before being indexed with a variable");
620             else {
621                 // it is okay for a run-time sized array
622                 checkRuntimeSizable(loc, *base);
623             }
624             base->getWritableType().setArrayVariablyIndexed();
625         }
626         if (base->getBasicType() == EbtBlock) {
627             if (base->getQualifier().storage == EvqBuffer)
628                 requireProfile(base->getLoc(), ~EEsProfile, "variable indexing buffer block array");
629             else if (base->getQualifier().storage == EvqUniform)
630                 profileRequires(base->getLoc(), EEsProfile, 320, Num_AEP_gpu_shader5, AEP_gpu_shader5,
631                                 "variable indexing uniform block array");
632             else {
633                 // input/output blocks either don't exist or can't be variably indexed
634             }
635         } else if (language == EShLangFragment && base->getQualifier().isPipeOutput())
636             requireProfile(base->getLoc(), ~EEsProfile, "variable indexing fragment shader output array");
637         else if (base->getBasicType() == EbtSampler && version >= 130) {
638             const char* explanation = "variable indexing sampler array";
639             requireProfile(base->getLoc(), EEsProfile | ECoreProfile | ECompatibilityProfile, explanation);
640             profileRequires(base->getLoc(), EEsProfile, 320, Num_AEP_gpu_shader5, AEP_gpu_shader5, explanation);
641             profileRequires(base->getLoc(), ECoreProfile | ECompatibilityProfile, 400, nullptr, explanation);
642         }
643 
644         result = intermediate.addIndex(EOpIndexIndirect, base, index, loc);
645     }
646 
647     // Insert valid dereferenced result type
648     TType newType(base->getType(), 0);
649     if (base->getType().getQualifier().isConstant() && index->getQualifier().isConstant()) {
650         newType.getQualifier().storage = EvqConst;
651         // If base or index is a specialization constant, the result should also be a specialization constant.
652         if (base->getType().getQualifier().isSpecConstant() || index->getQualifier().isSpecConstant()) {
653             newType.getQualifier().makeSpecConstant();
654         }
655     } else {
656         newType.getQualifier().storage = EvqTemporary;
657         newType.getQualifier().specConstant = false;
658     }
659     result->setType(newType);
660 
661     inheritMemoryQualifiers(base->getQualifier(), result->getWritableType().getQualifier());
662 
663     // Propagate nonuniform
664     if (base->getQualifier().isNonUniform() || index->getQualifier().isNonUniform())
665         result->getWritableType().getQualifier().nonUniform = true;
666 
667     if (anyIndexLimits)
668         handleIndexLimits(loc, base, index);
669 
670     return result;
671 }
672 
673 // for ES 2.0 (version 100) limitations for almost all index operations except vertex-shader uniforms
handleIndexLimits(const TSourceLoc &,TIntermTyped * base,TIntermTyped * index)674 void TParseContext::handleIndexLimits(const TSourceLoc& /*loc*/, TIntermTyped* base, TIntermTyped* index)
675 {
676     if ((! limits.generalSamplerIndexing && base->getBasicType() == EbtSampler) ||
677         (! limits.generalUniformIndexing && base->getQualifier().isUniformOrBuffer() && language != EShLangVertex) ||
678         (! limits.generalAttributeMatrixVectorIndexing && base->getQualifier().isPipeInput() && language == EShLangVertex && (base->getType().isMatrix() || base->getType().isVector())) ||
679         (! limits.generalConstantMatrixVectorIndexing && base->getAsConstantUnion()) ||
680         (! limits.generalVariableIndexing && ! base->getType().getQualifier().isUniformOrBuffer() &&
681                                              ! base->getType().getQualifier().isPipeInput() &&
682                                              ! base->getType().getQualifier().isPipeOutput() &&
683                                              ! base->getType().getQualifier().isConstant()) ||
684         (! limits.generalVaryingIndexing && (base->getType().getQualifier().isPipeInput() ||
685                                                 base->getType().getQualifier().isPipeOutput()))) {
686         // it's too early to know what the inductive variables are, save it for post processing
687         needsIndexLimitationChecking.push_back(index);
688     }
689 }
690 
691 // Make a shared symbol have a non-shared version that can be edited by the current
692 // compile, such that editing its type will not change the shared version and will
693 // effect all nodes sharing it.
makeEditable(TSymbol * & symbol)694 void TParseContext::makeEditable(TSymbol*& symbol)
695 {
696     TParseContextBase::makeEditable(symbol);
697 
698     // See if it's tied to IO resizing
699     if (isIoResizeArray(symbol->getType()))
700         ioArraySymbolResizeList.push_back(symbol);
701 }
702 
703 // Return true if this is a geometry shader input array or tessellation control output array
704 // or mesh shader output array.
isIoResizeArray(const TType & type) const705 bool TParseContext::isIoResizeArray(const TType& type) const
706 {
707     return type.isArray() &&
708            ((language == EShLangGeometry    && type.getQualifier().storage == EvqVaryingIn) ||
709             (language == EShLangTessControl && type.getQualifier().storage == EvqVaryingOut &&
710                 ! type.getQualifier().patch) ||
711             (language == EShLangFragment && type.getQualifier().storage == EvqVaryingIn &&
712                 (type.getQualifier().pervertexNV || type.getQualifier().pervertexEXT)) ||
713             (language == EShLangMesh && type.getQualifier().storage == EvqVaryingOut &&
714                 !type.getQualifier().perTaskNV));
715 }
716 
717 // If an array is not isIoResizeArray() but is an io array, make sure it has the right size
fixIoArraySize(const TSourceLoc & loc,TType & type)718 void TParseContext::fixIoArraySize(const TSourceLoc& loc, TType& type)
719 {
720     if (! type.isArray() || type.getQualifier().patch || symbolTable.atBuiltInLevel())
721         return;
722 
723     assert(! isIoResizeArray(type));
724 
725     if (type.getQualifier().storage != EvqVaryingIn || type.getQualifier().patch)
726         return;
727 
728     if (language == EShLangTessControl || language == EShLangTessEvaluation) {
729         if (type.getOuterArraySize() != resources.maxPatchVertices) {
730             if (type.isSizedArray())
731                 error(loc, "tessellation input array size must be gl_MaxPatchVertices or implicitly sized", "[]", "");
732             type.changeOuterArraySize(resources.maxPatchVertices);
733         }
734     }
735 }
736 
737 // Issue any errors if the non-array object is missing arrayness WRT
738 // shader I/O that has array requirements.
739 // All arrayness checking is handled in array paths, this is for
ioArrayCheck(const TSourceLoc & loc,const TType & type,const TString & identifier)740 void TParseContext::ioArrayCheck(const TSourceLoc& loc, const TType& type, const TString& identifier)
741 {
742     if (! type.isArray() && ! symbolTable.atBuiltInLevel()) {
743         if (type.getQualifier().isArrayedIo(language) && !type.getQualifier().layoutPassthrough)
744             error(loc, "type must be an array:", type.getStorageQualifierString(), identifier.c_str());
745     }
746 }
747 
748 // Handle a dereference of a geometry shader input array or tessellation control output array.
749 // See ioArraySymbolResizeList comment in ParseHelper.h.
750 //
handleIoResizeArrayAccess(const TSourceLoc &,TIntermTyped * base)751 void TParseContext::handleIoResizeArrayAccess(const TSourceLoc& /*loc*/, TIntermTyped* base)
752 {
753     TIntermSymbol* symbolNode = base->getAsSymbolNode();
754     assert(symbolNode);
755     if (! symbolNode)
756         return;
757 
758     // fix array size, if it can be fixed and needs to be fixed (will allow variable indexing)
759     if (symbolNode->getType().isUnsizedArray()) {
760         int newSize = getIoArrayImplicitSize(symbolNode->getType().getQualifier());
761         if (newSize > 0)
762             symbolNode->getWritableType().changeOuterArraySize(newSize);
763     }
764 }
765 
766 // If there has been an input primitive declaration (geometry shader) or an output
767 // number of vertices declaration(tessellation shader), make sure all input array types
768 // match it in size.  Types come either from nodes in the AST or symbols in the
769 // symbol table.
770 //
771 // Types without an array size will be given one.
772 // Types already having a size that is wrong will get an error.
773 //
checkIoArraysConsistency(const TSourceLoc & loc,bool tailOnly)774 void TParseContext::checkIoArraysConsistency(const TSourceLoc &loc, bool tailOnly)
775 {
776     int requiredSize = 0;
777     TString featureString;
778     size_t listSize = ioArraySymbolResizeList.size();
779     size_t i = 0;
780 
781     // If tailOnly = true, only check the last array symbol in the list.
782     if (tailOnly) {
783         i = listSize - 1;
784     }
785     for (bool firstIteration = true; i < listSize; ++i) {
786         TType &type = ioArraySymbolResizeList[i]->getWritableType();
787 
788         // As I/O array sizes don't change, fetch requiredSize only once,
789         // except for mesh shaders which could have different I/O array sizes based on type qualifiers.
790         if (firstIteration || (language == EShLangMesh)) {
791             requiredSize = getIoArrayImplicitSize(type.getQualifier(), &featureString);
792             if (requiredSize == 0)
793                 break;
794             firstIteration = false;
795         }
796 
797         checkIoArrayConsistency(loc, requiredSize, featureString.c_str(), type,
798                                 ioArraySymbolResizeList[i]->getName());
799     }
800 }
801 
getIoArrayImplicitSize(const TQualifier & qualifier,TString * featureString) const802 int TParseContext::getIoArrayImplicitSize(const TQualifier &qualifier, TString *featureString) const
803 {
804     int expectedSize = 0;
805     TString str = "unknown";
806     unsigned int maxVertices = intermediate.getVertices() != TQualifier::layoutNotSet ? intermediate.getVertices() : 0;
807 
808     if (language == EShLangGeometry) {
809         expectedSize = TQualifier::mapGeometryToSize(intermediate.getInputPrimitive());
810         str = TQualifier::getGeometryString(intermediate.getInputPrimitive());
811     }
812     else if (language == EShLangTessControl) {
813         expectedSize = maxVertices;
814         str = "vertices";
815     } else if (language == EShLangFragment) {
816         // Number of vertices for Fragment shader is always three.
817         expectedSize = 3;
818         str = "vertices";
819     } else if (language == EShLangMesh) {
820         unsigned int maxPrimitives =
821             intermediate.getPrimitives() != TQualifier::layoutNotSet ? intermediate.getPrimitives() : 0;
822         if (qualifier.builtIn == EbvPrimitiveIndicesNV) {
823             expectedSize = maxPrimitives * TQualifier::mapGeometryToSize(intermediate.getOutputPrimitive());
824             str = "max_primitives*";
825             str += TQualifier::getGeometryString(intermediate.getOutputPrimitive());
826         }
827         else if (qualifier.builtIn == EbvPrimitiveTriangleIndicesEXT || qualifier.builtIn == EbvPrimitiveLineIndicesEXT ||
828                  qualifier.builtIn == EbvPrimitivePointIndicesEXT) {
829             expectedSize = maxPrimitives;
830             str = "max_primitives";
831         }
832         else if (qualifier.isPerPrimitive()) {
833             expectedSize = maxPrimitives;
834             str = "max_primitives";
835         }
836         else {
837             expectedSize = maxVertices;
838             str = "max_vertices";
839         }
840     }
841     if (featureString)
842         *featureString = str;
843     return expectedSize;
844 }
845 
checkIoArrayConsistency(const TSourceLoc & loc,int requiredSize,const char * feature,TType & type,const TString & name)846 void TParseContext::checkIoArrayConsistency(const TSourceLoc& loc, int requiredSize, const char* feature, TType& type, const TString& name)
847 {
848     if (type.isUnsizedArray())
849         type.changeOuterArraySize(requiredSize);
850     else if (type.getOuterArraySize() != requiredSize) {
851         if (language == EShLangGeometry)
852             error(loc, "inconsistent input primitive for array size of", feature, name.c_str());
853         else if (language == EShLangTessControl)
854             error(loc, "inconsistent output number of vertices for array size of", feature, name.c_str());
855         else if (language == EShLangFragment) {
856             if (type.getOuterArraySize() > requiredSize)
857                 error(loc, " cannot be greater than 3 for pervertexEXT", feature, name.c_str());
858         }
859         else if (language == EShLangMesh)
860             error(loc, "inconsistent output array size of", feature, name.c_str());
861         else
862             assert(0);
863     }
864 }
865 
866 // Handle seeing a binary node with a math operation.
867 // Returns nullptr if not semantically allowed.
handleBinaryMath(const TSourceLoc & loc,const char * str,TOperator op,TIntermTyped * left,TIntermTyped * right)868 TIntermTyped* TParseContext::handleBinaryMath(const TSourceLoc& loc, const char* str, TOperator op, TIntermTyped* left, TIntermTyped* right)
869 {
870     rValueErrorCheck(loc, str, left->getAsTyped());
871     rValueErrorCheck(loc, str, right->getAsTyped());
872 
873     bool allowed = true;
874     switch (op) {
875     // TODO: Bring more source language-specific checks up from intermediate.cpp
876     // to the specific parse helpers for that source language.
877     case EOpLessThan:
878     case EOpGreaterThan:
879     case EOpLessThanEqual:
880     case EOpGreaterThanEqual:
881         if (! left->isScalar() || ! right->isScalar())
882             allowed = false;
883         break;
884     default:
885         break;
886     }
887 
888     if (((left->getType().contains16BitFloat() || right->getType().contains16BitFloat()) && !float16Arithmetic()) ||
889         ((left->getType().contains16BitInt() || right->getType().contains16BitInt()) && !int16Arithmetic()) ||
890         ((left->getType().contains8BitInt() || right->getType().contains8BitInt()) && !int8Arithmetic())) {
891         allowed = false;
892     }
893 
894     TIntermTyped* result = nullptr;
895     if (allowed) {
896         if ((left->isReference() || right->isReference()))
897             requireExtensions(loc, 1, &E_GL_EXT_buffer_reference2, "buffer reference math");
898         result = intermediate.addBinaryMath(op, left, right, loc);
899     }
900 
901     if (result == nullptr) {
902         bool enhanced = intermediate.getEnhancedMsgs();
903         binaryOpError(loc, str, left->getCompleteString(enhanced), right->getCompleteString(enhanced));
904     }
905 
906     return result;
907 }
908 
909 // Handle seeing a unary node with a math operation.
handleUnaryMath(const TSourceLoc & loc,const char * str,TOperator op,TIntermTyped * childNode)910 TIntermTyped* TParseContext::handleUnaryMath(const TSourceLoc& loc, const char* str, TOperator op, TIntermTyped* childNode)
911 {
912     rValueErrorCheck(loc, str, childNode);
913 
914     bool allowed = true;
915     if ((childNode->getType().contains16BitFloat() && !float16Arithmetic()) ||
916         (childNode->getType().contains16BitInt() && !int16Arithmetic()) ||
917         (childNode->getType().contains8BitInt() && !int8Arithmetic())) {
918         allowed = false;
919     }
920 
921     TIntermTyped* result = nullptr;
922     if (allowed)
923         result = intermediate.addUnaryMath(op, childNode, loc);
924 
925     if (result)
926         return result;
927     else {
928         bool enhanced = intermediate.getEnhancedMsgs();
929         unaryOpError(loc, str, childNode->getCompleteString(enhanced));
930     }
931 
932     return childNode;
933 }
934 
935 //
936 // Handle seeing a base.field dereference in the grammar.
937 //
handleDotDereference(const TSourceLoc & loc,TIntermTyped * base,const TString & field)938 TIntermTyped* TParseContext::handleDotDereference(const TSourceLoc& loc, TIntermTyped* base, const TString& field)
939 {
940     variableCheck(base);
941 
942     //
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().
946     //
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             bool enhanced = intermediate.getEnhancedMsgs();
957             error(loc, "does not operate on this type:", field.c_str(), base->getType().getCompleteString(enhanced).c_str());
958             return base;
959         }
960 
961         return intermediate.addMethod(base, TType(EbtInt), &field, loc);
962     }
963 
964     // It's not .length() if we get to here.
965 
966     if (base->isArray()) {
967         error(loc, "cannot apply to an array:", ".", field.c_str());
968 
969         return base;
970     }
971 
972     if (base->getType().isCoopMat()) {
973         error(loc, "cannot apply to a cooperative matrix type:", ".", field.c_str());
974         return base;
975     }
976 
977     // It's neither an array nor .length() if we get here,
978     // leaving swizzles and struct/block dereferences.
979 
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;
989         int member;
990         for (member = 0; member < (int)fields->size(); ++member) {
991             if ((*fields)[member].type->getFieldName() == field) {
992                 fieldFound = true;
993                 break;
994             }
995         }
996 
997         if (fieldFound) {
998             if (spvVersion.vulkan != 0 && spvVersion.vulkanRelaxed)
999                 result = vkRelaxedRemapDotDereference(loc, *base, *(*fields)[member].type, field);
1000 
1001             if (result == base)
1002             {
1003                 if (base->getType().getQualifier().isFrontEndConstant())
1004                     result = intermediate.foldDereference(base, member, loc);
1005                 else {
1006                     blockMemberExtensionCheck(loc, base, member, field);
1007                     TIntermTyped* index = intermediate.addConstantUnion(member, loc);
1008                     result = intermediate.addIndex(EOpIndexDirectStruct, base, index, loc);
1009                     result->setType(*(*fields)[member].type);
1010                     if ((*fields)[member].type->getQualifier().isIo())
1011                         intermediate.addIoAccessed(field);
1012                 }
1013             }
1014 
1015             inheritMemoryQualifiers(base->getQualifier(), result->getWritableType().getQualifier());
1016         } else {
1017             auto baseSymbol = base;
1018             while (baseSymbol->getAsSymbolNode() == nullptr) {
1019                 auto binaryNode = baseSymbol->getAsBinaryNode();
1020                 if (binaryNode == nullptr) break;
1021                 baseSymbol = binaryNode->getLeft();
1022             }
1023             if (baseSymbol->getAsSymbolNode() != nullptr) {
1024                 TString structName;
1025                 structName.append("\'").append(baseSymbol->getAsSymbolNode()->getName().c_str()).append("\'");
1026                 error(loc, "no such field in structure", field.c_str(), structName.c_str());
1027             } else {
1028                 error(loc, "no such field in structure", field.c_str(), "");
1029             }
1030         }
1031     } else
1032         error(loc, "does not apply to this type:", field.c_str(),
1033           base->getType().getCompleteString(intermediate.getEnhancedMsgs()).c_str());
1034 
1035     // Propagate noContraction up the dereference chain
1036     if (base->getQualifier().isNoContraction())
1037         result->getWritableType().getQualifier().setNoContraction();
1038 
1039     // Propagate nonuniform
1040     if (base->getQualifier().isNonUniform())
1041         result->getWritableType().getQualifier().nonUniform = true;
1042 
1043     return result;
1044 }
1045 
1046 //
1047 // Handle seeing a base.swizzle, a subset of base.identifier in the grammar.
1048 //
handleDotSwizzle(const TSourceLoc & loc,TIntermTyped * base,const TString & field)1049 TIntermTyped* TParseContext::handleDotSwizzle(const TSourceLoc& loc, TIntermTyped* base, const TString& field)
1050 {
1051     TIntermTyped* result = base;
1052     if (base->isScalar()) {
1053         const char* dotFeature = "scalar swizzle";
1054         requireProfile(loc, ~EEsProfile, dotFeature);
1055         profileRequires(loc, ~EEsProfile, 420, E_GL_ARB_shading_language_420pack, dotFeature);
1056     }
1057 
1058     TSwizzleSelectors<TVectorSelector> selectors;
1059     parseSwizzleSelector(loc, field, base->getVectorSize(), selectors);
1060 
1061     if (base->isVector() && selectors.size() != 1 && base->getType().contains16BitFloat())
1062         requireFloat16Arithmetic(loc, ".", "can't swizzle types containing float16");
1063     if (base->isVector() && selectors.size() != 1 && base->getType().contains16BitInt())
1064         requireInt16Arithmetic(loc, ".", "can't swizzle types containing (u)int16");
1065     if (base->isVector() && selectors.size() != 1 && base->getType().contains8BitInt())
1066         requireInt8Arithmetic(loc, ".", "can't swizzle types containing (u)int8");
1067 
1068     if (base->isScalar()) {
1069         if (selectors.size() == 1)
1070             return result;
1071         else {
1072             TType type(base->getBasicType(), EvqTemporary, selectors.size());
1073             // Swizzle operations propagate specialization-constantness
1074             if (base->getQualifier().isSpecConstant())
1075                 type.getQualifier().makeSpecConstant();
1076             return addConstructor(loc, base, type);
1077         }
1078     }
1079 
1080     if (base->getType().getQualifier().isFrontEndConstant())
1081         result = intermediate.foldSwizzle(base, selectors, loc);
1082     else {
1083         if (selectors.size() == 1) {
1084             TIntermTyped* index = intermediate.addConstantUnion(selectors[0], loc);
1085             result = intermediate.addIndex(EOpIndexDirect, base, index, loc);
1086             result->setType(TType(base->getBasicType(), EvqTemporary, base->getType().getQualifier().precision));
1087         } else {
1088             TIntermTyped* index = intermediate.addSwizzle(selectors, loc);
1089             result = intermediate.addIndex(EOpVectorSwizzle, base, index, loc);
1090             result->setType(TType(base->getBasicType(), EvqTemporary, base->getType().getQualifier().precision, selectors.size()));
1091         }
1092         // Swizzle operations propagate specialization-constantness
1093         if (base->getType().getQualifier().isSpecConstant())
1094             result->getWritableType().getQualifier().makeSpecConstant();
1095     }
1096 
1097     return result;
1098 }
1099 
blockMemberExtensionCheck(const TSourceLoc & loc,const TIntermTyped * base,int member,const TString & memberName)1100 void TParseContext::blockMemberExtensionCheck(const TSourceLoc& loc, const TIntermTyped* base, int member, const TString& memberName)
1101 {
1102     // a block that needs extension checking is either 'base', or if arrayed,
1103     // one level removed to the left
1104     const TIntermSymbol* baseSymbol = nullptr;
1105     if (base->getAsBinaryNode() == nullptr)
1106         baseSymbol = base->getAsSymbolNode();
1107     else
1108         baseSymbol = base->getAsBinaryNode()->getLeft()->getAsSymbolNode();
1109     if (baseSymbol == nullptr)
1110         return;
1111     const TSymbol* symbol = symbolTable.find(baseSymbol->getName());
1112     if (symbol == nullptr)
1113         return;
1114     const TVariable* variable = symbol->getAsVariable();
1115     if (variable == nullptr)
1116         return;
1117     if (!variable->hasMemberExtensions())
1118         return;
1119 
1120     // We now have a variable that is the base of a dot reference
1121     // with members that need extension checking.
1122     if (variable->getNumMemberExtensions(member) > 0)
1123         requireExtensions(loc, variable->getNumMemberExtensions(member), variable->getMemberExtensions(member), memberName.c_str());
1124 }
1125 
1126 //
1127 // Handle seeing a function declarator in the grammar.  This is the precursor
1128 // to recognizing a function prototype or function definition.
1129 //
handleFunctionDeclarator(const TSourceLoc & loc,TFunction & function,bool prototype)1130 TFunction* TParseContext::handleFunctionDeclarator(const TSourceLoc& loc, TFunction& function, bool prototype)
1131 {
1132     // ES can't declare prototypes inside functions
1133     if (! symbolTable.atGlobalLevel())
1134         requireProfile(loc, ~EEsProfile, "local function declaration");
1135 
1136     //
1137     // Multiple declarations of the same function name are allowed.
1138     //
1139     // If this is a definition, the definition production code will check for redefinitions
1140     // (we don't know at this point if it's a definition or not).
1141     //
1142     // Redeclarations (full signature match) are allowed.  But, return types and parameter qualifiers must also match.
1143     //  - except ES 100, which only allows a single prototype
1144     //
1145     // ES 100 does not allow redefining, but does allow overloading of built-in functions.
1146     // ES 300 does not allow redefining or overloading of built-in functions.
1147     //
1148     bool builtIn;
1149     TSymbol* symbol = symbolTable.find(function.getMangledName(), &builtIn);
1150     if (symbol && symbol->getAsFunction() && builtIn)
1151         requireProfile(loc, ~EEsProfile, "redefinition of built-in function");
1152     // Check the validity of using spirv_literal qualifier
1153     for (int i = 0; i < function.getParamCount(); ++i) {
1154         if (function[i].type->getQualifier().isSpirvLiteral() && function.getBuiltInOp() != EOpSpirvInst)
1155             error(loc, "'spirv_literal' can only be used on functions defined with 'spirv_instruction' for argument",
1156                   function.getName().c_str(), "%d", i + 1);
1157     }
1158 
1159     // For function declaration with SPIR-V instruction qualifier, always ignore the built-in function and
1160     // respect this redeclared one.
1161     if (symbol && builtIn && function.getBuiltInOp() == EOpSpirvInst)
1162         symbol = nullptr;
1163     const TFunction* prevDec = symbol ? symbol->getAsFunction() : nullptr;
1164     if (prevDec) {
1165         if (prevDec->isPrototyped() && prototype)
1166             profileRequires(loc, EEsProfile, 300, nullptr, "multiple prototypes for same function");
1167         if (prevDec->getType() != function.getType())
1168             error(loc, "overloaded functions must have the same return type", function.getName().c_str(), "");
1169         if (prevDec->getSpirvInstruction() != function.getSpirvInstruction()) {
1170             error(loc, "overloaded functions must have the same qualifiers", function.getName().c_str(),
1171                   "spirv_instruction");
1172         }
1173         for (int i = 0; i < prevDec->getParamCount(); ++i) {
1174             if ((*prevDec)[i].type->getQualifier().storage != function[i].type->getQualifier().storage)
1175                 error(loc, "overloaded functions must have the same parameter storage qualifiers for argument", function[i].type->getStorageQualifierString(), "%d", i+1);
1176 
1177             if ((*prevDec)[i].type->getQualifier().precision != function[i].type->getQualifier().precision)
1178                 error(loc, "overloaded functions must have the same parameter precision qualifiers for argument", function[i].type->getPrecisionQualifierString(), "%d", i+1);
1179         }
1180     }
1181 
1182     arrayObjectCheck(loc, function.getType(), "array in function return type");
1183 
1184     if (prototype) {
1185         // All built-in functions are defined, even though they don't have a body.
1186         // Count their prototype as a definition instead.
1187         if (symbolTable.atBuiltInLevel())
1188             function.setDefined();
1189         else {
1190             if (prevDec && ! builtIn)
1191                 symbol->getAsFunction()->setPrototyped();  // need a writable one, but like having prevDec as a const
1192             function.setPrototyped();
1193         }
1194     }
1195 
1196     // This insert won't actually insert it if it's a duplicate signature, but it will still check for
1197     // other forms of name collisions.
1198     if (! symbolTable.insert(function))
1199         error(loc, "function name is redeclaration of existing name", function.getName().c_str(), "");
1200 
1201     //
1202     // If this is a redeclaration, it could also be a definition,
1203     // in which case, we need to use the parameter names from this one, and not the one that's
1204     // being redeclared.  So, pass back this declaration, not the one in the symbol table.
1205     //
1206     return &function;
1207 }
1208 
1209 //
1210 // Handle seeing the function prototype in front of a function definition in the grammar.
1211 // The body is handled after this function returns.
1212 //
handleFunctionDefinition(const TSourceLoc & loc,TFunction & function)1213 TIntermAggregate* TParseContext::handleFunctionDefinition(const TSourceLoc& loc, TFunction& function)
1214 {
1215     currentCaller = function.getMangledName();
1216     TSymbol* symbol = symbolTable.find(function.getMangledName());
1217     TFunction* prevDec = symbol ? symbol->getAsFunction() : nullptr;
1218 
1219     if (! prevDec)
1220         error(loc, "can't find function", function.getName().c_str(), "");
1221     // Note:  'prevDec' could be 'function' if this is the first time we've seen function
1222     // as it would have just been put in the symbol table.  Otherwise, we're looking up
1223     // an earlier occurrence.
1224 
1225     if (prevDec && prevDec->isDefined()) {
1226         // Then this function already has a body.
1227         error(loc, "function already has a body", function.getName().c_str(), "");
1228     }
1229     if (prevDec && ! prevDec->isDefined()) {
1230         prevDec->setDefined();
1231 
1232         // Remember the return type for later checking for RETURN statements.
1233         currentFunctionType = &(prevDec->getType());
1234     } else
1235         currentFunctionType = new TType(EbtVoid);
1236     functionReturnsValue = false;
1237 
1238     // Check for entry point
1239     if (function.getName().compare(intermediate.getEntryPointName().c_str()) == 0) {
1240         intermediate.setEntryPointMangledName(function.getMangledName().c_str());
1241         intermediate.incrementEntryPointCount();
1242         inMain = true;
1243     } else
1244         inMain = false;
1245 
1246     //
1247     // Raise error message if main function takes any parameters or returns anything other than void
1248     //
1249     if (inMain) {
1250         if (function.getParamCount() > 0)
1251             error(loc, "function cannot take any parameter(s)", function.getName().c_str(), "");
1252         if (function.getType().getBasicType() != EbtVoid)
1253             error(loc, "", function.getType().getBasicTypeString().c_str(), "entry point cannot return a value");
1254         if (function.getLinkType() != ELinkNone)
1255             error(loc, "main function cannot be exported", "", "");
1256     }
1257 
1258     //
1259     // New symbol table scope for body of function plus its arguments
1260     //
1261     symbolTable.push();
1262 
1263     //
1264     // Insert parameters into the symbol table.
1265     // If the parameter has no name, it's not an error, just don't insert it
1266     // (could be used for unused args).
1267     //
1268     // Also, accumulate the list of parameters into the HIL, so lower level code
1269     // knows where to find parameters.
1270     //
1271     TIntermAggregate* paramNodes = new TIntermAggregate;
1272     for (int i = 0; i < function.getParamCount(); i++) {
1273         TParameter& param = function[i];
1274         if (param.name != nullptr) {
1275             TVariable *variable = new TVariable(param.name, *param.type);
1276 
1277             // Insert the parameters with name in the symbol table.
1278             if (! symbolTable.insert(*variable))
1279                 error(loc, "redefinition", variable->getName().c_str(), "");
1280             else {
1281                 // Transfer ownership of name pointer to symbol table.
1282                 param.name = nullptr;
1283 
1284                 // Add the parameter to the HIL
1285                 paramNodes = intermediate.growAggregate(paramNodes,
1286                                                         intermediate.addSymbol(*variable, loc),
1287                                                         loc);
1288             }
1289         } else
1290             paramNodes = intermediate.growAggregate(paramNodes, intermediate.addSymbol(*param.type, loc), loc);
1291     }
1292     paramNodes->setLinkType(function.getLinkType());
1293     intermediate.setAggregateOperator(paramNodes, EOpParameters, TType(EbtVoid), loc);
1294     loopNestingLevel = 0;
1295     statementNestingLevel = 0;
1296     controlFlowNestingLevel = 0;
1297     postEntryPointReturn = false;
1298 
1299     return paramNodes;
1300 }
1301 
1302 //
1303 // Handle seeing function call syntax in the grammar, which could be any of
1304 //  - .length() method
1305 //  - constructor
1306 //  - a call to a built-in function mapped to an operator
1307 //  - a call to a built-in function that will remain a function call (e.g., texturing)
1308 //  - user function
1309 //  - subroutine call (not implemented yet)
1310 //
handleFunctionCall(const TSourceLoc & loc,TFunction * function,TIntermNode * arguments)1311 TIntermTyped* TParseContext::handleFunctionCall(const TSourceLoc& loc, TFunction* function, TIntermNode* arguments)
1312 {
1313     TIntermTyped* result = nullptr;
1314 
1315     if (spvVersion.vulkan != 0 && spvVersion.vulkanRelaxed) {
1316         // allow calls that are invalid in Vulkan Semantics to be invisibily
1317         // remapped to equivalent valid functions
1318         result = vkRelaxedRemapFunctionCall(loc, function, arguments);
1319         if (result)
1320             return result;
1321     }
1322 
1323     if (function->getBuiltInOp() == EOpArrayLength)
1324         result = handleLengthMethod(loc, function, arguments);
1325     else if (function->getBuiltInOp() != EOpNull) {
1326         //
1327         // Then this should be a constructor.
1328         // Don't go through the symbol table for constructors.
1329         // Their parameters will be verified algorithmically.
1330         //
1331         TType type(EbtVoid);  // use this to get the type back
1332         if (! constructorError(loc, arguments, *function, function->getBuiltInOp(), type)) {
1333             //
1334             // It's a constructor, of type 'type'.
1335             //
1336             result = addConstructor(loc, arguments, type);
1337             if (result == nullptr)
1338                 error(loc, "cannot construct with these arguments", type.getCompleteString(intermediate.getEnhancedMsgs()).c_str(), "");
1339         }
1340     } else {
1341         //
1342         // Find it in the symbol table.
1343         //
1344         const TFunction* fnCandidate;
1345         bool builtIn {false};
1346         fnCandidate = findFunction(loc, *function, builtIn);
1347         if (fnCandidate) {
1348             // This is a declared function that might map to
1349             //  - a built-in operator,
1350             //  - a built-in function not mapped to an operator, or
1351             //  - a user function.
1352 
1353             // Error check for a function requiring specific extensions present.
1354             if (builtIn && fnCandidate->getNumExtensions())
1355                 requireExtensions(loc, fnCandidate->getNumExtensions(), fnCandidate->getExtensions(), fnCandidate->getName().c_str());
1356 
1357             if (builtIn && fnCandidate->getType().contains16BitFloat())
1358                 requireFloat16Arithmetic(loc, "built-in function", "float16 types can only be in uniform block or buffer storage");
1359             if (builtIn && fnCandidate->getType().contains16BitInt())
1360                 requireInt16Arithmetic(loc, "built-in function", "(u)int16 types can only be in uniform block or buffer storage");
1361             if (builtIn && fnCandidate->getType().contains8BitInt())
1362                 requireInt8Arithmetic(loc, "built-in function", "(u)int8 types can only be in uniform block or buffer storage");
1363 
1364             if (arguments != nullptr) {
1365                 // Make sure qualifications work for these arguments.
1366                 TIntermAggregate* aggregate = arguments->getAsAggregate();
1367                 for (int i = 0; i < fnCandidate->getParamCount(); ++i) {
1368                     // At this early point there is a slight ambiguity between whether an aggregate 'arguments'
1369                     // is the single argument itself or its children are the arguments.  Only one argument
1370                     // means take 'arguments' itself as the one argument.
1371                     TIntermNode* arg = fnCandidate->getParamCount() == 1 ? arguments : (aggregate ? aggregate->getSequence()[i] : arguments);
1372                     TQualifier& formalQualifier = (*fnCandidate)[i].type->getQualifier();
1373                     if (formalQualifier.isParamOutput()) {
1374                         if (lValueErrorCheck(arguments->getLoc(), "assign", arg->getAsTyped()))
1375                             error(arguments->getLoc(), "Non-L-value cannot be passed for 'out' or 'inout' parameters.", "out", "");
1376                     }
1377                     if (formalQualifier.isSpirvLiteral()) {
1378                         if (!arg->getAsTyped()->getQualifier().isFrontEndConstant()) {
1379                             error(arguments->getLoc(),
1380                                   "Non front-end constant expressions cannot be passed for 'spirv_literal' parameters.",
1381                                   "spirv_literal", "");
1382                         }
1383                     }
1384                     const TType& argType = arg->getAsTyped()->getType();
1385                     const TQualifier& argQualifier = argType.getQualifier();
1386                     bool containsBindlessSampler = intermediate.getBindlessMode() && argType.containsSampler();
1387                     if (argQualifier.isMemory() && !containsBindlessSampler && (argType.containsOpaque() || argType.isReference())) {
1388                         const char* message = "argument cannot drop memory qualifier when passed to formal parameter";
1389                         if (argQualifier.volatil && ! formalQualifier.volatil)
1390                             error(arguments->getLoc(), message, "volatile", "");
1391                         if (argQualifier.coherent && ! (formalQualifier.devicecoherent || formalQualifier.coherent))
1392                             error(arguments->getLoc(), message, "coherent", "");
1393                         if (argQualifier.devicecoherent && ! (formalQualifier.devicecoherent || formalQualifier.coherent))
1394                             error(arguments->getLoc(), message, "devicecoherent", "");
1395                         if (argQualifier.queuefamilycoherent && ! (formalQualifier.queuefamilycoherent || formalQualifier.devicecoherent || formalQualifier.coherent))
1396                             error(arguments->getLoc(), message, "queuefamilycoherent", "");
1397                         if (argQualifier.workgroupcoherent && ! (formalQualifier.workgroupcoherent || formalQualifier.queuefamilycoherent || formalQualifier.devicecoherent || formalQualifier.coherent))
1398                             error(arguments->getLoc(), message, "workgroupcoherent", "");
1399                         if (argQualifier.subgroupcoherent && ! (formalQualifier.subgroupcoherent || formalQualifier.workgroupcoherent || formalQualifier.queuefamilycoherent || formalQualifier.devicecoherent || formalQualifier.coherent))
1400                             error(arguments->getLoc(), message, "subgroupcoherent", "");
1401                         if (argQualifier.readonly && ! formalQualifier.readonly)
1402                             error(arguments->getLoc(), message, "readonly", "");
1403                         if (argQualifier.writeonly && ! formalQualifier.writeonly)
1404                             error(arguments->getLoc(), message, "writeonly", "");
1405                         // Don't check 'restrict', it is different than the rest:
1406                         // "...but only restrict can be taken away from a calling argument, by a formal parameter that
1407                         // lacks the restrict qualifier..."
1408                     }
1409                     if (!builtIn && argQualifier.getFormat() != formalQualifier.getFormat()) {
1410                         // we have mismatched formats, which should only be allowed if writeonly
1411                         // and at least one format is unknown
1412                         if (!formalQualifier.isWriteOnly() || (formalQualifier.getFormat() != ElfNone &&
1413                                                                   argQualifier.getFormat() != ElfNone))
1414                             error(arguments->getLoc(), "image formats must match", "format", "");
1415                     }
1416                     if (builtIn && arg->getAsTyped()->getType().contains16BitFloat())
1417                         requireFloat16Arithmetic(arguments->getLoc(), "built-in function", "float16 types can only be in uniform block or buffer storage");
1418                     if (builtIn && arg->getAsTyped()->getType().contains16BitInt())
1419                         requireInt16Arithmetic(arguments->getLoc(), "built-in function", "(u)int16 types can only be in uniform block or buffer storage");
1420                     if (builtIn && arg->getAsTyped()->getType().contains8BitInt())
1421                         requireInt8Arithmetic(arguments->getLoc(), "built-in function", "(u)int8 types can only be in uniform block or buffer storage");
1422 
1423                     // TODO 4.5 functionality:  A shader will fail to compile
1424                     // if the value passed to the memargument of an atomic memory function does not correspond to a buffer or
1425                     // shared variable. It is acceptable to pass an element of an array or a single component of a vector to the
1426                     // memargument of an atomic memory function, as long as the underlying array or vector is a buffer or
1427                     // shared variable.
1428                 }
1429 
1430                 // Convert 'in' arguments
1431                 addInputArgumentConversions(*fnCandidate, arguments);  // arguments may be modified if it's just a single argument node
1432             }
1433 
1434             if (builtIn && fnCandidate->getBuiltInOp() != EOpNull) {
1435                 // A function call mapped to a built-in operation.
1436                 result = handleBuiltInFunctionCall(loc, arguments, *fnCandidate);
1437             } else if (fnCandidate->getBuiltInOp() == EOpSpirvInst) {
1438                 // When SPIR-V instruction qualifier is specified, the function call is still mapped to a built-in operation.
1439                 result = handleBuiltInFunctionCall(loc, arguments, *fnCandidate);
1440             } else {
1441                 // This is a function call not mapped to built-in operator.
1442                 // It could still be a built-in function, but only if PureOperatorBuiltins == false.
1443                 result = intermediate.setAggregateOperator(arguments, EOpFunctionCall, fnCandidate->getType(), loc);
1444                 TIntermAggregate* call = result->getAsAggregate();
1445                 call->setName(fnCandidate->getMangledName());
1446 
1447                 // this is how we know whether the given function is a built-in function or a user-defined function
1448                 // if builtIn == false, it's a userDefined -> could be an overloaded built-in function also
1449                 // if builtIn == true, it's definitely a built-in function with EOpNull
1450                 if (! builtIn) {
1451                     call->setUserDefined();
1452                     if (symbolTable.atGlobalLevel()) {
1453                         requireProfile(loc, ~EEsProfile, "calling user function from global scope");
1454                         intermediate.addToCallGraph(infoSink, "main(", fnCandidate->getMangledName());
1455                     } else
1456                         intermediate.addToCallGraph(infoSink, currentCaller, fnCandidate->getMangledName());
1457                 }
1458 
1459                 if (builtIn)
1460                     nonOpBuiltInCheck(loc, *fnCandidate, *call);
1461                 else
1462                     userFunctionCallCheck(loc, *call);
1463             }
1464 
1465             // Convert 'out' arguments.  If it was a constant folded built-in, it won't be an aggregate anymore.
1466             // Built-ins with a single argument aren't called with an aggregate, but they also don't have an output.
1467             // Also, build the qualifier list for user function calls, which are always called with an aggregate.
1468             if (result->getAsAggregate()) {
1469                 TQualifierList& qualifierList = result->getAsAggregate()->getQualifierList();
1470                 for (int i = 0; i < fnCandidate->getParamCount(); ++i) {
1471                     TStorageQualifier qual = (*fnCandidate)[i].type->getQualifier().storage;
1472                     qualifierList.push_back(qual);
1473                 }
1474                 result = addOutputArgumentConversions(*fnCandidate, *result->getAsAggregate());
1475             }
1476 
1477             if (result->getAsTyped()->getType().isCoopMat() &&
1478                !result->getAsTyped()->getType().isParameterized()) {
1479                 assert(fnCandidate->getBuiltInOp() == EOpCooperativeMatrixMulAdd ||
1480                        fnCandidate->getBuiltInOp() == EOpCooperativeMatrixMulAddNV);
1481 
1482                 result->setType(result->getAsAggregate()->getSequence()[2]->getAsTyped()->getType());
1483             }
1484         }
1485     }
1486 
1487     // generic error recovery
1488     // TODO: simplification: localize all the error recoveries that look like this, and taking type into account to reduce cascades
1489     if (result == nullptr)
1490         result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
1491 
1492     return result;
1493 }
1494 
handleBuiltInFunctionCall(TSourceLoc loc,TIntermNode * arguments,const TFunction & function)1495 TIntermTyped* TParseContext::handleBuiltInFunctionCall(TSourceLoc loc, TIntermNode* arguments,
1496                                                        const TFunction& function)
1497 {
1498     checkLocation(loc, function.getBuiltInOp());
1499     TIntermTyped *result = intermediate.addBuiltInFunctionCall(loc, function.getBuiltInOp(),
1500                                                                function.getParamCount() == 1,
1501                                                                arguments, function.getType());
1502     if (result != nullptr && obeyPrecisionQualifiers())
1503         computeBuiltinPrecisions(*result, function);
1504 
1505     if (result == nullptr) {
1506         if (arguments == nullptr)
1507             error(loc, " wrong operand type", "Internal Error",
1508                                       "built in unary operator function.  Type: %s", "");
1509         else
1510             error(arguments->getLoc(), " wrong operand type", "Internal Error",
1511                                       "built in unary operator function.  Type: %s",
1512                                       static_cast<TIntermTyped*>(arguments)->getCompleteString(intermediate.getEnhancedMsgs()).c_str());
1513     } else if (result->getAsOperator())
1514         builtInOpCheck(loc, function, *result->getAsOperator());
1515 
1516     // Special handling for function call with SPIR-V instruction qualifier specified
1517     if (function.getBuiltInOp() == EOpSpirvInst) {
1518         if (auto agg = result->getAsAggregate()) {
1519             // Propogate spirv_by_reference/spirv_literal from parameters to arguments
1520             auto& sequence = agg->getSequence();
1521             for (unsigned i = 0; i < sequence.size(); ++i) {
1522                 if (function[i].type->getQualifier().isSpirvByReference())
1523                     sequence[i]->getAsTyped()->getQualifier().setSpirvByReference();
1524                 if (function[i].type->getQualifier().isSpirvLiteral())
1525                     sequence[i]->getAsTyped()->getQualifier().setSpirvLiteral();
1526             }
1527 
1528             // Attach the function call to SPIR-V intruction
1529             agg->setSpirvInstruction(function.getSpirvInstruction());
1530         } else if (auto unaryNode = result->getAsUnaryNode()) {
1531             // Propogate spirv_by_reference/spirv_literal from parameters to arguments
1532             if (function[0].type->getQualifier().isSpirvByReference())
1533                 unaryNode->getOperand()->getQualifier().setSpirvByReference();
1534             if (function[0].type->getQualifier().isSpirvLiteral())
1535                 unaryNode->getOperand()->getQualifier().setSpirvLiteral();
1536 
1537             // Attach the function call to SPIR-V intruction
1538             unaryNode->setSpirvInstruction(function.getSpirvInstruction());
1539         } else
1540             assert(0);
1541     }
1542 
1543     return result;
1544 }
1545 
1546 // "The operation of a built-in function can have a different precision
1547 // qualification than the precision qualification of the resulting value.
1548 // These two precision qualifications are established as follows.
1549 //
1550 // The precision qualification of the operation of a built-in function is
1551 // based on the precision qualification of its input arguments and formal
1552 // parameters:  When a formal parameter specifies a precision qualifier,
1553 // that is used, otherwise, the precision qualification of the calling
1554 // argument is used.  The highest precision of these will be the precision
1555 // qualification of the operation of the built-in function. Generally,
1556 // this is applied across all arguments to a built-in function, with the
1557 // exceptions being:
1558 //   - bitfieldExtract and bitfieldInsert ignore the 'offset' and 'bits'
1559 //     arguments.
1560 //   - interpolateAt* functions only look at the 'interpolant' argument.
1561 //
1562 // The precision qualification of the result of a built-in function is
1563 // determined in one of the following ways:
1564 //
1565 //   - For the texture sampling, image load, and image store functions,
1566 //     the precision of the return type matches the precision of the
1567 //     sampler type
1568 //
1569 //   Otherwise:
1570 //
1571 //   - For prototypes that do not specify a resulting precision qualifier,
1572 //     the precision will be the same as the precision of the operation.
1573 //
1574 //   - For prototypes that do specify a resulting precision qualifier,
1575 //     the specified precision qualifier is the precision qualification of
1576 //     the result."
1577 //
computeBuiltinPrecisions(TIntermTyped & node,const TFunction & function)1578 void TParseContext::computeBuiltinPrecisions(TIntermTyped& node, const TFunction& function)
1579 {
1580     TPrecisionQualifier operationPrecision = EpqNone;
1581     TPrecisionQualifier resultPrecision = EpqNone;
1582 
1583     TIntermOperator* opNode = node.getAsOperator();
1584     if (opNode == nullptr)
1585         return;
1586 
1587     if (TIntermUnary* unaryNode = node.getAsUnaryNode()) {
1588         operationPrecision = std::max(function[0].type->getQualifier().precision,
1589                                       unaryNode->getOperand()->getType().getQualifier().precision);
1590         if (function.getType().getBasicType() != EbtBool)
1591             resultPrecision = function.getType().getQualifier().precision == EpqNone ?
1592                                         operationPrecision :
1593                                         function.getType().getQualifier().precision;
1594     } else if (TIntermAggregate* agg = node.getAsAggregate()) {
1595         TIntermSequence& sequence = agg->getSequence();
1596         unsigned int numArgs = (unsigned int)sequence.size();
1597         switch (agg->getOp()) {
1598         case EOpBitfieldExtract:
1599             numArgs = 1;
1600             break;
1601         case EOpBitfieldInsert:
1602             numArgs = 2;
1603             break;
1604         case EOpInterpolateAtCentroid:
1605         case EOpInterpolateAtOffset:
1606         case EOpInterpolateAtSample:
1607             numArgs = 1;
1608             break;
1609         case EOpDebugPrintf:
1610             numArgs = 0;
1611             break;
1612         default:
1613             break;
1614         }
1615         // find the maximum precision from the arguments and parameters
1616         for (unsigned int arg = 0; arg < numArgs; ++arg) {
1617             operationPrecision = std::max(operationPrecision, sequence[arg]->getAsTyped()->getQualifier().precision);
1618             operationPrecision = std::max(operationPrecision, function[arg].type->getQualifier().precision);
1619         }
1620         // compute the result precision
1621         if (agg->isSampling() ||
1622             agg->getOp() == EOpImageLoad || agg->getOp() == EOpImageStore ||
1623             agg->getOp() == EOpImageLoadLod || agg->getOp() == EOpImageStoreLod)
1624             resultPrecision = sequence[0]->getAsTyped()->getQualifier().precision;
1625         else if (function.getType().getBasicType() != EbtBool)
1626             resultPrecision = function.getType().getQualifier().precision == EpqNone ?
1627                                         operationPrecision :
1628                                         function.getType().getQualifier().precision;
1629     }
1630 
1631     // Propagate precision through this node and its children. That algorithm stops
1632     // when a precision is found, so start by clearing this subroot precision
1633     opNode->getQualifier().precision = EpqNone;
1634     if (operationPrecision != EpqNone) {
1635         opNode->propagatePrecision(operationPrecision);
1636         opNode->setOperationPrecision(operationPrecision);
1637     }
1638     // Now, set the result precision, which might not match
1639     opNode->getQualifier().precision = resultPrecision;
1640 }
1641 
handleReturnValue(const TSourceLoc & loc,TIntermTyped * value)1642 TIntermNode* TParseContext::handleReturnValue(const TSourceLoc& loc, TIntermTyped* value)
1643 {
1644     storage16BitAssignmentCheck(loc, value->getType(), "return");
1645 
1646     functionReturnsValue = true;
1647     TIntermBranch* branch = nullptr;
1648     if (currentFunctionType->getBasicType() == EbtVoid) {
1649         error(loc, "void function cannot return a value", "return", "");
1650         branch = intermediate.addBranch(EOpReturn, loc);
1651     } else if (*currentFunctionType != value->getType()) {
1652         TIntermTyped* converted = intermediate.addConversion(EOpReturn, *currentFunctionType, value);
1653         if (converted) {
1654             if (*currentFunctionType != converted->getType())
1655                 error(loc, "cannot convert return value to function return type", "return", "");
1656             if (version < 420)
1657                 warn(loc, "type conversion on return values was not explicitly allowed until version 420",
1658                      "return", "");
1659             branch = intermediate.addBranch(EOpReturn, converted, loc);
1660         } else {
1661             error(loc, "type does not match, or is not convertible to, the function's return type", "return", "");
1662             branch = intermediate.addBranch(EOpReturn, value, loc);
1663         }
1664     } else {
1665         if (value->getType().isTexture() || value->getType().isImage()) {
1666             if (spvVersion.spv != 0)
1667                 error(loc, "sampler or image cannot be used as return type when generating SPIR-V", "return", "");
1668             else if (!extensionTurnedOn(E_GL_ARB_bindless_texture))
1669                 error(loc, "sampler or image can be used as return type only when the extension GL_ARB_bindless_texture enabled", "return", "");
1670         }
1671         branch = intermediate.addBranch(EOpReturn, value, loc);
1672     }
1673     branch->updatePrecision(currentFunctionType->getQualifier().precision);
1674     return branch;
1675 }
1676 
1677 // See if the operation is being done in an illegal location.
checkLocation(const TSourceLoc & loc,TOperator op)1678 void TParseContext::checkLocation(const TSourceLoc& loc, TOperator op)
1679 {
1680     switch (op) {
1681     case EOpBarrier:
1682         if (language == EShLangTessControl) {
1683             if (controlFlowNestingLevel > 0)
1684                 error(loc, "tessellation control barrier() cannot be placed within flow control", "", "");
1685             if (! inMain)
1686                 error(loc, "tessellation control barrier() must be in main()", "", "");
1687             else if (postEntryPointReturn)
1688                 error(loc, "tessellation control barrier() cannot be placed after a return from main()", "", "");
1689         }
1690         break;
1691     case EOpBeginInvocationInterlock:
1692         if (language != EShLangFragment)
1693             error(loc, "beginInvocationInterlockARB() must be in a fragment shader", "", "");
1694         if (! inMain)
1695             error(loc, "beginInvocationInterlockARB() must be in main()", "", "");
1696         else if (postEntryPointReturn)
1697             error(loc, "beginInvocationInterlockARB() cannot be placed after a return from main()", "", "");
1698         if (controlFlowNestingLevel > 0)
1699             error(loc, "beginInvocationInterlockARB() cannot be placed within flow control", "", "");
1700 
1701         if (beginInvocationInterlockCount > 0)
1702             error(loc, "beginInvocationInterlockARB() must only be called once", "", "");
1703         if (endInvocationInterlockCount > 0)
1704             error(loc, "beginInvocationInterlockARB() must be called before endInvocationInterlockARB()", "", "");
1705 
1706         beginInvocationInterlockCount++;
1707 
1708         // default to pixel_interlock_ordered
1709         if (intermediate.getInterlockOrdering() == EioNone)
1710             intermediate.setInterlockOrdering(EioPixelInterlockOrdered);
1711         break;
1712     case EOpEndInvocationInterlock:
1713         if (language != EShLangFragment)
1714             error(loc, "endInvocationInterlockARB() must be in a fragment shader", "", "");
1715         if (! inMain)
1716             error(loc, "endInvocationInterlockARB() must be in main()", "", "");
1717         else if (postEntryPointReturn)
1718             error(loc, "endInvocationInterlockARB() cannot be placed after a return from main()", "", "");
1719         if (controlFlowNestingLevel > 0)
1720             error(loc, "endInvocationInterlockARB() cannot be placed within flow control", "", "");
1721 
1722         if (endInvocationInterlockCount > 0)
1723             error(loc, "endInvocationInterlockARB() must only be called once", "", "");
1724         if (beginInvocationInterlockCount == 0)
1725             error(loc, "beginInvocationInterlockARB() must be called before endInvocationInterlockARB()", "", "");
1726 
1727         endInvocationInterlockCount++;
1728         break;
1729     default:
1730         break;
1731     }
1732 }
1733 
1734 // Finish processing object.length(). This started earlier in handleDotDereference(), where
1735 // the ".length" part was recognized and semantically checked, and finished here where the
1736 // function syntax "()" is recognized.
1737 //
1738 // Return resulting tree node.
handleLengthMethod(const TSourceLoc & loc,TFunction * function,TIntermNode * intermNode)1739 TIntermTyped* TParseContext::handleLengthMethod(const TSourceLoc& loc, TFunction* function, TIntermNode* intermNode)
1740 {
1741     int length = 0;
1742 
1743     if (function->getParamCount() > 0)
1744         error(loc, "method does not accept any arguments", function->getName().c_str(), "");
1745     else {
1746         const TType& type = intermNode->getAsTyped()->getType();
1747         if (type.isArray()) {
1748             if (type.isUnsizedArray()) {
1749                 if (intermNode->getAsSymbolNode() && isIoResizeArray(type)) {
1750                     // We could be between a layout declaration that gives a built-in io array implicit size and
1751                     // a user redeclaration of that array, meaning we have to substitute its implicit size here
1752                     // without actually redeclaring the array.  (It is an error to use a member before the
1753                     // redeclaration, but not an error to use the array name itself.)
1754                     const TString& name = intermNode->getAsSymbolNode()->getName();
1755                     if (name == "gl_in" || name == "gl_out" || name == "gl_MeshVerticesNV" ||
1756                         name == "gl_MeshPrimitivesNV") {
1757                         length = getIoArrayImplicitSize(type.getQualifier());
1758                     }
1759                 }
1760                 if (length == 0) {
1761                     if (intermNode->getAsSymbolNode() && isIoResizeArray(type))
1762                         error(loc, "", function->getName().c_str(), "array must first be sized by a redeclaration or layout qualifier");
1763                     else if (isRuntimeLength(*intermNode->getAsTyped())) {
1764                         // Create a unary op and let the back end handle it
1765                         return intermediate.addBuiltInFunctionCall(loc, EOpArrayLength, true, intermNode, TType(EbtInt));
1766                     } else
1767                         error(loc, "", function->getName().c_str(), "array must be declared with a size before using this method");
1768                 }
1769             } else if (type.getOuterArrayNode()) {
1770                 // If the array's outer size is specified by an intermediate node, it means the array's length
1771                 // was specified by a specialization constant. In such a case, we should return the node of the
1772                 // specialization constants to represent the length.
1773                 return type.getOuterArrayNode();
1774             } else
1775                 length = type.getOuterArraySize();
1776         } else if (type.isMatrix())
1777             length = type.getMatrixCols();
1778         else if (type.isVector())
1779             length = type.getVectorSize();
1780         else if (type.isCoopMat())
1781             return intermediate.addBuiltInFunctionCall(loc, EOpArrayLength, true, intermNode, TType(EbtInt));
1782         else {
1783             // we should not get here, because earlier semantic checking should have prevented this path
1784             error(loc, ".length()", "unexpected use of .length()", "");
1785         }
1786     }
1787 
1788     if (length == 0)
1789         length = 1;
1790 
1791     return intermediate.addConstantUnion(length, loc);
1792 }
1793 
1794 //
1795 // Add any needed implicit conversions for function-call arguments to input parameters.
1796 //
addInputArgumentConversions(const TFunction & function,TIntermNode * & arguments) const1797 void TParseContext::addInputArgumentConversions(const TFunction& function, TIntermNode*& arguments) const
1798 {
1799     TIntermAggregate* aggregate = arguments->getAsAggregate();
1800 
1801     // Process each argument's conversion
1802     for (int i = 0; i < function.getParamCount(); ++i) {
1803         // At this early point there is a slight ambiguity between whether an aggregate 'arguments'
1804         // is the single argument itself or its children are the arguments.  Only one argument
1805         // means take 'arguments' itself as the one argument.
1806         TIntermTyped* arg = function.getParamCount() == 1 ? arguments->getAsTyped() : (aggregate ? aggregate->getSequence()[i]->getAsTyped() : arguments->getAsTyped());
1807         if (*function[i].type != arg->getType()) {
1808             if (function[i].type->getQualifier().isParamInput() &&
1809                !function[i].type->isCoopMat()) {
1810                 // In-qualified arguments just need an extra node added above the argument to
1811                 // convert to the correct type.
1812                 arg = intermediate.addConversion(EOpFunctionCall, *function[i].type, arg);
1813                 if (arg) {
1814                     if (function.getParamCount() == 1)
1815                         arguments = arg;
1816                     else {
1817                         if (aggregate)
1818                             aggregate->getSequence()[i] = arg;
1819                         else
1820                             arguments = arg;
1821                     }
1822                 }
1823             }
1824         }
1825     }
1826 }
1827 
1828 //
1829 // Add any needed implicit output conversions for function-call arguments.  This
1830 // can require a new tree topology, complicated further by whether the function
1831 // has a return value.
1832 //
1833 // Returns a node of a subtree that evaluates to the return value of the function.
1834 //
addOutputArgumentConversions(const TFunction & function,TIntermAggregate & intermNode) const1835 TIntermTyped* TParseContext::addOutputArgumentConversions(const TFunction& function, TIntermAggregate& intermNode) const
1836 {
1837     TIntermSequence& arguments = intermNode.getSequence();
1838 
1839     // Will there be any output conversions?
1840     bool outputConversions = false;
1841     for (int i = 0; i < function.getParamCount(); ++i) {
1842         if (*function[i].type != arguments[i]->getAsTyped()->getType() && function[i].type->getQualifier().isParamOutput()) {
1843             outputConversions = true;
1844             break;
1845         }
1846     }
1847 
1848     if (! outputConversions)
1849         return &intermNode;
1850 
1851     // Setup for the new tree, if needed:
1852     //
1853     // Output conversions need a different tree topology.
1854     // Out-qualified arguments need a temporary of the correct type, with the call
1855     // followed by an assignment of the temporary to the original argument:
1856     //     void: function(arg, ...)  ->        (          function(tempArg, ...), arg = tempArg, ...)
1857     //     ret = function(arg, ...)  ->  ret = (tempRet = function(tempArg, ...), arg = tempArg, ..., tempRet)
1858     // Where the "tempArg" type needs no conversion as an argument, but will convert on assignment.
1859     TIntermTyped* conversionTree = nullptr;
1860     TVariable* tempRet = nullptr;
1861     if (intermNode.getBasicType() != EbtVoid) {
1862         // do the "tempRet = function(...), " bit from above
1863         tempRet = makeInternalVariable("tempReturn", intermNode.getType());
1864         TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, intermNode.getLoc());
1865         conversionTree = intermediate.addAssign(EOpAssign, tempRetNode, &intermNode, intermNode.getLoc());
1866     } else
1867         conversionTree = &intermNode;
1868 
1869     conversionTree = intermediate.makeAggregate(conversionTree);
1870 
1871     // Process each argument's conversion
1872     for (int i = 0; i < function.getParamCount(); ++i) {
1873         if (*function[i].type != arguments[i]->getAsTyped()->getType()) {
1874             if (function[i].type->getQualifier().isParamOutput()) {
1875                 // Out-qualified arguments need to use the topology set up above.
1876                 // do the " ...(tempArg, ...), arg = tempArg" bit from above
1877                 TType paramType;
1878                 paramType.shallowCopy(*function[i].type);
1879                 if (arguments[i]->getAsTyped()->getType().isParameterized() &&
1880                     !paramType.isParameterized()) {
1881                     paramType.shallowCopy(arguments[i]->getAsTyped()->getType());
1882                     paramType.copyTypeParameters(*arguments[i]->getAsTyped()->getType().getTypeParameters());
1883                 }
1884                 TVariable* tempArg = makeInternalVariable("tempArg", paramType);
1885                 tempArg->getWritableType().getQualifier().makeTemporary();
1886                 TIntermSymbol* tempArgNode = intermediate.addSymbol(*tempArg, intermNode.getLoc());
1887                 TIntermTyped* tempAssign = intermediate.addAssign(EOpAssign, arguments[i]->getAsTyped(), tempArgNode, arguments[i]->getLoc());
1888                 conversionTree = intermediate.growAggregate(conversionTree, tempAssign, arguments[i]->getLoc());
1889                 // replace the argument with another node for the same tempArg variable
1890                 arguments[i] = intermediate.addSymbol(*tempArg, intermNode.getLoc());
1891             }
1892         }
1893     }
1894 
1895     // Finalize the tree topology (see bigger comment above).
1896     if (tempRet) {
1897         // do the "..., tempRet" bit from above
1898         TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, intermNode.getLoc());
1899         conversionTree = intermediate.growAggregate(conversionTree, tempRetNode, intermNode.getLoc());
1900     }
1901     conversionTree = intermediate.setAggregateOperator(conversionTree, EOpComma, intermNode.getType(), intermNode.getLoc());
1902 
1903     return conversionTree;
1904 }
1905 
addAssign(const TSourceLoc & loc,TOperator op,TIntermTyped * left,TIntermTyped * right)1906 TIntermTyped* TParseContext::addAssign(const TSourceLoc& loc, TOperator op, TIntermTyped* left, TIntermTyped* right)
1907 {
1908     if ((op == EOpAddAssign || op == EOpSubAssign) && left->isReference())
1909         requireExtensions(loc, 1, &E_GL_EXT_buffer_reference2, "+= and -= on a buffer reference");
1910 
1911     if (op == EOpAssign && left->getBasicType() == EbtSampler && right->getBasicType() == EbtSampler)
1912         requireExtensions(loc, 1, &E_GL_ARB_bindless_texture, "sampler assignment for bindless texture");
1913 
1914     return intermediate.addAssign(op, left, right, loc);
1915 }
1916 
memorySemanticsCheck(const TSourceLoc & loc,const TFunction & fnCandidate,const TIntermOperator & callNode)1917 void TParseContext::memorySemanticsCheck(const TSourceLoc& loc, const TFunction& fnCandidate, const TIntermOperator& callNode)
1918 {
1919     const TIntermSequence* argp = &callNode.getAsAggregate()->getSequence();
1920 
1921     //const int gl_SemanticsRelaxed         = 0x0;
1922     const int gl_SemanticsAcquire         = 0x2;
1923     const int gl_SemanticsRelease         = 0x4;
1924     const int gl_SemanticsAcquireRelease  = 0x8;
1925     const int gl_SemanticsMakeAvailable   = 0x2000;
1926     const int gl_SemanticsMakeVisible     = 0x4000;
1927     const int gl_SemanticsVolatile        = 0x8000;
1928 
1929     //const int gl_StorageSemanticsNone     = 0x0;
1930     const int gl_StorageSemanticsBuffer   = 0x40;
1931     const int gl_StorageSemanticsShared   = 0x100;
1932     const int gl_StorageSemanticsImage    = 0x800;
1933     const int gl_StorageSemanticsOutput   = 0x1000;
1934 
1935 
1936     unsigned int semantics = 0, storageClassSemantics = 0;
1937     unsigned int semantics2 = 0, storageClassSemantics2 = 0;
1938 
1939     const TIntermTyped* arg0 = (*argp)[0]->getAsTyped();
1940     const bool isMS = arg0->getBasicType() == EbtSampler && arg0->getType().getSampler().isMultiSample();
1941 
1942     // Grab the semantics and storage class semantics from the operands, based on opcode
1943     switch (callNode.getOp()) {
1944     case EOpAtomicAdd:
1945     case EOpAtomicSubtract:
1946     case EOpAtomicMin:
1947     case EOpAtomicMax:
1948     case EOpAtomicAnd:
1949     case EOpAtomicOr:
1950     case EOpAtomicXor:
1951     case EOpAtomicExchange:
1952     case EOpAtomicStore:
1953         storageClassSemantics = (*argp)[3]->getAsConstantUnion()->getConstArray()[0].getIConst();
1954         semantics = (*argp)[4]->getAsConstantUnion()->getConstArray()[0].getIConst();
1955         break;
1956     case EOpAtomicLoad:
1957         storageClassSemantics = (*argp)[2]->getAsConstantUnion()->getConstArray()[0].getIConst();
1958         semantics = (*argp)[3]->getAsConstantUnion()->getConstArray()[0].getIConst();
1959         break;
1960     case EOpAtomicCompSwap:
1961         storageClassSemantics = (*argp)[4]->getAsConstantUnion()->getConstArray()[0].getIConst();
1962         semantics = (*argp)[5]->getAsConstantUnion()->getConstArray()[0].getIConst();
1963         storageClassSemantics2 = (*argp)[6]->getAsConstantUnion()->getConstArray()[0].getIConst();
1964         semantics2 = (*argp)[7]->getAsConstantUnion()->getConstArray()[0].getIConst();
1965         break;
1966 
1967     case EOpImageAtomicAdd:
1968     case EOpImageAtomicMin:
1969     case EOpImageAtomicMax:
1970     case EOpImageAtomicAnd:
1971     case EOpImageAtomicOr:
1972     case EOpImageAtomicXor:
1973     case EOpImageAtomicExchange:
1974     case EOpImageAtomicStore:
1975         storageClassSemantics = (*argp)[isMS ? 5 : 4]->getAsConstantUnion()->getConstArray()[0].getIConst();
1976         semantics = (*argp)[isMS ? 6 : 5]->getAsConstantUnion()->getConstArray()[0].getIConst();
1977         break;
1978     case EOpImageAtomicLoad:
1979         storageClassSemantics = (*argp)[isMS ? 4 : 3]->getAsConstantUnion()->getConstArray()[0].getIConst();
1980         semantics = (*argp)[isMS ? 5 : 4]->getAsConstantUnion()->getConstArray()[0].getIConst();
1981         break;
1982     case EOpImageAtomicCompSwap:
1983         storageClassSemantics = (*argp)[isMS ? 6 : 5]->getAsConstantUnion()->getConstArray()[0].getIConst();
1984         semantics = (*argp)[isMS ? 7 : 6]->getAsConstantUnion()->getConstArray()[0].getIConst();
1985         storageClassSemantics2 = (*argp)[isMS ? 8 : 7]->getAsConstantUnion()->getConstArray()[0].getIConst();
1986         semantics2 = (*argp)[isMS ? 9 : 8]->getAsConstantUnion()->getConstArray()[0].getIConst();
1987         break;
1988 
1989     case EOpBarrier:
1990         storageClassSemantics = (*argp)[2]->getAsConstantUnion()->getConstArray()[0].getIConst();
1991         semantics = (*argp)[3]->getAsConstantUnion()->getConstArray()[0].getIConst();
1992         break;
1993     case EOpMemoryBarrier:
1994         storageClassSemantics = (*argp)[1]->getAsConstantUnion()->getConstArray()[0].getIConst();
1995         semantics = (*argp)[2]->getAsConstantUnion()->getConstArray()[0].getIConst();
1996         break;
1997     default:
1998         break;
1999     }
2000 
2001     if ((semantics & gl_SemanticsAcquire) &&
2002         (callNode.getOp() == EOpAtomicStore || callNode.getOp() == EOpImageAtomicStore)) {
2003         error(loc, "gl_SemanticsAcquire must not be used with (image) atomic store",
2004               fnCandidate.getName().c_str(), "");
2005     }
2006     if ((semantics & gl_SemanticsRelease) &&
2007         (callNode.getOp() == EOpAtomicLoad || callNode.getOp() == EOpImageAtomicLoad)) {
2008         error(loc, "gl_SemanticsRelease must not be used with (image) atomic load",
2009               fnCandidate.getName().c_str(), "");
2010     }
2011     if ((semantics & gl_SemanticsAcquireRelease) &&
2012         (callNode.getOp() == EOpAtomicStore || callNode.getOp() == EOpImageAtomicStore ||
2013          callNode.getOp() == EOpAtomicLoad  || callNode.getOp() == EOpImageAtomicLoad)) {
2014         error(loc, "gl_SemanticsAcquireRelease must not be used with (image) atomic load/store",
2015               fnCandidate.getName().c_str(), "");
2016     }
2017     if (((semantics | semantics2) & ~(gl_SemanticsAcquire |
2018                                       gl_SemanticsRelease |
2019                                       gl_SemanticsAcquireRelease |
2020                                       gl_SemanticsMakeAvailable |
2021                                       gl_SemanticsMakeVisible |
2022                                       gl_SemanticsVolatile))) {
2023         error(loc, "Invalid semantics value", fnCandidate.getName().c_str(), "");
2024     }
2025     if (((storageClassSemantics | storageClassSemantics2) & ~(gl_StorageSemanticsBuffer |
2026                                                               gl_StorageSemanticsShared |
2027                                                               gl_StorageSemanticsImage |
2028                                                               gl_StorageSemanticsOutput))) {
2029         error(loc, "Invalid storage class semantics value", fnCandidate.getName().c_str(), "");
2030     }
2031 
2032     if (callNode.getOp() == EOpMemoryBarrier) {
2033         if (!IsPow2(semantics & (gl_SemanticsAcquire | gl_SemanticsRelease | gl_SemanticsAcquireRelease))) {
2034             error(loc, "Semantics must include exactly one of gl_SemanticsRelease, gl_SemanticsAcquire, or "
2035                        "gl_SemanticsAcquireRelease", fnCandidate.getName().c_str(), "");
2036         }
2037     } else {
2038         if (semantics & (gl_SemanticsAcquire | gl_SemanticsRelease | gl_SemanticsAcquireRelease)) {
2039             if (!IsPow2(semantics & (gl_SemanticsAcquire | gl_SemanticsRelease | gl_SemanticsAcquireRelease))) {
2040                 error(loc, "Semantics must not include multiple of gl_SemanticsRelease, gl_SemanticsAcquire, or "
2041                            "gl_SemanticsAcquireRelease", fnCandidate.getName().c_str(), "");
2042             }
2043         }
2044         if (semantics2 & (gl_SemanticsAcquire | gl_SemanticsRelease | gl_SemanticsAcquireRelease)) {
2045             if (!IsPow2(semantics2 & (gl_SemanticsAcquire | gl_SemanticsRelease | gl_SemanticsAcquireRelease))) {
2046                 error(loc, "semUnequal must not include multiple of gl_SemanticsRelease, gl_SemanticsAcquire, or "
2047                            "gl_SemanticsAcquireRelease", fnCandidate.getName().c_str(), "");
2048             }
2049         }
2050     }
2051     if (callNode.getOp() == EOpMemoryBarrier) {
2052         if (storageClassSemantics == 0) {
2053             error(loc, "Storage class semantics must not be zero", fnCandidate.getName().c_str(), "");
2054         }
2055     }
2056     if (callNode.getOp() == EOpBarrier && semantics != 0 && storageClassSemantics == 0) {
2057         error(loc, "Storage class semantics must not be zero", fnCandidate.getName().c_str(), "");
2058     }
2059     if ((callNode.getOp() == EOpAtomicCompSwap || callNode.getOp() == EOpImageAtomicCompSwap) &&
2060         (semantics2 & (gl_SemanticsRelease | gl_SemanticsAcquireRelease))) {
2061         error(loc, "semUnequal must not be gl_SemanticsRelease or gl_SemanticsAcquireRelease",
2062               fnCandidate.getName().c_str(), "");
2063     }
2064     if ((semantics & gl_SemanticsMakeAvailable) &&
2065         !(semantics & (gl_SemanticsRelease | gl_SemanticsAcquireRelease))) {
2066         error(loc, "gl_SemanticsMakeAvailable requires gl_SemanticsRelease or gl_SemanticsAcquireRelease",
2067               fnCandidate.getName().c_str(), "");
2068     }
2069     if ((semantics & gl_SemanticsMakeVisible) &&
2070         !(semantics & (gl_SemanticsAcquire | gl_SemanticsAcquireRelease))) {
2071         error(loc, "gl_SemanticsMakeVisible requires gl_SemanticsAcquire or gl_SemanticsAcquireRelease",
2072               fnCandidate.getName().c_str(), "");
2073     }
2074     if ((semantics & gl_SemanticsVolatile) &&
2075         (callNode.getOp() == EOpMemoryBarrier || callNode.getOp() == EOpBarrier)) {
2076         error(loc, "gl_SemanticsVolatile must not be used with memoryBarrier or controlBarrier",
2077               fnCandidate.getName().c_str(), "");
2078     }
2079     if ((callNode.getOp() == EOpAtomicCompSwap || callNode.getOp() == EOpImageAtomicCompSwap) &&
2080         ((semantics ^ semantics2) & gl_SemanticsVolatile)) {
2081         error(loc, "semEqual and semUnequal must either both include gl_SemanticsVolatile or neither",
2082               fnCandidate.getName().c_str(), "");
2083     }
2084 }
2085 
2086 //
2087 // Do additional checking of built-in function calls that is not caught
2088 // by normal semantic checks on argument type, extension tagging, etc.
2089 //
2090 // Assumes there has been a semantically correct match to a built-in function prototype.
2091 //
builtInOpCheck(const TSourceLoc & loc,const TFunction & fnCandidate,TIntermOperator & callNode)2092 void TParseContext::builtInOpCheck(const TSourceLoc& loc, const TFunction& fnCandidate, TIntermOperator& callNode)
2093 {
2094     // Set up convenience accessors to the argument(s).  There is almost always
2095     // multiple arguments for the cases below, but when there might be one,
2096     // check the unaryArg first.
2097     const TIntermSequence* argp = nullptr;   // confusing to use [] syntax on a pointer, so this is to help get a reference
2098     const TIntermTyped* unaryArg = nullptr;
2099     const TIntermTyped* arg0 = nullptr;
2100     if (callNode.getAsAggregate()) {
2101         argp = &callNode.getAsAggregate()->getSequence();
2102         if (argp->size() > 0)
2103             arg0 = (*argp)[0]->getAsTyped();
2104     } else {
2105         assert(callNode.getAsUnaryNode());
2106         unaryArg = callNode.getAsUnaryNode()->getOperand();
2107         arg0 = unaryArg;
2108     }
2109 
2110     TString featureString;
2111     const char* feature = nullptr;
2112     switch (callNode.getOp()) {
2113     case EOpTextureGather:
2114     case EOpTextureGatherOffset:
2115     case EOpTextureGatherOffsets:
2116     {
2117         // Figure out which variants are allowed by what extensions,
2118         // and what arguments must be constant for which situations.
2119 
2120         featureString = fnCandidate.getName();
2121         featureString += "(...)";
2122         feature = featureString.c_str();
2123         profileRequires(loc, EEsProfile, 310, nullptr, feature);
2124         int compArg = -1;  // track which argument, if any, is the constant component argument
2125         switch (callNode.getOp()) {
2126         case EOpTextureGather:
2127             // More than two arguments needs gpu_shader5, and rectangular or shadow needs gpu_shader5,
2128             // otherwise, need GL_ARB_texture_gather.
2129             if (fnCandidate.getParamCount() > 2 || fnCandidate[0].type->getSampler().dim == EsdRect || fnCandidate[0].type->getSampler().shadow) {
2130                 profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_gpu_shader5, feature);
2131                 if (! fnCandidate[0].type->getSampler().shadow)
2132                     compArg = 2;
2133             } else
2134                 profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_texture_gather, feature);
2135             break;
2136         case EOpTextureGatherOffset:
2137             // GL_ARB_texture_gather is good enough for 2D non-shadow textures with no component argument
2138             if (fnCandidate[0].type->getSampler().dim == Esd2D && ! fnCandidate[0].type->getSampler().shadow && fnCandidate.getParamCount() == 3)
2139                 profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_texture_gather, feature);
2140             else
2141                 profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_gpu_shader5, feature);
2142             if (! (*argp)[fnCandidate[0].type->getSampler().shadow ? 3 : 2]->getAsConstantUnion())
2143                 profileRequires(loc, EEsProfile, 320, Num_AEP_gpu_shader5, AEP_gpu_shader5,
2144                                 "non-constant offset argument");
2145             if (! fnCandidate[0].type->getSampler().shadow)
2146                 compArg = 3;
2147             break;
2148         case EOpTextureGatherOffsets:
2149             profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_gpu_shader5, feature);
2150             if (! fnCandidate[0].type->getSampler().shadow)
2151                 compArg = 3;
2152             // check for constant offsets
2153             if (! (*argp)[fnCandidate[0].type->getSampler().shadow ? 3 : 2]->getAsConstantUnion())
2154                 error(loc, "must be a compile-time constant:", feature, "offsets argument");
2155             break;
2156         default:
2157             break;
2158         }
2159 
2160         if (compArg > 0 && compArg < fnCandidate.getParamCount()) {
2161             if ((*argp)[compArg]->getAsConstantUnion()) {
2162                 int value = (*argp)[compArg]->getAsConstantUnion()->getConstArray()[0].getIConst();
2163                 if (value < 0 || value > 3)
2164                     error(loc, "must be 0, 1, 2, or 3:", feature, "component argument");
2165             } else
2166                 error(loc, "must be a compile-time constant:", feature, "component argument");
2167         }
2168 
2169         bool bias = false;
2170         if (callNode.getOp() == EOpTextureGather)
2171             bias = fnCandidate.getParamCount() > 3;
2172         else if (callNode.getOp() == EOpTextureGatherOffset ||
2173                  callNode.getOp() == EOpTextureGatherOffsets)
2174             bias = fnCandidate.getParamCount() > 4;
2175 
2176         if (bias) {
2177             featureString = fnCandidate.getName();
2178             featureString += "with bias argument";
2179             feature = featureString.c_str();
2180             profileRequires(loc, ~EEsProfile, 450, nullptr, feature);
2181             requireExtensions(loc, 1, &E_GL_AMD_texture_gather_bias_lod, feature);
2182         }
2183         break;
2184     }
2185 
2186     case EOpTexture:
2187     case EOpTextureLod:
2188     {
2189         if ((fnCandidate.getParamCount() > 2) && ((*argp)[1]->getAsTyped()->getType().getBasicType() == EbtFloat) &&
2190             ((*argp)[1]->getAsTyped()->getType().getVectorSize() == 4) && fnCandidate[0].type->getSampler().shadow) {
2191             featureString = fnCandidate.getName();
2192             if (callNode.getOp() == EOpTexture)
2193                 featureString += "(..., float bias)";
2194             else
2195                 featureString += "(..., float lod)";
2196             feature = featureString.c_str();
2197 
2198             if ((fnCandidate[0].type->getSampler().dim == Esd2D && fnCandidate[0].type->getSampler().arrayed) || //2D Array Shadow
2199                 (fnCandidate[0].type->getSampler().dim == EsdCube && fnCandidate[0].type->getSampler().arrayed && fnCandidate.getParamCount() > 3) || // Cube Array Shadow
2200                 (fnCandidate[0].type->getSampler().dim == EsdCube && callNode.getOp() == EOpTextureLod)) { // Cube Shadow
2201                 requireExtensions(loc, 1, &E_GL_EXT_texture_shadow_lod, feature);
2202                 if (isEsProfile()) {
2203                     if (version < 320 &&
2204                         !extensionsTurnedOn(Num_AEP_texture_cube_map_array, AEP_texture_cube_map_array))
2205                         error(loc, "GL_EXT_texture_shadow_lod not supported for this ES version", feature, "");
2206                     else
2207                         profileRequires(loc, EEsProfile, 320, nullptr, feature);
2208                 } else { // Desktop
2209                     profileRequires(loc, ~EEsProfile, 130, nullptr, feature);
2210                 }
2211             }
2212         }
2213         break;
2214     }
2215 
2216     case EOpSparseTextureGather:
2217     case EOpSparseTextureGatherOffset:
2218     case EOpSparseTextureGatherOffsets:
2219     {
2220         bool bias = false;
2221         if (callNode.getOp() == EOpSparseTextureGather)
2222             bias = fnCandidate.getParamCount() > 4;
2223         else if (callNode.getOp() == EOpSparseTextureGatherOffset ||
2224                  callNode.getOp() == EOpSparseTextureGatherOffsets)
2225             bias = fnCandidate.getParamCount() > 5;
2226 
2227         if (bias) {
2228             featureString = fnCandidate.getName();
2229             featureString += "with bias argument";
2230             feature = featureString.c_str();
2231             profileRequires(loc, ~EEsProfile, 450, nullptr, feature);
2232             requireExtensions(loc, 1, &E_GL_AMD_texture_gather_bias_lod, feature);
2233         }
2234         // As per GL_ARB_sparse_texture2 extension "Offsets" parameter must be constant integral expression
2235         // for sparseTextureGatherOffsetsARB just as textureGatherOffsets
2236         if (callNode.getOp() == EOpSparseTextureGatherOffsets) {
2237             int offsetsArg = arg0->getType().getSampler().shadow ? 3 : 2;
2238             if (!(*argp)[offsetsArg]->getAsConstantUnion())
2239                 error(loc, "argument must be compile-time constant", "offsets", "");
2240         }
2241         break;
2242     }
2243 
2244     case EOpSparseTextureGatherLod:
2245     case EOpSparseTextureGatherLodOffset:
2246     case EOpSparseTextureGatherLodOffsets:
2247     {
2248         requireExtensions(loc, 1, &E_GL_ARB_sparse_texture2, fnCandidate.getName().c_str());
2249         break;
2250     }
2251 
2252     case EOpSwizzleInvocations:
2253     {
2254         if (! (*argp)[1]->getAsConstantUnion())
2255             error(loc, "argument must be compile-time constant", "offset", "");
2256         else {
2257             unsigned offset[4] = {};
2258             offset[0] = (*argp)[1]->getAsConstantUnion()->getConstArray()[0].getUConst();
2259             offset[1] = (*argp)[1]->getAsConstantUnion()->getConstArray()[1].getUConst();
2260             offset[2] = (*argp)[1]->getAsConstantUnion()->getConstArray()[2].getUConst();
2261             offset[3] = (*argp)[1]->getAsConstantUnion()->getConstArray()[3].getUConst();
2262             if (offset[0] > 3 || offset[1] > 3 || offset[2] > 3 || offset[3] > 3)
2263                 error(loc, "components must be in the range [0, 3]", "offset", "");
2264         }
2265 
2266         break;
2267     }
2268 
2269     case EOpSwizzleInvocationsMasked:
2270     {
2271         if (! (*argp)[1]->getAsConstantUnion())
2272             error(loc, "argument must be compile-time constant", "mask", "");
2273         else {
2274             unsigned mask[3] = {};
2275             mask[0] = (*argp)[1]->getAsConstantUnion()->getConstArray()[0].getUConst();
2276             mask[1] = (*argp)[1]->getAsConstantUnion()->getConstArray()[1].getUConst();
2277             mask[2] = (*argp)[1]->getAsConstantUnion()->getConstArray()[2].getUConst();
2278             if (mask[0] > 31 || mask[1] > 31 || mask[2] > 31)
2279                 error(loc, "components must be in the range [0, 31]", "mask", "");
2280         }
2281 
2282         break;
2283     }
2284 
2285     case EOpTextureOffset:
2286     case EOpTextureFetchOffset:
2287     case EOpTextureProjOffset:
2288     case EOpTextureLodOffset:
2289     case EOpTextureProjLodOffset:
2290     case EOpTextureGradOffset:
2291     case EOpTextureProjGradOffset:
2292     {
2293         // Handle texture-offset limits checking
2294         // Pick which argument has to hold constant offsets
2295         int arg = -1;
2296         switch (callNode.getOp()) {
2297         case EOpTextureOffset:          arg = 2;  break;
2298         case EOpTextureFetchOffset:     arg = (arg0->getType().getSampler().isRect()) ? 2 : 3; break;
2299         case EOpTextureProjOffset:      arg = 2;  break;
2300         case EOpTextureLodOffset:       arg = 3;  break;
2301         case EOpTextureProjLodOffset:   arg = 3;  break;
2302         case EOpTextureGradOffset:      arg = 4;  break;
2303         case EOpTextureProjGradOffset:  arg = 4;  break;
2304         default:
2305             assert(0);
2306             break;
2307         }
2308 
2309         if (arg > 0) {
2310 
2311             bool f16ShadowCompare = (*argp)[1]->getAsTyped()->getBasicType() == EbtFloat16 &&
2312                                     arg0->getType().getSampler().shadow;
2313             if (f16ShadowCompare)
2314                 ++arg;
2315             if (! (*argp)[arg]->getAsTyped()->getQualifier().isConstant())
2316                 error(loc, "argument must be compile-time constant", "texel offset", "");
2317             else if ((*argp)[arg]->getAsConstantUnion()) {
2318                 const TType& type = (*argp)[arg]->getAsTyped()->getType();
2319                 for (int c = 0; c < type.getVectorSize(); ++c) {
2320                     int offset = (*argp)[arg]->getAsConstantUnion()->getConstArray()[c].getIConst();
2321                     if (offset > resources.maxProgramTexelOffset || offset < resources.minProgramTexelOffset)
2322                         error(loc, "value is out of range:", "texel offset",
2323                               "[gl_MinProgramTexelOffset, gl_MaxProgramTexelOffset]");
2324                 }
2325             }
2326 
2327             if (callNode.getOp() == EOpTextureOffset) {
2328                 TSampler s = arg0->getType().getSampler();
2329                 if (s.is2D() && s.isArrayed() && s.isShadow()) {
2330                     if (
2331                         ((*argp)[1]->getAsTyped()->getType().getBasicType() == EbtFloat) &&
2332                         ((*argp)[1]->getAsTyped()->getType().getVectorSize() == 4) &&
2333                         (fnCandidate.getParamCount() == 4)) {
2334                         featureString = fnCandidate.getName() + " for sampler2DArrayShadow";
2335                         feature = featureString.c_str();
2336                         requireExtensions(loc, 1, &E_GL_EXT_texture_shadow_lod, feature);
2337                         profileRequires(loc, EEsProfile, 300, nullptr, feature);
2338                         profileRequires(loc, ~EEsProfile, 130, nullptr, feature);
2339                     }
2340                     else if (isEsProfile())
2341                         error(loc, "TextureOffset does not support sampler2DArrayShadow : ", "sampler", "ES Profile");
2342                     else if (version <= 420)
2343                         error(loc, "TextureOffset does not support sampler2DArrayShadow : ", "sampler", "version <= 420");
2344                 }
2345             }
2346 
2347             if (callNode.getOp() == EOpTextureLodOffset) {
2348                 TSampler s = arg0->getType().getSampler();
2349                 if (s.is2D() && s.isArrayed() && s.isShadow() &&
2350                     ((*argp)[1]->getAsTyped()->getType().getBasicType() == EbtFloat) &&
2351                     ((*argp)[1]->getAsTyped()->getType().getVectorSize() == 4) &&
2352                     (fnCandidate.getParamCount() == 4)) {
2353                         featureString = fnCandidate.getName() + " for sampler2DArrayShadow";
2354                         feature = featureString.c_str();
2355                         profileRequires(loc, EEsProfile, 300, nullptr, feature);
2356                         profileRequires(loc, ~EEsProfile, 130, nullptr, feature);
2357                         requireExtensions(loc, 1, &E_GL_EXT_texture_shadow_lod, feature);
2358                 }
2359             }
2360         }
2361 
2362         break;
2363     }
2364 
2365     case EOpTraceNV:
2366         if (!(*argp)[10]->getAsConstantUnion())
2367             error(loc, "argument must be compile-time constant", "payload number", "a");
2368         break;
2369     case EOpTraceRayMotionNV:
2370         if (!(*argp)[11]->getAsConstantUnion())
2371             error(loc, "argument must be compile-time constant", "payload number", "a");
2372         break;
2373     case EOpTraceKHR:
2374         if (!(*argp)[10]->getAsConstantUnion())
2375             error(loc, "argument must be compile-time constant", "payload number", "a");
2376         else {
2377             unsigned int location = (*argp)[10]->getAsConstantUnion()->getAsConstantUnion()->getConstArray()[0].getUConst();
2378             if (!extensionTurnedOn(E_GL_EXT_spirv_intrinsics) && intermediate.checkLocationRT(0, location) < 0)
2379                 error(loc, "with layout(location =", "no rayPayloadEXT/rayPayloadInEXT declared", "%d)", location);
2380         }
2381         break;
2382     case EOpExecuteCallableNV:
2383         if (!(*argp)[1]->getAsConstantUnion())
2384             error(loc, "argument must be compile-time constant", "callable data number", "");
2385         break;
2386     case EOpExecuteCallableKHR:
2387         if (!(*argp)[1]->getAsConstantUnion())
2388             error(loc, "argument must be compile-time constant", "callable data number", "");
2389         else {
2390             unsigned int location = (*argp)[1]->getAsConstantUnion()->getAsConstantUnion()->getConstArray()[0].getUConst();
2391             if (!extensionTurnedOn(E_GL_EXT_spirv_intrinsics) && intermediate.checkLocationRT(1, location) < 0)
2392                 error(loc, "with layout(location =", "no callableDataEXT/callableDataInEXT declared", "%d)", location);
2393         }
2394         break;
2395 
2396     case EOpHitObjectTraceRayNV:
2397         if (!(*argp)[11]->getAsConstantUnion())
2398             error(loc, "argument must be compile-time constant", "payload number", "");
2399         else {
2400             unsigned int location = (*argp)[11]->getAsConstantUnion()->getAsConstantUnion()->getConstArray()[0].getUConst();
2401             if (!extensionTurnedOn(E_GL_EXT_spirv_intrinsics) && intermediate.checkLocationRT(0, location) < 0)
2402                 error(loc, "with layout(location =", "no rayPayloadEXT/rayPayloadInEXT declared", "%d)", location);
2403         }
2404         break;
2405     case EOpHitObjectTraceRayMotionNV:
2406         if (!(*argp)[12]->getAsConstantUnion())
2407             error(loc, "argument must be compile-time constant", "payload number", "");
2408         else {
2409             unsigned int location = (*argp)[12]->getAsConstantUnion()->getAsConstantUnion()->getConstArray()[0].getUConst();
2410             if (!extensionTurnedOn(E_GL_EXT_spirv_intrinsics) && intermediate.checkLocationRT(0, location) < 0)
2411                 error(loc, "with layout(location =", "no rayPayloadEXT/rayPayloadInEXT declared", "%d)", location);
2412         }
2413         break;
2414     case EOpHitObjectExecuteShaderNV:
2415         if (!(*argp)[1]->getAsConstantUnion())
2416             error(loc, "argument must be compile-time constant", "payload number", "");
2417         else {
2418             unsigned int location = (*argp)[1]->getAsConstantUnion()->getAsConstantUnion()->getConstArray()[0].getUConst();
2419             if (!extensionTurnedOn(E_GL_EXT_spirv_intrinsics) && intermediate.checkLocationRT(0, location) < 0)
2420                 error(loc, "with layout(location =", "no rayPayloadEXT/rayPayloadInEXT declared", "%d)", location);
2421         }
2422         break;
2423     case EOpHitObjectRecordHitNV:
2424         if (!(*argp)[12]->getAsConstantUnion())
2425             error(loc, "argument must be compile-time constant", "hitobjectattribute number", "");
2426         else {
2427             unsigned int location = (*argp)[12]->getAsConstantUnion()->getAsConstantUnion()->getConstArray()[0].getUConst();
2428             if (!extensionTurnedOn(E_GL_EXT_spirv_intrinsics) && intermediate.checkLocationRT(2, location) < 0)
2429                 error(loc, "with layout(location =", "no hitObjectAttributeNV declared", "%d)", location);
2430         }
2431         break;
2432     case EOpHitObjectRecordHitMotionNV:
2433         if (!(*argp)[13]->getAsConstantUnion())
2434             error(loc, "argument must be compile-time constant", "hitobjectattribute number", "");
2435         else {
2436             unsigned int location = (*argp)[13]->getAsConstantUnion()->getAsConstantUnion()->getConstArray()[0].getUConst();
2437             if (!extensionTurnedOn(E_GL_EXT_spirv_intrinsics) && intermediate.checkLocationRT(2, location) < 0)
2438                 error(loc, "with layout(location =", "no hitObjectAttributeNV declared", "%d)", location);
2439         }
2440         break;
2441     case EOpHitObjectRecordHitWithIndexNV:
2442         if (!(*argp)[11]->getAsConstantUnion())
2443             error(loc, "argument must be compile-time constant", "hitobjectattribute number", "");
2444         else {
2445             unsigned int location = (*argp)[11]->getAsConstantUnion()->getAsConstantUnion()->getConstArray()[0].getUConst();
2446             if (!extensionTurnedOn(E_GL_EXT_spirv_intrinsics) && intermediate.checkLocationRT(2, location) < 0)
2447                 error(loc, "with layout(location =", "no hitObjectAttributeNV declared", "%d)", location);
2448         }
2449         break;
2450     case EOpHitObjectRecordHitWithIndexMotionNV:
2451         if (!(*argp)[12]->getAsConstantUnion())
2452             error(loc, "argument must be compile-time constant", "hitobjectattribute number", "");
2453         else {
2454             unsigned int location = (*argp)[12]->getAsConstantUnion()->getAsConstantUnion()->getConstArray()[0].getUConst();
2455             if (!extensionTurnedOn(E_GL_EXT_spirv_intrinsics) && intermediate.checkLocationRT(2, location) < 0)
2456                 error(loc, "with layout(location =", "no hitObjectAttributeNV declared", "%d)", location);
2457         }
2458         break;
2459     case EOpHitObjectGetAttributesNV:
2460         if (!(*argp)[1]->getAsConstantUnion())
2461             error(loc, "argument must be compile-time constant", "hitobjectattribute number", "");
2462         else {
2463             unsigned int location = (*argp)[1]->getAsConstantUnion()->getAsConstantUnion()->getConstArray()[0].getUConst();
2464             if (!extensionTurnedOn(E_GL_EXT_spirv_intrinsics) && intermediate.checkLocationRT(2, location) < 0)
2465                 error(loc, "with layout(location =", "no hitObjectAttributeNV declared", "%d)", location);
2466         }
2467         break;
2468 
2469     case EOpRayQueryGetIntersectionType:
2470     case EOpRayQueryGetIntersectionT:
2471     case EOpRayQueryGetIntersectionInstanceCustomIndex:
2472     case EOpRayQueryGetIntersectionInstanceId:
2473     case EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2474     case EOpRayQueryGetIntersectionGeometryIndex:
2475     case EOpRayQueryGetIntersectionPrimitiveIndex:
2476     case EOpRayQueryGetIntersectionBarycentrics:
2477     case EOpRayQueryGetIntersectionFrontFace:
2478     case EOpRayQueryGetIntersectionObjectRayDirection:
2479     case EOpRayQueryGetIntersectionObjectRayOrigin:
2480     case EOpRayQueryGetIntersectionObjectToWorld:
2481     case EOpRayQueryGetIntersectionWorldToObject:
2482     case EOpRayQueryGetIntersectionTriangleVertexPositionsEXT:
2483         if (!(*argp)[1]->getAsConstantUnion())
2484             error(loc, "argument must be compile-time constant", "committed", "");
2485         break;
2486 
2487     case EOpTextureQuerySamples:
2488     case EOpImageQuerySamples:
2489         // GL_ARB_shader_texture_image_samples
2490         profileRequires(loc, ~EEsProfile, 450, E_GL_ARB_shader_texture_image_samples, "textureSamples and imageSamples");
2491         break;
2492 
2493     case EOpImageAtomicAdd:
2494     case EOpImageAtomicMin:
2495     case EOpImageAtomicMax:
2496     case EOpImageAtomicAnd:
2497     case EOpImageAtomicOr:
2498     case EOpImageAtomicXor:
2499     case EOpImageAtomicExchange:
2500     case EOpImageAtomicCompSwap:
2501     case EOpImageAtomicLoad:
2502     case EOpImageAtomicStore:
2503     {
2504         // Make sure the image types have the correct layout() format and correct argument types
2505         const TType& imageType = arg0->getType();
2506         if (imageType.getSampler().type == EbtInt || imageType.getSampler().type == EbtUint ||
2507             imageType.getSampler().type == EbtInt64 || imageType.getSampler().type == EbtUint64) {
2508             if (imageType.getQualifier().getFormat() != ElfR32i && imageType.getQualifier().getFormat() != ElfR32ui &&
2509                 imageType.getQualifier().getFormat() != ElfR64i && imageType.getQualifier().getFormat() != ElfR64ui)
2510                 error(loc, "only supported on image with format r32i or r32ui", fnCandidate.getName().c_str(), "");
2511             if (callNode.getType().getBasicType() == EbtInt64 && imageType.getQualifier().getFormat() != ElfR64i)
2512                 error(loc, "only supported on image with format r64i", fnCandidate.getName().c_str(), "");
2513             else if (callNode.getType().getBasicType() == EbtUint64 && imageType.getQualifier().getFormat() != ElfR64ui)
2514                 error(loc, "only supported on image with format r64ui", fnCandidate.getName().c_str(), "");
2515         } else if (imageType.getSampler().type == EbtFloat) {
2516             if (fnCandidate.getName().compare(0, 19, "imageAtomicExchange") == 0) {
2517                 // imageAtomicExchange doesn't require an extension
2518             } else if ((fnCandidate.getName().compare(0, 14, "imageAtomicAdd") == 0) ||
2519                        (fnCandidate.getName().compare(0, 15, "imageAtomicLoad") == 0) ||
2520                        (fnCandidate.getName().compare(0, 16, "imageAtomicStore") == 0)) {
2521                 requireExtensions(loc, 1, &E_GL_EXT_shader_atomic_float, fnCandidate.getName().c_str());
2522             } else if ((fnCandidate.getName().compare(0, 14, "imageAtomicMin") == 0) ||
2523                        (fnCandidate.getName().compare(0, 14, "imageAtomicMax") == 0)) {
2524                 requireExtensions(loc, 1, &E_GL_EXT_shader_atomic_float2, fnCandidate.getName().c_str());
2525             } else {
2526                 error(loc, "only supported on integer images", fnCandidate.getName().c_str(), "");
2527             }
2528             if (imageType.getQualifier().getFormat() != ElfR32f && isEsProfile())
2529                 error(loc, "only supported on image with format r32f", fnCandidate.getName().c_str(), "");
2530         } else {
2531             error(loc, "not supported on this image type", fnCandidate.getName().c_str(), "");
2532         }
2533 
2534         const size_t maxArgs = imageType.getSampler().isMultiSample() ? 5 : 4;
2535         if (argp->size() > maxArgs) {
2536             requireExtensions(loc, 1, &E_GL_KHR_memory_scope_semantics, fnCandidate.getName().c_str());
2537             memorySemanticsCheck(loc, fnCandidate, callNode);
2538         }
2539 
2540         break;
2541     }
2542 
2543     case EOpAtomicAdd:
2544     case EOpAtomicSubtract:
2545     case EOpAtomicMin:
2546     case EOpAtomicMax:
2547     case EOpAtomicAnd:
2548     case EOpAtomicOr:
2549     case EOpAtomicXor:
2550     case EOpAtomicExchange:
2551     case EOpAtomicCompSwap:
2552     case EOpAtomicLoad:
2553     case EOpAtomicStore:
2554     {
2555         if (argp->size() > 3) {
2556             requireExtensions(loc, 1, &E_GL_KHR_memory_scope_semantics, fnCandidate.getName().c_str());
2557             memorySemanticsCheck(loc, fnCandidate, callNode);
2558             if ((callNode.getOp() == EOpAtomicAdd || callNode.getOp() == EOpAtomicExchange ||
2559                 callNode.getOp() == EOpAtomicLoad || callNode.getOp() == EOpAtomicStore) &&
2560                 (arg0->getType().getBasicType() == EbtFloat ||
2561                  arg0->getType().getBasicType() == EbtDouble)) {
2562                 requireExtensions(loc, 1, &E_GL_EXT_shader_atomic_float, fnCandidate.getName().c_str());
2563             } else if ((callNode.getOp() == EOpAtomicAdd || callNode.getOp() == EOpAtomicExchange ||
2564                         callNode.getOp() == EOpAtomicLoad || callNode.getOp() == EOpAtomicStore ||
2565                         callNode.getOp() == EOpAtomicMin || callNode.getOp() == EOpAtomicMax) &&
2566                        arg0->getType().isFloatingDomain()) {
2567                 requireExtensions(loc, 1, &E_GL_EXT_shader_atomic_float2, fnCandidate.getName().c_str());
2568             }
2569         } else if (arg0->getType().getBasicType() == EbtInt64 || arg0->getType().getBasicType() == EbtUint64) {
2570             const char* const extensions[2] = { E_GL_NV_shader_atomic_int64,
2571                                                 E_GL_EXT_shader_atomic_int64 };
2572             requireExtensions(loc, 2, extensions, fnCandidate.getName().c_str());
2573         } else if ((callNode.getOp() == EOpAtomicAdd || callNode.getOp() == EOpAtomicExchange) &&
2574                    (arg0->getType().getBasicType() == EbtFloat ||
2575                     arg0->getType().getBasicType() == EbtDouble)) {
2576             requireExtensions(loc, 1, &E_GL_EXT_shader_atomic_float, fnCandidate.getName().c_str());
2577         } else if ((callNode.getOp() == EOpAtomicAdd || callNode.getOp() == EOpAtomicExchange ||
2578                     callNode.getOp() == EOpAtomicLoad || callNode.getOp() == EOpAtomicStore ||
2579                     callNode.getOp() == EOpAtomicMin || callNode.getOp() == EOpAtomicMax) &&
2580                    arg0->getType().isFloatingDomain()) {
2581             requireExtensions(loc, 1, &E_GL_EXT_shader_atomic_float2, fnCandidate.getName().c_str());
2582         }
2583 
2584         const TIntermTyped* base = TIntermediate::traverseLValueBase(arg0, true, true);
2585         const char* errMsg = "Only l-values corresponding to shader block storage or shared variables can be used with "
2586                              "atomic memory functions.";
2587         if (base) {
2588             const TType* refType = (base->getType().isReference()) ? base->getType().getReferentType() : nullptr;
2589             const TQualifier& qualifier =
2590                 (refType != nullptr) ? refType->getQualifier() : base->getType().getQualifier();
2591             if (qualifier.storage != EvqShared && qualifier.storage != EvqBuffer &&
2592                 qualifier.storage != EvqtaskPayloadSharedEXT)
2593                 error(loc, errMsg, fnCandidate.getName().c_str(), "");
2594         } else {
2595             error(loc, errMsg, fnCandidate.getName().c_str(), "");
2596         }
2597 
2598         break;
2599     }
2600 
2601     case EOpInterpolateAtCentroid:
2602     case EOpInterpolateAtSample:
2603     case EOpInterpolateAtOffset:
2604     case EOpInterpolateAtVertex: {
2605         if (arg0->getType().getQualifier().storage != EvqVaryingIn) {
2606             // Traverse down the left branch of arg0 to ensure this argument is a valid interpolant.
2607             //
2608             // For desktop GL >4.3 we effectively only need to ensure that arg0 represents an l-value from an
2609             // input declaration.
2610             //
2611             // For desktop GL <= 4.3 and ES, we must also ensure that swizzling is not used
2612             //
2613             // For ES, we must also ensure that a field selection operator (i.e., '.') is not used on a named
2614             // struct.
2615 
2616             const bool esProfile = isEsProfile();
2617             const bool swizzleOkay = !esProfile && (version >= 440);
2618 
2619             std::string interpolantErrorMsg = "first argument must be an interpolant, or interpolant-array element";
2620             bool isValid = true; // Assume that the interpolant is valid until we find a condition making it invalid
2621             bool isIn = false;   // Checks whether or not the interpolant is a shader input
2622             bool structAccessOp = false; // Whether or not the previous node in the chain is a struct accessor
2623             TIntermediate::traverseLValueBase(
2624                 arg0, swizzleOkay, false,
2625                 [&isValid, &isIn, &interpolantErrorMsg, esProfile, &structAccessOp](const TIntermNode& n) -> bool {
2626                     auto* type = n.getAsTyped();
2627                     if (type) {
2628                         if (type->getType().getQualifier().storage == EvqVaryingIn) {
2629                             isIn = true;
2630                         }
2631                         // If a field accessor was used, it can only be used to access a field with an input block, not a struct.
2632                         if (structAccessOp && (type->getType().getBasicType() != EbtBlock)) {
2633                             interpolantErrorMsg +=
2634                                 ". Using the field of a named struct as an interpolant argument is not "
2635                                 "allowed (ES-only).";
2636                             isValid = false;
2637                         }
2638                     }
2639 
2640                     // ES has different requirements for interpolants than GL
2641                     if (esProfile) {
2642                         // Swizzling will be taken care of by the 'swizzleOkay' argument passsed to traverseLValueBase,
2643                         // so we only ned to check whether or not a field accessor has been used with a named struct.
2644                         auto* binary = n.getAsBinaryNode();
2645                         if (binary && (binary->getOp() == EOpIndexDirectStruct)) {
2646                             structAccessOp = true;
2647                         }
2648                     }
2649                     // Don't continue traversing if we know we have an invalid interpolant at this point.
2650                     return isValid;
2651                 });
2652             if (!isIn || !isValid) {
2653                 error(loc, interpolantErrorMsg.c_str(), fnCandidate.getName().c_str(), "");
2654             }
2655         }
2656 
2657         if (callNode.getOp() == EOpInterpolateAtVertex) {
2658             if (!arg0->getType().getQualifier().isExplicitInterpolation())
2659                 error(loc, "argument must be qualified as __explicitInterpAMD in", "interpolant", "");
2660             else {
2661                 if (! (*argp)[1]->getAsConstantUnion())
2662                     error(loc, "argument must be compile-time constant", "vertex index", "");
2663                 else {
2664                     unsigned vertexIdx = (*argp)[1]->getAsConstantUnion()->getConstArray()[0].getUConst();
2665                     if (vertexIdx > 2)
2666                         error(loc, "must be in the range [0, 2]", "vertex index", "");
2667                 }
2668             }
2669         }
2670     } break;
2671 
2672     case EOpEmitStreamVertex:
2673     case EOpEndStreamPrimitive:
2674         if (version == 150)
2675             requireExtensions(loc, 1, &E_GL_ARB_gpu_shader5, "if the verison is 150 , the EmitStreamVertex and EndStreamPrimitive only support at extension GL_ARB_gpu_shader5");
2676         intermediate.setMultiStream();
2677         break;
2678 
2679     case EOpSubgroupClusteredAdd:
2680     case EOpSubgroupClusteredMul:
2681     case EOpSubgroupClusteredMin:
2682     case EOpSubgroupClusteredMax:
2683     case EOpSubgroupClusteredAnd:
2684     case EOpSubgroupClusteredOr:
2685     case EOpSubgroupClusteredXor:
2686         // The <clusterSize> as used in the subgroupClustered<op>() operations must be:
2687         // - An integral constant expression.
2688         // - At least 1.
2689         // - A power of 2.
2690         if ((*argp)[1]->getAsConstantUnion() == nullptr)
2691             error(loc, "argument must be compile-time constant", "cluster size", "");
2692         else {
2693             int size = (*argp)[1]->getAsConstantUnion()->getConstArray()[0].getIConst();
2694             if (size < 1)
2695                 error(loc, "argument must be at least 1", "cluster size", "");
2696             else if (!IsPow2(size))
2697                 error(loc, "argument must be a power of 2", "cluster size", "");
2698         }
2699         break;
2700 
2701     case EOpSubgroupBroadcast:
2702     case EOpSubgroupQuadBroadcast:
2703         if (spvVersion.spv < EShTargetSpv_1_5) {
2704             // <id> must be an integral constant expression.
2705             if ((*argp)[1]->getAsConstantUnion() == nullptr)
2706                 error(loc, "argument must be compile-time constant", "id", "");
2707         }
2708         break;
2709 
2710     case EOpBarrier:
2711     case EOpMemoryBarrier:
2712         if (argp->size() > 0) {
2713             requireExtensions(loc, 1, &E_GL_KHR_memory_scope_semantics, fnCandidate.getName().c_str());
2714             memorySemanticsCheck(loc, fnCandidate, callNode);
2715         }
2716         break;
2717 
2718     case EOpMix:
2719         if (profile == EEsProfile && version < 310) {
2720             // Look for specific signatures
2721             if ((*argp)[0]->getAsTyped()->getBasicType() != EbtFloat &&
2722                 (*argp)[1]->getAsTyped()->getBasicType() != EbtFloat &&
2723                 (*argp)[2]->getAsTyped()->getBasicType() == EbtBool) {
2724                 requireExtensions(loc, 1, &E_GL_EXT_shader_integer_mix, "specific signature of builtin mix");
2725             }
2726         }
2727 
2728         if (profile != EEsProfile && version < 450) {
2729             if ((*argp)[0]->getAsTyped()->getBasicType() != EbtFloat &&
2730                 (*argp)[0]->getAsTyped()->getBasicType() != EbtDouble &&
2731                 (*argp)[1]->getAsTyped()->getBasicType() != EbtFloat &&
2732                 (*argp)[1]->getAsTyped()->getBasicType() != EbtDouble &&
2733                 (*argp)[2]->getAsTyped()->getBasicType() == EbtBool) {
2734                 requireExtensions(loc, 1, &E_GL_EXT_shader_integer_mix, fnCandidate.getName().c_str());
2735             }
2736         }
2737 
2738         break;
2739 
2740     default:
2741         break;
2742     }
2743 
2744     // Texture operations on texture objects (aside from texelFetch on a
2745     // textureBuffer) require EXT_samplerless_texture_functions.
2746     switch (callNode.getOp()) {
2747     case EOpTextureQuerySize:
2748     case EOpTextureQueryLevels:
2749     case EOpTextureQuerySamples:
2750     case EOpTextureFetch:
2751     case EOpTextureFetchOffset:
2752     {
2753         const TSampler& sampler = fnCandidate[0].type->getSampler();
2754 
2755         const bool isTexture = sampler.isTexture() && !sampler.isCombined();
2756         const bool isBuffer = sampler.isBuffer();
2757         const bool isFetch = callNode.getOp() == EOpTextureFetch || callNode.getOp() == EOpTextureFetchOffset;
2758 
2759         if (isTexture && (!isBuffer || !isFetch))
2760             requireExtensions(loc, 1, &E_GL_EXT_samplerless_texture_functions, fnCandidate.getName().c_str());
2761 
2762         break;
2763     }
2764 
2765     default:
2766         break;
2767     }
2768 
2769     if (callNode.isSubgroup()) {
2770         // these require SPIR-V 1.3
2771         if (spvVersion.spv > 0 && spvVersion.spv < EShTargetSpv_1_3)
2772             error(loc, "requires SPIR-V 1.3", "subgroup op", "");
2773 
2774         // Check that if extended types are being used that the correct extensions are enabled.
2775         if (arg0 != nullptr) {
2776             const TType& type = arg0->getType();
2777             bool enhanced = intermediate.getEnhancedMsgs();
2778             switch (type.getBasicType()) {
2779             default:
2780                 break;
2781             case EbtInt8:
2782             case EbtUint8:
2783                 requireExtensions(loc, 1, &E_GL_EXT_shader_subgroup_extended_types_int8, type.getCompleteString(enhanced).c_str());
2784                 break;
2785             case EbtInt16:
2786             case EbtUint16:
2787                 requireExtensions(loc, 1, &E_GL_EXT_shader_subgroup_extended_types_int16, type.getCompleteString(enhanced).c_str());
2788                 break;
2789             case EbtInt64:
2790             case EbtUint64:
2791                 requireExtensions(loc, 1, &E_GL_EXT_shader_subgroup_extended_types_int64, type.getCompleteString(enhanced).c_str());
2792                 break;
2793             case EbtFloat16:
2794                 requireExtensions(loc, 1, &E_GL_EXT_shader_subgroup_extended_types_float16, type.getCompleteString(enhanced).c_str());
2795                 break;
2796             }
2797         }
2798     }
2799 }
2800 
2801 
2802 // Deprecated!  Use PureOperatorBuiltins == true instead, in which case this
2803 // functionality is handled in builtInOpCheck() instead of here.
2804 //
2805 // Do additional checking of built-in function calls that were not mapped
2806 // to built-in operations (e.g., texturing functions).
2807 //
2808 // Assumes there has been a semantically correct match to a built-in function.
2809 //
nonOpBuiltInCheck(const TSourceLoc & loc,const TFunction & fnCandidate,TIntermAggregate & callNode)2810 void TParseContext::nonOpBuiltInCheck(const TSourceLoc& loc, const TFunction& fnCandidate, TIntermAggregate& callNode)
2811 {
2812     // Further maintenance of this function is deprecated, because the "correct"
2813     // future-oriented design is to not have to do string compares on function names.
2814 
2815     // If PureOperatorBuiltins == true, then all built-ins should be mapped
2816     // to a TOperator, and this function would then never get called.
2817 
2818     assert(PureOperatorBuiltins == false);
2819 
2820     // built-in texturing functions get their return value precision from the precision of the sampler
2821     if (fnCandidate.getType().getQualifier().precision == EpqNone &&
2822         fnCandidate.getParamCount() > 0 && fnCandidate[0].type->getBasicType() == EbtSampler)
2823         callNode.getQualifier().precision = callNode.getSequence()[0]->getAsTyped()->getQualifier().precision;
2824 
2825     if (fnCandidate.getName().compare(0, 7, "texture") == 0) {
2826         if (fnCandidate.getName().compare(0, 13, "textureGather") == 0) {
2827             TString featureString = fnCandidate.getName() + "(...)";
2828             const char* feature = featureString.c_str();
2829             profileRequires(loc, EEsProfile, 310, nullptr, feature);
2830 
2831             int compArg = -1;  // track which argument, if any, is the constant component argument
2832             if (fnCandidate.getName().compare("textureGatherOffset") == 0) {
2833                 // GL_ARB_texture_gather is good enough for 2D non-shadow textures with no component argument
2834                 if (fnCandidate[0].type->getSampler().dim == Esd2D && ! fnCandidate[0].type->getSampler().shadow && fnCandidate.getParamCount() == 3)
2835                     profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_texture_gather, feature);
2836                 else
2837                     profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_gpu_shader5, feature);
2838                 int offsetArg = fnCandidate[0].type->getSampler().shadow ? 3 : 2;
2839                 if (! callNode.getSequence()[offsetArg]->getAsConstantUnion())
2840                     profileRequires(loc, EEsProfile, 320, Num_AEP_gpu_shader5, AEP_gpu_shader5,
2841                                     "non-constant offset argument");
2842                 if (! fnCandidate[0].type->getSampler().shadow)
2843                     compArg = 3;
2844             } else if (fnCandidate.getName().compare("textureGatherOffsets") == 0) {
2845                 profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_gpu_shader5, feature);
2846                 if (! fnCandidate[0].type->getSampler().shadow)
2847                     compArg = 3;
2848                 // check for constant offsets
2849                 int offsetArg = fnCandidate[0].type->getSampler().shadow ? 3 : 2;
2850                 if (! callNode.getSequence()[offsetArg]->getAsConstantUnion())
2851                     error(loc, "must be a compile-time constant:", feature, "offsets argument");
2852             } else if (fnCandidate.getName().compare("textureGather") == 0) {
2853                 // More than two arguments needs gpu_shader5, and rectangular or shadow needs gpu_shader5,
2854                 // otherwise, need GL_ARB_texture_gather.
2855                 if (fnCandidate.getParamCount() > 2 || fnCandidate[0].type->getSampler().dim == EsdRect || fnCandidate[0].type->getSampler().shadow) {
2856                     profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_gpu_shader5, feature);
2857                     if (! fnCandidate[0].type->getSampler().shadow)
2858                         compArg = 2;
2859                 } else
2860                     profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_texture_gather, feature);
2861             }
2862 
2863             if (compArg > 0 && compArg < fnCandidate.getParamCount()) {
2864                 if (callNode.getSequence()[compArg]->getAsConstantUnion()) {
2865                     int value = callNode.getSequence()[compArg]->getAsConstantUnion()->getConstArray()[0].getIConst();
2866                     if (value < 0 || value > 3)
2867                         error(loc, "must be 0, 1, 2, or 3:", feature, "component argument");
2868                 } else
2869                     error(loc, "must be a compile-time constant:", feature, "component argument");
2870             }
2871         } else {
2872             // this is only for functions not starting "textureGather"...
2873             if (fnCandidate.getName().find("Offset") != TString::npos) {
2874 
2875                 // Handle texture-offset limits checking
2876                 int arg = -1;
2877                 if (fnCandidate.getName().compare("textureOffset") == 0)
2878                     arg = 2;
2879                 else if (fnCandidate.getName().compare("texelFetchOffset") == 0)
2880                     arg = 3;
2881                 else if (fnCandidate.getName().compare("textureProjOffset") == 0)
2882                     arg = 2;
2883                 else if (fnCandidate.getName().compare("textureLodOffset") == 0)
2884                     arg = 3;
2885                 else if (fnCandidate.getName().compare("textureProjLodOffset") == 0)
2886                     arg = 3;
2887                 else if (fnCandidate.getName().compare("textureGradOffset") == 0)
2888                     arg = 4;
2889                 else if (fnCandidate.getName().compare("textureProjGradOffset") == 0)
2890                     arg = 4;
2891 
2892                 if (arg > 0) {
2893                     if (! callNode.getSequence()[arg]->getAsConstantUnion())
2894                         error(loc, "argument must be compile-time constant", "texel offset", "");
2895                     else {
2896                         const TType& type = callNode.getSequence()[arg]->getAsTyped()->getType();
2897                         for (int c = 0; c < type.getVectorSize(); ++c) {
2898                             int offset = callNode.getSequence()[arg]->getAsConstantUnion()->getConstArray()[c].getIConst();
2899                             if (offset > resources.maxProgramTexelOffset || offset < resources.minProgramTexelOffset)
2900                                 error(loc, "value is out of range:", "texel offset", "[gl_MinProgramTexelOffset, gl_MaxProgramTexelOffset]");
2901                         }
2902                     }
2903                 }
2904             }
2905         }
2906     }
2907 
2908     // GL_ARB_shader_texture_image_samples
2909     if (fnCandidate.getName().compare(0, 14, "textureSamples") == 0 || fnCandidate.getName().compare(0, 12, "imageSamples") == 0)
2910         profileRequires(loc, ~EEsProfile, 450, E_GL_ARB_shader_texture_image_samples, "textureSamples and imageSamples");
2911 
2912     if (fnCandidate.getName().compare(0, 11, "imageAtomic") == 0) {
2913         const TType& imageType = callNode.getSequence()[0]->getAsTyped()->getType();
2914         if (imageType.getSampler().type == EbtInt || imageType.getSampler().type == EbtUint) {
2915             if (imageType.getQualifier().getFormat() != ElfR32i && imageType.getQualifier().getFormat() != ElfR32ui)
2916                 error(loc, "only supported on image with format r32i or r32ui", fnCandidate.getName().c_str(), "");
2917         } else {
2918             if (fnCandidate.getName().compare(0, 19, "imageAtomicExchange") != 0)
2919                 error(loc, "only supported on integer images", fnCandidate.getName().c_str(), "");
2920             else if (imageType.getQualifier().getFormat() != ElfR32f && isEsProfile())
2921                 error(loc, "only supported on image with format r32f", fnCandidate.getName().c_str(), "");
2922         }
2923     }
2924 }
2925 
2926 //
2927 // Do any extra checking for a user function call.
2928 //
userFunctionCallCheck(const TSourceLoc & loc,TIntermAggregate & callNode)2929 void TParseContext::userFunctionCallCheck(const TSourceLoc& loc, TIntermAggregate& callNode)
2930 {
2931     TIntermSequence& arguments = callNode.getSequence();
2932 
2933     for (int i = 0; i < (int)arguments.size(); ++i)
2934         samplerConstructorLocationCheck(loc, "call argument", arguments[i]);
2935 }
2936 
2937 //
2938 // Emit an error if this is a sampler constructor
2939 //
samplerConstructorLocationCheck(const TSourceLoc & loc,const char * token,TIntermNode * node)2940 void TParseContext::samplerConstructorLocationCheck(const TSourceLoc& loc, const char* token, TIntermNode* node)
2941 {
2942     if (node->getAsOperator() && node->getAsOperator()->getOp() == EOpConstructTextureSampler)
2943         error(loc, "sampler constructor must appear at point of use", token, "");
2944 }
2945 
2946 //
2947 // Handle seeing a built-in constructor in a grammar production.
2948 //
handleConstructorCall(const TSourceLoc & loc,const TPublicType & publicType)2949 TFunction* TParseContext::handleConstructorCall(const TSourceLoc& loc, const TPublicType& publicType)
2950 {
2951     TType type(publicType);
2952     type.getQualifier().precision = EpqNone;
2953 
2954     if (type.isArray()) {
2955         profileRequires(loc, ENoProfile, 120, E_GL_3DL_array_objects, "arrayed constructor");
2956         profileRequires(loc, EEsProfile, 300, nullptr, "arrayed constructor");
2957     }
2958 
2959     // Reuse EOpConstructTextureSampler for bindless image constructor
2960     // uvec2 imgHandle;
2961     // imageLoad(image1D(imgHandle), 0);
2962     if (type.isImage() && extensionTurnedOn(E_GL_ARB_bindless_texture))
2963     {
2964         intermediate.setBindlessImageMode(currentCaller, AstRefTypeFunc);
2965     }
2966 
2967     TOperator op = intermediate.mapTypeToConstructorOp(type);
2968 
2969     if (op == EOpNull) {
2970       if (intermediate.getEnhancedMsgs() && type.getBasicType() == EbtSampler)
2971             error(loc, "function not supported in this version; use texture() instead", "texture*D*", "");
2972         else
2973             error(loc, "cannot construct this type", type.getBasicString(), "");
2974         op = EOpConstructFloat;
2975         TType errorType(EbtFloat);
2976         type.shallowCopy(errorType);
2977     }
2978 
2979     TString empty("");
2980 
2981     return new TFunction(&empty, type, op);
2982 }
2983 
2984 // Handle seeing a precision qualifier in the grammar.
handlePrecisionQualifier(const TSourceLoc &,TQualifier & qualifier,TPrecisionQualifier precision)2985 void TParseContext::handlePrecisionQualifier(const TSourceLoc& /*loc*/, TQualifier& qualifier, TPrecisionQualifier precision)
2986 {
2987     if (obeyPrecisionQualifiers())
2988         qualifier.precision = precision;
2989 }
2990 
2991 // Check for messages to give on seeing a precision qualifier used in a
2992 // declaration in the grammar.
checkPrecisionQualifier(const TSourceLoc & loc,TPrecisionQualifier)2993 void TParseContext::checkPrecisionQualifier(const TSourceLoc& loc, TPrecisionQualifier)
2994 {
2995     if (precisionManager.shouldWarnAboutDefaults()) {
2996         warn(loc, "all default precisions are highp; use precision statements to quiet warning, e.g.:\n"
2997                   "         \"precision mediump int; precision highp float;\"", "", "");
2998         precisionManager.defaultWarningGiven();
2999     }
3000 }
3001 
3002 //
3003 // Same error message for all places assignments don't work.
3004 //
assignError(const TSourceLoc & loc,const char * op,TString left,TString right)3005 void TParseContext::assignError(const TSourceLoc& loc, const char* op, TString left, TString right)
3006 {
3007     error(loc, "", op, "cannot convert from '%s' to '%s'",
3008           right.c_str(), left.c_str());
3009 }
3010 
3011 //
3012 // Same error message for all places unary operations don't work.
3013 //
unaryOpError(const TSourceLoc & loc,const char * op,TString operand)3014 void TParseContext::unaryOpError(const TSourceLoc& loc, const char* op, TString operand)
3015 {
3016    error(loc, " wrong operand type", op,
3017           "no operation '%s' exists that takes an operand of type %s (or there is no acceptable conversion)",
3018           op, operand.c_str());
3019 }
3020 
3021 //
3022 // Same error message for all binary operations don't work.
3023 //
binaryOpError(const TSourceLoc & loc,const char * op,TString left,TString right)3024 void TParseContext::binaryOpError(const TSourceLoc& loc, const char* op, TString left, TString right)
3025 {
3026     error(loc, " wrong operand types:", op,
3027             "no operation '%s' exists that takes a left-hand operand of type '%s' and "
3028             "a right operand of type '%s' (or there is no acceptable conversion)",
3029             op, left.c_str(), right.c_str());
3030 }
3031 
3032 //
3033 // A basic type of EbtVoid is a key that the name string was seen in the source, but
3034 // it was not found as a variable in the symbol table.  If so, give the error
3035 // message and insert a dummy variable in the symbol table to prevent future errors.
3036 //
variableCheck(TIntermTyped * & nodePtr)3037 void TParseContext::variableCheck(TIntermTyped*& nodePtr)
3038 {
3039     TIntermSymbol* symbol = nodePtr->getAsSymbolNode();
3040     if (! symbol)
3041         return;
3042 
3043     if (symbol->getType().getBasicType() == EbtVoid) {
3044         const char *extraInfoFormat = "";
3045         if (spvVersion.vulkan != 0 && symbol->getName() == "gl_VertexID") {
3046           extraInfoFormat = "(Did you mean gl_VertexIndex?)";
3047         } else if (spvVersion.vulkan != 0 && symbol->getName() == "gl_InstanceID") {
3048           extraInfoFormat = "(Did you mean gl_InstanceIndex?)";
3049         }
3050         error(symbol->getLoc(), "undeclared identifier", symbol->getName().c_str(), extraInfoFormat);
3051 
3052         // Add to symbol table to prevent future error messages on the same name
3053         if (symbol->getName().size() > 0) {
3054             TVariable* fakeVariable = new TVariable(&symbol->getName(), TType(EbtFloat));
3055             symbolTable.insert(*fakeVariable);
3056 
3057             // substitute a symbol node for this new variable
3058             nodePtr = intermediate.addSymbol(*fakeVariable, symbol->getLoc());
3059         }
3060     } else {
3061         switch (symbol->getQualifier().storage) {
3062         case EvqPointCoord:
3063             profileRequires(symbol->getLoc(), ENoProfile, 120, nullptr, "gl_PointCoord");
3064             break;
3065         default: break; // some compilers want this
3066         }
3067     }
3068 }
3069 
3070 //
3071 // Both test and if necessary, spit out an error, to see if the node is really
3072 // an l-value that can be operated on this way.
3073 //
3074 // Returns true if there was an error.
3075 //
lValueErrorCheck(const TSourceLoc & loc,const char * op,TIntermTyped * node)3076 bool TParseContext::lValueErrorCheck(const TSourceLoc& loc, const char* op, TIntermTyped* node)
3077 {
3078     TIntermBinary* binaryNode = node->getAsBinaryNode();
3079 
3080     if (binaryNode) {
3081         bool errorReturn = false;
3082 
3083         switch(binaryNode->getOp()) {
3084         case EOpIndexDirect:
3085         case EOpIndexIndirect:
3086             // ...  tessellation control shader ...
3087             // If a per-vertex output variable is used as an l-value, it is a
3088             // compile-time or link-time error if the expression indicating the
3089             // vertex index is not the identifier gl_InvocationID.
3090             if (language == EShLangTessControl) {
3091                 const TType& leftType = binaryNode->getLeft()->getType();
3092                 if (leftType.getQualifier().storage == EvqVaryingOut && ! leftType.getQualifier().patch && binaryNode->getLeft()->getAsSymbolNode()) {
3093                     // we have a per-vertex output
3094                     const TIntermSymbol* rightSymbol = binaryNode->getRight()->getAsSymbolNode();
3095                     if (! rightSymbol || rightSymbol->getQualifier().builtIn != EbvInvocationId)
3096                         error(loc, "tessellation-control per-vertex output l-value must be indexed with gl_InvocationID", "[]", "");
3097                 }
3098             }
3099             break; // left node is checked by base class
3100         case EOpVectorSwizzle:
3101             errorReturn = lValueErrorCheck(loc, op, binaryNode->getLeft());
3102             if (!errorReturn) {
3103                 int offset[4] = {0,0,0,0};
3104 
3105                 TIntermTyped* rightNode = binaryNode->getRight();
3106                 TIntermAggregate *aggrNode = rightNode->getAsAggregate();
3107 
3108                 for (TIntermSequence::iterator p = aggrNode->getSequence().begin();
3109                                                p != aggrNode->getSequence().end(); p++) {
3110                     int value = (*p)->getAsTyped()->getAsConstantUnion()->getConstArray()[0].getIConst();
3111                     offset[value]++;
3112                     if (offset[value] > 1) {
3113                         error(loc, " l-value of swizzle cannot have duplicate components", op, "", "");
3114 
3115                         return true;
3116                     }
3117                 }
3118             }
3119 
3120             return errorReturn;
3121         default:
3122             break;
3123         }
3124 
3125         if (errorReturn) {
3126             error(loc, " l-value required", op, "", "");
3127             return true;
3128         }
3129     }
3130 
3131     if (binaryNode && binaryNode->getOp() == EOpIndexDirectStruct && binaryNode->getLeft()->isReference())
3132         return false;
3133 
3134     // Let the base class check errors
3135     if (TParseContextBase::lValueErrorCheck(loc, op, node))
3136         return true;
3137 
3138     const char* symbol = nullptr;
3139     TIntermSymbol* symNode = node->getAsSymbolNode();
3140     if (symNode != nullptr)
3141         symbol = symNode->getName().c_str();
3142 
3143     const char* message = nullptr;
3144     switch (node->getQualifier().storage) {
3145     case EvqVaryingIn:      message = "can't modify shader input";   break;
3146     case EvqInstanceId:     message = "can't modify gl_InstanceID";  break;
3147     case EvqVertexId:       message = "can't modify gl_VertexID";    break;
3148     case EvqFace:           message = "can't modify gl_FrontFace";   break;
3149     case EvqFragCoord:      message = "can't modify gl_FragCoord";   break;
3150     case EvqPointCoord:     message = "can't modify gl_PointCoord";  break;
3151     case EvqFragDepth:
3152         intermediate.setDepthReplacing();
3153         // "In addition, it is an error to statically write to gl_FragDepth in the fragment shader."
3154         if (isEsProfile() && intermediate.getEarlyFragmentTests())
3155             message = "can't modify gl_FragDepth if using early_fragment_tests";
3156         break;
3157     case EvqFragStencil:
3158         intermediate.setStencilReplacing();
3159         // "In addition, it is an error to statically write to gl_FragDepth in the fragment shader."
3160         if (isEsProfile() && intermediate.getEarlyFragmentTests())
3161             message = "can't modify EvqFragStencil if using early_fragment_tests";
3162         break;
3163 
3164     case EvqtaskPayloadSharedEXT:
3165         if (language == EShLangMesh)
3166             message = "can't modify variable with storage qualifier taskPayloadSharedEXT in mesh shaders";
3167         break;
3168     default:
3169         break;
3170     }
3171 
3172     if (message == nullptr && binaryNode == nullptr && symNode == nullptr) {
3173         error(loc, " l-value required", op, "", "");
3174 
3175         return true;
3176     }
3177 
3178     //
3179     // Everything else is okay, no error.
3180     //
3181     if (message == nullptr)
3182         return false;
3183 
3184     //
3185     // If we get here, we have an error and a message.
3186     //
3187     if (symNode)
3188         error(loc, " l-value required", op, "\"%s\" (%s)", symbol, message);
3189     else
3190         error(loc, " l-value required", op, "(%s)", message);
3191 
3192     return true;
3193 }
3194 
3195 // Test for and give an error if the node can't be read from.
rValueErrorCheck(const TSourceLoc & loc,const char * op,TIntermTyped * node)3196 void TParseContext::rValueErrorCheck(const TSourceLoc& loc, const char* op, TIntermTyped* node)
3197 {
3198     // Let the base class check errors
3199     TParseContextBase::rValueErrorCheck(loc, op, node);
3200 
3201     TIntermSymbol* symNode = node->getAsSymbolNode();
3202     if (!(symNode && symNode->getQualifier().isWriteOnly())) // base class checks
3203         if (symNode && symNode->getQualifier().isExplicitInterpolation())
3204             error(loc, "can't read from explicitly-interpolated object: ", op, symNode->getName().c_str());
3205 
3206     // local_size_{xyz} must be assigned or specialized before gl_WorkGroupSize can be assigned.
3207     if(node->getQualifier().builtIn == EbvWorkGroupSize &&
3208        !(intermediate.isLocalSizeSet() || intermediate.isLocalSizeSpecialized()))
3209         error(loc, "can't read from gl_WorkGroupSize before a fixed workgroup size has been declared", op, "");
3210 }
3211 
3212 //
3213 // Both test, and if necessary spit out an error, to see if the node is really
3214 // a constant.
3215 //
constantValueCheck(TIntermTyped * node,const char * token)3216 void TParseContext::constantValueCheck(TIntermTyped* node, const char* token)
3217 {
3218     if (! node->getQualifier().isConstant())
3219         error(node->getLoc(), "constant expression required", token, "");
3220 }
3221 
3222 //
3223 // Both test, and if necessary spit out an error, to see if the node is really
3224 // a 32-bit integer or can implicitly convert to one.
3225 //
integerCheck(const TIntermTyped * node,const char * token)3226 void TParseContext::integerCheck(const TIntermTyped* node, const char* token)
3227 {
3228     auto from_type = node->getBasicType();
3229     if ((from_type == EbtInt || from_type == EbtUint ||
3230          intermediate.canImplicitlyPromote(from_type, EbtInt, EOpNull) ||
3231          intermediate.canImplicitlyPromote(from_type, EbtUint, EOpNull)) && node->isScalar())
3232         return;
3233 
3234     error(node->getLoc(), "scalar integer expression required", token, "");
3235 }
3236 
3237 //
3238 // Both test, and if necessary spit out an error, to see if we are currently
3239 // globally scoped.
3240 //
globalCheck(const TSourceLoc & loc,const char * token)3241 void TParseContext::globalCheck(const TSourceLoc& loc, const char* token)
3242 {
3243     if (! symbolTable.atGlobalLevel())
3244         error(loc, "not allowed in nested scope", token, "");
3245 }
3246 
3247 //
3248 // Reserved errors for GLSL.
3249 //
reservedErrorCheck(const TSourceLoc & loc,const TString & identifier)3250 void TParseContext::reservedErrorCheck(const TSourceLoc& loc, const TString& identifier)
3251 {
3252     // "Identifiers starting with "gl_" are reserved for use by OpenGL, and may not be
3253     // declared in a shader; this results in a compile-time error."
3254     if (! symbolTable.atBuiltInLevel()) {
3255         if (builtInName(identifier) && !extensionTurnedOn(E_GL_EXT_spirv_intrinsics))
3256             // The extension GL_EXT_spirv_intrinsics allows us to declare identifiers starting with "gl_".
3257             error(loc, "identifiers starting with \"gl_\" are reserved", identifier.c_str(), "");
3258 
3259         // "__" are not supposed to be an error.  ES 300 (and desktop) added the clarification:
3260         // "In addition, all identifiers containing two consecutive underscores (__) are
3261         // reserved; using such a name does not itself result in an error, but may result
3262         // in undefined behavior."
3263         // however, before that, ES tests required an error.
3264         if (identifier.find("__") != TString::npos && !extensionTurnedOn(E_GL_EXT_spirv_intrinsics)) {
3265             // The extension GL_EXT_spirv_intrinsics allows us to declare identifiers starting with "__".
3266             if (isEsProfile() && version < 300)
3267                 error(loc, "identifiers containing consecutive underscores (\"__\") are reserved, and an error if version < 300", identifier.c_str(), "");
3268             else
3269                 warn(loc, "identifiers containing consecutive underscores (\"__\") are reserved", identifier.c_str(), "");
3270         }
3271     }
3272 }
3273 
3274 //
3275 // Reserved errors for the preprocessor.
3276 //
reservedPpErrorCheck(const TSourceLoc & loc,const char * identifier,const char * op)3277 void TParseContext::reservedPpErrorCheck(const TSourceLoc& loc, const char* identifier, const char* op)
3278 {
3279     // "__" are not supposed to be an error.  ES 300 (and desktop) added the clarification:
3280     // "All macro names containing two consecutive underscores ( __ ) are reserved;
3281     // defining such a name does not itself result in an error, but may result in
3282     // undefined behavior.  All macro names prefixed with "GL_" ("GL" followed by a
3283     // single underscore) are also reserved, and defining such a name results in a
3284     // compile-time error."
3285     // however, before that, ES tests required an error.
3286     if (strncmp(identifier, "GL_", 3) == 0 && !extensionTurnedOn(E_GL_EXT_spirv_intrinsics))
3287         // The extension GL_EXT_spirv_intrinsics allows us to declare macros prefixed with "GL_".
3288         ppError(loc, "names beginning with \"GL_\" can't be (un)defined:", op,  identifier);
3289     else if (strncmp(identifier, "defined", 8) == 0)
3290         if (relaxedErrors())
3291             ppWarn(loc, "\"defined\" is (un)defined:", op,  identifier);
3292         else
3293             ppError(loc, "\"defined\" can't be (un)defined:", op,  identifier);
3294     else if (strstr(identifier, "__") != nullptr && !extensionTurnedOn(E_GL_EXT_spirv_intrinsics)) {
3295         // The extension GL_EXT_spirv_intrinsics allows us to declare macros prefixed with "__".
3296         if (isEsProfile() && version >= 300 &&
3297             (strcmp(identifier, "__LINE__") == 0 ||
3298              strcmp(identifier, "__FILE__") == 0 ||
3299              strcmp(identifier, "__VERSION__") == 0))
3300             ppError(loc, "predefined names can't be (un)defined:", op,  identifier);
3301         else {
3302             if (isEsProfile() && version < 300 && !relaxedErrors())
3303                 ppError(loc, "names containing consecutive underscores are reserved, and an error if version < 300:", op, identifier);
3304             else
3305                 ppWarn(loc, "names containing consecutive underscores are reserved:", op, identifier);
3306         }
3307     }
3308 }
3309 
3310 //
3311 // See if this version/profile allows use of the line-continuation character '\'.
3312 //
3313 // Returns true if a line continuation should be done.
3314 //
lineContinuationCheck(const TSourceLoc & loc,bool endOfComment)3315 bool TParseContext::lineContinuationCheck(const TSourceLoc& loc, bool endOfComment)
3316 {
3317     const char* message = "line continuation";
3318 
3319     bool lineContinuationAllowed = (isEsProfile() && version >= 300) ||
3320                                    (!isEsProfile() && (version >= 420 || extensionTurnedOn(E_GL_ARB_shading_language_420pack)));
3321 
3322     if (endOfComment) {
3323         if (lineContinuationAllowed)
3324             warn(loc, "used at end of comment; the following line is still part of the comment", message, "");
3325         else
3326             warn(loc, "used at end of comment, but this version does not provide line continuation", message, "");
3327 
3328         return lineContinuationAllowed;
3329     }
3330 
3331     if (relaxedErrors()) {
3332         if (! lineContinuationAllowed)
3333             warn(loc, "not allowed in this version", message, "");
3334         return true;
3335     } else {
3336         profileRequires(loc, EEsProfile, 300, nullptr, message);
3337         profileRequires(loc, ~EEsProfile, 420, E_GL_ARB_shading_language_420pack, message);
3338     }
3339 
3340     return lineContinuationAllowed;
3341 }
3342 
builtInName(const TString & identifier)3343 bool TParseContext::builtInName(const TString& identifier)
3344 {
3345     return identifier.compare(0, 3, "gl_") == 0;
3346 }
3347 
3348 //
3349 // Make sure there is enough data and not too many arguments provided to the
3350 // constructor to build something of the type of the constructor.  Also returns
3351 // the type of the constructor.
3352 //
3353 // Part of establishing type is establishing specialization-constness.
3354 // We don't yet know "top down" whether type is a specialization constant,
3355 // but a const constructor can becomes a specialization constant if any of
3356 // its children are, subject to KHR_vulkan_glsl rules:
3357 //
3358 //     - int(), uint(), and bool() constructors for type conversions
3359 //       from any of the following types to any of the following types:
3360 //         * int
3361 //         * uint
3362 //         * bool
3363 //     - vector versions of the above conversion constructors
3364 //
3365 // Returns true if there was an error in construction.
3366 //
constructorError(const TSourceLoc & loc,TIntermNode * node,TFunction & function,TOperator op,TType & type)3367 bool TParseContext::constructorError(const TSourceLoc& loc, TIntermNode* node, TFunction& function, TOperator op, TType& type)
3368 {
3369     // See if the constructor does not establish the main type, only requalifies
3370     // it, in which case the type comes from the argument instead of from the
3371     // constructor function.
3372     switch (op) {
3373     case EOpConstructNonuniform:
3374         if (node != nullptr && node->getAsTyped() != nullptr) {
3375             type.shallowCopy(node->getAsTyped()->getType());
3376             type.getQualifier().makeTemporary();
3377             type.getQualifier().nonUniform = true;
3378         }
3379         break;
3380     default:
3381         type.shallowCopy(function.getType());
3382         break;
3383     }
3384 
3385     TString constructorString;
3386     if (intermediate.getEnhancedMsgs())
3387         constructorString.append(type.getCompleteString(true, false, false, true)).append(" constructor");
3388     else
3389         constructorString.append("constructor");
3390 
3391     // See if it's a matrix
3392     bool constructingMatrix = false;
3393     switch (op) {
3394     case EOpConstructTextureSampler:
3395         return constructorTextureSamplerError(loc, function);
3396     case EOpConstructMat2x2:
3397     case EOpConstructMat2x3:
3398     case EOpConstructMat2x4:
3399     case EOpConstructMat3x2:
3400     case EOpConstructMat3x3:
3401     case EOpConstructMat3x4:
3402     case EOpConstructMat4x2:
3403     case EOpConstructMat4x3:
3404     case EOpConstructMat4x4:
3405     case EOpConstructDMat2x2:
3406     case EOpConstructDMat2x3:
3407     case EOpConstructDMat2x4:
3408     case EOpConstructDMat3x2:
3409     case EOpConstructDMat3x3:
3410     case EOpConstructDMat3x4:
3411     case EOpConstructDMat4x2:
3412     case EOpConstructDMat4x3:
3413     case EOpConstructDMat4x4:
3414     case EOpConstructF16Mat2x2:
3415     case EOpConstructF16Mat2x3:
3416     case EOpConstructF16Mat2x4:
3417     case EOpConstructF16Mat3x2:
3418     case EOpConstructF16Mat3x3:
3419     case EOpConstructF16Mat3x4:
3420     case EOpConstructF16Mat4x2:
3421     case EOpConstructF16Mat4x3:
3422     case EOpConstructF16Mat4x4:
3423         constructingMatrix = true;
3424         break;
3425     default:
3426         break;
3427     }
3428 
3429     //
3430     // Walk the arguments for first-pass checks and collection of information.
3431     //
3432 
3433     int size = 0;
3434     bool constType = true;
3435     bool specConstType = false;   // value is only valid if constType is true
3436     bool full = false;
3437     bool overFull = false;
3438     bool matrixInMatrix = false;
3439     bool arrayArg = false;
3440     bool floatArgument = false;
3441     bool intArgument = false;
3442     for (int arg = 0; arg < function.getParamCount(); ++arg) {
3443         if (function[arg].type->isArray()) {
3444             if (function[arg].type->isUnsizedArray()) {
3445                 // Can't construct from an unsized array.
3446                 error(loc, "array argument must be sized", constructorString.c_str(), "");
3447                 return true;
3448             }
3449             arrayArg = true;
3450         }
3451         if (constructingMatrix && function[arg].type->isMatrix())
3452             matrixInMatrix = true;
3453 
3454         // 'full' will go to true when enough args have been seen.  If we loop
3455         // again, there is an extra argument.
3456         if (full) {
3457             // For vectors and matrices, it's okay to have too many components
3458             // available, but not okay to have unused arguments.
3459             overFull = true;
3460         }
3461 
3462         size += function[arg].type->computeNumComponents();
3463         if (op != EOpConstructStruct && ! type.isArray() && size >= type.computeNumComponents())
3464             full = true;
3465 
3466         if (! function[arg].type->getQualifier().isConstant())
3467             constType = false;
3468         if (function[arg].type->getQualifier().isSpecConstant())
3469             specConstType = true;
3470         if (function[arg].type->isFloatingDomain())
3471             floatArgument = true;
3472         if (function[arg].type->isIntegerDomain())
3473             intArgument = true;
3474         if (type.isStruct()) {
3475             if (function[arg].type->contains16BitFloat()) {
3476                 requireFloat16Arithmetic(loc, constructorString.c_str(), "can't construct structure containing 16-bit type");
3477             }
3478             if (function[arg].type->contains16BitInt()) {
3479                 requireInt16Arithmetic(loc, constructorString.c_str(), "can't construct structure containing 16-bit type");
3480             }
3481             if (function[arg].type->contains8BitInt()) {
3482                 requireInt8Arithmetic(loc, constructorString.c_str(), "can't construct structure containing 8-bit type");
3483             }
3484         }
3485     }
3486     if (op == EOpConstructNonuniform)
3487         constType = false;
3488 
3489     switch (op) {
3490     case EOpConstructFloat16:
3491     case EOpConstructF16Vec2:
3492     case EOpConstructF16Vec3:
3493     case EOpConstructF16Vec4:
3494         if (type.isArray())
3495             requireFloat16Arithmetic(loc, constructorString.c_str(), "16-bit arrays not supported");
3496         if (type.isVector() && function.getParamCount() != 1)
3497             requireFloat16Arithmetic(loc, constructorString.c_str(), "16-bit vectors only take vector types");
3498         break;
3499     case EOpConstructUint16:
3500     case EOpConstructU16Vec2:
3501     case EOpConstructU16Vec3:
3502     case EOpConstructU16Vec4:
3503     case EOpConstructInt16:
3504     case EOpConstructI16Vec2:
3505     case EOpConstructI16Vec3:
3506     case EOpConstructI16Vec4:
3507         if (type.isArray())
3508             requireInt16Arithmetic(loc, constructorString.c_str(), "16-bit arrays not supported");
3509         if (type.isVector() && function.getParamCount() != 1)
3510             requireInt16Arithmetic(loc, constructorString.c_str(), "16-bit vectors only take vector types");
3511         break;
3512     case EOpConstructUint8:
3513     case EOpConstructU8Vec2:
3514     case EOpConstructU8Vec3:
3515     case EOpConstructU8Vec4:
3516     case EOpConstructInt8:
3517     case EOpConstructI8Vec2:
3518     case EOpConstructI8Vec3:
3519     case EOpConstructI8Vec4:
3520         if (type.isArray())
3521             requireInt8Arithmetic(loc, constructorString.c_str(), "8-bit arrays not supported");
3522         if (type.isVector() && function.getParamCount() != 1)
3523             requireInt8Arithmetic(loc, constructorString.c_str(), "8-bit vectors only take vector types");
3524         break;
3525     default:
3526         break;
3527     }
3528 
3529     // inherit constness from children
3530     if (constType) {
3531         bool makeSpecConst;
3532         // Finish pinning down spec-const semantics
3533         if (specConstType) {
3534             switch (op) {
3535             case EOpConstructInt8:
3536             case EOpConstructInt:
3537             case EOpConstructUint:
3538             case EOpConstructBool:
3539             case EOpConstructBVec2:
3540             case EOpConstructBVec3:
3541             case EOpConstructBVec4:
3542             case EOpConstructIVec2:
3543             case EOpConstructIVec3:
3544             case EOpConstructIVec4:
3545             case EOpConstructUVec2:
3546             case EOpConstructUVec3:
3547             case EOpConstructUVec4:
3548             case EOpConstructUint8:
3549             case EOpConstructInt16:
3550             case EOpConstructUint16:
3551             case EOpConstructInt64:
3552             case EOpConstructUint64:
3553             case EOpConstructI8Vec2:
3554             case EOpConstructI8Vec3:
3555             case EOpConstructI8Vec4:
3556             case EOpConstructU8Vec2:
3557             case EOpConstructU8Vec3:
3558             case EOpConstructU8Vec4:
3559             case EOpConstructI16Vec2:
3560             case EOpConstructI16Vec3:
3561             case EOpConstructI16Vec4:
3562             case EOpConstructU16Vec2:
3563             case EOpConstructU16Vec3:
3564             case EOpConstructU16Vec4:
3565             case EOpConstructI64Vec2:
3566             case EOpConstructI64Vec3:
3567             case EOpConstructI64Vec4:
3568             case EOpConstructU64Vec2:
3569             case EOpConstructU64Vec3:
3570             case EOpConstructU64Vec4:
3571                 // This was the list of valid ones, if they aren't converting from float
3572                 // and aren't making an array.
3573                 makeSpecConst = ! floatArgument && ! type.isArray();
3574                 break;
3575 
3576             case EOpConstructVec2:
3577             case EOpConstructVec3:
3578             case EOpConstructVec4:
3579                 // This was the list of valid ones, if they aren't converting from int
3580                 // and aren't making an array.
3581                 makeSpecConst = ! intArgument && !type.isArray();
3582                 break;
3583 
3584             default:
3585                 // anything else wasn't white-listed in the spec as a conversion
3586                 makeSpecConst = false;
3587                 break;
3588             }
3589         } else
3590             makeSpecConst = false;
3591 
3592         if (makeSpecConst)
3593             type.getQualifier().makeSpecConstant();
3594         else if (specConstType)
3595             type.getQualifier().makeTemporary();
3596         else
3597             type.getQualifier().storage = EvqConst;
3598     }
3599 
3600     if (type.isArray()) {
3601         if (function.getParamCount() == 0) {
3602             error(loc, "array constructor must have at least one argument", constructorString.c_str(), "");
3603             return true;
3604         }
3605 
3606         if (type.isUnsizedArray()) {
3607             // auto adapt the constructor type to the number of arguments
3608             type.changeOuterArraySize(function.getParamCount());
3609         } else if (type.getOuterArraySize() != function.getParamCount()) {
3610             error(loc, "array constructor needs one argument per array element", constructorString.c_str(), "");
3611             return true;
3612         }
3613 
3614         if (type.isArrayOfArrays()) {
3615             // Types have to match, but we're still making the type.
3616             // Finish making the type, and the comparison is done later
3617             // when checking for conversion.
3618             TArraySizes& arraySizes = *type.getArraySizes();
3619 
3620             // At least the dimensionalities have to match.
3621             if (! function[0].type->isArray() ||
3622                     arraySizes.getNumDims() != function[0].type->getArraySizes()->getNumDims() + 1) {
3623                 error(loc, "array constructor argument not correct type to construct array element", constructorString.c_str(), "");
3624                 return true;
3625             }
3626 
3627             if (arraySizes.isInnerUnsized()) {
3628                 // "Arrays of arrays ..., and the size for any dimension is optional"
3629                 // That means we need to adopt (from the first argument) the other array sizes into the type.
3630                 for (int d = 1; d < arraySizes.getNumDims(); ++d) {
3631                     if (arraySizes.getDimSize(d) == UnsizedArraySize) {
3632                         arraySizes.setDimSize(d, function[0].type->getArraySizes()->getDimSize(d - 1));
3633                     }
3634                 }
3635             }
3636         }
3637     }
3638 
3639     if (arrayArg && op != EOpConstructStruct && ! type.isArrayOfArrays()) {
3640         error(loc, "constructing non-array constituent from array argument", constructorString.c_str(), "");
3641         return true;
3642     }
3643 
3644     if (matrixInMatrix && ! type.isArray()) {
3645         profileRequires(loc, ENoProfile, 120, nullptr, "constructing matrix from matrix");
3646 
3647         // "If a matrix argument is given to a matrix constructor,
3648         // it is a compile-time error to have any other arguments."
3649         if (function.getParamCount() != 1)
3650             error(loc, "matrix constructed from matrix can only have one argument", constructorString.c_str(), "");
3651         return false;
3652     }
3653 
3654     if (overFull) {
3655         error(loc, "too many arguments", constructorString.c_str(), "");
3656         return true;
3657     }
3658 
3659     if (op == EOpConstructStruct && ! type.isArray() && (int)type.getStruct()->size() != function.getParamCount()) {
3660         error(loc, "Number of constructor parameters does not match the number of structure fields", constructorString.c_str(), "");
3661         return true;
3662     }
3663 
3664     if ((op != EOpConstructStruct && size != 1 && size < type.computeNumComponents()) ||
3665         (op == EOpConstructStruct && size < type.computeNumComponents())) {
3666         error(loc, "not enough data provided for construction", constructorString.c_str(), "");
3667         return true;
3668     }
3669 
3670     if (type.isCoopMat() && function.getParamCount() != 1) {
3671         error(loc, "wrong number of arguments", constructorString.c_str(), "");
3672         return true;
3673     }
3674     if (type.isCoopMat() &&
3675         !(function[0].type->isScalar() || function[0].type->isCoopMat())) {
3676         error(loc, "Cooperative matrix constructor argument must be scalar or cooperative matrix", constructorString.c_str(), "");
3677         return true;
3678     }
3679 
3680     TIntermTyped* typed = node->getAsTyped();
3681     if (type.isCoopMat() && typed->getType().isCoopMat() &&
3682         !type.sameCoopMatShapeAndUse(typed->getType())) {
3683         error(loc, "Cooperative matrix type parameters mismatch", constructorString.c_str(), "");
3684         return true;
3685     }
3686 
3687     if (typed == nullptr) {
3688         error(loc, "constructor argument does not have a type", constructorString.c_str(), "");
3689         return true;
3690     }
3691     if (op != EOpConstructStruct && op != EOpConstructNonuniform && typed->getBasicType() == EbtSampler) {
3692         if (op == EOpConstructUVec2 && extensionTurnedOn(E_GL_ARB_bindless_texture)) {
3693             intermediate.setBindlessTextureMode(currentCaller, AstRefTypeFunc);
3694         }
3695         else {
3696             error(loc, "cannot convert a sampler", constructorString.c_str(), "");
3697             return true;
3698         }
3699     }
3700     if (op != EOpConstructStruct && typed->isAtomic()) {
3701         error(loc, "cannot convert an atomic_uint", constructorString.c_str(), "");
3702         return true;
3703     }
3704     if (typed->getBasicType() == EbtVoid) {
3705         error(loc, "cannot convert a void", constructorString.c_str(), "");
3706         return true;
3707     }
3708 
3709     return false;
3710 }
3711 
3712 // Verify all the correct semantics for constructing a combined texture/sampler.
3713 // Return true if the semantics are incorrect.
constructorTextureSamplerError(const TSourceLoc & loc,const TFunction & function)3714 bool TParseContext::constructorTextureSamplerError(const TSourceLoc& loc, const TFunction& function)
3715 {
3716     TString constructorName = function.getType().getBasicTypeString();  // TODO: performance: should not be making copy; interface needs to change
3717     const char* token = constructorName.c_str();
3718     // verify the constructor for bindless texture, the input must be ivec2 or uvec2
3719     if (function.getParamCount() == 1) {
3720         TType* pType = function[0].type;
3721         TBasicType basicType = pType->getBasicType();
3722         bool isIntegerVec2 = ((basicType == EbtUint || basicType == EbtInt) && pType->getVectorSize() == 2);
3723         bool bindlessMode = extensionTurnedOn(E_GL_ARB_bindless_texture);
3724         if (isIntegerVec2 && bindlessMode) {
3725             if (pType->getSampler().isImage())
3726                 intermediate.setBindlessImageMode(currentCaller, AstRefTypeFunc);
3727             else
3728                 intermediate.setBindlessTextureMode(currentCaller, AstRefTypeFunc);
3729             return false;
3730         } else {
3731             if (!bindlessMode)
3732                 error(loc, "sampler-constructor requires the extension GL_ARB_bindless_texture enabled", token, "");
3733             else
3734                 error(loc, "sampler-constructor requires the input to be ivec2 or uvec2", token, "");
3735             return true;
3736         }
3737     }
3738 
3739     // exactly two arguments needed
3740     if (function.getParamCount() != 2) {
3741         error(loc, "sampler-constructor requires two arguments", token, "");
3742         return true;
3743     }
3744 
3745     // For now, not allowing arrayed constructors, the rest of this function
3746     // is set up to allow them, if this test is removed:
3747     if (function.getType().isArray()) {
3748         error(loc, "sampler-constructor cannot make an array of samplers", token, "");
3749         return true;
3750     }
3751 
3752     // first argument
3753     //  * the constructor's first argument must be a texture type
3754     //  * the dimensionality (1D, 2D, 3D, Cube, Rect, Buffer, MS, and Array)
3755     //    of the texture type must match that of the constructed sampler type
3756     //    (that is, the suffixes of the type of the first argument and the
3757     //    type of the constructor will be spelled the same way)
3758     if (function[0].type->getBasicType() != EbtSampler ||
3759         ! function[0].type->getSampler().isTexture() ||
3760         function[0].type->isArray()) {
3761         error(loc, "sampler-constructor first argument must be a scalar *texture* type", token, "");
3762         return true;
3763     }
3764     // simulate the first argument's impact on the result type, so it can be compared with the encapsulated operator!=()
3765     TSampler texture = function.getType().getSampler();
3766     texture.setCombined(false);
3767     texture.shadow = false;
3768     if (texture != function[0].type->getSampler()) {
3769         error(loc, "sampler-constructor first argument must be a *texture* type"
3770                    " matching the dimensionality and sampled type of the constructor", token, "");
3771         return true;
3772     }
3773 
3774     // second argument
3775     //   * the constructor's second argument must be a scalar of type
3776     //     *sampler* or *samplerShadow*
3777     if (  function[1].type->getBasicType() != EbtSampler ||
3778         ! function[1].type->getSampler().isPureSampler() ||
3779           function[1].type->isArray()) {
3780         error(loc, "sampler-constructor second argument must be a scalar sampler or samplerShadow", token, "");
3781         return true;
3782     }
3783 
3784     return false;
3785 }
3786 
3787 // Checks to see if a void variable has been declared and raise an error message for such a case
3788 //
3789 // returns true in case of an error
3790 //
voidErrorCheck(const TSourceLoc & loc,const TString & identifier,const TBasicType basicType)3791 bool TParseContext::voidErrorCheck(const TSourceLoc& loc, const TString& identifier, const TBasicType basicType)
3792 {
3793     if (basicType == EbtVoid) {
3794         error(loc, "illegal use of type 'void'", identifier.c_str(), "");
3795         return true;
3796     }
3797 
3798     return false;
3799 }
3800 
3801 // Checks to see if the node (for the expression) contains a scalar boolean expression or not
boolCheck(const TSourceLoc & loc,const TIntermTyped * type)3802 void TParseContext::boolCheck(const TSourceLoc& loc, const TIntermTyped* type)
3803 {
3804     if (type->getBasicType() != EbtBool || type->isArray() || type->isMatrix() || type->isVector())
3805         error(loc, "boolean expression expected", "", "");
3806 }
3807 
3808 // This function checks to see if the node (for the expression) contains a scalar boolean expression or not
boolCheck(const TSourceLoc & loc,const TPublicType & pType)3809 void TParseContext::boolCheck(const TSourceLoc& loc, const TPublicType& pType)
3810 {
3811     if (pType.basicType != EbtBool || pType.arraySizes || pType.matrixCols > 1 || (pType.vectorSize > 1))
3812         error(loc, "boolean expression expected", "", "");
3813 }
3814 
samplerCheck(const TSourceLoc & loc,const TType & type,const TString & identifier,TIntermTyped *)3815 void TParseContext::samplerCheck(const TSourceLoc& loc, const TType& type, const TString& identifier, TIntermTyped* /*initializer*/)
3816 {
3817     // Check that the appropriate extension is enabled if external sampler is used.
3818     // There are two extensions. The correct one must be used based on GLSL version.
3819     if (type.getBasicType() == EbtSampler && type.getSampler().isExternal()) {
3820         if (version < 300) {
3821             requireExtensions(loc, 1, &E_GL_OES_EGL_image_external, "samplerExternalOES");
3822         } else {
3823             requireExtensions(loc, 1, &E_GL_OES_EGL_image_external_essl3, "samplerExternalOES");
3824         }
3825     }
3826     if (type.getSampler().isYuv()) {
3827         requireExtensions(loc, 1, &E_GL_EXT_YUV_target, "__samplerExternal2DY2YEXT");
3828     }
3829 
3830     if (type.getQualifier().storage == EvqUniform)
3831         return;
3832 
3833     if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtSampler)) {
3834         // For bindless texture, sampler can be declared as an struct member
3835         if (extensionTurnedOn(E_GL_ARB_bindless_texture)) {
3836             if (type.getSampler().isImage())
3837                 intermediate.setBindlessImageMode(currentCaller, AstRefTypeVar);
3838             else
3839                 intermediate.setBindlessTextureMode(currentCaller, AstRefTypeVar);
3840         }
3841         else {
3842             error(loc, "non-uniform struct contains a sampler or image:", type.getBasicTypeString().c_str(), identifier.c_str());
3843         }
3844     }
3845     else if (type.getBasicType() == EbtSampler && type.getQualifier().storage != EvqUniform) {
3846         // For bindless texture, sampler can be declared as an input/output/block member
3847         if (extensionTurnedOn(E_GL_ARB_bindless_texture)) {
3848             if (type.getSampler().isImage())
3849                 intermediate.setBindlessImageMode(currentCaller, AstRefTypeVar);
3850             else
3851                 intermediate.setBindlessTextureMode(currentCaller, AstRefTypeVar);
3852         }
3853         else {
3854             // non-uniform sampler
3855             // not yet:  okay if it has an initializer
3856             // if (! initializer)
3857             if (type.getSampler().isAttachmentEXT() && type.getQualifier().storage != EvqTileImageEXT)
3858                  error(loc, "can only be used in tileImageEXT variables or function parameters:", type.getBasicTypeString().c_str(), identifier.c_str());
3859              else if (type.getQualifier().storage != EvqTileImageEXT)
3860                  error(loc, "sampler/image types can only be used in uniform variables or function parameters:", type.getBasicTypeString().c_str(), identifier.c_str());
3861         }
3862     }
3863 }
3864 
atomicUintCheck(const TSourceLoc & loc,const TType & type,const TString & identifier)3865 void TParseContext::atomicUintCheck(const TSourceLoc& loc, const TType& type, const TString& identifier)
3866 {
3867     if (type.getQualifier().storage == EvqUniform)
3868         return;
3869 
3870     if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtAtomicUint))
3871         error(loc, "non-uniform struct contains an atomic_uint:", type.getBasicTypeString().c_str(), identifier.c_str());
3872     else if (type.getBasicType() == EbtAtomicUint && type.getQualifier().storage != EvqUniform)
3873         error(loc, "atomic_uints can only be used in uniform variables or function parameters:", type.getBasicTypeString().c_str(), identifier.c_str());
3874 }
3875 
accStructCheck(const TSourceLoc & loc,const TType & type,const TString & identifier)3876 void TParseContext::accStructCheck(const TSourceLoc& loc, const TType& type, const TString& identifier)
3877 {
3878     if (type.getQualifier().storage == EvqUniform)
3879         return;
3880 
3881     if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtAccStruct))
3882         error(loc, "non-uniform struct contains an accelerationStructureNV:", type.getBasicTypeString().c_str(), identifier.c_str());
3883     else if (type.getBasicType() == EbtAccStruct && type.getQualifier().storage != EvqUniform)
3884         error(loc, "accelerationStructureNV can only be used in uniform variables or function parameters:",
3885             type.getBasicTypeString().c_str(), identifier.c_str());
3886 
3887 }
3888 
transparentOpaqueCheck(const TSourceLoc & loc,const TType & type,const TString & identifier)3889 void TParseContext::transparentOpaqueCheck(const TSourceLoc& loc, const TType& type, const TString& identifier)
3890 {
3891     if (parsingBuiltins)
3892         return;
3893 
3894     if (type.getQualifier().storage != EvqUniform)
3895         return;
3896 
3897     if (type.containsNonOpaque()) {
3898         // Vulkan doesn't allow transparent uniforms outside of blocks
3899         if (spvVersion.vulkan > 0 && !spvVersion.vulkanRelaxed)
3900             vulkanRemoved(loc, "non-opaque uniforms outside a block");
3901         // OpenGL wants locations on these (unless they are getting automapped)
3902         if (spvVersion.openGl > 0 && !type.getQualifier().hasLocation() && !intermediate.getAutoMapLocations())
3903             error(loc, "non-opaque uniform variables need a layout(location=L)", identifier.c_str(), "");
3904     }
3905 }
3906 
3907 //
3908 // Qualifier checks knowing the qualifier and that it is a member of a struct/block.
3909 //
memberQualifierCheck(glslang::TPublicType & publicType)3910 void TParseContext::memberQualifierCheck(glslang::TPublicType& publicType)
3911 {
3912     globalQualifierFixCheck(publicType.loc, publicType.qualifier, true);
3913     checkNoShaderLayouts(publicType.loc, publicType.shaderQualifiers);
3914     if (publicType.qualifier.isNonUniform()) {
3915         error(publicType.loc, "not allowed on block or structure members", "nonuniformEXT", "");
3916         publicType.qualifier.nonUniform = false;
3917     }
3918 }
3919 
3920 //
3921 // Check/fix just a full qualifier (no variables or types yet, but qualifier is complete) at global level.
3922 //
globalQualifierFixCheck(const TSourceLoc & loc,TQualifier & qualifier,bool isMemberCheck,const TPublicType * publicType)3923 void TParseContext::globalQualifierFixCheck(const TSourceLoc& loc, TQualifier& qualifier, bool isMemberCheck, const TPublicType* publicType)
3924 {
3925     bool nonuniformOkay = false;
3926 
3927     // move from parameter/unknown qualifiers to pipeline in/out qualifiers
3928     switch (qualifier.storage) {
3929     case EvqIn:
3930         profileRequires(loc, ENoProfile, 130, nullptr, "in for stage inputs");
3931         profileRequires(loc, EEsProfile, 300, nullptr, "in for stage inputs");
3932         qualifier.storage = EvqVaryingIn;
3933         nonuniformOkay = true;
3934         break;
3935     case EvqOut:
3936         profileRequires(loc, ENoProfile, 130, nullptr, "out for stage outputs");
3937         profileRequires(loc, EEsProfile, 300, nullptr, "out for stage outputs");
3938         qualifier.storage = EvqVaryingOut;
3939         if (intermediate.isInvariantAll())
3940             qualifier.invariant = true;
3941         break;
3942     case EvqInOut:
3943         qualifier.storage = EvqVaryingIn;
3944         error(loc, "cannot use 'inout' at global scope", "", "");
3945         break;
3946     case EvqGlobal:
3947     case EvqTemporary:
3948         nonuniformOkay = true;
3949         break;
3950     case EvqUniform:
3951         // According to GLSL spec: The std430 qualifier is supported only for shader storage blocks; a shader using
3952         // the std430 qualifier on a uniform block will fail to compile.
3953         // Only check the global declaration: layout(std430) uniform;
3954         if (blockName == nullptr &&
3955             qualifier.layoutPacking == ElpStd430)
3956         {
3957             requireExtensions(loc, 1, &E_GL_EXT_scalar_block_layout, "default std430 layout for uniform");
3958         }
3959 
3960         if (publicType != nullptr && publicType->isImage() &&
3961             (qualifier.layoutFormat > ElfExtSizeGuard && qualifier.layoutFormat < ElfCount))
3962             qualifier.layoutFormat = mapLegacyLayoutFormat(qualifier.layoutFormat, publicType->sampler.getBasicType());
3963 
3964         break;
3965     default:
3966         break;
3967     }
3968 
3969     if (!nonuniformOkay && qualifier.isNonUniform())
3970         error(loc, "for non-parameter, can only apply to 'in' or no storage qualifier", "nonuniformEXT", "");
3971 
3972     if (qualifier.isSpirvByReference())
3973         error(loc, "can only apply to parameter", "spirv_by_reference", "");
3974 
3975     if (qualifier.isSpirvLiteral())
3976         error(loc, "can only apply to parameter", "spirv_literal", "");
3977 
3978     // Storage qualifier isn't ready for memberQualifierCheck, we should skip invariantCheck for it.
3979     if (!isMemberCheck || structNestingLevel > 0)
3980         invariantCheck(loc, qualifier);
3981 }
3982 
3983 //
3984 // Check a full qualifier and type (no variable yet) at global level.
3985 //
globalQualifierTypeCheck(const TSourceLoc & loc,const TQualifier & qualifier,const TPublicType & publicType)3986 void TParseContext::globalQualifierTypeCheck(const TSourceLoc& loc, const TQualifier& qualifier, const TPublicType& publicType)
3987 {
3988     if (! symbolTable.atGlobalLevel())
3989         return;
3990 
3991     if (!(publicType.userDef && publicType.userDef->isReference()) && !parsingBuiltins) {
3992         if (qualifier.isMemoryQualifierImageAndSSBOOnly() && ! publicType.isImage() && publicType.qualifier.storage != EvqBuffer) {
3993             error(loc, "memory qualifiers cannot be used on this type", "", "");
3994         } else if (qualifier.isMemory() && (publicType.basicType != EbtSampler) && !publicType.qualifier.isUniformOrBuffer()) {
3995             error(loc, "memory qualifiers cannot be used on this type", "", "");
3996         }
3997     }
3998 
3999     if (qualifier.storage == EvqBuffer &&
4000         publicType.basicType != EbtBlock &&
4001         !qualifier.hasBufferReference())
4002         error(loc, "buffers can be declared only as blocks", "buffer", "");
4003 
4004     if (qualifier.storage != EvqVaryingIn && publicType.basicType == EbtDouble &&
4005         extensionTurnedOn(E_GL_ARB_vertex_attrib_64bit) && language == EShLangVertex &&
4006         version < 400) {
4007         profileRequires(loc, ECoreProfile | ECompatibilityProfile, 410, E_GL_ARB_gpu_shader_fp64, "vertex-shader `double` type");
4008     }
4009     if (qualifier.storage != EvqVaryingIn && qualifier.storage != EvqVaryingOut)
4010         return;
4011 
4012     if (publicType.shaderQualifiers.hasBlendEquation())
4013         error(loc, "can only be applied to a standalone 'out'", "blend equation", "");
4014 
4015     // now, knowing it is a shader in/out, do all the in/out semantic checks
4016 
4017     if (publicType.basicType == EbtBool && !parsingBuiltins) {
4018         error(loc, "cannot be bool", GetStorageQualifierString(qualifier.storage), "");
4019         return;
4020     }
4021 
4022     if (isTypeInt(publicType.basicType) || publicType.basicType == EbtDouble) {
4023         profileRequires(loc, EEsProfile, 300, nullptr, "non-float shader input/output");
4024         profileRequires(loc, ~EEsProfile, 130, nullptr, "non-float shader input/output");
4025     }
4026 
4027     if (!qualifier.flat && !qualifier.isExplicitInterpolation() && !qualifier.isPervertexNV() && !qualifier.isPervertexEXT()) {
4028         if (isTypeInt(publicType.basicType) ||
4029             publicType.basicType == EbtDouble ||
4030             (publicType.userDef && (   publicType.userDef->containsBasicType(EbtInt)
4031                                     || publicType.userDef->containsBasicType(EbtUint)
4032                                     || publicType.userDef->contains16BitInt()
4033                                     || publicType.userDef->contains8BitInt()
4034                                     || publicType.userDef->contains64BitInt()
4035                                     || publicType.userDef->containsDouble()))) {
4036             if (qualifier.storage == EvqVaryingIn && language == EShLangFragment)
4037                 error(loc, "must be qualified as flat", TType::getBasicString(publicType.basicType), GetStorageQualifierString(qualifier.storage));
4038             else if (qualifier.storage == EvqVaryingOut && language == EShLangVertex && version == 300)
4039                 error(loc, "must be qualified as flat", TType::getBasicString(publicType.basicType), GetStorageQualifierString(qualifier.storage));
4040         }
4041     }
4042 
4043     if (qualifier.isPatch() && qualifier.isInterpolation())
4044         error(loc, "cannot use interpolation qualifiers with patch", "patch", "");
4045 
4046     if (qualifier.isTaskPayload() && publicType.basicType == EbtBlock)
4047         error(loc, "taskPayloadSharedEXT variables should not be declared as interface blocks", "taskPayloadSharedEXT", "");
4048 
4049     if (qualifier.isTaskMemory() && publicType.basicType != EbtBlock)
4050         error(loc, "taskNV variables can be declared only as blocks", "taskNV", "");
4051 
4052     if (qualifier.storage == EvqVaryingIn) {
4053         switch (language) {
4054         case EShLangVertex:
4055             if (publicType.basicType == EbtStruct) {
4056                 error(loc, "cannot be a structure", GetStorageQualifierString(qualifier.storage), "");
4057                 return;
4058             }
4059             if (publicType.arraySizes) {
4060                 requireProfile(loc, ~EEsProfile, "vertex input arrays");
4061                 profileRequires(loc, ENoProfile, 150, nullptr, "vertex input arrays");
4062             }
4063             if (publicType.basicType == EbtDouble)
4064                 profileRequires(loc, ~EEsProfile, 410, E_GL_ARB_vertex_attrib_64bit, "vertex-shader `double` type input");
4065             if (qualifier.isAuxiliary() || qualifier.isInterpolation() || qualifier.isMemory() || qualifier.invariant)
4066                 error(loc, "vertex input cannot be further qualified", "", "");
4067             break;
4068         case EShLangFragment:
4069             if (publicType.userDef) {
4070                 profileRequires(loc, EEsProfile, 300, nullptr, "fragment-shader struct input");
4071                 profileRequires(loc, ~EEsProfile, 150, nullptr, "fragment-shader struct input");
4072                 if (publicType.userDef->containsStructure())
4073                     requireProfile(loc, ~EEsProfile, "fragment-shader struct input containing structure");
4074                 if (publicType.userDef->containsArray())
4075                     requireProfile(loc, ~EEsProfile, "fragment-shader struct input containing an array");
4076             }
4077             break;
4078        case EShLangCompute:
4079             if (! symbolTable.atBuiltInLevel())
4080                 error(loc, "global storage input qualifier cannot be used in a compute shader", "in", "");
4081             break;
4082        case EShLangTessControl:
4083             if (qualifier.patch)
4084                 error(loc, "can only use on output in tessellation-control shader", "patch", "");
4085             break;
4086         default:
4087             break;
4088         }
4089     } else {
4090         // qualifier.storage == EvqVaryingOut
4091         switch (language) {
4092         case EShLangVertex:
4093             if (publicType.userDef) {
4094                 profileRequires(loc, EEsProfile, 300, nullptr, "vertex-shader struct output");
4095                 profileRequires(loc, ~EEsProfile, 150, nullptr, "vertex-shader struct output");
4096                 if (publicType.userDef->containsStructure())
4097                     requireProfile(loc, ~EEsProfile, "vertex-shader struct output containing structure");
4098                 if (publicType.userDef->containsArray())
4099                     requireProfile(loc, ~EEsProfile, "vertex-shader struct output containing an array");
4100             }
4101 
4102             break;
4103         case EShLangFragment:
4104             profileRequires(loc, EEsProfile, 300, nullptr, "fragment shader output");
4105             if (publicType.basicType == EbtStruct) {
4106                 error(loc, "cannot be a structure", GetStorageQualifierString(qualifier.storage), "");
4107                 return;
4108             }
4109             if (publicType.matrixRows > 0) {
4110                 error(loc, "cannot be a matrix", GetStorageQualifierString(qualifier.storage), "");
4111                 return;
4112             }
4113             if (qualifier.isAuxiliary())
4114                 error(loc, "can't use auxiliary qualifier on a fragment output", "centroid/sample/patch", "");
4115             if (qualifier.isInterpolation())
4116                 error(loc, "can't use interpolation qualifier on a fragment output", "flat/smooth/noperspective", "");
4117             if (publicType.basicType == EbtDouble || publicType.basicType == EbtInt64 || publicType.basicType == EbtUint64)
4118                 error(loc, "cannot contain a double, int64, or uint64", GetStorageQualifierString(qualifier.storage), "");
4119         break;
4120 
4121         case EShLangCompute:
4122             error(loc, "global storage output qualifier cannot be used in a compute shader", "out", "");
4123             break;
4124         case EShLangTessEvaluation:
4125             if (qualifier.patch)
4126                 error(loc, "can only use on input in tessellation-evaluation shader", "patch", "");
4127             break;
4128         default:
4129             break;
4130         }
4131     }
4132 }
4133 
4134 //
4135 // Merge characteristics of the 'src' qualifier into the 'dst'.
4136 // If there is duplication, issue error messages, unless 'force'
4137 // is specified, which means to just override default settings.
4138 //
4139 // Also, when force is false, it will be assumed that 'src' follows
4140 // 'dst', for the purpose of error checking order for versions
4141 // that require specific orderings of qualifiers.
4142 //
mergeQualifiers(const TSourceLoc & loc,TQualifier & dst,const TQualifier & src,bool force)4143 void TParseContext::mergeQualifiers(const TSourceLoc& loc, TQualifier& dst, const TQualifier& src, bool force)
4144 {
4145     // Multiple auxiliary qualifiers (mostly done later by 'individual qualifiers')
4146     if (src.isAuxiliary() && dst.isAuxiliary())
4147         error(loc, "can only have one auxiliary qualifier (centroid, patch, and sample)", "", "");
4148 
4149     // Multiple interpolation qualifiers (mostly done later by 'individual qualifiers')
4150     if (src.isInterpolation() && dst.isInterpolation())
4151         error(loc, "can only have one interpolation qualifier (flat, smooth, noperspective, __explicitInterpAMD)", "", "");
4152 
4153     // Ordering
4154     if (! force && ((!isEsProfile() && version < 420) ||
4155                     (isEsProfile() && version < 310))
4156                 && ! extensionTurnedOn(E_GL_ARB_shading_language_420pack)) {
4157         // non-function parameters
4158         if (src.isNoContraction() && (dst.invariant || dst.isInterpolation() || dst.isAuxiliary() || dst.storage != EvqTemporary || dst.precision != EpqNone))
4159             error(loc, "precise qualifier must appear first", "", "");
4160         if (src.invariant && (dst.isInterpolation() || dst.isAuxiliary() || dst.storage != EvqTemporary || dst.precision != EpqNone))
4161             error(loc, "invariant qualifier must appear before interpolation, storage, and precision qualifiers ", "", "");
4162         else if (src.isInterpolation() && (dst.isAuxiliary() || dst.storage != EvqTemporary || dst.precision != EpqNone))
4163             error(loc, "interpolation qualifiers must appear before storage and precision qualifiers", "", "");
4164         else if (src.isAuxiliary() && (dst.storage != EvqTemporary || dst.precision != EpqNone))
4165             error(loc, "Auxiliary qualifiers (centroid, patch, and sample) must appear before storage and precision qualifiers", "", "");
4166         else if (src.storage != EvqTemporary && (dst.precision != EpqNone))
4167             error(loc, "precision qualifier must appear as last qualifier", "", "");
4168 
4169         // function parameters
4170         if (src.isNoContraction() && (dst.storage == EvqConst || dst.storage == EvqIn || dst.storage == EvqOut))
4171             error(loc, "precise qualifier must appear first", "", "");
4172         if (src.storage == EvqConst && (dst.storage == EvqIn || dst.storage == EvqOut))
4173             error(loc, "in/out must appear before const", "", "");
4174     }
4175 
4176     // Storage qualification
4177     if (dst.storage == EvqTemporary || dst.storage == EvqGlobal)
4178         dst.storage = src.storage;
4179     else if ((dst.storage == EvqIn  && src.storage == EvqOut) ||
4180              (dst.storage == EvqOut && src.storage == EvqIn))
4181         dst.storage = EvqInOut;
4182     else if ((dst.storage == EvqIn    && src.storage == EvqConst) ||
4183              (dst.storage == EvqConst && src.storage == EvqIn))
4184         dst.storage = EvqConstReadOnly;
4185     else if (src.storage != EvqTemporary &&
4186              src.storage != EvqGlobal)
4187         error(loc, "too many storage qualifiers", GetStorageQualifierString(src.storage), "");
4188 
4189     // Precision qualifiers
4190     if (! force && src.precision != EpqNone && dst.precision != EpqNone)
4191         error(loc, "only one precision qualifier allowed", GetPrecisionQualifierString(src.precision), "");
4192     if (dst.precision == EpqNone || (force && src.precision != EpqNone))
4193         dst.precision = src.precision;
4194 
4195     if (!force && ((src.coherent && (dst.devicecoherent || dst.queuefamilycoherent || dst.workgroupcoherent || dst.subgroupcoherent || dst.shadercallcoherent)) ||
4196                    (src.devicecoherent && (dst.coherent || dst.queuefamilycoherent || dst.workgroupcoherent || dst.subgroupcoherent || dst.shadercallcoherent)) ||
4197                    (src.queuefamilycoherent && (dst.coherent || dst.devicecoherent || dst.workgroupcoherent || dst.subgroupcoherent || dst.shadercallcoherent)) ||
4198                    (src.workgroupcoherent && (dst.coherent || dst.devicecoherent || dst.queuefamilycoherent || dst.subgroupcoherent || dst.shadercallcoherent)) ||
4199                    (src.subgroupcoherent  && (dst.coherent || dst.devicecoherent || dst.queuefamilycoherent || dst.workgroupcoherent || dst.shadercallcoherent)) ||
4200                    (src.shadercallcoherent && (dst.coherent || dst.devicecoherent || dst.queuefamilycoherent || dst.workgroupcoherent || dst.subgroupcoherent)))) {
4201         error(loc, "only one coherent/devicecoherent/queuefamilycoherent/workgroupcoherent/subgroupcoherent/shadercallcoherent qualifier allowed",
4202             GetPrecisionQualifierString(src.precision), "");
4203     }
4204 
4205     // Layout qualifiers
4206     mergeObjectLayoutQualifiers(dst, src, false);
4207 
4208     // individual qualifiers
4209     bool repeated = false;
4210     #define MERGE_SINGLETON(field) repeated |= dst.field && src.field; dst.field |= src.field;
4211     MERGE_SINGLETON(invariant);
4212     MERGE_SINGLETON(centroid);
4213     MERGE_SINGLETON(smooth);
4214     MERGE_SINGLETON(flat);
4215     MERGE_SINGLETON(specConstant);
4216     MERGE_SINGLETON(noContraction);
4217     MERGE_SINGLETON(nopersp);
4218     MERGE_SINGLETON(explicitInterp);
4219     MERGE_SINGLETON(perPrimitiveNV);
4220     MERGE_SINGLETON(perViewNV);
4221     MERGE_SINGLETON(perTaskNV);
4222     MERGE_SINGLETON(patch);
4223     MERGE_SINGLETON(sample);
4224     MERGE_SINGLETON(coherent);
4225     MERGE_SINGLETON(devicecoherent);
4226     MERGE_SINGLETON(queuefamilycoherent);
4227     MERGE_SINGLETON(workgroupcoherent);
4228     MERGE_SINGLETON(subgroupcoherent);
4229     MERGE_SINGLETON(shadercallcoherent);
4230     MERGE_SINGLETON(nonprivate);
4231     MERGE_SINGLETON(volatil);
4232     MERGE_SINGLETON(restrict);
4233     MERGE_SINGLETON(readonly);
4234     MERGE_SINGLETON(writeonly);
4235     MERGE_SINGLETON(nonUniform);
4236 
4237     // SPIR-V storage class qualifier (GL_EXT_spirv_intrinsics)
4238     dst.spirvStorageClass = src.spirvStorageClass;
4239 
4240     // SPIR-V decorate qualifiers (GL_EXT_spirv_intrinsics)
4241     if (src.hasSpirvDecorate()) {
4242         if (dst.hasSpirvDecorate()) {
4243             const TSpirvDecorate& srcSpirvDecorate = src.getSpirvDecorate();
4244             TSpirvDecorate& dstSpirvDecorate = dst.getSpirvDecorate();
4245             for (auto& decorate : srcSpirvDecorate.decorates) {
4246                 if (dstSpirvDecorate.decorates.find(decorate.first) != dstSpirvDecorate.decorates.end())
4247                     error(loc, "too many SPIR-V decorate qualifiers", "spirv_decorate", "(decoration=%u)", decorate.first);
4248                 else
4249                     dstSpirvDecorate.decorates.insert(decorate);
4250             }
4251 
4252             for (auto& decorateId : srcSpirvDecorate.decorateIds) {
4253                 if (dstSpirvDecorate.decorateIds.find(decorateId.first) != dstSpirvDecorate.decorateIds.end())
4254                     error(loc, "too many SPIR-V decorate qualifiers", "spirv_decorate_id", "(decoration=%u)", decorateId.first);
4255                 else
4256                     dstSpirvDecorate.decorateIds.insert(decorateId);
4257             }
4258 
4259             for (auto& decorateString : srcSpirvDecorate.decorateStrings) {
4260                 if (dstSpirvDecorate.decorates.find(decorateString.first) != dstSpirvDecorate.decorates.end())
4261                     error(loc, "too many SPIR-V decorate qualifiers", "spirv_decorate_string", "(decoration=%u)", decorateString.first);
4262                 else
4263                     dstSpirvDecorate.decorateStrings.insert(decorateString);
4264             }
4265         } else {
4266             dst.spirvDecorate = src.spirvDecorate;
4267         }
4268     }
4269 
4270     if (repeated)
4271         error(loc, "replicated qualifiers", "", "");
4272 }
4273 
setDefaultPrecision(const TSourceLoc & loc,TPublicType & publicType,TPrecisionQualifier qualifier)4274 void TParseContext::setDefaultPrecision(const TSourceLoc& loc, TPublicType& publicType, TPrecisionQualifier qualifier)
4275 {
4276     TBasicType basicType = publicType.basicType;
4277 
4278     if (basicType == EbtSampler) {
4279         defaultSamplerPrecision[computeSamplerTypeIndex(publicType.sampler)] = qualifier;
4280 
4281         return;  // all is well
4282     }
4283 
4284     if (basicType == EbtInt || basicType == EbtFloat) {
4285         if (publicType.isScalar()) {
4286             defaultPrecision[basicType] = qualifier;
4287             if (basicType == EbtInt) {
4288                 defaultPrecision[EbtUint] = qualifier;
4289                 precisionManager.explicitIntDefaultSeen();
4290             } else
4291                 precisionManager.explicitFloatDefaultSeen();
4292 
4293             return;  // all is well
4294         }
4295     }
4296 
4297     if (basicType == EbtAtomicUint) {
4298         if (qualifier != EpqHigh)
4299             error(loc, "can only apply highp to atomic_uint", "precision", "");
4300 
4301         return;
4302     }
4303 
4304     error(loc, "cannot apply precision statement to this type; use 'float', 'int' or a sampler type", TType::getBasicString(basicType), "");
4305 }
4306 
4307 // used to flatten the sampler type space into a single dimension
4308 // correlates with the declaration of defaultSamplerPrecision[]
computeSamplerTypeIndex(TSampler & sampler)4309 int TParseContext::computeSamplerTypeIndex(TSampler& sampler)
4310 {
4311     int arrayIndex    = sampler.arrayed         ? 1 : 0;
4312     int shadowIndex   = sampler.shadow          ? 1 : 0;
4313     int externalIndex = sampler.isExternal()    ? 1 : 0;
4314     int imageIndex    = sampler.isImageClass()  ? 1 : 0;
4315     int msIndex       = sampler.isMultiSample() ? 1 : 0;
4316 
4317     int flattened = EsdNumDims * (EbtNumTypes * (2 * (2 * (2 * (2 * arrayIndex + msIndex) + imageIndex) + shadowIndex) +
4318                                                  externalIndex) + sampler.type) + sampler.dim;
4319     assert(flattened < maxSamplerIndex);
4320 
4321     return flattened;
4322 }
4323 
getDefaultPrecision(TPublicType & publicType)4324 TPrecisionQualifier TParseContext::getDefaultPrecision(TPublicType& publicType)
4325 {
4326     if (publicType.basicType == EbtSampler)
4327         return defaultSamplerPrecision[computeSamplerTypeIndex(publicType.sampler)];
4328     else
4329         return defaultPrecision[publicType.basicType];
4330 }
4331 
precisionQualifierCheck(const TSourceLoc & loc,TBasicType baseType,TQualifier & qualifier,bool isCoopMat)4332 void TParseContext::precisionQualifierCheck(const TSourceLoc& loc, TBasicType baseType, TQualifier& qualifier, bool isCoopMat)
4333 {
4334     // Built-in symbols are allowed some ambiguous precisions, to be pinned down
4335     // later by context.
4336     if (! obeyPrecisionQualifiers() || parsingBuiltins)
4337         return;
4338 
4339     if (baseType == EbtAtomicUint && qualifier.precision != EpqNone && qualifier.precision != EpqHigh)
4340         error(loc, "atomic counters can only be highp", "atomic_uint", "");
4341 
4342     if (isCoopMat)
4343         return;
4344 
4345     if (baseType == EbtFloat || baseType == EbtUint || baseType == EbtInt || baseType == EbtSampler || baseType == EbtAtomicUint) {
4346         if (qualifier.precision == EpqNone) {
4347             if (relaxedErrors())
4348                 warn(loc, "type requires declaration of default precision qualifier", TType::getBasicString(baseType), "substituting 'mediump'");
4349             else
4350                 error(loc, "type requires declaration of default precision qualifier", TType::getBasicString(baseType), "");
4351             qualifier.precision = EpqMedium;
4352             defaultPrecision[baseType] = EpqMedium;
4353         }
4354     } else if (qualifier.precision != EpqNone)
4355         error(loc, "type cannot have precision qualifier", TType::getBasicString(baseType), "");
4356 }
4357 
parameterTypeCheck(const TSourceLoc & loc,TStorageQualifier qualifier,const TType & type)4358 void TParseContext::parameterTypeCheck(const TSourceLoc& loc, TStorageQualifier qualifier, const TType& type)
4359 {
4360     if ((qualifier == EvqOut || qualifier == EvqInOut) && type.isOpaque() && !intermediate.getBindlessMode())
4361         error(loc, "samplers and atomic_uints cannot be output parameters", type.getBasicTypeString().c_str(), "");
4362     if (!parsingBuiltins && type.contains16BitFloat())
4363         requireFloat16Arithmetic(loc, type.getBasicTypeString().c_str(), "float16 types can only be in uniform block or buffer storage");
4364     if (!parsingBuiltins && type.contains16BitInt())
4365         requireInt16Arithmetic(loc, type.getBasicTypeString().c_str(), "(u)int16 types can only be in uniform block or buffer storage");
4366     if (!parsingBuiltins && type.contains8BitInt())
4367         requireInt8Arithmetic(loc, type.getBasicTypeString().c_str(), "(u)int8 types can only be in uniform block or buffer storage");
4368 }
4369 
containsFieldWithBasicType(const TType & type,TBasicType basicType)4370 bool TParseContext::containsFieldWithBasicType(const TType& type, TBasicType basicType)
4371 {
4372     if (type.getBasicType() == basicType)
4373         return true;
4374 
4375     if (type.getBasicType() == EbtStruct) {
4376         const TTypeList& structure = *type.getStruct();
4377         for (unsigned int i = 0; i < structure.size(); ++i) {
4378             if (containsFieldWithBasicType(*structure[i].type, basicType))
4379                 return true;
4380         }
4381     }
4382 
4383     return false;
4384 }
4385 
4386 //
4387 // Do size checking for an array type's size.
4388 //
arraySizeCheck(const TSourceLoc & loc,TIntermTyped * expr,TArraySize & sizePair,const char * sizeType,const bool allowZero)4389 void TParseContext::arraySizeCheck(const TSourceLoc& loc, TIntermTyped* expr, TArraySize& sizePair,
4390                                    const char* sizeType, const bool allowZero)
4391 {
4392     bool isConst = false;
4393     sizePair.node = nullptr;
4394 
4395     int size = 1;
4396 
4397     TIntermConstantUnion* constant = expr->getAsConstantUnion();
4398     if (constant) {
4399         // handle true (non-specialization) constant
4400         size = constant->getConstArray()[0].getIConst();
4401         isConst = true;
4402     } else {
4403         // see if it's a specialization constant instead
4404         if (expr->getQualifier().isSpecConstant()) {
4405             isConst = true;
4406             sizePair.node = expr;
4407             TIntermSymbol* symbol = expr->getAsSymbolNode();
4408             if (symbol && symbol->getConstArray().size() > 0)
4409                 size = symbol->getConstArray()[0].getIConst();
4410         } else if (expr->getAsUnaryNode() && expr->getAsUnaryNode()->getOp() == glslang::EOpArrayLength &&
4411                    expr->getAsUnaryNode()->getOperand()->getType().isCoopMatNV()) {
4412             isConst = true;
4413             size = 1;
4414             sizePair.node = expr->getAsUnaryNode();
4415         }
4416     }
4417 
4418     sizePair.size = size;
4419 
4420     if (! isConst || (expr->getBasicType() != EbtInt && expr->getBasicType() != EbtUint)) {
4421         error(loc, sizeType, "", "must be a constant integer expression");
4422         return;
4423     }
4424 
4425     if (allowZero) {
4426         if (size < 0) {
4427             error(loc, sizeType, "", "must be a non-negative integer");
4428             return;
4429         }
4430     } else {
4431         if (size <= 0) {
4432             error(loc, sizeType, "", "must be a positive integer");
4433             return;
4434         }
4435     }
4436 }
4437 
4438 //
4439 // See if this qualifier can be an array.
4440 //
4441 // Returns true if there is an error.
4442 //
arrayQualifierError(const TSourceLoc & loc,const TQualifier & qualifier)4443 bool TParseContext::arrayQualifierError(const TSourceLoc& loc, const TQualifier& qualifier)
4444 {
4445     if (qualifier.storage == EvqConst) {
4446         profileRequires(loc, ENoProfile, 120, E_GL_3DL_array_objects, "const array");
4447         profileRequires(loc, EEsProfile, 300, nullptr, "const array");
4448     }
4449 
4450     if (qualifier.storage == EvqVaryingIn && language == EShLangVertex) {
4451         requireProfile(loc, ~EEsProfile, "vertex input arrays");
4452         profileRequires(loc, ENoProfile, 150, nullptr, "vertex input arrays");
4453     }
4454 
4455     return false;
4456 }
4457 
4458 //
4459 // See if this qualifier and type combination can be an array.
4460 // Assumes arrayQualifierError() was also called to catch the type-invariant tests.
4461 //
4462 // Returns true if there is an error.
4463 //
arrayError(const TSourceLoc & loc,const TType & type)4464 bool TParseContext::arrayError(const TSourceLoc& loc, const TType& type)
4465 {
4466     if (type.getQualifier().storage == EvqVaryingOut && language == EShLangVertex) {
4467         if (type.isArrayOfArrays())
4468             requireProfile(loc, ~EEsProfile, "vertex-shader array-of-array output");
4469         else if (type.isStruct())
4470             requireProfile(loc, ~EEsProfile, "vertex-shader array-of-struct output");
4471     }
4472     if (type.getQualifier().storage == EvqVaryingIn && language == EShLangFragment) {
4473         if (type.isArrayOfArrays())
4474             requireProfile(loc, ~EEsProfile, "fragment-shader array-of-array input");
4475         else if (type.isStruct())
4476             requireProfile(loc, ~EEsProfile, "fragment-shader array-of-struct input");
4477     }
4478     if (type.getQualifier().storage == EvqVaryingOut && language == EShLangFragment) {
4479         if (type.isArrayOfArrays())
4480             requireProfile(loc, ~EEsProfile, "fragment-shader array-of-array output");
4481     }
4482 
4483     return false;
4484 }
4485 
4486 //
4487 // Require array to be completely sized
4488 //
arraySizeRequiredCheck(const TSourceLoc & loc,const TArraySizes & arraySizes)4489 void TParseContext::arraySizeRequiredCheck(const TSourceLoc& loc, const TArraySizes& arraySizes)
4490 {
4491     if (!parsingBuiltins && arraySizes.hasUnsized())
4492         error(loc, "array size required", "", "");
4493 }
4494 
structArrayCheck(const TSourceLoc &,const TType & type)4495 void TParseContext::structArrayCheck(const TSourceLoc& /*loc*/, const TType& type)
4496 {
4497     const TTypeList& structure = *type.getStruct();
4498     for (int m = 0; m < (int)structure.size(); ++m) {
4499         const TType& member = *structure[m].type;
4500         if (member.isArray())
4501             arraySizeRequiredCheck(structure[m].loc, *member.getArraySizes());
4502     }
4503 }
4504 
arraySizesCheck(const TSourceLoc & loc,const TQualifier & qualifier,TArraySizes * arraySizes,const TIntermTyped * initializer,bool lastMember)4505 void TParseContext::arraySizesCheck(const TSourceLoc& loc, const TQualifier& qualifier, TArraySizes* arraySizes,
4506     const TIntermTyped* initializer, bool lastMember)
4507 {
4508     assert(arraySizes);
4509 
4510     // always allow special built-in ins/outs sized to topologies
4511     if (parsingBuiltins)
4512         return;
4513 
4514     // initializer must be a sized array, in which case
4515     // allow the initializer to set any unknown array sizes
4516     if (initializer != nullptr) {
4517         if (initializer->getType().isUnsizedArray())
4518             error(loc, "array initializer must be sized", "[]", "");
4519         return;
4520     }
4521 
4522     // No environment allows any non-outer-dimension to be implicitly sized
4523     if (arraySizes->isInnerUnsized()) {
4524         error(loc, "only outermost dimension of an array of arrays can be implicitly sized", "[]", "");
4525         arraySizes->clearInnerUnsized();
4526     }
4527 
4528     if (arraySizes->isInnerSpecialization() &&
4529         (qualifier.storage != EvqTemporary && qualifier.storage != EvqGlobal && qualifier.storage != EvqShared && qualifier.storage != EvqConst))
4530         error(loc, "only outermost dimension of an array of arrays can be a specialization constant", "[]", "");
4531 
4532     // desktop always allows outer-dimension-unsized variable arrays,
4533     if (!isEsProfile())
4534         return;
4535 
4536     // for ES, if size isn't coming from an initializer, it has to be explicitly declared now,
4537     // with very few exceptions
4538 
4539     // implicitly-sized io exceptions:
4540     switch (language) {
4541     case EShLangGeometry:
4542         if (qualifier.storage == EvqVaryingIn)
4543             if ((isEsProfile() && version >= 320) ||
4544                 extensionsTurnedOn(Num_AEP_geometry_shader, AEP_geometry_shader))
4545                 return;
4546         break;
4547     case EShLangTessControl:
4548         if ( qualifier.storage == EvqVaryingIn ||
4549             (qualifier.storage == EvqVaryingOut && ! qualifier.isPatch()))
4550             if ((isEsProfile() && version >= 320) ||
4551                 extensionsTurnedOn(Num_AEP_tessellation_shader, AEP_tessellation_shader))
4552                 return;
4553         break;
4554     case EShLangTessEvaluation:
4555         if ((qualifier.storage == EvqVaryingIn && ! qualifier.isPatch()) ||
4556              qualifier.storage == EvqVaryingOut)
4557             if ((isEsProfile() && version >= 320) ||
4558                 extensionsTurnedOn(Num_AEP_tessellation_shader, AEP_tessellation_shader))
4559                 return;
4560         break;
4561     case EShLangMesh:
4562         if (qualifier.storage == EvqVaryingOut)
4563             if ((isEsProfile() && version >= 320) ||
4564                 extensionsTurnedOn(Num_AEP_mesh_shader, AEP_mesh_shader))
4565                 return;
4566         break;
4567     default:
4568         break;
4569     }
4570 
4571     // last member of ssbo block exception:
4572     if (qualifier.storage == EvqBuffer && lastMember)
4573         return;
4574 
4575     arraySizeRequiredCheck(loc, *arraySizes);
4576 }
4577 
arrayOfArrayVersionCheck(const TSourceLoc & loc,const TArraySizes * sizes)4578 void TParseContext::arrayOfArrayVersionCheck(const TSourceLoc& loc, const TArraySizes* sizes)
4579 {
4580     if (sizes == nullptr || sizes->getNumDims() == 1)
4581         return;
4582 
4583     const char* feature = "arrays of arrays";
4584 
4585     requireProfile(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, feature);
4586     profileRequires(loc, EEsProfile, 310, nullptr, feature);
4587     profileRequires(loc, ECoreProfile | ECompatibilityProfile, 430, nullptr, feature);
4588 }
4589 
4590 //
4591 // Do all the semantic checking for declaring or redeclaring an array, with and
4592 // without a size, and make the right changes to the symbol table.
4593 //
declareArray(const TSourceLoc & loc,const TString & identifier,const TType & type,TSymbol * & symbol)4594 void TParseContext::declareArray(const TSourceLoc& loc, const TString& identifier, const TType& type, TSymbol*& symbol)
4595 {
4596     if (symbol == nullptr) {
4597         bool currentScope;
4598         symbol = symbolTable.find(identifier, nullptr, &currentScope);
4599 
4600         if (symbol && builtInName(identifier) && ! symbolTable.atBuiltInLevel()) {
4601             // bad shader (errors already reported) trying to redeclare a built-in name as an array
4602             symbol = nullptr;
4603             return;
4604         }
4605         if (symbol == nullptr || ! currentScope) {
4606             //
4607             // Successfully process a new definition.
4608             // (Redeclarations have to take place at the same scope; otherwise they are hiding declarations)
4609             //
4610             symbol = new TVariable(&identifier, type);
4611             symbolTable.insert(*symbol);
4612             if (symbolTable.atGlobalLevel())
4613                 trackLinkage(*symbol);
4614 
4615             if (! symbolTable.atBuiltInLevel()) {
4616                 if (isIoResizeArray(type)) {
4617                     ioArraySymbolResizeList.push_back(symbol);
4618                     checkIoArraysConsistency(loc, true);
4619                 } else
4620                     fixIoArraySize(loc, symbol->getWritableType());
4621             }
4622 
4623             return;
4624         }
4625         if (symbol->getAsAnonMember()) {
4626             error(loc, "cannot redeclare a user-block member array", identifier.c_str(), "");
4627             symbol = nullptr;
4628             return;
4629         }
4630     }
4631 
4632     //
4633     // Process a redeclaration.
4634     //
4635 
4636     if (symbol == nullptr) {
4637         error(loc, "array variable name expected", identifier.c_str(), "");
4638         return;
4639     }
4640 
4641     // redeclareBuiltinVariable() should have already done the copyUp()
4642     TType& existingType = symbol->getWritableType();
4643 
4644     if (! existingType.isArray()) {
4645         error(loc, "redeclaring non-array as array", identifier.c_str(), "");
4646         return;
4647     }
4648 
4649     if (! existingType.sameElementType(type)) {
4650         error(loc, "redeclaration of array with a different element type", identifier.c_str(), "");
4651         return;
4652     }
4653 
4654     if (! existingType.sameInnerArrayness(type)) {
4655         error(loc, "redeclaration of array with a different array dimensions or sizes", identifier.c_str(), "");
4656         return;
4657     }
4658 
4659     if (existingType.isSizedArray()) {
4660         // be more leniant for input arrays to geometry shaders and tessellation control outputs, where the redeclaration is the same size
4661         if (! (isIoResizeArray(type) && existingType.getOuterArraySize() == type.getOuterArraySize()))
4662             error(loc, "redeclaration of array with size", identifier.c_str(), "");
4663         return;
4664     }
4665 
4666     arrayLimitCheck(loc, identifier, type.getOuterArraySize());
4667 
4668     existingType.updateArraySizes(type);
4669 
4670     if (isIoResizeArray(type))
4671         checkIoArraysConsistency(loc);
4672 }
4673 
4674 // Policy and error check for needing a runtime sized array.
checkRuntimeSizable(const TSourceLoc & loc,const TIntermTyped & base)4675 void TParseContext::checkRuntimeSizable(const TSourceLoc& loc, const TIntermTyped& base)
4676 {
4677     // runtime length implies runtime sizeable, so no problem
4678     if (isRuntimeLength(base))
4679         return;
4680 
4681     if (base.getType().getQualifier().builtIn == EbvSampleMask)
4682         return;
4683 
4684     // Check for last member of a bufferreference type, which is runtime sizeable
4685     // but doesn't support runtime length
4686     if (base.getType().getQualifier().storage == EvqBuffer) {
4687         const TIntermBinary* binary = base.getAsBinaryNode();
4688         if (binary != nullptr &&
4689             binary->getOp() == EOpIndexDirectStruct &&
4690             binary->getLeft()->isReference()) {
4691 
4692             const int index = binary->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
4693             const int memberCount = (int)binary->getLeft()->getType().getReferentType()->getStruct()->size();
4694             if (index == memberCount - 1)
4695                 return;
4696         }
4697     }
4698 
4699     // check for additional things allowed by GL_EXT_nonuniform_qualifier
4700     if (base.getBasicType() == EbtSampler || base.getBasicType() == EbtAccStruct || base.getBasicType() == EbtRayQuery ||
4701         base.getBasicType() == EbtHitObjectNV || (base.getBasicType() == EbtBlock && base.getType().getQualifier().isUniformOrBuffer()))
4702         requireExtensions(loc, 1, &E_GL_EXT_nonuniform_qualifier, "variable index");
4703     else
4704         error(loc, "", "[", "array must be redeclared with a size before being indexed with a variable");
4705 }
4706 
4707 // Policy decision for whether a run-time .length() is allowed.
isRuntimeLength(const TIntermTyped & base) const4708 bool TParseContext::isRuntimeLength(const TIntermTyped& base) const
4709 {
4710     if (base.getType().getQualifier().storage == EvqBuffer) {
4711         // in a buffer block
4712         const TIntermBinary* binary = base.getAsBinaryNode();
4713         if (binary != nullptr && binary->getOp() == EOpIndexDirectStruct) {
4714             // is it the last member?
4715             const int index = binary->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
4716 
4717             if (binary->getLeft()->isReference())
4718                 return false;
4719 
4720             const int memberCount = (int)binary->getLeft()->getType().getStruct()->size();
4721             if (index == memberCount - 1)
4722                 return true;
4723         }
4724     }
4725 
4726     return false;
4727 }
4728 
4729 // Check if mesh perviewNV attributes have a view dimension
4730 // and resize it to gl_MaxMeshViewCountNV when implicitly sized.
checkAndResizeMeshViewDim(const TSourceLoc & loc,TType & type,bool isBlockMember)4731 void TParseContext::checkAndResizeMeshViewDim(const TSourceLoc& loc, TType& type, bool isBlockMember)
4732 {
4733     // see if member is a per-view attribute
4734     if (!type.getQualifier().isPerView())
4735         return;
4736 
4737     if ((isBlockMember && type.isArray()) || (!isBlockMember && type.isArrayOfArrays())) {
4738         // since we don't have the maxMeshViewCountNV set during parsing builtins, we hardcode the value.
4739         int maxViewCount = parsingBuiltins ? 4 : resources.maxMeshViewCountNV;
4740         // For block members, outermost array dimension is the view dimension.
4741         // For non-block members, outermost array dimension is the vertex/primitive dimension
4742         // and 2nd outermost is the view dimension.
4743         int viewDim = isBlockMember ? 0 : 1;
4744         int viewDimSize = type.getArraySizes()->getDimSize(viewDim);
4745 
4746         if (viewDimSize != UnsizedArraySize && viewDimSize != maxViewCount)
4747             error(loc, "mesh view output array size must be gl_MaxMeshViewCountNV or implicitly sized", "[]", "");
4748         else if (viewDimSize == UnsizedArraySize)
4749             type.getArraySizes()->setDimSize(viewDim, maxViewCount);
4750     }
4751     else {
4752         error(loc, "requires a view array dimension", "perviewNV", "");
4753     }
4754 }
4755 
4756 // Returns true if the first argument to the #line directive is the line number for the next line.
4757 //
4758 // Desktop, pre-version 3.30:  "After processing this directive
4759 // (including its new-line), the implementation will behave as if it is compiling at line number line+1 and
4760 // source string number source-string-number."
4761 //
4762 // Desktop, version 3.30 and later, and ES:  "After processing this directive
4763 // (including its new-line), the implementation will behave as if it is compiling at line number line and
4764 // source string number source-string-number.
lineDirectiveShouldSetNextLine() const4765 bool TParseContext::lineDirectiveShouldSetNextLine() const
4766 {
4767     return isEsProfile() || version >= 330;
4768 }
4769 
4770 //
4771 // Enforce non-initializer type/qualifier rules.
4772 //
nonInitConstCheck(const TSourceLoc & loc,TString & identifier,TType & type)4773 void TParseContext::nonInitConstCheck(const TSourceLoc& loc, TString& identifier, TType& type)
4774 {
4775     //
4776     // Make the qualifier make sense, given that there is not an initializer.
4777     //
4778     if (type.getQualifier().storage == EvqConst ||
4779         type.getQualifier().storage == EvqConstReadOnly) {
4780         type.getQualifier().makeTemporary();
4781         error(loc, "variables with qualifier 'const' must be initialized", identifier.c_str(), "");
4782     }
4783 }
4784 
4785 //
4786 // See if the identifier is a built-in symbol that can be redeclared, and if so,
4787 // copy the symbol table's read-only built-in variable to the current
4788 // global level, where it can be modified based on the passed in type.
4789 //
4790 // Returns nullptr if no redeclaration took place; meaning a normal declaration still
4791 // needs to occur for it, not necessarily an error.
4792 //
4793 // Returns a redeclared and type-modified variable if a redeclarated occurred.
4794 //
redeclareBuiltinVariable(const TSourceLoc & loc,const TString & identifier,const TQualifier & qualifier,const TShaderQualifiers & publicType)4795 TSymbol* TParseContext::redeclareBuiltinVariable(const TSourceLoc& loc, const TString& identifier,
4796                                                  const TQualifier& qualifier, const TShaderQualifiers& publicType)
4797 {
4798     if (! builtInName(identifier) || symbolTable.atBuiltInLevel() || ! symbolTable.atGlobalLevel())
4799         return nullptr;
4800 
4801     bool nonEsRedecls = (!isEsProfile() && (version >= 130 || identifier == "gl_TexCoord"));
4802     bool    esRedecls = (isEsProfile() &&
4803                          (version >= 320 || extensionsTurnedOn(Num_AEP_shader_io_blocks, AEP_shader_io_blocks)));
4804     if (! esRedecls && ! nonEsRedecls)
4805         return nullptr;
4806 
4807     // Special case when using GL_ARB_separate_shader_objects
4808     bool ssoPre150 = false;  // means the only reason this variable is redeclared is due to this combination
4809     if (!isEsProfile() && version <= 140 && extensionTurnedOn(E_GL_ARB_separate_shader_objects)) {
4810         if (identifier == "gl_Position"     ||
4811             identifier == "gl_PointSize"    ||
4812             identifier == "gl_ClipVertex"   ||
4813             identifier == "gl_FogFragCoord")
4814             ssoPre150 = true;
4815     }
4816 
4817     // Potentially redeclaring a built-in variable...
4818 
4819     if (ssoPre150 ||
4820         (identifier == "gl_FragDepth"           && ((nonEsRedecls && version >= 420) || esRedecls)) ||
4821         (identifier == "gl_FragCoord"           && ((nonEsRedecls && version >= 140) || esRedecls)) ||
4822          identifier == "gl_ClipDistance"                                                            ||
4823          identifier == "gl_CullDistance"                                                            ||
4824          identifier == "gl_ShadingRateEXT"                                                          ||
4825          identifier == "gl_PrimitiveShadingRateEXT"                                                 ||
4826          identifier == "gl_FrontColor"                                                              ||
4827          identifier == "gl_BackColor"                                                               ||
4828          identifier == "gl_FrontSecondaryColor"                                                     ||
4829          identifier == "gl_BackSecondaryColor"                                                      ||
4830          identifier == "gl_SecondaryColor"                                                          ||
4831         (identifier == "gl_Color"               && language == EShLangFragment)                     ||
4832         (identifier == "gl_FragStencilRefARB"   && (nonEsRedecls && version >= 140)
4833                                                 && language == EShLangFragment)                     ||
4834          identifier == "gl_SampleMask"                                                              ||
4835          identifier == "gl_Layer"                                                                   ||
4836          identifier == "gl_PrimitiveIndicesNV"                                                      ||
4837          identifier == "gl_PrimitivePointIndicesEXT"                                                ||
4838          identifier == "gl_PrimitiveLineIndicesEXT"                                                 ||
4839          identifier == "gl_PrimitiveTriangleIndicesEXT"                                             ||
4840          identifier == "gl_TexCoord") {
4841 
4842         // Find the existing symbol, if any.
4843         bool builtIn;
4844         TSymbol* symbol = symbolTable.find(identifier, &builtIn);
4845 
4846         // If the symbol was not found, this must be a version/profile/stage
4847         // that doesn't have it.
4848         if (! symbol)
4849             return nullptr;
4850 
4851         // If it wasn't at a built-in level, then it's already been redeclared;
4852         // that is, this is a redeclaration of a redeclaration; reuse that initial
4853         // redeclaration.  Otherwise, make the new one.
4854         if (builtIn) {
4855             makeEditable(symbol);
4856             symbolTable.amendSymbolIdLevel(*symbol);
4857         }
4858 
4859         // Now, modify the type of the copy, as per the type of the current redeclaration.
4860 
4861         TQualifier& symbolQualifier = symbol->getWritableType().getQualifier();
4862         if (ssoPre150) {
4863             if (intermediate.inIoAccessed(identifier))
4864                 error(loc, "cannot redeclare after use", identifier.c_str(), "");
4865             if (qualifier.hasLayout())
4866                 error(loc, "cannot apply layout qualifier to", "redeclaration", symbol->getName().c_str());
4867             if (qualifier.isMemory() || qualifier.isAuxiliary() || (language == EShLangVertex   && qualifier.storage != EvqVaryingOut) ||
4868                                                                    (language == EShLangFragment && qualifier.storage != EvqVaryingIn))
4869                 error(loc, "cannot change storage, memory, or auxiliary qualification of", "redeclaration", symbol->getName().c_str());
4870             if (! qualifier.smooth)
4871                 error(loc, "cannot change interpolation qualification of", "redeclaration", symbol->getName().c_str());
4872         } else if (identifier == "gl_FrontColor"          ||
4873                    identifier == "gl_BackColor"           ||
4874                    identifier == "gl_FrontSecondaryColor" ||
4875                    identifier == "gl_BackSecondaryColor"  ||
4876                    identifier == "gl_SecondaryColor"      ||
4877                    identifier == "gl_Color") {
4878             symbolQualifier.flat = qualifier.flat;
4879             symbolQualifier.smooth = qualifier.smooth;
4880             symbolQualifier.nopersp = qualifier.nopersp;
4881             if (qualifier.hasLayout())
4882                 error(loc, "cannot apply layout qualifier to", "redeclaration", symbol->getName().c_str());
4883             if (qualifier.isMemory() || qualifier.isAuxiliary() || symbol->getType().getQualifier().storage != qualifier.storage)
4884                 error(loc, "cannot change storage, memory, or auxiliary qualification of", "redeclaration", symbol->getName().c_str());
4885         } else if (identifier == "gl_TexCoord"     ||
4886                    identifier == "gl_ClipDistance" ||
4887                    identifier == "gl_CullDistance") {
4888             if (qualifier.hasLayout() || qualifier.isMemory() || qualifier.isAuxiliary() ||
4889                 qualifier.nopersp != symbolQualifier.nopersp || qualifier.flat != symbolQualifier.flat ||
4890                 symbolQualifier.storage != qualifier.storage)
4891                 error(loc, "cannot change qualification of", "redeclaration", symbol->getName().c_str());
4892         } else if (identifier == "gl_FragCoord") {
4893             if (!intermediate.getTexCoordRedeclared() && intermediate.inIoAccessed("gl_FragCoord"))
4894                 error(loc, "cannot redeclare after use", "gl_FragCoord", "");
4895             if (qualifier.nopersp != symbolQualifier.nopersp || qualifier.flat != symbolQualifier.flat ||
4896                 qualifier.isMemory() || qualifier.isAuxiliary())
4897                 error(loc, "can only change layout qualification of", "redeclaration", symbol->getName().c_str());
4898             if (qualifier.storage != EvqVaryingIn)
4899                 error(loc, "cannot change input storage qualification of", "redeclaration", symbol->getName().c_str());
4900             if (! builtIn && (publicType.pixelCenterInteger != intermediate.getPixelCenterInteger() ||
4901                               publicType.originUpperLeft != intermediate.getOriginUpperLeft()))
4902                 error(loc, "cannot redeclare with different qualification:", "redeclaration", symbol->getName().c_str());
4903 
4904 
4905             intermediate.setTexCoordRedeclared();
4906             if (publicType.pixelCenterInteger)
4907                 intermediate.setPixelCenterInteger();
4908             if (publicType.originUpperLeft)
4909                 intermediate.setOriginUpperLeft();
4910         } else if (identifier == "gl_FragDepth") {
4911             if (qualifier.nopersp != symbolQualifier.nopersp || qualifier.flat != symbolQualifier.flat ||
4912                 qualifier.isMemory() || qualifier.isAuxiliary())
4913                 error(loc, "can only change layout qualification of", "redeclaration", symbol->getName().c_str());
4914             if (qualifier.storage != EvqVaryingOut)
4915                 error(loc, "cannot change output storage qualification of", "redeclaration", symbol->getName().c_str());
4916             if (publicType.layoutDepth != EldNone) {
4917                 if (intermediate.inIoAccessed("gl_FragDepth"))
4918                     error(loc, "cannot redeclare after use", "gl_FragDepth", "");
4919                 if (! intermediate.setDepth(publicType.layoutDepth))
4920                     error(loc, "all redeclarations must use the same depth layout on", "redeclaration", symbol->getName().c_str());
4921             }
4922         } else if (identifier == "gl_FragStencilRefARB") {
4923             if (qualifier.nopersp != symbolQualifier.nopersp || qualifier.flat != symbolQualifier.flat ||
4924                 qualifier.isMemory() || qualifier.isAuxiliary())
4925                 error(loc, "can only change layout qualification of", "redeclaration", symbol->getName().c_str());
4926             if (qualifier.storage != EvqVaryingOut)
4927                 error(loc, "cannot change output storage qualification of", "redeclaration", symbol->getName().c_str());
4928             if (publicType.layoutStencil != ElsNone) {
4929                 if (intermediate.inIoAccessed("gl_FragStencilRefARB"))
4930                     error(loc, "cannot redeclare after use", "gl_FragStencilRefARB", "");
4931                 if (!intermediate.setStencil(publicType.layoutStencil))
4932                     error(loc, "all redeclarations must use the same stencil layout on", "redeclaration",
4933                           symbol->getName().c_str());
4934             }
4935         }
4936         else if (
4937             identifier == "gl_PrimitiveIndicesNV") {
4938             if (qualifier.hasLayout())
4939                 error(loc, "cannot apply layout qualifier to", "redeclaration", symbol->getName().c_str());
4940             if (qualifier.storage != EvqVaryingOut)
4941                 error(loc, "cannot change output storage qualification of", "redeclaration", symbol->getName().c_str());
4942         }
4943         else if (identifier == "gl_SampleMask") {
4944             if (!publicType.layoutOverrideCoverage) {
4945                 error(loc, "redeclaration only allowed for override_coverage layout", "redeclaration", symbol->getName().c_str());
4946             }
4947             intermediate.setLayoutOverrideCoverage();
4948         }
4949         else if (identifier == "gl_Layer") {
4950             if (!qualifier.layoutViewportRelative && qualifier.layoutSecondaryViewportRelativeOffset == -2048)
4951                 error(loc, "redeclaration only allowed for viewport_relative or secondary_view_offset layout", "redeclaration", symbol->getName().c_str());
4952             symbolQualifier.layoutViewportRelative = qualifier.layoutViewportRelative;
4953             symbolQualifier.layoutSecondaryViewportRelativeOffset = qualifier.layoutSecondaryViewportRelativeOffset;
4954         }
4955 
4956         // TODO: semantics quality: separate smooth from nothing declared, then use IsInterpolation for several tests above
4957 
4958         return symbol;
4959     }
4960 
4961     return nullptr;
4962 }
4963 
4964 //
4965 // Either redeclare the requested block, or give an error message why it can't be done.
4966 //
4967 // TODO: functionality: explicitly sizing members of redeclared blocks is not giving them an explicit size
redeclareBuiltinBlock(const TSourceLoc & loc,TTypeList & newTypeList,const TString & blockName,const TString * instanceName,TArraySizes * arraySizes)4968 void TParseContext::redeclareBuiltinBlock(const TSourceLoc& loc, TTypeList& newTypeList, const TString& blockName,
4969     const TString* instanceName, TArraySizes* arraySizes)
4970 {
4971     const char* feature = "built-in block redeclaration";
4972     profileRequires(loc, EEsProfile, 320, Num_AEP_shader_io_blocks, AEP_shader_io_blocks, feature);
4973     profileRequires(loc, ~EEsProfile, 410, E_GL_ARB_separate_shader_objects, feature);
4974 
4975     if (blockName != "gl_PerVertex" && blockName != "gl_PerFragment" &&
4976         blockName != "gl_MeshPerVertexNV" && blockName != "gl_MeshPerPrimitiveNV" &&
4977         blockName != "gl_MeshPerVertexEXT" && blockName != "gl_MeshPerPrimitiveEXT") {
4978         error(loc, "cannot redeclare block: ", "block declaration", blockName.c_str());
4979         return;
4980     }
4981 
4982     // Redeclaring a built-in block...
4983 
4984     if (instanceName && ! builtInName(*instanceName)) {
4985         error(loc, "cannot redeclare a built-in block with a user name", instanceName->c_str(), "");
4986         return;
4987     }
4988 
4989     // Blocks with instance names are easy to find, lookup the instance name,
4990     // Anonymous blocks need to be found via a member.
4991     bool builtIn;
4992     TSymbol* block;
4993     if (instanceName)
4994         block = symbolTable.find(*instanceName, &builtIn);
4995     else
4996         block = symbolTable.find(newTypeList.front().type->getFieldName(), &builtIn);
4997 
4998     // If the block was not found, this must be a version/profile/stage
4999     // that doesn't have it, or the instance name is wrong.
5000     const char* errorName = instanceName ? instanceName->c_str() : newTypeList.front().type->getFieldName().c_str();
5001     if (! block) {
5002         error(loc, "no declaration found for redeclaration", errorName, "");
5003         return;
5004     }
5005     // Built-in blocks cannot be redeclared more than once, which if happened,
5006     // we'd be finding the already redeclared one here, rather than the built in.
5007     if (! builtIn) {
5008         error(loc, "can only redeclare a built-in block once, and before any use", blockName.c_str(), "");
5009         return;
5010     }
5011 
5012     // Copy the block to make a writable version, to insert into the block table after editing.
5013     block = symbolTable.copyUpDeferredInsert(block);
5014 
5015     if (block->getType().getBasicType() != EbtBlock) {
5016         error(loc, "cannot redeclare a non block as a block", errorName, "");
5017         return;
5018     }
5019 
5020     // Fix XFB stuff up, it applies to the order of the redeclaration, not
5021     // the order of the original members.
5022     if (currentBlockQualifier.storage == EvqVaryingOut && globalOutputDefaults.hasXfbBuffer()) {
5023         if (!currentBlockQualifier.hasXfbBuffer())
5024             currentBlockQualifier.layoutXfbBuffer = globalOutputDefaults.layoutXfbBuffer;
5025         if (!currentBlockQualifier.hasStream())
5026             currentBlockQualifier.layoutStream = globalOutputDefaults.layoutStream;
5027         fixXfbOffsets(currentBlockQualifier, newTypeList);
5028     }
5029 
5030     // Edit and error check the container against the redeclaration
5031     //  - remove unused members
5032     //  - ensure remaining qualifiers/types match
5033 
5034     TType& type = block->getWritableType();
5035 
5036     // if gl_PerVertex is redeclared for the purpose of passing through "gl_Position"
5037     // for passthrough purpose, the redeclared block should have the same qualifers as
5038     // the current one
5039     if (currentBlockQualifier.layoutPassthrough) {
5040         type.getQualifier().layoutPassthrough = currentBlockQualifier.layoutPassthrough;
5041         type.getQualifier().storage = currentBlockQualifier.storage;
5042         type.getQualifier().layoutStream = currentBlockQualifier.layoutStream;
5043         type.getQualifier().layoutXfbBuffer = currentBlockQualifier.layoutXfbBuffer;
5044     }
5045 
5046     TTypeList::iterator member = type.getWritableStruct()->begin();
5047     size_t numOriginalMembersFound = 0;
5048     while (member != type.getStruct()->end()) {
5049         // look for match
5050         bool found = false;
5051         TTypeList::const_iterator newMember;
5052         TSourceLoc memberLoc;
5053         memberLoc.init();
5054         for (newMember = newTypeList.begin(); newMember != newTypeList.end(); ++newMember) {
5055             if (member->type->getFieldName() == newMember->type->getFieldName()) {
5056                 found = true;
5057                 memberLoc = newMember->loc;
5058                 break;
5059             }
5060         }
5061 
5062         if (found) {
5063             ++numOriginalMembersFound;
5064             // - ensure match between redeclared members' types
5065             // - check for things that can't be changed
5066             // - update things that can be changed
5067             TType& oldType = *member->type;
5068             const TType& newType = *newMember->type;
5069             if (! newType.sameElementType(oldType))
5070                 error(memberLoc, "cannot redeclare block member with a different type", member->type->getFieldName().c_str(), "");
5071             if (oldType.isArray() != newType.isArray())
5072                 error(memberLoc, "cannot change arrayness of redeclared block member", member->type->getFieldName().c_str(), "");
5073             else if (! oldType.getQualifier().isPerView() && ! oldType.sameArrayness(newType) && oldType.isSizedArray())
5074                 error(memberLoc, "cannot change array size of redeclared block member", member->type->getFieldName().c_str(), "");
5075             else if (! oldType.getQualifier().isPerView() && newType.isArray())
5076                 arrayLimitCheck(loc, member->type->getFieldName(), newType.getOuterArraySize());
5077             if (oldType.getQualifier().isPerView() && ! newType.getQualifier().isPerView())
5078                 error(memberLoc, "missing perviewNV qualifier to redeclared block member", member->type->getFieldName().c_str(), "");
5079             else if (! oldType.getQualifier().isPerView() && newType.getQualifier().isPerView())
5080                 error(memberLoc, "cannot add perviewNV qualifier to redeclared block member", member->type->getFieldName().c_str(), "");
5081             else if (newType.getQualifier().isPerView()) {
5082                 if (oldType.getArraySizes()->getNumDims() != newType.getArraySizes()->getNumDims())
5083                     error(memberLoc, "cannot change arrayness of redeclared block member", member->type->getFieldName().c_str(), "");
5084                 else if (! newType.isUnsizedArray() && newType.getOuterArraySize() != resources.maxMeshViewCountNV)
5085                     error(loc, "mesh view output array size must be gl_MaxMeshViewCountNV or implicitly sized", "[]", "");
5086                 else if (newType.getArraySizes()->getNumDims() == 2) {
5087                     int innerDimSize = newType.getArraySizes()->getDimSize(1);
5088                     arrayLimitCheck(memberLoc, member->type->getFieldName(), innerDimSize);
5089                     oldType.getArraySizes()->setDimSize(1, innerDimSize);
5090                 }
5091             }
5092             if (oldType.getQualifier().isPerPrimitive() && ! newType.getQualifier().isPerPrimitive())
5093                 error(memberLoc, "missing perprimitiveNV qualifier to redeclared block member", member->type->getFieldName().c_str(), "");
5094             else if (! oldType.getQualifier().isPerPrimitive() && newType.getQualifier().isPerPrimitive())
5095                 error(memberLoc, "cannot add perprimitiveNV qualifier to redeclared block member", member->type->getFieldName().c_str(), "");
5096             if (newType.getQualifier().isMemory())
5097                 error(memberLoc, "cannot add memory qualifier to redeclared block member", member->type->getFieldName().c_str(), "");
5098             if (newType.getQualifier().hasNonXfbLayout())
5099                 error(memberLoc, "cannot add non-XFB layout to redeclared block member", member->type->getFieldName().c_str(), "");
5100             if (newType.getQualifier().patch)
5101                 error(memberLoc, "cannot add patch to redeclared block member", member->type->getFieldName().c_str(), "");
5102             if (newType.getQualifier().hasXfbBuffer() &&
5103                 newType.getQualifier().layoutXfbBuffer != currentBlockQualifier.layoutXfbBuffer)
5104                 error(memberLoc, "member cannot contradict block (or what block inherited from global)", "xfb_buffer", "");
5105             if (newType.getQualifier().hasStream() &&
5106                 newType.getQualifier().layoutStream != currentBlockQualifier.layoutStream)
5107                 error(memberLoc, "member cannot contradict block (or what block inherited from global)", "xfb_stream", "");
5108             oldType.getQualifier().centroid = newType.getQualifier().centroid;
5109             oldType.getQualifier().sample = newType.getQualifier().sample;
5110             oldType.getQualifier().invariant = newType.getQualifier().invariant;
5111             oldType.getQualifier().noContraction = newType.getQualifier().noContraction;
5112             oldType.getQualifier().smooth = newType.getQualifier().smooth;
5113             oldType.getQualifier().flat = newType.getQualifier().flat;
5114             oldType.getQualifier().nopersp = newType.getQualifier().nopersp;
5115             oldType.getQualifier().layoutXfbOffset = newType.getQualifier().layoutXfbOffset;
5116             oldType.getQualifier().layoutXfbBuffer = newType.getQualifier().layoutXfbBuffer;
5117             oldType.getQualifier().layoutXfbStride = newType.getQualifier().layoutXfbStride;
5118             if (oldType.getQualifier().layoutXfbOffset != TQualifier::layoutXfbBufferEnd) {
5119                 // If any member has an xfb_offset, then the block's xfb_buffer inherents current xfb_buffer,
5120                 // and for xfb processing, the member needs it as well, along with xfb_stride.
5121                 type.getQualifier().layoutXfbBuffer = currentBlockQualifier.layoutXfbBuffer;
5122                 oldType.getQualifier().layoutXfbBuffer = currentBlockQualifier.layoutXfbBuffer;
5123             }
5124             if (oldType.isUnsizedArray() && newType.isSizedArray())
5125                 oldType.changeOuterArraySize(newType.getOuterArraySize());
5126 
5127             //  check and process the member's type, which will include managing xfb information
5128             layoutTypeCheck(loc, oldType);
5129 
5130             // go to next member
5131             ++member;
5132         } else {
5133             // For missing members of anonymous blocks that have been redeclared,
5134             // hide the original (shared) declaration.
5135             // Instance-named blocks can just have the member removed.
5136             if (instanceName)
5137                 member = type.getWritableStruct()->erase(member);
5138             else {
5139                 member->type->hideMember();
5140                 ++member;
5141             }
5142         }
5143     }
5144 
5145     if (spvVersion.vulkan > 0) {
5146         // ...then streams apply to built-in blocks, instead of them being only on stream 0
5147         type.getQualifier().layoutStream = currentBlockQualifier.layoutStream;
5148     }
5149 
5150     if (numOriginalMembersFound < newTypeList.size())
5151         error(loc, "block redeclaration has extra members", blockName.c_str(), "");
5152     if (type.isArray() != (arraySizes != nullptr) ||
5153         (type.isArray() && arraySizes != nullptr && type.getArraySizes()->getNumDims() != arraySizes->getNumDims()))
5154         error(loc, "cannot change arrayness of redeclared block", blockName.c_str(), "");
5155     else if (type.isArray()) {
5156         // At this point, we know both are arrays and both have the same number of dimensions.
5157 
5158         // It is okay for a built-in block redeclaration to be unsized, and keep the size of the
5159         // original block declaration.
5160         if (!arraySizes->isSized() && type.isSizedArray())
5161             arraySizes->changeOuterSize(type.getOuterArraySize());
5162 
5163         // And, okay to be giving a size to the array, by the redeclaration
5164         if (!type.isSizedArray() && arraySizes->isSized())
5165             type.changeOuterArraySize(arraySizes->getOuterSize());
5166 
5167         // Now, they must match in all dimensions.
5168         if (type.isSizedArray() && *type.getArraySizes() != *arraySizes)
5169             error(loc, "cannot change array size of redeclared block", blockName.c_str(), "");
5170     }
5171 
5172     symbolTable.insert(*block);
5173 
5174     // Check for general layout qualifier errors
5175     layoutObjectCheck(loc, *block);
5176 
5177     // Tracking for implicit sizing of array
5178     if (isIoResizeArray(block->getType())) {
5179         ioArraySymbolResizeList.push_back(block);
5180         checkIoArraysConsistency(loc, true);
5181     } else if (block->getType().isArray())
5182         fixIoArraySize(loc, block->getWritableType());
5183 
5184     // Save it in the AST for linker use.
5185     trackLinkage(*block);
5186 }
5187 
paramCheckFixStorage(const TSourceLoc & loc,const TStorageQualifier & qualifier,TType & type)5188 void TParseContext::paramCheckFixStorage(const TSourceLoc& loc, const TStorageQualifier& qualifier, TType& type)
5189 {
5190     switch (qualifier) {
5191     case EvqConst:
5192     case EvqConstReadOnly:
5193         type.getQualifier().storage = EvqConstReadOnly;
5194         break;
5195     case EvqIn:
5196     case EvqOut:
5197     case EvqInOut:
5198     case EvqTileImageEXT:
5199         type.getQualifier().storage = qualifier;
5200         break;
5201     case EvqGlobal:
5202     case EvqTemporary:
5203         type.getQualifier().storage = EvqIn;
5204         break;
5205     default:
5206         type.getQualifier().storage = EvqIn;
5207         error(loc, "storage qualifier not allowed on function parameter", GetStorageQualifierString(qualifier), "");
5208         break;
5209     }
5210 }
5211 
paramCheckFix(const TSourceLoc & loc,const TQualifier & qualifier,TType & type)5212 void TParseContext::paramCheckFix(const TSourceLoc& loc, const TQualifier& qualifier, TType& type)
5213 {
5214     if (qualifier.isMemory()) {
5215         type.getQualifier().volatil   = qualifier.volatil;
5216         type.getQualifier().coherent  = qualifier.coherent;
5217         type.getQualifier().devicecoherent  = qualifier.devicecoherent ;
5218         type.getQualifier().queuefamilycoherent  = qualifier.queuefamilycoherent;
5219         type.getQualifier().workgroupcoherent  = qualifier.workgroupcoherent;
5220         type.getQualifier().subgroupcoherent  = qualifier.subgroupcoherent;
5221         type.getQualifier().shadercallcoherent = qualifier.shadercallcoherent;
5222         type.getQualifier().nonprivate = qualifier.nonprivate;
5223         type.getQualifier().readonly  = qualifier.readonly;
5224         type.getQualifier().writeonly = qualifier.writeonly;
5225         type.getQualifier().restrict  = qualifier.restrict;
5226     }
5227 
5228     if (qualifier.isAuxiliary() ||
5229         qualifier.isInterpolation())
5230         error(loc, "cannot use auxiliary or interpolation qualifiers on a function parameter", "", "");
5231     if (qualifier.hasLayout())
5232         error(loc, "cannot use layout qualifiers on a function parameter", "", "");
5233     if (qualifier.invariant)
5234         error(loc, "cannot use invariant qualifier on a function parameter", "", "");
5235     if (qualifier.isNoContraction()) {
5236         if (qualifier.isParamOutput())
5237             type.getQualifier().setNoContraction();
5238         else
5239             warn(loc, "qualifier has no effect on non-output parameters", "precise", "");
5240     }
5241     if (qualifier.isNonUniform())
5242         type.getQualifier().nonUniform = qualifier.nonUniform;
5243     if (qualifier.isSpirvByReference())
5244         type.getQualifier().setSpirvByReference();
5245     if (qualifier.isSpirvLiteral()) {
5246         if (type.getBasicType() == EbtFloat || type.getBasicType() == EbtInt || type.getBasicType() == EbtUint ||
5247             type.getBasicType() == EbtBool)
5248             type.getQualifier().setSpirvLiteral();
5249         else
5250             error(loc, "cannot use spirv_literal qualifier", type.getBasicTypeString().c_str(), "");
5251     }
5252 
5253     paramCheckFixStorage(loc, qualifier.storage, type);
5254 }
5255 
nestedBlockCheck(const TSourceLoc & loc)5256 void TParseContext::nestedBlockCheck(const TSourceLoc& loc)
5257 {
5258     if (structNestingLevel > 0 || blockNestingLevel > 0)
5259         error(loc, "cannot nest a block definition inside a structure or block", "", "");
5260     ++blockNestingLevel;
5261 }
5262 
nestedStructCheck(const TSourceLoc & loc)5263 void TParseContext::nestedStructCheck(const TSourceLoc& loc)
5264 {
5265     if (structNestingLevel > 0 || blockNestingLevel > 0)
5266         error(loc, "cannot nest a structure definition inside a structure or block", "", "");
5267     ++structNestingLevel;
5268 }
5269 
arrayObjectCheck(const TSourceLoc & loc,const TType & type,const char * op)5270 void TParseContext::arrayObjectCheck(const TSourceLoc& loc, const TType& type, const char* op)
5271 {
5272     // Some versions don't allow comparing arrays or structures containing arrays
5273     if (type.containsArray()) {
5274         profileRequires(loc, ENoProfile, 120, E_GL_3DL_array_objects, op);
5275         profileRequires(loc, EEsProfile, 300, nullptr, op);
5276     }
5277 }
5278 
opaqueCheck(const TSourceLoc & loc,const TType & type,const char * op)5279 void TParseContext::opaqueCheck(const TSourceLoc& loc, const TType& type, const char* op)
5280 {
5281     if (containsFieldWithBasicType(type, EbtSampler) && !extensionTurnedOn(E_GL_ARB_bindless_texture))
5282         error(loc, "can't use with samplers or structs containing samplers", op, "");
5283 }
5284 
referenceCheck(const TSourceLoc & loc,const TType & type,const char * op)5285 void TParseContext::referenceCheck(const TSourceLoc& loc, const TType& type, const char* op)
5286 {
5287     if (containsFieldWithBasicType(type, EbtReference))
5288         error(loc, "can't use with reference types", op, "");
5289 }
5290 
storage16BitAssignmentCheck(const TSourceLoc & loc,const TType & type,const char * op)5291 void TParseContext::storage16BitAssignmentCheck(const TSourceLoc& loc, const TType& type, const char* op)
5292 {
5293     if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtFloat16))
5294         requireFloat16Arithmetic(loc, op, "can't use with structs containing float16");
5295 
5296     if (type.isArray() && type.getBasicType() == EbtFloat16)
5297         requireFloat16Arithmetic(loc, op, "can't use with arrays containing float16");
5298 
5299     if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtInt16))
5300         requireInt16Arithmetic(loc, op, "can't use with structs containing int16");
5301 
5302     if (type.isArray() && type.getBasicType() == EbtInt16)
5303         requireInt16Arithmetic(loc, op, "can't use with arrays containing int16");
5304 
5305     if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtUint16))
5306         requireInt16Arithmetic(loc, op, "can't use with structs containing uint16");
5307 
5308     if (type.isArray() && type.getBasicType() == EbtUint16)
5309         requireInt16Arithmetic(loc, op, "can't use with arrays containing uint16");
5310 
5311     if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtInt8))
5312         requireInt8Arithmetic(loc, op, "can't use with structs containing int8");
5313 
5314     if (type.isArray() && type.getBasicType() == EbtInt8)
5315         requireInt8Arithmetic(loc, op, "can't use with arrays containing int8");
5316 
5317     if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtUint8))
5318         requireInt8Arithmetic(loc, op, "can't use with structs containing uint8");
5319 
5320     if (type.isArray() && type.getBasicType() == EbtUint8)
5321         requireInt8Arithmetic(loc, op, "can't use with arrays containing uint8");
5322 }
5323 
specializationCheck(const TSourceLoc & loc,const TType & type,const char * op)5324 void TParseContext::specializationCheck(const TSourceLoc& loc, const TType& type, const char* op)
5325 {
5326     if (type.containsSpecializationSize())
5327         error(loc, "can't use with types containing arrays sized with a specialization constant", op, "");
5328 }
5329 
structTypeCheck(const TSourceLoc &,TPublicType & publicType)5330 void TParseContext::structTypeCheck(const TSourceLoc& /*loc*/, TPublicType& publicType)
5331 {
5332     const TTypeList& typeList = *publicType.userDef->getStruct();
5333 
5334     // fix and check for member storage qualifiers and types that don't belong within a structure
5335     for (unsigned int member = 0; member < typeList.size(); ++member) {
5336         TQualifier& memberQualifier = typeList[member].type->getQualifier();
5337         const TSourceLoc& memberLoc = typeList[member].loc;
5338         if (memberQualifier.isAuxiliary() ||
5339             memberQualifier.isInterpolation() ||
5340             (memberQualifier.storage != EvqTemporary && memberQualifier.storage != EvqGlobal))
5341             error(memberLoc, "cannot use storage or interpolation qualifiers on structure members", typeList[member].type->getFieldName().c_str(), "");
5342         if (memberQualifier.isMemory())
5343             error(memberLoc, "cannot use memory qualifiers on structure members", typeList[member].type->getFieldName().c_str(), "");
5344         if (memberQualifier.hasLayout()) {
5345             error(memberLoc, "cannot use layout qualifiers on structure members", typeList[member].type->getFieldName().c_str(), "");
5346             memberQualifier.clearLayout();
5347         }
5348         if (memberQualifier.invariant)
5349             error(memberLoc, "cannot use invariant qualifier on structure members", typeList[member].type->getFieldName().c_str(), "");
5350     }
5351 }
5352 
5353 //
5354 // See if this loop satisfies the limitations for ES 2.0 (version 100) for loops in Appendex A:
5355 //
5356 // "The loop index has type int or float.
5357 //
5358 // "The for statement has the form:
5359 //     for ( init-declaration ; condition ; expression )
5360 //     init-declaration has the form: type-specifier identifier = constant-expression
5361 //     condition has the form:  loop-index relational_operator constant-expression
5362 //         where relational_operator is one of: > >= < <= == or !=
5363 //     expression [sic] has one of the following forms:
5364 //         loop-index++
5365 //         loop-index--
5366 //         loop-index += constant-expression
5367 //         loop-index -= constant-expression
5368 //
5369 // The body is handled in an AST traversal.
5370 //
inductiveLoopCheck(const TSourceLoc & loc,TIntermNode * init,TIntermLoop * loop)5371 void TParseContext::inductiveLoopCheck(const TSourceLoc& loc, TIntermNode* init, TIntermLoop* loop)
5372 {
5373     // loop index init must exist and be a declaration, which shows up in the AST as an aggregate of size 1 of the declaration
5374     bool badInit = false;
5375     if (! init || ! init->getAsAggregate() || init->getAsAggregate()->getSequence().size() != 1)
5376         badInit = true;
5377     TIntermBinary* binaryInit = nullptr;
5378     if (! badInit) {
5379         // get the declaration assignment
5380         binaryInit = init->getAsAggregate()->getSequence()[0]->getAsBinaryNode();
5381         if (! binaryInit)
5382             badInit = true;
5383     }
5384     if (badInit) {
5385         error(loc, "inductive-loop init-declaration requires the form \"type-specifier loop-index = constant-expression\"", "limitations", "");
5386         return;
5387     }
5388 
5389     // loop index must be type int or float
5390     if (! binaryInit->getType().isScalar() || (binaryInit->getBasicType() != EbtInt && binaryInit->getBasicType() != EbtFloat)) {
5391         error(loc, "inductive loop requires a scalar 'int' or 'float' loop index", "limitations", "");
5392         return;
5393     }
5394 
5395     // init is the form "loop-index = constant"
5396     if (binaryInit->getOp() != EOpAssign || ! binaryInit->getLeft()->getAsSymbolNode() || ! binaryInit->getRight()->getAsConstantUnion()) {
5397         error(loc, "inductive-loop init-declaration requires the form \"type-specifier loop-index = constant-expression\"", "limitations", "");
5398         return;
5399     }
5400 
5401     // get the unique id of the loop index
5402     long long loopIndex = binaryInit->getLeft()->getAsSymbolNode()->getId();
5403     inductiveLoopIds.insert(loopIndex);
5404 
5405     // condition's form must be "loop-index relational-operator constant-expression"
5406     bool badCond = ! loop->getTest();
5407     if (! badCond) {
5408         TIntermBinary* binaryCond = loop->getTest()->getAsBinaryNode();
5409         badCond = ! binaryCond;
5410         if (! badCond) {
5411             switch (binaryCond->getOp()) {
5412             case EOpGreaterThan:
5413             case EOpGreaterThanEqual:
5414             case EOpLessThan:
5415             case EOpLessThanEqual:
5416             case EOpEqual:
5417             case EOpNotEqual:
5418                 break;
5419             default:
5420                 badCond = true;
5421             }
5422         }
5423         if (binaryCond && (! binaryCond->getLeft()->getAsSymbolNode() ||
5424                            binaryCond->getLeft()->getAsSymbolNode()->getId() != loopIndex ||
5425                            ! binaryCond->getRight()->getAsConstantUnion()))
5426             badCond = true;
5427     }
5428     if (badCond) {
5429         error(loc, "inductive-loop condition requires the form \"loop-index <comparison-op> constant-expression\"", "limitations", "");
5430         return;
5431     }
5432 
5433     // loop-index++
5434     // loop-index--
5435     // loop-index += constant-expression
5436     // loop-index -= constant-expression
5437     bool badTerminal = ! loop->getTerminal();
5438     if (! badTerminal) {
5439         TIntermUnary* unaryTerminal = loop->getTerminal()->getAsUnaryNode();
5440         TIntermBinary* binaryTerminal = loop->getTerminal()->getAsBinaryNode();
5441         if (unaryTerminal || binaryTerminal) {
5442             switch(loop->getTerminal()->getAsOperator()->getOp()) {
5443             case EOpPostDecrement:
5444             case EOpPostIncrement:
5445             case EOpAddAssign:
5446             case EOpSubAssign:
5447                 break;
5448             default:
5449                 badTerminal = true;
5450             }
5451         } else
5452             badTerminal = true;
5453         if (binaryTerminal && (! binaryTerminal->getLeft()->getAsSymbolNode() ||
5454                                binaryTerminal->getLeft()->getAsSymbolNode()->getId() != loopIndex ||
5455                                ! binaryTerminal->getRight()->getAsConstantUnion()))
5456             badTerminal = true;
5457         if (unaryTerminal && (! unaryTerminal->getOperand()->getAsSymbolNode() ||
5458                               unaryTerminal->getOperand()->getAsSymbolNode()->getId() != loopIndex))
5459             badTerminal = true;
5460     }
5461     if (badTerminal) {
5462         error(loc, "inductive-loop termination requires the form \"loop-index++, loop-index--, loop-index += constant-expression, or loop-index -= constant-expression\"", "limitations", "");
5463         return;
5464     }
5465 
5466     // the body
5467     inductiveLoopBodyCheck(loop->getBody(), loopIndex, symbolTable);
5468 }
5469 
5470 // Do limit checks for built-in arrays.
arrayLimitCheck(const TSourceLoc & loc,const TString & identifier,int size)5471 void TParseContext::arrayLimitCheck(const TSourceLoc& loc, const TString& identifier, int size)
5472 {
5473     if (identifier.compare("gl_TexCoord") == 0)
5474         limitCheck(loc, size, "gl_MaxTextureCoords", "gl_TexCoord array size");
5475     else if (identifier.compare("gl_ClipDistance") == 0)
5476         limitCheck(loc, size, "gl_MaxClipDistances", "gl_ClipDistance array size");
5477     else if (identifier.compare("gl_CullDistance") == 0)
5478         limitCheck(loc, size, "gl_MaxCullDistances", "gl_CullDistance array size");
5479     else if (identifier.compare("gl_ClipDistancePerViewNV") == 0)
5480         limitCheck(loc, size, "gl_MaxClipDistances", "gl_ClipDistancePerViewNV array size");
5481     else if (identifier.compare("gl_CullDistancePerViewNV") == 0)
5482         limitCheck(loc, size, "gl_MaxCullDistances", "gl_CullDistancePerViewNV array size");
5483 }
5484 
5485 // See if the provided value is less than or equal to the symbol indicated by limit,
5486 // which should be a constant in the symbol table.
limitCheck(const TSourceLoc & loc,int value,const char * limit,const char * feature)5487 void TParseContext::limitCheck(const TSourceLoc& loc, int value, const char* limit, const char* feature)
5488 {
5489     TSymbol* symbol = symbolTable.find(limit);
5490     assert(symbol->getAsVariable());
5491     const TConstUnionArray& constArray = symbol->getAsVariable()->getConstArray();
5492     assert(! constArray.empty());
5493     if (value > constArray[0].getIConst())
5494         error(loc, "must be less than or equal to", feature, "%s (%d)", limit, constArray[0].getIConst());
5495 }
5496 
5497 //
5498 // Do any additional error checking, etc., once we know the parsing is done.
5499 //
finish()5500 void TParseContext::finish()
5501 {
5502     TParseContextBase::finish();
5503 
5504     if (parsingBuiltins)
5505         return;
5506 
5507     // Check on array indexes for ES 2.0 (version 100) limitations.
5508     for (size_t i = 0; i < needsIndexLimitationChecking.size(); ++i)
5509         constantIndexExpressionCheck(needsIndexLimitationChecking[i]);
5510 
5511     // Check for stages that are enabled by extension.
5512     // Can't do this at the beginning, it is chicken and egg to add a stage by
5513     // extension.
5514     // Stage-specific features were correctly tested for already, this is just
5515     // about the stage itself.
5516     switch (language) {
5517     case EShLangGeometry:
5518         if (isEsProfile() && version == 310)
5519             requireExtensions(getCurrentLoc(), Num_AEP_geometry_shader, AEP_geometry_shader, "geometry shaders");
5520         break;
5521     case EShLangTessControl:
5522     case EShLangTessEvaluation:
5523         if (isEsProfile() && version == 310)
5524             requireExtensions(getCurrentLoc(), Num_AEP_tessellation_shader, AEP_tessellation_shader, "tessellation shaders");
5525         else if (!isEsProfile() && version < 400)
5526             requireExtensions(getCurrentLoc(), 1, &E_GL_ARB_tessellation_shader, "tessellation shaders");
5527         break;
5528     case EShLangCompute:
5529         if (!isEsProfile() && version < 430)
5530             requireExtensions(getCurrentLoc(), 1, &E_GL_ARB_compute_shader, "compute shaders");
5531         break;
5532     case EShLangTask:
5533         requireExtensions(getCurrentLoc(), Num_AEP_mesh_shader, AEP_mesh_shader, "task shaders");
5534         break;
5535     case EShLangMesh:
5536         requireExtensions(getCurrentLoc(), Num_AEP_mesh_shader, AEP_mesh_shader, "mesh shaders");
5537         break;
5538     default:
5539         break;
5540     }
5541 
5542     // Set default outputs for GL_NV_geometry_shader_passthrough
5543     if (language == EShLangGeometry && extensionTurnedOn(E_SPV_NV_geometry_shader_passthrough)) {
5544         if (intermediate.getOutputPrimitive() == ElgNone) {
5545             switch (intermediate.getInputPrimitive()) {
5546             case ElgPoints:      intermediate.setOutputPrimitive(ElgPoints);    break;
5547             case ElgLines:       intermediate.setOutputPrimitive(ElgLineStrip); break;
5548             case ElgTriangles:   intermediate.setOutputPrimitive(ElgTriangleStrip); break;
5549             default: break;
5550             }
5551         }
5552         if (intermediate.getVertices() == TQualifier::layoutNotSet) {
5553             switch (intermediate.getInputPrimitive()) {
5554             case ElgPoints:      intermediate.setVertices(1); break;
5555             case ElgLines:       intermediate.setVertices(2); break;
5556             case ElgTriangles:   intermediate.setVertices(3); break;
5557             default: break;
5558             }
5559         }
5560     }
5561 }
5562 
5563 //
5564 // Layout qualifier stuff.
5565 //
5566 
5567 // Put the id's layout qualification into the public type, for qualifiers not having a number set.
5568 // This is before we know any type information for error checking.
setLayoutQualifier(const TSourceLoc & loc,TPublicType & publicType,TString & id)5569 void TParseContext::setLayoutQualifier(const TSourceLoc& loc, TPublicType& publicType, TString& id)
5570 {
5571     std::transform(id.begin(), id.end(), id.begin(), ::tolower);
5572 
5573     if (id == TQualifier::getLayoutMatrixString(ElmColumnMajor)) {
5574         publicType.qualifier.layoutMatrix = ElmColumnMajor;
5575         return;
5576     }
5577     if (id == TQualifier::getLayoutMatrixString(ElmRowMajor)) {
5578         publicType.qualifier.layoutMatrix = ElmRowMajor;
5579         return;
5580     }
5581     if (id == TQualifier::getLayoutPackingString(ElpPacked)) {
5582         if (spvVersion.spv != 0) {
5583             if (spvVersion.vulkanRelaxed)
5584                 return; // silently ignore qualifier
5585             else
5586                 spvRemoved(loc, "packed");
5587         }
5588         publicType.qualifier.layoutPacking = ElpPacked;
5589         return;
5590     }
5591     if (id == TQualifier::getLayoutPackingString(ElpShared)) {
5592         if (spvVersion.spv != 0) {
5593             if (spvVersion.vulkanRelaxed)
5594                 return; // silently ignore qualifier
5595             else
5596                 spvRemoved(loc, "shared");
5597         }
5598         publicType.qualifier.layoutPacking = ElpShared;
5599         return;
5600     }
5601     if (id == TQualifier::getLayoutPackingString(ElpStd140)) {
5602         publicType.qualifier.layoutPacking = ElpStd140;
5603         return;
5604     }
5605     if (id == TQualifier::getLayoutPackingString(ElpStd430)) {
5606         requireProfile(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, "std430");
5607         profileRequires(loc, ECoreProfile | ECompatibilityProfile, 430, E_GL_ARB_shader_storage_buffer_object, "std430");
5608         profileRequires(loc, EEsProfile, 310, nullptr, "std430");
5609         publicType.qualifier.layoutPacking = ElpStd430;
5610         return;
5611     }
5612     if (id == TQualifier::getLayoutPackingString(ElpScalar)) {
5613         requireVulkan(loc, "scalar");
5614         requireExtensions(loc, 1, &E_GL_EXT_scalar_block_layout, "scalar block layout");
5615         publicType.qualifier.layoutPacking = ElpScalar;
5616         return;
5617     }
5618     // TODO: compile-time performance: may need to stop doing linear searches
5619     for (TLayoutFormat format = (TLayoutFormat)(ElfNone + 1); format < ElfCount; format = (TLayoutFormat)(format + 1)) {
5620         if (id == TQualifier::getLayoutFormatString(format)) {
5621             if ((format > ElfEsFloatGuard && format < ElfFloatGuard) ||
5622                 (format > ElfEsIntGuard && format < ElfIntGuard) ||
5623                 (format > ElfEsUintGuard && format < ElfCount))
5624                 requireProfile(loc, ENoProfile | ECoreProfile | ECompatibilityProfile, "image load-store format");
5625             profileRequires(loc, ENoProfile | ECoreProfile | ECompatibilityProfile, 420, E_GL_ARB_shader_image_load_store, "image load store");
5626             profileRequires(loc, EEsProfile, 310, E_GL_ARB_shader_image_load_store, "image load store");
5627             publicType.qualifier.layoutFormat = format;
5628             return;
5629         }
5630     }
5631     if (id == "push_constant") {
5632         requireVulkan(loc, "push_constant");
5633         publicType.qualifier.layoutPushConstant = true;
5634         return;
5635     }
5636     if (id == "buffer_reference") {
5637         requireVulkan(loc, "buffer_reference");
5638         requireExtensions(loc, 1, &E_GL_EXT_buffer_reference, "buffer_reference");
5639         publicType.qualifier.layoutBufferReference = true;
5640         intermediate.setUseStorageBuffer();
5641         intermediate.setUsePhysicalStorageBuffer();
5642         return;
5643     }
5644     if (id == "bindless_sampler") {
5645         requireExtensions(loc, 1, &E_GL_ARB_bindless_texture, "bindless_sampler");
5646         publicType.qualifier.layoutBindlessSampler = true;
5647         intermediate.setBindlessTextureMode(currentCaller, AstRefTypeLayout);
5648         return;
5649     }
5650     if (id == "bindless_image") {
5651         requireExtensions(loc, 1, &E_GL_ARB_bindless_texture, "bindless_image");
5652         publicType.qualifier.layoutBindlessImage = true;
5653         intermediate.setBindlessImageMode(currentCaller, AstRefTypeLayout);
5654         return;
5655     }
5656     if (id == "bound_sampler") {
5657         requireExtensions(loc, 1, &E_GL_ARB_bindless_texture, "bound_sampler");
5658         publicType.qualifier.layoutBindlessSampler = false;
5659         return;
5660     }
5661     if (id == "bound_image") {
5662         requireExtensions(loc, 1, &E_GL_ARB_bindless_texture, "bound_image");
5663         publicType.qualifier.layoutBindlessImage = false;
5664         return;
5665     }
5666     if (language == EShLangGeometry || language == EShLangTessEvaluation || language == EShLangMesh) {
5667         if (id == TQualifier::getGeometryString(ElgTriangles)) {
5668             publicType.shaderQualifiers.geometry = ElgTriangles;
5669             return;
5670         }
5671         if (language == EShLangGeometry || language == EShLangMesh) {
5672             if (id == TQualifier::getGeometryString(ElgPoints)) {
5673                 publicType.shaderQualifiers.geometry = ElgPoints;
5674                 return;
5675             }
5676             if (id == TQualifier::getGeometryString(ElgLines)) {
5677                 publicType.shaderQualifiers.geometry = ElgLines;
5678                 return;
5679             }
5680             if (language == EShLangGeometry) {
5681                 if (id == TQualifier::getGeometryString(ElgLineStrip)) {
5682                     publicType.shaderQualifiers.geometry = ElgLineStrip;
5683                     return;
5684                 }
5685                 if (id == TQualifier::getGeometryString(ElgLinesAdjacency)) {
5686                     publicType.shaderQualifiers.geometry = ElgLinesAdjacency;
5687                     return;
5688                 }
5689                 if (id == TQualifier::getGeometryString(ElgTrianglesAdjacency)) {
5690                     publicType.shaderQualifiers.geometry = ElgTrianglesAdjacency;
5691                     return;
5692                 }
5693                 if (id == TQualifier::getGeometryString(ElgTriangleStrip)) {
5694                     publicType.shaderQualifiers.geometry = ElgTriangleStrip;
5695                     return;
5696                 }
5697                 if (id == "passthrough") {
5698                     requireExtensions(loc, 1, &E_SPV_NV_geometry_shader_passthrough, "geometry shader passthrough");
5699                     publicType.qualifier.layoutPassthrough = true;
5700                     intermediate.setGeoPassthroughEXT();
5701                     return;
5702                 }
5703             }
5704         } else {
5705             assert(language == EShLangTessEvaluation);
5706 
5707             // input primitive
5708             if (id == TQualifier::getGeometryString(ElgTriangles)) {
5709                 publicType.shaderQualifiers.geometry = ElgTriangles;
5710                 return;
5711             }
5712             if (id == TQualifier::getGeometryString(ElgQuads)) {
5713                 publicType.shaderQualifiers.geometry = ElgQuads;
5714                 return;
5715             }
5716             if (id == TQualifier::getGeometryString(ElgIsolines)) {
5717                 publicType.shaderQualifiers.geometry = ElgIsolines;
5718                 return;
5719             }
5720 
5721             // vertex spacing
5722             if (id == TQualifier::getVertexSpacingString(EvsEqual)) {
5723                 publicType.shaderQualifiers.spacing = EvsEqual;
5724                 return;
5725             }
5726             if (id == TQualifier::getVertexSpacingString(EvsFractionalEven)) {
5727                 publicType.shaderQualifiers.spacing = EvsFractionalEven;
5728                 return;
5729             }
5730             if (id == TQualifier::getVertexSpacingString(EvsFractionalOdd)) {
5731                 publicType.shaderQualifiers.spacing = EvsFractionalOdd;
5732                 return;
5733             }
5734 
5735             // triangle order
5736             if (id == TQualifier::getVertexOrderString(EvoCw)) {
5737                 publicType.shaderQualifiers.order = EvoCw;
5738                 return;
5739             }
5740             if (id == TQualifier::getVertexOrderString(EvoCcw)) {
5741                 publicType.shaderQualifiers.order = EvoCcw;
5742                 return;
5743             }
5744 
5745             // point mode
5746             if (id == "point_mode") {
5747                 publicType.shaderQualifiers.pointMode = true;
5748                 return;
5749             }
5750         }
5751     }
5752     if (language == EShLangFragment) {
5753         if (id == "origin_upper_left") {
5754             requireProfile(loc, ECoreProfile | ECompatibilityProfile | ENoProfile, "origin_upper_left");
5755             if (profile == ENoProfile) {
5756                 profileRequires(loc,ECoreProfile | ECompatibilityProfile, 140, E_GL_ARB_fragment_coord_conventions, "origin_upper_left");
5757             }
5758 
5759             publicType.shaderQualifiers.originUpperLeft = true;
5760             return;
5761         }
5762         if (id == "pixel_center_integer") {
5763             requireProfile(loc, ECoreProfile | ECompatibilityProfile | ENoProfile, "pixel_center_integer");
5764             if (profile == ENoProfile) {
5765                 profileRequires(loc,ECoreProfile | ECompatibilityProfile, 140, E_GL_ARB_fragment_coord_conventions, "pixel_center_integer");
5766             }
5767             publicType.shaderQualifiers.pixelCenterInteger = true;
5768             return;
5769         }
5770         if (id == "early_fragment_tests") {
5771             profileRequires(loc, ENoProfile | ECoreProfile | ECompatibilityProfile, 420, E_GL_ARB_shader_image_load_store, "early_fragment_tests");
5772             profileRequires(loc, EEsProfile, 310, nullptr, "early_fragment_tests");
5773             publicType.shaderQualifiers.earlyFragmentTests = true;
5774             return;
5775         }
5776         if (id == "early_and_late_fragment_tests_amd") {
5777             profileRequires(loc, ENoProfile | ECoreProfile | ECompatibilityProfile, 420, E_GL_AMD_shader_early_and_late_fragment_tests, "early_and_late_fragment_tests_amd");
5778             profileRequires(loc, EEsProfile, 310, nullptr, "early_and_late_fragment_tests_amd");
5779             publicType.shaderQualifiers.earlyAndLateFragmentTestsAMD = true;
5780             return;
5781         }
5782         if (id == "post_depth_coverage") {
5783             requireExtensions(loc, Num_post_depth_coverageEXTs, post_depth_coverageEXTs, "post depth coverage");
5784             if (extensionTurnedOn(E_GL_ARB_post_depth_coverage)) {
5785                 publicType.shaderQualifiers.earlyFragmentTests = true;
5786             }
5787             publicType.shaderQualifiers.postDepthCoverage = true;
5788             return;
5789         }
5790         /* id is transformed into lower case in the beginning of this function. */
5791         if (id == "non_coherent_color_attachment_readext") {
5792             requireExtensions(loc, 1, &E_GL_EXT_shader_tile_image, "non_coherent_color_attachment_readEXT");
5793             publicType.shaderQualifiers.nonCoherentColorAttachmentReadEXT = true;
5794             return;
5795         }
5796         if (id == "non_coherent_depth_attachment_readext") {
5797             requireExtensions(loc, 1, &E_GL_EXT_shader_tile_image, "non_coherent_depth_attachment_readEXT");
5798             publicType.shaderQualifiers.nonCoherentDepthAttachmentReadEXT = true;
5799             return;
5800         }
5801         if (id == "non_coherent_stencil_attachment_readext") {
5802             requireExtensions(loc, 1, &E_GL_EXT_shader_tile_image, "non_coherent_stencil_attachment_readEXT");
5803             publicType.shaderQualifiers.nonCoherentStencilAttachmentReadEXT = true;
5804             return;
5805         }
5806         for (TLayoutDepth depth = (TLayoutDepth)(EldNone + 1); depth < EldCount; depth = (TLayoutDepth)(depth+1)) {
5807             if (id == TQualifier::getLayoutDepthString(depth)) {
5808                 requireProfile(loc, ECoreProfile | ECompatibilityProfile, "depth layout qualifier");
5809                 profileRequires(loc, ECoreProfile | ECompatibilityProfile, 420, nullptr, "depth layout qualifier");
5810                 publicType.shaderQualifiers.layoutDepth = depth;
5811                 return;
5812             }
5813         }
5814         for (TLayoutStencil stencil = (TLayoutStencil)(ElsNone + 1); stencil < ElsCount; stencil = (TLayoutStencil)(stencil+1)) {
5815             if (id == TQualifier::getLayoutStencilString(stencil)) {
5816                 requireProfile(loc, ECoreProfile | ECompatibilityProfile, "stencil layout qualifier");
5817                 profileRequires(loc, ECoreProfile | ECompatibilityProfile, 420, nullptr, "stencil layout qualifier");
5818                 publicType.shaderQualifiers.layoutStencil = stencil;
5819                 return;
5820             }
5821         }
5822         for (TInterlockOrdering order = (TInterlockOrdering)(EioNone + 1); order < EioCount; order = (TInterlockOrdering)(order+1)) {
5823             if (id == TQualifier::getInterlockOrderingString(order)) {
5824                 requireProfile(loc, ECoreProfile | ECompatibilityProfile, "fragment shader interlock layout qualifier");
5825                 profileRequires(loc, ECoreProfile | ECompatibilityProfile, 450, nullptr, "fragment shader interlock layout qualifier");
5826                 requireExtensions(loc, 1, &E_GL_ARB_fragment_shader_interlock, TQualifier::getInterlockOrderingString(order));
5827                 if (order == EioShadingRateInterlockOrdered || order == EioShadingRateInterlockUnordered)
5828                     requireExtensions(loc, 1, &E_GL_NV_shading_rate_image, TQualifier::getInterlockOrderingString(order));
5829                 publicType.shaderQualifiers.interlockOrdering = order;
5830                 return;
5831             }
5832         }
5833         if (id.compare(0, 13, "blend_support") == 0) {
5834             bool found = false;
5835             for (TBlendEquationShift be = (TBlendEquationShift)0; be < EBlendCount; be = (TBlendEquationShift)(be + 1)) {
5836                 if (id == TQualifier::getBlendEquationString(be)) {
5837                     profileRequires(loc, EEsProfile, 320, E_GL_KHR_blend_equation_advanced, "blend equation");
5838                     profileRequires(loc, ~EEsProfile, 0, E_GL_KHR_blend_equation_advanced, "blend equation");
5839                     intermediate.addBlendEquation(be);
5840                     publicType.shaderQualifiers.blendEquation = true;
5841                     found = true;
5842                     break;
5843                 }
5844             }
5845             if (! found)
5846                 error(loc, "unknown blend equation", "blend_support", "");
5847             return;
5848         }
5849         if (id == "override_coverage") {
5850             requireExtensions(loc, 1, &E_GL_NV_sample_mask_override_coverage, "sample mask override coverage");
5851             publicType.shaderQualifiers.layoutOverrideCoverage = true;
5852             return;
5853         }
5854     }
5855     if (language == EShLangVertex ||
5856         language == EShLangTessControl ||
5857         language == EShLangTessEvaluation ||
5858         language == EShLangGeometry ) {
5859         if (id == "viewport_relative") {
5860             requireExtensions(loc, 1, &E_GL_NV_viewport_array2, "view port array2");
5861             publicType.qualifier.layoutViewportRelative = true;
5862             return;
5863         }
5864     } else {
5865         if (language == EShLangRayGen || language == EShLangIntersect ||
5866         language == EShLangAnyHit || language == EShLangClosestHit ||
5867         language == EShLangMiss || language == EShLangCallable) {
5868             if (id == "shaderrecordnv" || id == "shaderrecordext") {
5869                 if (id == "shaderrecordnv") {
5870                     requireExtensions(loc, 1, &E_GL_NV_ray_tracing, "shader record NV");
5871                 } else {
5872                     requireExtensions(loc, 1, &E_GL_EXT_ray_tracing, "shader record EXT");
5873                 }
5874                 publicType.qualifier.layoutShaderRecord = true;
5875                 return;
5876             } else if (id == "hitobjectshaderrecordnv") {
5877                 requireExtensions(loc, 1, &E_GL_NV_shader_invocation_reorder, "hitobject shader record NV");
5878                 publicType.qualifier.layoutHitObjectShaderRecordNV = true;
5879                 return;
5880             }
5881 
5882         }
5883     }
5884     if (language == EShLangCompute) {
5885         if (id.compare(0, 17, "derivative_group_") == 0) {
5886             requireExtensions(loc, 1, &E_GL_NV_compute_shader_derivatives, "compute shader derivatives");
5887             if (id == "derivative_group_quadsnv") {
5888                 publicType.shaderQualifiers.layoutDerivativeGroupQuads = true;
5889                 return;
5890             } else if (id == "derivative_group_linearnv") {
5891                 publicType.shaderQualifiers.layoutDerivativeGroupLinear = true;
5892                 return;
5893             }
5894         }
5895     }
5896 
5897     if (id == "primitive_culling") {
5898         requireExtensions(loc, 1, &E_GL_EXT_ray_flags_primitive_culling, "primitive culling");
5899         publicType.shaderQualifiers.layoutPrimitiveCulling = true;
5900         return;
5901     }
5902 
5903     error(loc, "unrecognized layout identifier, or qualifier requires assignment (e.g., binding = 4)", id.c_str(), "");
5904 }
5905 
5906 // Put the id's layout qualifier value into the public type, for qualifiers having a number set.
5907 // This is before we know any type information for error checking.
setLayoutQualifier(const TSourceLoc & loc,TPublicType & publicType,TString & id,const TIntermTyped * node)5908 void TParseContext::setLayoutQualifier(const TSourceLoc& loc, TPublicType& publicType, TString& id, const TIntermTyped* node)
5909 {
5910     const char* feature = "layout-id value";
5911     const char* nonLiteralFeature = "non-literal layout-id value";
5912 
5913     integerCheck(node, feature);
5914     const TIntermConstantUnion* constUnion = node->getAsConstantUnion();
5915     int value;
5916     bool nonLiteral = false;
5917     if (constUnion) {
5918         value = constUnion->getConstArray()[0].getIConst();
5919         if (! constUnion->isLiteral()) {
5920             requireProfile(loc, ECoreProfile | ECompatibilityProfile, nonLiteralFeature);
5921             profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, E_GL_ARB_enhanced_layouts, nonLiteralFeature);
5922         }
5923     } else {
5924         // grammar should have give out the error message
5925         value = 0;
5926         nonLiteral = true;
5927     }
5928 
5929     if (value < 0) {
5930         error(loc, "cannot be negative", feature, "");
5931         return;
5932     }
5933 
5934     std::transform(id.begin(), id.end(), id.begin(), ::tolower);
5935 
5936     if (id == "offset") {
5937         // "offset" can be for either
5938         //  - uniform offsets
5939         //  - atomic_uint offsets
5940         const char* feature = "offset";
5941         if (spvVersion.spv == 0) {
5942             requireProfile(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, feature);
5943             const char* exts[2] = { E_GL_ARB_enhanced_layouts, E_GL_ARB_shader_atomic_counters };
5944             profileRequires(loc, ECoreProfile | ECompatibilityProfile, 420, 2, exts, feature);
5945             profileRequires(loc, EEsProfile, 310, nullptr, feature);
5946         }
5947         publicType.qualifier.layoutOffset = value;
5948         publicType.qualifier.explicitOffset = true;
5949         if (nonLiteral)
5950             error(loc, "needs a literal integer", "offset", "");
5951         return;
5952     } else if (id == "align") {
5953         const char* feature = "uniform buffer-member align";
5954         if (spvVersion.spv == 0) {
5955             requireProfile(loc, ECoreProfile | ECompatibilityProfile, feature);
5956             profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, E_GL_ARB_enhanced_layouts, feature);
5957         }
5958         // "The specified alignment must be a power of 2, or a compile-time error results."
5959         if (! IsPow2(value))
5960             error(loc, "must be a power of 2", "align", "");
5961         else
5962             publicType.qualifier.layoutAlign = value;
5963         if (nonLiteral)
5964             error(loc, "needs a literal integer", "align", "");
5965         return;
5966     } else if (id == "location") {
5967         profileRequires(loc, EEsProfile, 300, nullptr, "location");
5968         const char* exts[2] = { E_GL_ARB_separate_shader_objects, E_GL_ARB_explicit_attrib_location };
5969         // GL_ARB_explicit_uniform_location requires 330 or GL_ARB_explicit_attrib_location we do not need to add it here
5970         profileRequires(loc, ~EEsProfile, 330, 2, exts, "location");
5971         if ((unsigned int)value >= TQualifier::layoutLocationEnd)
5972             error(loc, "location is too large", id.c_str(), "");
5973         else
5974             publicType.qualifier.layoutLocation = value;
5975         if (nonLiteral)
5976             error(loc, "needs a literal integer", "location", "");
5977         return;
5978     } else if (id == "set") {
5979         if ((unsigned int)value >= TQualifier::layoutSetEnd)
5980             error(loc, "set is too large", id.c_str(), "");
5981         else
5982             publicType.qualifier.layoutSet = value;
5983         if (value != 0)
5984             requireVulkan(loc, "descriptor set");
5985         if (nonLiteral)
5986             error(loc, "needs a literal integer", "set", "");
5987         return;
5988     } else if (id == "binding") {
5989         profileRequires(loc, ~EEsProfile, 420, E_GL_ARB_shading_language_420pack, "binding");
5990         profileRequires(loc, EEsProfile, 310, nullptr, "binding");
5991         if ((unsigned int)value >= TQualifier::layoutBindingEnd)
5992             error(loc, "binding is too large", id.c_str(), "");
5993         else
5994             publicType.qualifier.layoutBinding = value;
5995         if (nonLiteral)
5996             error(loc, "needs a literal integer", "binding", "");
5997         return;
5998     }
5999     if (id == "constant_id") {
6000         requireSpv(loc, "constant_id");
6001         if (value >= (int)TQualifier::layoutSpecConstantIdEnd) {
6002             error(loc, "specialization-constant id is too large", id.c_str(), "");
6003         } else {
6004             publicType.qualifier.layoutSpecConstantId = value;
6005             publicType.qualifier.specConstant = true;
6006             if (! intermediate.addUsedConstantId(value))
6007                 error(loc, "specialization-constant id already used", id.c_str(), "");
6008         }
6009         if (nonLiteral)
6010             error(loc, "needs a literal integer", "constant_id", "");
6011         return;
6012     }
6013     if (id == "component") {
6014         requireProfile(loc, ECoreProfile | ECompatibilityProfile, "component");
6015         profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, E_GL_ARB_enhanced_layouts, "component");
6016         if ((unsigned)value >= TQualifier::layoutComponentEnd)
6017             error(loc, "component is too large", id.c_str(), "");
6018         else
6019             publicType.qualifier.layoutComponent = value;
6020         if (nonLiteral)
6021             error(loc, "needs a literal integer", "component", "");
6022         return;
6023     }
6024     if (id.compare(0, 4, "xfb_") == 0) {
6025         // "Any shader making any static use (after preprocessing) of any of these
6026         // *xfb_* qualifiers will cause the shader to be in a transform feedback
6027         // capturing mode and hence responsible for describing the transform feedback
6028         // setup."
6029         intermediate.setXfbMode();
6030         const char* feature = "transform feedback qualifier";
6031         requireStage(loc, (EShLanguageMask)(EShLangVertexMask | EShLangGeometryMask | EShLangTessControlMask | EShLangTessEvaluationMask), feature);
6032         requireProfile(loc, ECoreProfile | ECompatibilityProfile, feature);
6033         profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, E_GL_ARB_enhanced_layouts, feature);
6034         if (id == "xfb_buffer") {
6035             // "It is a compile-time error to specify an *xfb_buffer* that is greater than
6036             // the implementation-dependent constant gl_MaxTransformFeedbackBuffers."
6037             if (value >= resources.maxTransformFeedbackBuffers)
6038                 error(loc, "buffer is too large:", id.c_str(), "gl_MaxTransformFeedbackBuffers is %d", resources.maxTransformFeedbackBuffers);
6039             if (value >= (int)TQualifier::layoutXfbBufferEnd)
6040                 error(loc, "buffer is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbBufferEnd-1);
6041             else
6042                 publicType.qualifier.layoutXfbBuffer = value;
6043             if (nonLiteral)
6044                 error(loc, "needs a literal integer", "xfb_buffer", "");
6045             return;
6046         } else if (id == "xfb_offset") {
6047             if (value >= (int)TQualifier::layoutXfbOffsetEnd)
6048                 error(loc, "offset is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbOffsetEnd-1);
6049             else
6050                 publicType.qualifier.layoutXfbOffset = value;
6051             if (nonLiteral)
6052                 error(loc, "needs a literal integer", "xfb_offset", "");
6053             return;
6054         } else if (id == "xfb_stride") {
6055             // "The resulting stride (implicit or explicit), when divided by 4, must be less than or equal to the
6056             // implementation-dependent constant gl_MaxTransformFeedbackInterleavedComponents."
6057             if (value > 4 * resources.maxTransformFeedbackInterleavedComponents) {
6058                 error(loc, "1/4 stride is too large:", id.c_str(), "gl_MaxTransformFeedbackInterleavedComponents is %d",
6059                     resources.maxTransformFeedbackInterleavedComponents);
6060             }
6061             if (value >= (int)TQualifier::layoutXfbStrideEnd)
6062                 error(loc, "stride is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbStrideEnd-1);
6063             else
6064                 publicType.qualifier.layoutXfbStride = value;
6065             if (nonLiteral)
6066                 error(loc, "needs a literal integer", "xfb_stride", "");
6067             return;
6068         }
6069     }
6070     if (id == "input_attachment_index") {
6071         requireVulkan(loc, "input_attachment_index");
6072         if (value >= (int)TQualifier::layoutAttachmentEnd)
6073             error(loc, "attachment index is too large", id.c_str(), "");
6074         else
6075             publicType.qualifier.layoutAttachment = value;
6076         if (nonLiteral)
6077             error(loc, "needs a literal integer", "input_attachment_index", "");
6078         return;
6079     }
6080     if (id == "num_views") {
6081         requireExtensions(loc, Num_OVR_multiview_EXTs, OVR_multiview_EXTs, "num_views");
6082         publicType.shaderQualifiers.numViews = value;
6083         if (nonLiteral)
6084             error(loc, "needs a literal integer", "num_views", "");
6085         return;
6086     }
6087     if (language == EShLangVertex ||
6088         language == EShLangTessControl ||
6089         language == EShLangTessEvaluation ||
6090         language == EShLangGeometry) {
6091         if (id == "secondary_view_offset") {
6092             requireExtensions(loc, 1, &E_GL_NV_stereo_view_rendering, "stereo view rendering");
6093             publicType.qualifier.layoutSecondaryViewportRelativeOffset = value;
6094             if (nonLiteral)
6095                 error(loc, "needs a literal integer", "secondary_view_offset", "");
6096             return;
6097         }
6098     }
6099 
6100     if (id == "buffer_reference_align") {
6101         requireExtensions(loc, 1, &E_GL_EXT_buffer_reference, "buffer_reference_align");
6102         if (! IsPow2(value))
6103             error(loc, "must be a power of 2", "buffer_reference_align", "");
6104         else
6105             publicType.qualifier.layoutBufferReferenceAlign = IntLog2(value);
6106         if (nonLiteral)
6107             error(loc, "needs a literal integer", "buffer_reference_align", "");
6108         return;
6109     }
6110 
6111     switch (language) {
6112     case EShLangTessControl:
6113         if (id == "vertices") {
6114             if (value == 0)
6115                 error(loc, "must be greater than 0", "vertices", "");
6116             else
6117                 publicType.shaderQualifiers.vertices = value;
6118             if (nonLiteral)
6119                 error(loc, "needs a literal integer", "vertices", "");
6120             return;
6121         }
6122         break;
6123 
6124     case EShLangGeometry:
6125         if (id == "invocations") {
6126             profileRequires(loc, ECompatibilityProfile | ECoreProfile, 400, nullptr, "invocations");
6127             if (value == 0)
6128                 error(loc, "must be at least 1", "invocations", "");
6129             else
6130                 publicType.shaderQualifiers.invocations = value;
6131             if (nonLiteral)
6132                 error(loc, "needs a literal integer", "invocations", "");
6133             return;
6134         }
6135         if (id == "max_vertices") {
6136             publicType.shaderQualifiers.vertices = value;
6137             if (value > resources.maxGeometryOutputVertices)
6138                 error(loc, "too large, must be less than gl_MaxGeometryOutputVertices", "max_vertices", "");
6139             if (nonLiteral)
6140                 error(loc, "needs a literal integer", "max_vertices", "");
6141             return;
6142         }
6143         if (id == "stream") {
6144             requireProfile(loc, ~EEsProfile, "selecting output stream");
6145             publicType.qualifier.layoutStream = value;
6146             if (value > 0)
6147                 intermediate.setMultiStream();
6148             if (nonLiteral)
6149                 error(loc, "needs a literal integer", "stream", "");
6150             return;
6151         }
6152         break;
6153 
6154     case EShLangFragment:
6155         if (id == "index") {
6156             requireProfile(loc, ECompatibilityProfile | ECoreProfile | EEsProfile, "index layout qualifier on fragment output");
6157             const char* exts[2] = { E_GL_ARB_separate_shader_objects, E_GL_ARB_explicit_attrib_location };
6158             profileRequires(loc, ECompatibilityProfile | ECoreProfile, 330, 2, exts, "index layout qualifier on fragment output");
6159             profileRequires(loc, EEsProfile ,310, E_GL_EXT_blend_func_extended, "index layout qualifier on fragment output");
6160             // "It is also a compile-time error if a fragment shader sets a layout index to less than 0 or greater than 1."
6161             if (value < 0 || value > 1) {
6162                 value = 0;
6163                 error(loc, "value must be 0 or 1", "index", "");
6164             }
6165 
6166             publicType.qualifier.layoutIndex = value;
6167             if (nonLiteral)
6168                 error(loc, "needs a literal integer", "index", "");
6169             return;
6170         }
6171         break;
6172 
6173     case EShLangMesh:
6174         if (id == "max_vertices") {
6175             requireExtensions(loc, Num_AEP_mesh_shader, AEP_mesh_shader, "max_vertices");
6176             publicType.shaderQualifiers.vertices = value;
6177             int max = extensionTurnedOn(E_GL_EXT_mesh_shader) ? resources.maxMeshOutputVerticesEXT
6178                                                               : resources.maxMeshOutputVerticesNV;
6179             if (value > max) {
6180                 TString maxsErrtring = "too large, must be less than ";
6181                 maxsErrtring.append(extensionTurnedOn(E_GL_EXT_mesh_shader) ? "gl_MaxMeshOutputVerticesEXT"
6182                                                                             : "gl_MaxMeshOutputVerticesNV");
6183                 error(loc, maxsErrtring.c_str(), "max_vertices", "");
6184             }
6185             if (nonLiteral)
6186                 error(loc, "needs a literal integer", "max_vertices", "");
6187             return;
6188         }
6189         if (id == "max_primitives") {
6190             requireExtensions(loc, Num_AEP_mesh_shader, AEP_mesh_shader, "max_primitives");
6191             publicType.shaderQualifiers.primitives = value;
6192             int max = extensionTurnedOn(E_GL_EXT_mesh_shader) ? resources.maxMeshOutputPrimitivesEXT
6193                                                               : resources.maxMeshOutputPrimitivesNV;
6194             if (value > max) {
6195                 TString maxsErrtring = "too large, must be less than ";
6196                 maxsErrtring.append(extensionTurnedOn(E_GL_EXT_mesh_shader) ? "gl_MaxMeshOutputPrimitivesEXT"
6197                                                                             : "gl_MaxMeshOutputPrimitivesNV");
6198                 error(loc, maxsErrtring.c_str(), "max_primitives", "");
6199             }
6200             if (nonLiteral)
6201                 error(loc, "needs a literal integer", "max_primitives", "");
6202             return;
6203         }
6204         // Fall through
6205 
6206     case EShLangTask:
6207         // Fall through
6208     case EShLangCompute:
6209         if (id.compare(0, 11, "local_size_") == 0) {
6210             if (language == EShLangMesh || language == EShLangTask) {
6211                 requireExtensions(loc, Num_AEP_mesh_shader, AEP_mesh_shader, "gl_WorkGroupSize");
6212             } else {
6213                 profileRequires(loc, EEsProfile, 310, nullptr, "gl_WorkGroupSize");
6214                 profileRequires(loc, ~EEsProfile, 430, E_GL_ARB_compute_shader, "gl_WorkGroupSize");
6215             }
6216             if (nonLiteral)
6217                 error(loc, "needs a literal integer", "local_size", "");
6218             if (id.size() == 12 && value == 0) {
6219                 error(loc, "must be at least 1", id.c_str(), "");
6220                 return;
6221             }
6222             if (id == "local_size_x") {
6223                 publicType.shaderQualifiers.localSize[0] = value;
6224                 publicType.shaderQualifiers.localSizeNotDefault[0] = true;
6225                 return;
6226             }
6227             if (id == "local_size_y") {
6228                 publicType.shaderQualifiers.localSize[1] = value;
6229                 publicType.shaderQualifiers.localSizeNotDefault[1] = true;
6230                 return;
6231             }
6232             if (id == "local_size_z") {
6233                 publicType.shaderQualifiers.localSize[2] = value;
6234                 publicType.shaderQualifiers.localSizeNotDefault[2] = true;
6235                 return;
6236             }
6237             if (spvVersion.spv != 0) {
6238                 if (id == "local_size_x_id") {
6239                     publicType.shaderQualifiers.localSizeSpecId[0] = value;
6240                     return;
6241                 }
6242                 if (id == "local_size_y_id") {
6243                     publicType.shaderQualifiers.localSizeSpecId[1] = value;
6244                     return;
6245                 }
6246                 if (id == "local_size_z_id") {
6247                     publicType.shaderQualifiers.localSizeSpecId[2] = value;
6248                     return;
6249                 }
6250             }
6251         }
6252         break;
6253 
6254     default:
6255         break;
6256     }
6257 
6258     error(loc, "there is no such layout identifier for this stage taking an assigned value", id.c_str(), "");
6259 }
6260 
6261 // Merge any layout qualifier information from src into dst, leaving everything else in dst alone
6262 //
6263 // "More than one layout qualifier may appear in a single declaration.
6264 // Additionally, the same layout-qualifier-name can occur multiple times
6265 // within a layout qualifier or across multiple layout qualifiers in the
6266 // same declaration. When the same layout-qualifier-name occurs
6267 // multiple times, in a single declaration, the last occurrence overrides
6268 // the former occurrence(s).  Further, if such a layout-qualifier-name
6269 // will effect subsequent declarations or other observable behavior, it
6270 // is only the last occurrence that will have any effect, behaving as if
6271 // the earlier occurrence(s) within the declaration are not present.
6272 // This is also true for overriding layout-qualifier-names, where one
6273 // overrides the other (e.g., row_major vs. column_major); only the last
6274 // occurrence has any effect."
mergeObjectLayoutQualifiers(TQualifier & dst,const TQualifier & src,bool inheritOnly)6275 void TParseContext::mergeObjectLayoutQualifiers(TQualifier& dst, const TQualifier& src, bool inheritOnly)
6276 {
6277     if (src.hasMatrix())
6278         dst.layoutMatrix = src.layoutMatrix;
6279     if (src.hasPacking())
6280         dst.layoutPacking = src.layoutPacking;
6281 
6282     if (src.hasStream())
6283         dst.layoutStream = src.layoutStream;
6284     if (src.hasFormat())
6285         dst.layoutFormat = src.layoutFormat;
6286     if (src.hasXfbBuffer())
6287         dst.layoutXfbBuffer = src.layoutXfbBuffer;
6288     if (src.hasBufferReferenceAlign())
6289         dst.layoutBufferReferenceAlign = src.layoutBufferReferenceAlign;
6290 
6291     if (src.hasAlign())
6292         dst.layoutAlign = src.layoutAlign;
6293 
6294     if (! inheritOnly) {
6295         if (src.hasLocation())
6296             dst.layoutLocation = src.layoutLocation;
6297         if (src.hasOffset())
6298             dst.layoutOffset = src.layoutOffset;
6299         if (src.hasSet())
6300             dst.layoutSet = src.layoutSet;
6301         if (src.layoutBinding != TQualifier::layoutBindingEnd)
6302             dst.layoutBinding = src.layoutBinding;
6303 
6304         if (src.hasSpecConstantId())
6305             dst.layoutSpecConstantId = src.layoutSpecConstantId;
6306 
6307         if (src.hasComponent())
6308             dst.layoutComponent = src.layoutComponent;
6309         if (src.hasIndex())
6310             dst.layoutIndex = src.layoutIndex;
6311         if (src.hasXfbStride())
6312             dst.layoutXfbStride = src.layoutXfbStride;
6313         if (src.hasXfbOffset())
6314             dst.layoutXfbOffset = src.layoutXfbOffset;
6315         if (src.hasAttachment())
6316             dst.layoutAttachment = src.layoutAttachment;
6317         if (src.layoutPushConstant)
6318             dst.layoutPushConstant = true;
6319 
6320         if (src.layoutBufferReference)
6321             dst.layoutBufferReference = true;
6322 
6323         if (src.layoutPassthrough)
6324             dst.layoutPassthrough = true;
6325         if (src.layoutViewportRelative)
6326             dst.layoutViewportRelative = true;
6327         if (src.layoutSecondaryViewportRelativeOffset != -2048)
6328             dst.layoutSecondaryViewportRelativeOffset = src.layoutSecondaryViewportRelativeOffset;
6329         if (src.layoutShaderRecord)
6330             dst.layoutShaderRecord = true;
6331         if (src.layoutBindlessSampler)
6332             dst.layoutBindlessSampler = true;
6333         if (src.layoutBindlessImage)
6334             dst.layoutBindlessImage = true;
6335         if (src.pervertexNV)
6336             dst.pervertexNV = true;
6337         if (src.pervertexEXT)
6338             dst.pervertexEXT = true;
6339         if (src.layoutHitObjectShaderRecordNV)
6340             dst.layoutHitObjectShaderRecordNV = true;
6341     }
6342 }
6343 
6344 // Do error layout error checking given a full variable/block declaration.
layoutObjectCheck(const TSourceLoc & loc,const TSymbol & symbol)6345 void TParseContext::layoutObjectCheck(const TSourceLoc& loc, const TSymbol& symbol)
6346 {
6347     const TType& type = symbol.getType();
6348     const TQualifier& qualifier = type.getQualifier();
6349 
6350     // first, cross check WRT to just the type
6351     layoutTypeCheck(loc, type);
6352 
6353     // now, any remaining error checking based on the object itself
6354 
6355     if (qualifier.hasAnyLocation()) {
6356         switch (qualifier.storage) {
6357         case EvqUniform:
6358         case EvqBuffer:
6359             if (symbol.getAsVariable() == nullptr)
6360                 error(loc, "can only be used on variable declaration", "location", "");
6361             break;
6362         default:
6363             break;
6364         }
6365     }
6366 
6367     // user-variable location check, which are required for SPIR-V in/out:
6368     //  - variables have it directly,
6369     //  - blocks have it on each member (already enforced), so check first one
6370     if (spvVersion.spv > 0 && !parsingBuiltins && qualifier.builtIn == EbvNone &&
6371         !qualifier.hasLocation() && !intermediate.getAutoMapLocations()) {
6372 
6373         switch (qualifier.storage) {
6374         case EvqVaryingIn:
6375         case EvqVaryingOut:
6376             if (!type.getQualifier().isTaskMemory() && !type.getQualifier().hasSpirvDecorate() &&
6377                 (type.getBasicType() != EbtBlock ||
6378                  (!(*type.getStruct())[0].type->getQualifier().hasLocation() &&
6379                    (*type.getStruct())[0].type->getQualifier().builtIn == EbvNone)))
6380                 error(loc, "SPIR-V requires location for user input/output", "location", "");
6381             break;
6382         default:
6383             break;
6384         }
6385     }
6386 
6387     // Check packing and matrix
6388     if (qualifier.hasUniformLayout()) {
6389         switch (qualifier.storage) {
6390         case EvqUniform:
6391         case EvqBuffer:
6392             if (type.getBasicType() != EbtBlock) {
6393                 if (qualifier.hasMatrix())
6394                     error(loc, "cannot specify matrix layout on a variable declaration", "layout", "");
6395                 if (qualifier.hasPacking())
6396                     error(loc, "cannot specify packing on a variable declaration", "layout", "");
6397                 // "The offset qualifier can only be used on block members of blocks..."
6398                 if (qualifier.hasOffset() && !type.isAtomic())
6399                     error(loc, "cannot specify on a variable declaration", "offset", "");
6400                 // "The align qualifier can only be used on blocks or block members..."
6401                 if (qualifier.hasAlign())
6402                     error(loc, "cannot specify on a variable declaration", "align", "");
6403                 if (qualifier.isPushConstant())
6404                     error(loc, "can only specify on a uniform block", "push_constant", "");
6405                 if (qualifier.isShaderRecord())
6406                     error(loc, "can only specify on a buffer block", "shaderRecordNV", "");
6407                 if (qualifier.hasLocation() && type.isAtomic())
6408                     error(loc, "cannot specify on atomic counter", "location", "");
6409             }
6410             break;
6411         default:
6412             // these were already filtered by layoutTypeCheck() (or its callees)
6413             break;
6414         }
6415     }
6416 }
6417 
6418 // "For some blocks declared as arrays, the location can only be applied at the block level:
6419 // When a block is declared as an array where additional locations are needed for each member
6420 // for each block array element, it is a compile-time error to specify locations on the block
6421 // members.  That is, when locations would be under specified by applying them on block members,
6422 // they are not allowed on block members.  For arrayed interfaces (those generally having an
6423 // extra level of arrayness due to interface expansion), the outer array is stripped before
6424 // applying this rule."
layoutMemberLocationArrayCheck(const TSourceLoc & loc,bool memberWithLocation,TArraySizes * arraySizes)6425 void TParseContext::layoutMemberLocationArrayCheck(const TSourceLoc& loc, bool memberWithLocation,
6426     TArraySizes* arraySizes)
6427 {
6428     if (memberWithLocation && arraySizes != nullptr) {
6429         if (arraySizes->getNumDims() > (currentBlockQualifier.isArrayedIo(language) ? 1 : 0))
6430             error(loc, "cannot use in a block array where new locations are needed for each block element",
6431                        "location", "");
6432     }
6433 }
6434 
6435 // Do layout error checking with respect to a type.
layoutTypeCheck(const TSourceLoc & loc,const TType & type)6436 void TParseContext::layoutTypeCheck(const TSourceLoc& loc, const TType& type)
6437 {
6438     const TQualifier& qualifier = type.getQualifier();
6439 
6440     // first, intra-layout qualifier-only error checking
6441     layoutQualifierCheck(loc, qualifier);
6442 
6443     // now, error checking combining type and qualifier
6444 
6445     if (qualifier.hasAnyLocation()) {
6446         if (qualifier.hasLocation()) {
6447             if (qualifier.storage == EvqVaryingOut && language == EShLangFragment) {
6448                 if (qualifier.layoutLocation >= (unsigned int)resources.maxDrawBuffers)
6449                     error(loc, "too large for fragment output", "location", "");
6450             }
6451         }
6452         if (qualifier.hasComponent()) {
6453             // "It is a compile-time error if this sequence of components gets larger than 3."
6454             if (qualifier.layoutComponent + type.getVectorSize() * (type.getBasicType() == EbtDouble ? 2 : 1) > 4)
6455                 error(loc, "type overflows the available 4 components", "component", "");
6456 
6457             // "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."
6458             if (type.isMatrix() || type.getBasicType() == EbtBlock || type.getBasicType() == EbtStruct)
6459                 error(loc, "cannot apply to a matrix, structure, or block", "component", "");
6460 
6461             // " It is a compile-time error to use component 1 or 3 as the beginning of a double or dvec2."
6462             if (type.getBasicType() == EbtDouble)
6463                 if (qualifier.layoutComponent & 1)
6464                     error(loc, "doubles cannot start on an odd-numbered component", "component", "");
6465         }
6466 
6467         switch (qualifier.storage) {
6468         case EvqVaryingIn:
6469         case EvqVaryingOut:
6470             if (type.getBasicType() == EbtBlock)
6471                 profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, E_GL_ARB_enhanced_layouts, "location qualifier on in/out block");
6472             if (type.getQualifier().isTaskMemory())
6473                 error(loc, "cannot apply to taskNV in/out blocks", "location", "");
6474             break;
6475         case EvqUniform:
6476         case EvqBuffer:
6477             if (type.getBasicType() == EbtBlock)
6478                 error(loc, "cannot apply to uniform or buffer block", "location", "");
6479             else if (type.getBasicType() == EbtSampler && type.getSampler().isAttachmentEXT())
6480                 error(loc, "only applies to", "location", "%s with storage tileImageEXT", type.getBasicTypeString().c_str());
6481             break;
6482         case EvqtaskPayloadSharedEXT:
6483             error(loc, "cannot apply to taskPayloadSharedEXT", "location", "");
6484             break;
6485         case EvqPayload:
6486         case EvqPayloadIn:
6487         case EvqHitAttr:
6488         case EvqCallableData:
6489         case EvqCallableDataIn:
6490         case EvqHitObjectAttrNV:
6491         case EvqSpirvStorageClass:
6492             break;
6493         case EvqTileImageEXT:
6494             break;
6495         default:
6496             error(loc, "can only apply to uniform, buffer, in, or out storage qualifiers", "location", "");
6497             break;
6498         }
6499 
6500         bool typeCollision;
6501         int repeated = intermediate.addUsedLocation(qualifier, type, typeCollision);
6502         if (repeated >= 0 && ! typeCollision)
6503             error(loc, "overlapping use of location", "location", "%d", repeated);
6504         // "fragment-shader outputs/tileImageEXT ... if two variables are placed within the same
6505         // location, they must have the same underlying type (floating-point or integer)"
6506         if (typeCollision && language == EShLangFragment && (qualifier.isPipeOutput() || qualifier.storage == EvqTileImageEXT))
6507             error(loc, "fragment outputs or tileImageEXTs sharing the same location", "location", "%d must be the same basic type", repeated);
6508     }
6509 
6510     if (qualifier.hasXfbOffset() && qualifier.hasXfbBuffer()) {
6511         if (type.isUnsizedArray()) {
6512             error(loc, "unsized array", "xfb_offset", "in buffer %d", qualifier.layoutXfbBuffer);
6513         } else {
6514             int repeated = intermediate.addXfbBufferOffset(type);
6515             if (repeated >= 0)
6516                 error(loc, "overlapping offsets at", "xfb_offset", "offset %d in buffer %d", repeated, qualifier.layoutXfbBuffer);
6517         }
6518 
6519         // "The offset must be a multiple of the size of the first component of the first
6520         // qualified variable or block member, or a compile-time error results. Further, if applied to an aggregate
6521         // containing a double or 64-bit integer, the offset must also be a multiple of 8..."
6522         if ((type.containsBasicType(EbtDouble) || type.containsBasicType(EbtInt64) || type.containsBasicType(EbtUint64)) &&
6523             ! IsMultipleOfPow2(qualifier.layoutXfbOffset, 8))
6524             error(loc, "type contains double or 64-bit integer; xfb_offset must be a multiple of 8", "xfb_offset", "");
6525         else if ((type.containsBasicType(EbtBool) || type.containsBasicType(EbtFloat) ||
6526                   type.containsBasicType(EbtInt) || type.containsBasicType(EbtUint)) &&
6527                  ! IsMultipleOfPow2(qualifier.layoutXfbOffset, 4))
6528             error(loc, "must be a multiple of size of first component", "xfb_offset", "");
6529         // ..., if applied to an aggregate containing a half float or 16-bit integer, the offset must also be a multiple of 2..."
6530         else if ((type.contains16BitFloat() || type.containsBasicType(EbtInt16) || type.containsBasicType(EbtUint16)) &&
6531                  !IsMultipleOfPow2(qualifier.layoutXfbOffset, 2))
6532             error(loc, "type contains half float or 16-bit integer; xfb_offset must be a multiple of 2", "xfb_offset", "");
6533     }
6534     if (qualifier.hasXfbStride() && qualifier.hasXfbBuffer()) {
6535         if (! intermediate.setXfbBufferStride(qualifier.layoutXfbBuffer, qualifier.layoutXfbStride))
6536             error(loc, "all stride settings must match for xfb buffer", "xfb_stride", "%d", qualifier.layoutXfbBuffer);
6537     }
6538 
6539     if (qualifier.hasBinding()) {
6540         // Binding checking, from the spec:
6541         //
6542         // "If the binding point for any uniform or shader storage block instance is less than zero, or greater than or
6543         // equal to the implementation-dependent maximum number of uniform buffer bindings, a compile-time
6544         // error will occur. When the binding identifier is used with a uniform or shader storage block instanced as
6545         // an array of size N, all elements of the array from binding through binding + N - 1 must be within this
6546         // range."
6547         //
6548         if (!type.isOpaque() && type.getBasicType() != EbtBlock && type.getBasicType() != EbtSpirvType)
6549             error(loc, "requires block, or sampler/image, or atomic-counter type", "binding", "");
6550         if (type.getBasicType() == EbtSampler) {
6551             int lastBinding = qualifier.layoutBinding;
6552             if (type.isArray()) {
6553                 if (spvVersion.vulkan == 0) {
6554                     if (type.isSizedArray())
6555                         lastBinding += (type.getCumulativeArraySize() - 1);
6556                     else {
6557                         warn(loc, "assuming binding count of one for compile-time checking of binding numbers for unsized array", "[]", "");
6558                     }
6559                 }
6560             }
6561             if (spvVersion.vulkan == 0 && lastBinding >= resources.maxCombinedTextureImageUnits)
6562                 error(loc, "sampler binding not less than gl_MaxCombinedTextureImageUnits", "binding", type.isArray() ? "(using array)" : "");
6563         }
6564         if (type.isAtomic() && !spvVersion.vulkanRelaxed) {
6565             if (qualifier.layoutBinding >= (unsigned int)resources.maxAtomicCounterBindings) {
6566                 error(loc, "atomic_uint binding is too large; see gl_MaxAtomicCounterBindings", "binding", "");
6567                 return;
6568             }
6569         }
6570     } else if (!intermediate.getAutoMapBindings()) {
6571         // some types require bindings
6572 
6573         // atomic_uint
6574         if (type.isAtomic())
6575             error(loc, "layout(binding=X) is required", "atomic_uint", "");
6576 
6577         // SPIR-V
6578         if (spvVersion.spv > 0) {
6579             if (qualifier.isUniformOrBuffer()) {
6580                 if (type.getBasicType() == EbtBlock && !qualifier.isPushConstant() &&
6581                        !qualifier.isShaderRecord() &&
6582                        !qualifier.hasAttachment() &&
6583                        !qualifier.hasBufferReference())
6584                     error(loc, "uniform/buffer blocks require layout(binding=X)", "binding", "");
6585                 else if (spvVersion.vulkan > 0 && type.getBasicType() == EbtSampler && !type.getSampler().isAttachmentEXT())
6586                     error(loc, "sampler/texture/image requires layout(binding=X)", "binding", "");
6587             }
6588         }
6589     }
6590 
6591     // some things can't have arrays of arrays
6592     if (type.isArrayOfArrays()) {
6593         if (spvVersion.vulkan > 0) {
6594             if (type.isOpaque() || (type.getQualifier().isUniformOrBuffer() && type.getBasicType() == EbtBlock))
6595                 warn(loc, "Generating SPIR-V array-of-arrays, but Vulkan only supports single array level for this resource", "[][]", "");
6596         }
6597     }
6598 
6599     // "The offset qualifier can only be used on block members of blocks..."
6600     if (qualifier.hasOffset()) {
6601         if (type.getBasicType() == EbtBlock)
6602             error(loc, "only applies to block members, not blocks", "offset", "");
6603     }
6604 
6605     // Image format
6606     if (qualifier.hasFormat()) {
6607         if (! type.isImage() && !intermediate.getBindlessImageMode())
6608             error(loc, "only apply to images", TQualifier::getLayoutFormatString(qualifier.getFormat()), "");
6609         else {
6610             if (type.getSampler().type == EbtFloat && qualifier.getFormat() > ElfFloatGuard)
6611                 error(loc, "does not apply to floating point images", TQualifier::getLayoutFormatString(qualifier.getFormat()), "");
6612             if (type.getSampler().type == EbtInt && (qualifier.getFormat() < ElfFloatGuard || qualifier.getFormat() > ElfIntGuard))
6613                 error(loc, "does not apply to signed integer images", TQualifier::getLayoutFormatString(qualifier.getFormat()), "");
6614             if (type.getSampler().type == EbtUint && qualifier.getFormat() < ElfIntGuard)
6615                 error(loc, "does not apply to unsigned integer images", TQualifier::getLayoutFormatString(qualifier.getFormat()), "");
6616 
6617             if (isEsProfile()) {
6618                 // "Except for image variables qualified with the format qualifiers r32f, r32i, and r32ui, image variables must
6619                 // specify either memory qualifier readonly or the memory qualifier writeonly."
6620                 if (! (qualifier.getFormat() == ElfR32f || qualifier.getFormat() == ElfR32i || qualifier.getFormat() == ElfR32ui)) {
6621                     if (! qualifier.isReadOnly() && ! qualifier.isWriteOnly())
6622                         error(loc, "format requires readonly or writeonly memory qualifier", TQualifier::getLayoutFormatString(qualifier.getFormat()), "");
6623                 }
6624             }
6625         }
6626     } else if (type.isImage() && ! qualifier.isWriteOnly() && !intermediate.getBindlessImageMode()) {
6627         const char *explanation = "image variables not declared 'writeonly' and without a format layout qualifier";
6628         requireProfile(loc, ECoreProfile | ECompatibilityProfile, explanation);
6629         profileRequires(loc, ECoreProfile | ECompatibilityProfile, 0, E_GL_EXT_shader_image_load_formatted, explanation);
6630     }
6631 
6632     if (qualifier.isPushConstant()) {
6633         if (type.getBasicType() != EbtBlock)
6634             error(loc, "can only be used with a block", "push_constant", "");
6635         if (type.isArray())
6636             error(loc, "Push constants blocks can't be an array", "push_constant", "");
6637     }
6638 
6639     if (qualifier.hasBufferReference() && type.getBasicType() != EbtBlock)
6640         error(loc, "can only be used with a block", "buffer_reference", "");
6641 
6642     if (qualifier.isShaderRecord() && type.getBasicType() != EbtBlock)
6643         error(loc, "can only be used with a block", "shaderRecordNV", "");
6644 
6645     // input attachment
6646     if (type.isSubpass()) {
6647         if (extensionTurnedOn(E_GL_EXT_shader_tile_image))
6648 	    error(loc, "can not be used with GL_EXT_shader_tile_image enabled", type.getSampler().getString().c_str(), "");
6649         if (! qualifier.hasAttachment())
6650             error(loc, "requires an input_attachment_index layout qualifier", "subpass", "");
6651     } else {
6652         if (qualifier.hasAttachment())
6653             error(loc, "can only be used with a subpass", "input_attachment_index", "");
6654     }
6655 
6656     // specialization-constant id
6657     if (qualifier.hasSpecConstantId()) {
6658         if (type.getQualifier().storage != EvqConst)
6659             error(loc, "can only be applied to 'const'-qualified scalar", "constant_id", "");
6660         if (! type.isScalar())
6661             error(loc, "can only be applied to a scalar", "constant_id", "");
6662         switch (type.getBasicType())
6663         {
6664         case EbtInt8:
6665         case EbtUint8:
6666         case EbtInt16:
6667         case EbtUint16:
6668         case EbtInt:
6669         case EbtUint:
6670         case EbtInt64:
6671         case EbtUint64:
6672         case EbtBool:
6673         case EbtFloat:
6674         case EbtDouble:
6675         case EbtFloat16:
6676             break;
6677         default:
6678             error(loc, "cannot be applied to this type", "constant_id", "");
6679             break;
6680         }
6681     }
6682 }
6683 
storageCanHaveLayoutInBlock(const enum TStorageQualifier storage)6684 static bool storageCanHaveLayoutInBlock(const enum TStorageQualifier storage)
6685 {
6686     switch (storage) {
6687     case EvqUniform:
6688     case EvqBuffer:
6689     case EvqShared:
6690         return true;
6691     default:
6692         return false;
6693     }
6694 }
6695 
6696 // Do layout error checking that can be done within a layout qualifier proper, not needing to know
6697 // if there are blocks, atomic counters, variables, etc.
layoutQualifierCheck(const TSourceLoc & loc,const TQualifier & qualifier)6698 void TParseContext::layoutQualifierCheck(const TSourceLoc& loc, const TQualifier& qualifier)
6699 {
6700     if (qualifier.storage == EvqShared && qualifier.hasLayout()) {
6701         if (spvVersion.spv > 0 && spvVersion.spv < EShTargetSpv_1_4) {
6702             error(loc, "shared block requires at least SPIR-V 1.4", "shared block", "");
6703         }
6704         profileRequires(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, 0, E_GL_EXT_shared_memory_block, "shared block");
6705     }
6706 
6707     // "It is a compile-time error to use *component* without also specifying the location qualifier (order does not matter)."
6708     if (qualifier.hasComponent() && ! qualifier.hasLocation())
6709         error(loc, "must specify 'location' to use 'component'", "component", "");
6710 
6711     if (qualifier.hasAnyLocation()) {
6712 
6713         // "As with input layout qualifiers, all shaders except compute shaders
6714         // allow *location* layout qualifiers on output variable declarations,
6715         // output block declarations, and output block member declarations."
6716 
6717         switch (qualifier.storage) {
6718         case EvqVaryingIn:
6719         {
6720             const char* feature = "location qualifier on input";
6721             if (isEsProfile() && version < 310)
6722                 requireStage(loc, EShLangVertex, feature);
6723             else
6724                 requireStage(loc, (EShLanguageMask)~EShLangComputeMask, feature);
6725             if (language == EShLangVertex) {
6726                 const char* exts[2] = { E_GL_ARB_separate_shader_objects, E_GL_ARB_explicit_attrib_location };
6727                 profileRequires(loc, ~EEsProfile, 330, 2, exts, feature);
6728                 profileRequires(loc, EEsProfile, 300, nullptr, feature);
6729             } else {
6730                 profileRequires(loc, ~EEsProfile, 410, E_GL_ARB_separate_shader_objects, feature);
6731                 profileRequires(loc, EEsProfile, 310, nullptr, feature);
6732             }
6733             break;
6734         }
6735         case EvqVaryingOut:
6736         {
6737             const char* feature = "location qualifier on output";
6738             if (isEsProfile() && version < 310)
6739                 requireStage(loc, EShLangFragment, feature);
6740             else
6741                 requireStage(loc, (EShLanguageMask)~EShLangComputeMask, feature);
6742             if (language == EShLangFragment) {
6743                 const char* exts[2] = { E_GL_ARB_separate_shader_objects, E_GL_ARB_explicit_attrib_location };
6744                 profileRequires(loc, ~EEsProfile, 330, 2, exts, feature);
6745                 profileRequires(loc, EEsProfile, 300, nullptr, feature);
6746             } else {
6747                 profileRequires(loc, ~EEsProfile, 410, E_GL_ARB_separate_shader_objects, feature);
6748                 profileRequires(loc, EEsProfile, 310, nullptr, feature);
6749             }
6750             break;
6751         }
6752         case EvqUniform:
6753         case EvqBuffer:
6754         {
6755             const char* feature = "location qualifier on uniform or buffer";
6756             requireProfile(loc, EEsProfile | ECoreProfile | ECompatibilityProfile | ENoProfile, feature);
6757             profileRequires(loc, ~EEsProfile, 330, E_GL_ARB_explicit_attrib_location, feature);
6758             profileRequires(loc, ~EEsProfile, 430, E_GL_ARB_explicit_uniform_location, feature);
6759             profileRequires(loc, EEsProfile, 310, nullptr, feature);
6760             break;
6761         }
6762         default:
6763             break;
6764         }
6765         if (qualifier.hasIndex()) {
6766             if (qualifier.storage != EvqVaryingOut)
6767                 error(loc, "can only be used on an output", "index", "");
6768             if (! qualifier.hasLocation())
6769                 error(loc, "can only be used with an explicit location", "index", "");
6770         }
6771     }
6772 
6773     if (qualifier.hasBinding()) {
6774         if (! qualifier.isUniformOrBuffer() && !qualifier.isTaskMemory())
6775             error(loc, "requires uniform or buffer storage qualifier", "binding", "");
6776     }
6777     if (qualifier.hasStream()) {
6778         if (!qualifier.isPipeOutput())
6779             error(loc, "can only be used on an output", "stream", "");
6780     }
6781     if (qualifier.hasXfb()) {
6782         if (!qualifier.isPipeOutput())
6783             error(loc, "can only be used on an output", "xfb layout qualifier", "");
6784     }
6785     if (qualifier.hasUniformLayout()) {
6786         if (!storageCanHaveLayoutInBlock(qualifier.storage) && !qualifier.isTaskMemory()) {
6787             if (qualifier.hasMatrix() || qualifier.hasPacking())
6788                 error(loc, "matrix or packing qualifiers can only be used on a uniform or buffer", "layout", "");
6789             if (qualifier.hasOffset() || qualifier.hasAlign())
6790                 error(loc, "offset/align can only be used on a uniform or buffer", "layout", "");
6791         }
6792     }
6793     if (qualifier.isPushConstant()) {
6794         if (qualifier.storage != EvqUniform)
6795             error(loc, "can only be used with a uniform", "push_constant", "");
6796         if (qualifier.hasSet())
6797             error(loc, "cannot be used with push_constant", "set", "");
6798         if (qualifier.hasBinding())
6799             error(loc, "cannot be used with push_constant", "binding", "");
6800     }
6801     if (qualifier.hasBufferReference()) {
6802         if (qualifier.storage != EvqBuffer)
6803             error(loc, "can only be used with buffer", "buffer_reference", "");
6804     }
6805     if (qualifier.isShaderRecord()) {
6806         if (qualifier.storage != EvqBuffer)
6807             error(loc, "can only be used with a buffer", "shaderRecordNV", "");
6808         if (qualifier.hasBinding())
6809             error(loc, "cannot be used with shaderRecordNV", "binding", "");
6810         if (qualifier.hasSet())
6811             error(loc, "cannot be used with shaderRecordNV", "set", "");
6812 
6813     }
6814 
6815     if (qualifier.storage == EvqTileImageEXT) {
6816         if (qualifier.hasSet())
6817             error(loc, "cannot be used with tileImageEXT", "set", "");
6818         if (!qualifier.hasLocation())
6819             error(loc, "can only be used with an explicit location", "tileImageEXT", "");
6820     }
6821 
6822     if (qualifier.storage == EvqHitAttr && qualifier.hasLayout()) {
6823         error(loc, "cannot apply layout qualifiers to hitAttributeNV variable", "hitAttributeNV", "");
6824     }
6825 }
6826 
6827 // For places that can't have shader-level layout qualifiers
checkNoShaderLayouts(const TSourceLoc & loc,const TShaderQualifiers & shaderQualifiers)6828 void TParseContext::checkNoShaderLayouts(const TSourceLoc& loc, const TShaderQualifiers& shaderQualifiers)
6829 {
6830     const char* message = "can only apply to a standalone qualifier";
6831 
6832     if (shaderQualifiers.geometry != ElgNone)
6833         error(loc, message, TQualifier::getGeometryString(shaderQualifiers.geometry), "");
6834     if (shaderQualifiers.spacing != EvsNone)
6835         error(loc, message, TQualifier::getVertexSpacingString(shaderQualifiers.spacing), "");
6836     if (shaderQualifiers.order != EvoNone)
6837         error(loc, message, TQualifier::getVertexOrderString(shaderQualifiers.order), "");
6838     if (shaderQualifiers.pointMode)
6839         error(loc, message, "point_mode", "");
6840     if (shaderQualifiers.invocations != TQualifier::layoutNotSet)
6841         error(loc, message, "invocations", "");
6842     for (int i = 0; i < 3; ++i) {
6843         if (shaderQualifiers.localSize[i] > 1)
6844             error(loc, message, "local_size", "");
6845         if (shaderQualifiers.localSizeSpecId[i] != TQualifier::layoutNotSet)
6846             error(loc, message, "local_size id", "");
6847     }
6848     if (shaderQualifiers.vertices != TQualifier::layoutNotSet) {
6849         if (language == EShLangGeometry || language == EShLangMesh)
6850             error(loc, message, "max_vertices", "");
6851         else if (language == EShLangTessControl)
6852             error(loc, message, "vertices", "");
6853         else
6854             assert(0);
6855     }
6856     if (shaderQualifiers.earlyFragmentTests)
6857         error(loc, message, "early_fragment_tests", "");
6858     if (shaderQualifiers.postDepthCoverage)
6859         error(loc, message, "post_depth_coverage", "");
6860     if (shaderQualifiers.nonCoherentColorAttachmentReadEXT)
6861         error(loc, message, "non_coherent_color_attachment_readEXT", "");
6862     if (shaderQualifiers.nonCoherentDepthAttachmentReadEXT)
6863         error(loc, message, "non_coherent_depth_attachment_readEXT", "");
6864     if (shaderQualifiers.nonCoherentStencilAttachmentReadEXT)
6865         error(loc, message, "non_coherent_stencil_attachment_readEXT", "");
6866     if (shaderQualifiers.primitives != TQualifier::layoutNotSet) {
6867         if (language == EShLangMesh)
6868             error(loc, message, "max_primitives", "");
6869         else
6870             assert(0);
6871     }
6872     if (shaderQualifiers.hasBlendEquation())
6873         error(loc, message, "blend equation", "");
6874     if (shaderQualifiers.numViews != TQualifier::layoutNotSet)
6875         error(loc, message, "num_views", "");
6876     if (shaderQualifiers.interlockOrdering != EioNone)
6877         error(loc, message, TQualifier::getInterlockOrderingString(shaderQualifiers.interlockOrdering), "");
6878     if (shaderQualifiers.layoutPrimitiveCulling)
6879         error(loc, "can only be applied as standalone", "primitive_culling", "");
6880 }
6881 
6882 // Correct and/or advance an object's offset layout qualifier.
fixOffset(const TSourceLoc & loc,TSymbol & symbol)6883 void TParseContext::fixOffset(const TSourceLoc& loc, TSymbol& symbol)
6884 {
6885     const TQualifier& qualifier = symbol.getType().getQualifier();
6886     if (symbol.getType().isAtomic()) {
6887         if (qualifier.hasBinding() && (int)qualifier.layoutBinding < resources.maxAtomicCounterBindings) {
6888 
6889             // Set the offset
6890             int offset;
6891             if (qualifier.hasOffset())
6892                 offset = qualifier.layoutOffset;
6893             else
6894                 offset = atomicUintOffsets[qualifier.layoutBinding];
6895 
6896             if (offset % 4 != 0)
6897                 error(loc, "atomic counters offset should align based on 4:", "offset", "%d", offset);
6898 
6899             symbol.getWritableType().getQualifier().layoutOffset = offset;
6900 
6901             // Check for overlap
6902             int numOffsets = 4;
6903             if (symbol.getType().isArray()) {
6904                 if (symbol.getType().isSizedArray() && !symbol.getType().getArraySizes()->isInnerUnsized())
6905                     numOffsets *= symbol.getType().getCumulativeArraySize();
6906                 else {
6907                     // "It is a compile-time error to declare an unsized array of atomic_uint."
6908                     error(loc, "array must be explicitly sized", "atomic_uint", "");
6909                 }
6910             }
6911             int repeated = intermediate.addUsedOffsets(qualifier.layoutBinding, offset, numOffsets);
6912             if (repeated >= 0)
6913                 error(loc, "atomic counters sharing the same offset:", "offset", "%d", repeated);
6914 
6915             // Bump the default offset
6916             atomicUintOffsets[qualifier.layoutBinding] = offset + numOffsets;
6917         }
6918     }
6919 }
6920 
6921 //
6922 // Look up a function name in the symbol table, and make sure it is a function.
6923 //
6924 // Return the function symbol if found, otherwise nullptr.
6925 //
findFunction(const TSourceLoc & loc,const TFunction & call,bool & builtIn)6926 const TFunction* TParseContext::findFunction(const TSourceLoc& loc, const TFunction& call, bool& builtIn)
6927 {
6928     if (symbolTable.isFunctionNameVariable(call.getName())) {
6929         error(loc, "can't use function syntax on variable", call.getName().c_str(), "");
6930         return nullptr;
6931     }
6932 
6933     const TFunction* function = nullptr;
6934 
6935     // debugPrintfEXT has var args and is in the symbol table as "debugPrintfEXT()",
6936     // mangled to "debugPrintfEXT("
6937     if (call.getName() == "debugPrintfEXT") {
6938         TSymbol* symbol = symbolTable.find("debugPrintfEXT(", &builtIn);
6939         if (symbol)
6940             return symbol->getAsFunction();
6941     }
6942 
6943     bool explicitTypesEnabled = extensionTurnedOn(E_GL_EXT_shader_explicit_arithmetic_types) ||
6944                                 extensionTurnedOn(E_GL_EXT_shader_explicit_arithmetic_types_int8) ||
6945                                 extensionTurnedOn(E_GL_EXT_shader_explicit_arithmetic_types_int16) ||
6946                                 extensionTurnedOn(E_GL_EXT_shader_explicit_arithmetic_types_int32) ||
6947                                 extensionTurnedOn(E_GL_EXT_shader_explicit_arithmetic_types_int64) ||
6948                                 extensionTurnedOn(E_GL_EXT_shader_explicit_arithmetic_types_float16) ||
6949                                 extensionTurnedOn(E_GL_EXT_shader_explicit_arithmetic_types_float32) ||
6950                                 extensionTurnedOn(E_GL_EXT_shader_explicit_arithmetic_types_float64);
6951 
6952     if (isEsProfile())
6953         function = (explicitTypesEnabled && version >= 310)
6954                    ? findFunctionExplicitTypes(loc, call, builtIn)
6955                    : ((extensionTurnedOn(E_GL_EXT_shader_implicit_conversions) && version >= 310)
6956                       ? findFunction120(loc, call, builtIn)
6957                       : findFunctionExact(loc, call, builtIn));
6958     else if (version < 120)
6959         function = findFunctionExact(loc, call, builtIn);
6960     else if (version < 400) {
6961         bool needfindFunction400 = extensionTurnedOn(E_GL_ARB_gpu_shader_fp64) || extensionTurnedOn(E_GL_ARB_gpu_shader5);
6962         function = needfindFunction400 ? findFunction400(loc, call, builtIn) : findFunction120(loc, call, builtIn);
6963     }
6964     else if (explicitTypesEnabled)
6965         function = findFunctionExplicitTypes(loc, call, builtIn);
6966     else
6967         function = findFunction400(loc, call, builtIn);
6968 
6969     return function;
6970 }
6971 
6972 // Function finding algorithm for ES and desktop 110.
findFunctionExact(const TSourceLoc & loc,const TFunction & call,bool & builtIn)6973 const TFunction* TParseContext::findFunctionExact(const TSourceLoc& loc, const TFunction& call, bool& builtIn)
6974 {
6975     TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn);
6976     if (symbol == nullptr) {
6977         error(loc, "no matching overloaded function found", call.getName().c_str(), "");
6978 
6979         return nullptr;
6980     }
6981 
6982     return symbol->getAsFunction();
6983 }
6984 
6985 // Function finding algorithm for desktop versions 120 through 330.
findFunction120(const TSourceLoc & loc,const TFunction & call,bool & builtIn)6986 const TFunction* TParseContext::findFunction120(const TSourceLoc& loc, const TFunction& call, bool& builtIn)
6987 {
6988     // first, look for an exact match
6989     TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn);
6990     if (symbol)
6991         return symbol->getAsFunction();
6992 
6993     // exact match not found, look through a list of overloaded functions of the same name
6994 
6995     // "If no exact match is found, then [implicit conversions] will be applied to find a match. Mismatched types
6996     // on input parameters (in or inout or default) must have a conversion from the calling argument type to the
6997     // formal parameter type. Mismatched types on output parameters (out or inout) must have a conversion
6998     // from the formal parameter type to the calling argument type.  When argument conversions are used to find
6999     // a match, it is a semantic error if there are multiple ways to apply these conversions to make the call match
7000     // more than one function."
7001 
7002     const TFunction* candidate = nullptr;
7003     TVector<const TFunction*> candidateList;
7004     symbolTable.findFunctionNameList(call.getMangledName(), candidateList, builtIn);
7005 
7006     for (auto it = candidateList.begin(); it != candidateList.end(); ++it) {
7007         const TFunction& function = *(*it);
7008 
7009         // to even be a potential match, number of arguments has to match
7010         if (call.getParamCount() != function.getParamCount())
7011             continue;
7012 
7013         bool possibleMatch = true;
7014         for (int i = 0; i < function.getParamCount(); ++i) {
7015             // same types is easy
7016             if (*function[i].type == *call[i].type)
7017                 continue;
7018 
7019             // We have a mismatch in type, see if it is implicitly convertible
7020 
7021             if (function[i].type->isArray() || call[i].type->isArray() ||
7022                 ! function[i].type->sameElementShape(*call[i].type))
7023                 possibleMatch = false;
7024             else {
7025                 // do direction-specific checks for conversion of basic type
7026                 if (function[i].type->getQualifier().isParamInput()) {
7027                     if (! intermediate.canImplicitlyPromote(call[i].type->getBasicType(), function[i].type->getBasicType()))
7028                         possibleMatch = false;
7029                 }
7030                 if (function[i].type->getQualifier().isParamOutput()) {
7031                     if (! intermediate.canImplicitlyPromote(function[i].type->getBasicType(), call[i].type->getBasicType()))
7032                         possibleMatch = false;
7033                 }
7034             }
7035             if (! possibleMatch)
7036                 break;
7037         }
7038         if (possibleMatch) {
7039             if (candidate) {
7040                 // our second match, meaning ambiguity
7041                 error(loc, "ambiguous function signature match: multiple signatures match under implicit type conversion", call.getName().c_str(), "");
7042             } else
7043                 candidate = &function;
7044         }
7045     }
7046 
7047     if (candidate == nullptr)
7048         error(loc, "no matching overloaded function found", call.getName().c_str(), "");
7049 
7050     return candidate;
7051 }
7052 
7053 // Function finding algorithm for desktop version 400 and above.
7054 //
7055 // "When function calls are resolved, an exact type match for all the arguments
7056 // is sought. If an exact match is found, all other functions are ignored, and
7057 // the exact match is used. If no exact match is found, then the implicit
7058 // conversions in section 4.1.10 Implicit Conversions will be applied to find
7059 // a match. Mismatched types on input parameters (in or inout or default) must
7060 // have a conversion from the calling argument type to the formal parameter type.
7061 // Mismatched types on output parameters (out or inout) must have a conversion
7062 // from the formal parameter type to the calling argument type.
7063 //
7064 // "If implicit conversions can be used to find more than one matching function,
7065 // a single best-matching function is sought. To determine a best match, the
7066 // conversions between calling argument and formal parameter types are compared
7067 // for each function argument and pair of matching functions. After these
7068 // comparisons are performed, each pair of matching functions are compared.
7069 // A function declaration A is considered a better match than function
7070 // declaration B if
7071 //
7072 //  * for at least one function argument, the conversion for that argument in A
7073 //    is better than the corresponding conversion in B; and
7074 //  * there is no function argument for which the conversion in B is better than
7075 //    the corresponding conversion in A.
7076 //
7077 // "If a single function declaration is considered a better match than every
7078 // other matching function declaration, it will be used. Otherwise, a
7079 // compile-time semantic error for an ambiguous overloaded function call occurs.
7080 //
7081 // "To determine whether the conversion for a single argument in one match is
7082 // better than that for another match, the following rules are applied, in order:
7083 //
7084 //  1. An exact match is better than a match involving any implicit conversion.
7085 //  2. A match involving an implicit conversion from float to double is better
7086 //     than a match involving any other implicit conversion.
7087 //  3. A match involving an implicit conversion from either int or uint to float
7088 //     is better than a match involving an implicit conversion from either int
7089 //     or uint to double.
7090 //
7091 // "If none of the rules above apply to a particular pair of conversions, neither
7092 // conversion is considered better than the other."
7093 //
findFunction400(const TSourceLoc & loc,const TFunction & call,bool & builtIn)7094 const TFunction* TParseContext::findFunction400(const TSourceLoc& loc, const TFunction& call, bool& builtIn)
7095 {
7096     // first, look for an exact match
7097     TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn);
7098     if (symbol)
7099         return symbol->getAsFunction();
7100 
7101     // no exact match, use the generic selector, parameterized by the GLSL rules
7102 
7103     // create list of candidates to send
7104     TVector<const TFunction*> candidateList;
7105     symbolTable.findFunctionNameList(call.getMangledName(), candidateList, builtIn);
7106 
7107     // can 'from' convert to 'to'?
7108     const auto convertible = [this,builtIn](const TType& from, const TType& to, TOperator, int) -> bool {
7109         if (from == to)
7110             return true;
7111         if (from.coopMatParameterOK(to))
7112             return true;
7113         // Allow a sized array to be passed through an unsized array parameter, for coopMatLoad/Store functions
7114         if (builtIn && from.isArray() && to.isUnsizedArray()) {
7115             TType fromElementType(from, 0);
7116             TType toElementType(to, 0);
7117             if (fromElementType == toElementType)
7118                 return true;
7119         }
7120         if (from.isArray() || to.isArray() || ! from.sameElementShape(to))
7121             return false;
7122         if (from.isCoopMat() && to.isCoopMat())
7123             return from.sameCoopMatBaseType(to);
7124         return intermediate.canImplicitlyPromote(from.getBasicType(), to.getBasicType());
7125     };
7126 
7127     // Is 'to2' a better conversion than 'to1'?
7128     // Ties should not be considered as better.
7129     // Assumes 'convertible' already said true.
7130     const auto better = [](const TType& from, const TType& to1, const TType& to2) -> bool {
7131         // 1. exact match
7132         if (from == to2)
7133             return from != to1;
7134         if (from == to1)
7135             return false;
7136 
7137         // 2. float -> double is better
7138         if (from.getBasicType() == EbtFloat) {
7139             if (to2.getBasicType() == EbtDouble && to1.getBasicType() != EbtDouble)
7140                 return true;
7141         }
7142 
7143         // 3. -> float is better than -> double
7144         return to2.getBasicType() == EbtFloat && to1.getBasicType() == EbtDouble;
7145     };
7146 
7147     // for ambiguity reporting
7148     bool tie = false;
7149 
7150     // send to the generic selector
7151     const TFunction* bestMatch = selectFunction(candidateList, call, convertible, better, tie);
7152 
7153     if (bestMatch == nullptr)
7154         error(loc, "no matching overloaded function found", call.getName().c_str(), "");
7155     else if (tie)
7156         error(loc, "ambiguous best function under implicit type conversion", call.getName().c_str(), "");
7157 
7158     return bestMatch;
7159 }
7160 
7161 // "To determine whether the conversion for a single argument in one match
7162 //  is better than that for another match, the conversion is assigned of the
7163 //  three ranks ordered from best to worst:
7164 //   1. Exact match: no conversion.
7165 //    2. Promotion: integral or floating-point promotion.
7166 //    3. Conversion: integral conversion, floating-point conversion,
7167 //       floating-integral conversion.
7168 //  A conversion C1 is better than a conversion C2 if the rank of C1 is
7169 //  better than the rank of C2."
findFunctionExplicitTypes(const TSourceLoc & loc,const TFunction & call,bool & builtIn)7170 const TFunction* TParseContext::findFunctionExplicitTypes(const TSourceLoc& loc, const TFunction& call, bool& builtIn)
7171 {
7172     // first, look for an exact match
7173     TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn);
7174     if (symbol)
7175         return symbol->getAsFunction();
7176 
7177     // no exact match, use the generic selector, parameterized by the GLSL rules
7178 
7179     // create list of candidates to send
7180     TVector<const TFunction*> candidateList;
7181     symbolTable.findFunctionNameList(call.getMangledName(), candidateList, builtIn);
7182 
7183     // can 'from' convert to 'to'?
7184     const auto convertible = [this,builtIn](const TType& from, const TType& to, TOperator, int) -> bool {
7185         if (from == to)
7186             return true;
7187         if (from.coopMatParameterOK(to))
7188             return true;
7189         // Allow a sized array to be passed through an unsized array parameter, for coopMatLoad/Store functions
7190         if (builtIn && from.isArray() && to.isUnsizedArray()) {
7191             TType fromElementType(from, 0);
7192             TType toElementType(to, 0);
7193             if (fromElementType == toElementType)
7194                 return true;
7195         }
7196         if (from.isArray() || to.isArray() || ! from.sameElementShape(to))
7197             return false;
7198         if (from.isCoopMat() && to.isCoopMat())
7199             return from.sameCoopMatBaseType(to);
7200         return intermediate.canImplicitlyPromote(from.getBasicType(), to.getBasicType());
7201     };
7202 
7203     // Is 'to2' a better conversion than 'to1'?
7204     // Ties should not be considered as better.
7205     // Assumes 'convertible' already said true.
7206     const auto better = [this](const TType& from, const TType& to1, const TType& to2) -> bool {
7207         // 1. exact match
7208         if (from == to2)
7209             return from != to1;
7210         if (from == to1)
7211             return false;
7212 
7213         // 2. Promotion (integral, floating-point) is better
7214         TBasicType from_type = from.getBasicType();
7215         TBasicType to1_type = to1.getBasicType();
7216         TBasicType to2_type = to2.getBasicType();
7217         bool isPromotion1 = (intermediate.isIntegralPromotion(from_type, to1_type) ||
7218                              intermediate.isFPPromotion(from_type, to1_type));
7219         bool isPromotion2 = (intermediate.isIntegralPromotion(from_type, to2_type) ||
7220                              intermediate.isFPPromotion(from_type, to2_type));
7221         if (isPromotion2)
7222             return !isPromotion1;
7223         if(isPromotion1)
7224             return false;
7225 
7226         // 3. Conversion (integral, floating-point , floating-integral)
7227         bool isConversion1 = (intermediate.isIntegralConversion(from_type, to1_type) ||
7228                               intermediate.isFPConversion(from_type, to1_type) ||
7229                               intermediate.isFPIntegralConversion(from_type, to1_type));
7230         bool isConversion2 = (intermediate.isIntegralConversion(from_type, to2_type) ||
7231                               intermediate.isFPConversion(from_type, to2_type) ||
7232                               intermediate.isFPIntegralConversion(from_type, to2_type));
7233 
7234         return isConversion2 && !isConversion1;
7235     };
7236 
7237     // for ambiguity reporting
7238     bool tie = false;
7239 
7240     // send to the generic selector
7241     const TFunction* bestMatch = selectFunction(candidateList, call, convertible, better, tie);
7242 
7243     if (bestMatch == nullptr)
7244         error(loc, "no matching overloaded function found", call.getName().c_str(), "");
7245     else if (tie)
7246         error(loc, "ambiguous best function under implicit type conversion", call.getName().c_str(), "");
7247 
7248     return bestMatch;
7249 }
7250 
7251 //
7252 // Adjust function calls that aren't declared in Vulkan to a
7253 // calls with equivalent effects
7254 //
vkRelaxedRemapFunctionCall(const TSourceLoc & loc,TFunction * function,TIntermNode * arguments)7255 TIntermTyped* TParseContext::vkRelaxedRemapFunctionCall(const TSourceLoc& loc, TFunction* function, TIntermNode* arguments)
7256 {
7257     TIntermTyped* result = nullptr;
7258 
7259     if (function->getBuiltInOp() != EOpNull) {
7260         return nullptr;
7261     }
7262 
7263     if (function->getName() == "atomicCounterIncrement") {
7264         // change atomicCounterIncrement into an atomicAdd of 1
7265         TString name("atomicAdd");
7266         TType uintType(EbtUint);
7267 
7268         TFunction realFunc(&name, function->getType());
7269 
7270         // Use copyParam to avoid shared ownership of the 'type' field
7271         // of the parameter.
7272         for (int i = 0; i < function->getParamCount(); ++i) {
7273             realFunc.addParameter(TParameter().copyParam((*function)[i]));
7274         }
7275 
7276         TParameter tmpP = { nullptr, &uintType };
7277         realFunc.addParameter(TParameter().copyParam(tmpP));
7278         arguments = intermediate.growAggregate(arguments, intermediate.addConstantUnion(1, loc, true));
7279 
7280         result = handleFunctionCall(loc, &realFunc, arguments);
7281     } else if (function->getName() == "atomicCounterDecrement") {
7282         // change atomicCounterDecrement into an atomicAdd with -1
7283         // and subtract 1 from result, to return post-decrement value
7284         TString name("atomicAdd");
7285         TType uintType(EbtUint);
7286 
7287         TFunction realFunc(&name, function->getType());
7288 
7289         for (int i = 0; i < function->getParamCount(); ++i) {
7290             realFunc.addParameter(TParameter().copyParam((*function)[i]));
7291         }
7292 
7293         TParameter tmpP = { nullptr, &uintType };
7294         realFunc.addParameter(TParameter().copyParam(tmpP));
7295         arguments = intermediate.growAggregate(arguments, intermediate.addConstantUnion(-1, loc, true));
7296 
7297         result = handleFunctionCall(loc, &realFunc, arguments);
7298 
7299         // post decrement, so that it matches AtomicCounterDecrement semantics
7300         if (result) {
7301             result = handleBinaryMath(loc, "-", EOpSub, result, intermediate.addConstantUnion(1, loc, true));
7302         }
7303     } else if (function->getName() == "atomicCounter") {
7304         // change atomicCounter into a direct read of the variable
7305         if (arguments->getAsTyped()) {
7306             result = arguments->getAsTyped();
7307         }
7308     }
7309 
7310     return result;
7311 }
7312 
7313 // When a declaration includes a type, but not a variable name, it can be used
7314 // to establish defaults.
declareTypeDefaults(const TSourceLoc & loc,const TPublicType & publicType)7315 void TParseContext::declareTypeDefaults(const TSourceLoc& loc, const TPublicType& publicType)
7316 {
7317     if (publicType.basicType == EbtAtomicUint && publicType.qualifier.hasBinding()) {
7318         if (publicType.qualifier.layoutBinding >= (unsigned int)resources.maxAtomicCounterBindings) {
7319             error(loc, "atomic_uint binding is too large", "binding", "");
7320             return;
7321         }
7322         if (publicType.qualifier.hasOffset())
7323             atomicUintOffsets[publicType.qualifier.layoutBinding] = publicType.qualifier.layoutOffset;
7324         return;
7325     }
7326 
7327     if (publicType.arraySizes) {
7328         error(loc, "expect an array name", "", "");
7329     }
7330 
7331     if (publicType.qualifier.hasLayout() && !publicType.qualifier.hasBufferReference())
7332         warn(loc, "useless application of layout qualifier", "layout", "");
7333 }
7334 
coopMatTypeParametersCheck(const TSourceLoc & loc,const TPublicType & publicType)7335 void TParseContext::coopMatTypeParametersCheck(const TSourceLoc& loc, const TPublicType& publicType)
7336 {
7337     if (parsingBuiltins)
7338         return;
7339     if (publicType.isCoopmatKHR()) {
7340         if (publicType.typeParameters == nullptr) {
7341             error(loc, "coopmat missing type parameters", "", "");
7342             return;
7343         }
7344         switch (publicType.typeParameters->basicType) {
7345         case EbtFloat:
7346         case EbtFloat16:
7347         case EbtInt:
7348         case EbtInt8:
7349         case EbtInt16:
7350         case EbtUint:
7351         case EbtUint8:
7352         case EbtUint16:
7353             break;
7354         default:
7355             error(loc, "coopmat invalid basic type", TType::getBasicString(publicType.typeParameters->basicType), "");
7356             break;
7357         }
7358         if (publicType.typeParameters->arraySizes->getNumDims() != 4) {
7359             error(loc, "coopmat incorrect number of type parameters", "", "");
7360             return;
7361         }
7362         int use = publicType.typeParameters->arraySizes->getDimSize(3);
7363         if (use < 0 || use > 2) {
7364             error(loc, "coopmat invalid matrix Use", "", "");
7365             return;
7366         }
7367     }
7368 }
7369 
vkRelaxedRemapUniformVariable(const TSourceLoc & loc,TString & identifier,const TPublicType & publicType,TArraySizes *,TIntermTyped * initializer,TType & type)7370 bool TParseContext::vkRelaxedRemapUniformVariable(const TSourceLoc& loc, TString& identifier, const TPublicType& publicType,
7371     TArraySizes*, TIntermTyped* initializer, TType& type)
7372 {
7373     vkRelaxedRemapUniformMembers(loc, publicType, type, identifier);
7374 
7375     if (parsingBuiltins || symbolTable.atBuiltInLevel() || !symbolTable.atGlobalLevel() ||
7376         type.getQualifier().storage != EvqUniform ||
7377         !(type.containsNonOpaque() || type.getBasicType() == EbtAtomicUint || (type.containsSampler() && type.isStruct()))) {
7378         return false;
7379     }
7380 
7381     if (type.getQualifier().hasLocation()) {
7382         warn(loc, "ignoring layout qualifier for uniform", identifier.c_str(), "location");
7383         type.getQualifier().layoutLocation = TQualifier::layoutLocationEnd;
7384     }
7385 
7386     if (initializer) {
7387         warn(loc, "Ignoring initializer for uniform", identifier.c_str(), "");
7388         initializer = nullptr;
7389     }
7390 
7391     if (type.isArray()) {
7392         // do array size checks here
7393         arraySizesCheck(loc, type.getQualifier(), type.getArraySizes(), initializer, false);
7394 
7395         if (arrayQualifierError(loc, type.getQualifier()) || arrayError(loc, type)) {
7396             error(loc, "array param error", identifier.c_str(), "");
7397         }
7398     }
7399 
7400     // do some checking on the type as it was declared
7401     layoutTypeCheck(loc, type);
7402 
7403     int bufferBinding = TQualifier::layoutBindingEnd;
7404     TVariable* updatedBlock = nullptr;
7405 
7406     // Convert atomic_uint into members of a buffer block
7407     if (type.isAtomic()) {
7408         type.setBasicType(EbtUint);
7409         type.getQualifier().storage = EvqBuffer;
7410 
7411         type.getQualifier().volatil = true;
7412         type.getQualifier().coherent = true;
7413 
7414         // xxTODO: use logic from fixOffset() to apply explicit member offset
7415         bufferBinding = type.getQualifier().layoutBinding;
7416         type.getQualifier().layoutBinding = TQualifier::layoutBindingEnd;
7417         type.getQualifier().explicitOffset = false;
7418         growAtomicCounterBlock(bufferBinding, loc, type, identifier, nullptr);
7419         updatedBlock = atomicCounterBuffers[bufferBinding];
7420     }
7421 
7422     if (!updatedBlock) {
7423         growGlobalUniformBlock(loc, type, identifier, nullptr);
7424         updatedBlock = globalUniformBlock;
7425     }
7426 
7427     //
7428     //      don't assign explicit member offsets here
7429     //      if any are assigned, need to be updated here and in the merge/link step
7430     // fixBlockUniformOffsets(updatedBlock->getWritableType().getQualifier(), *updatedBlock->getWritableType().getWritableStruct());
7431 
7432     // checks on update buffer object
7433     layoutObjectCheck(loc, *updatedBlock);
7434 
7435     TSymbol* symbol = symbolTable.find(identifier);
7436 
7437     if (!symbol) {
7438         if (updatedBlock == globalUniformBlock)
7439             error(loc, "error adding uniform to default uniform block", identifier.c_str(), "");
7440         else
7441             error(loc, "error adding atomic counter to atomic counter block", identifier.c_str(), "");
7442         return false;
7443     }
7444 
7445     // merge qualifiers
7446     mergeObjectLayoutQualifiers(updatedBlock->getWritableType().getQualifier(), type.getQualifier(), true);
7447 
7448     return true;
7449 }
7450 
7451 template <typename Function>
ForEachOpaque(const TType & type,const TString & path,Function callback)7452 static void ForEachOpaque(const TType& type, const TString& path, Function callback)
7453 {
7454     auto recursion = [&callback](const TType& type, const TString& path, bool skipArray, auto& recursion) -> void {
7455         if (!skipArray && type.isArray())
7456         {
7457             std::vector<int> indices(type.getArraySizes()->getNumDims());
7458             for (int flatIndex = 0;
7459                  flatIndex < type.getArraySizes()->getCumulativeSize();
7460                  ++flatIndex)
7461             {
7462                 TString subscriptPath = path;
7463                 for (size_t dimIndex = 0; dimIndex < indices.size(); ++dimIndex)
7464                 {
7465                     int index = indices[dimIndex];
7466                     subscriptPath.append("[");
7467                     subscriptPath.append(String(index));
7468                     subscriptPath.append("]");
7469                 }
7470 
7471                 recursion(type, subscriptPath, true, recursion);
7472 
7473                 for (size_t dimIndex = 0; dimIndex < indices.size(); ++dimIndex)
7474                 {
7475                     ++indices[dimIndex];
7476                     if (indices[dimIndex] < type.getArraySizes()->getDimSize(dimIndex))
7477                         break;
7478                     else
7479                         indices[dimIndex] = 0;
7480                 }
7481             }
7482         }
7483 
7484         else if (type.isStruct() && type.containsOpaque())
7485         {
7486             const TTypeList& types = *type.getStruct();
7487             for (const TTypeLoc& typeLoc : types)
7488             {
7489                 TString nextPath = path;
7490                 nextPath.append(".");
7491                 nextPath.append(typeLoc.type->getFieldName());
7492 
7493                 recursion(*(typeLoc.type), nextPath, false, recursion);
7494             }
7495         }
7496 
7497         else if (type.isOpaque())
7498         {
7499             callback(type, path);
7500         }
7501     };
7502 
7503     recursion(type, path, false, recursion);
7504 }
7505 
vkRelaxedRemapUniformMembers(const TSourceLoc & loc,const TPublicType & publicType,const TType & type,const TString & identifier)7506 void TParseContext::vkRelaxedRemapUniformMembers(const TSourceLoc& loc, const TPublicType& publicType, const TType& type,
7507     const TString& identifier)
7508 {
7509     if (!type.isStruct() || !type.containsOpaque())
7510         return;
7511 
7512     ForEachOpaque(type, identifier,
7513                   [&publicType, &loc, this](const TType& type, const TString& path) {
7514                       TArraySizes arraySizes = {};
7515                       if (type.getArraySizes()) arraySizes = *type.getArraySizes();
7516                       TTypeParameters typeParameters = {};
7517                       if (type.getTypeParameters()) typeParameters = *type.getTypeParameters();
7518 
7519                       TPublicType memberType{};
7520                       memberType.basicType = type.getBasicType();
7521                       memberType.sampler = type.getSampler();
7522                       memberType.qualifier = type.getQualifier();
7523                       memberType.vectorSize = type.getVectorSize();
7524                       memberType.matrixCols = type.getMatrixCols();
7525                       memberType.matrixRows = type.getMatrixRows();
7526                       memberType.coopmatNV = type.isCoopMatNV();
7527                       memberType.coopmatKHR = type.isCoopMatKHR();
7528                       memberType.arraySizes = nullptr;
7529                       memberType.userDef = nullptr;
7530                       memberType.loc = loc;
7531                       memberType.typeParameters = (type.getTypeParameters() ? &typeParameters : nullptr);
7532                       memberType.spirvType = nullptr;
7533 
7534                       memberType.qualifier.storage = publicType.qualifier.storage;
7535                       memberType.shaderQualifiers = publicType.shaderQualifiers;
7536 
7537                       TString& structMemberName = *NewPoolTString(path.c_str()); // A copy is required due to declareVariable() signature.
7538                       declareVariable(loc, structMemberName, memberType, nullptr, nullptr);
7539                   });
7540 }
7541 
vkRelaxedRemapFunctionParameter(TFunction * function,TParameter & param,std::vector<int> * newParams)7542 void TParseContext::vkRelaxedRemapFunctionParameter(TFunction* function, TParameter& param, std::vector<int>* newParams)
7543 {
7544     function->addParameter(param);
7545 
7546     if (!param.type->isStruct() || !param.type->containsOpaque())
7547         return;
7548 
7549     ForEachOpaque(*param.type, (param.name ? *param.name : param.type->getFieldName()),
7550                   [function, param, newParams](const TType& type, const TString& path) {
7551                       TString* memberName = NewPoolTString(path.c_str());
7552 
7553                       TType* memberType = new TType();
7554                       memberType->shallowCopy(type);
7555                       memberType->getQualifier().storage = param.type->getQualifier().storage;
7556                       memberType->clearArraySizes();
7557 
7558                       TParameter memberParam = {};
7559                       memberParam.name = memberName;
7560                       memberParam.type = memberType;
7561                       memberParam.defaultValue = nullptr;
7562                       function->addParameter(memberParam);
7563                       if (newParams)
7564                           newParams->push_back(function->getParamCount()-1);
7565                   });
7566 }
7567 
7568 //
7569 // Generates a valid GLSL dereferencing string for the input TIntermNode
7570 //
7571 struct AccessChainTraverser : public TIntermTraverser {
AccessChainTraverserglslang::AccessChainTraverser7572     AccessChainTraverser() : TIntermTraverser(false, false, true)
7573     {}
7574 
7575     TString path = "";
7576 
visitBinaryglslang::AccessChainTraverser7577     bool visitBinary(TVisit, TIntermBinary* binary) override {
7578         if (binary->getOp() == EOpIndexDirectStruct)
7579         {
7580             const TTypeList& members = *binary->getLeft()->getType().getStruct();
7581             const TTypeLoc& member =
7582                 members[binary->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst()];
7583             TString memberName = member.type->getFieldName();
7584 
7585             if (path != "")
7586                 path.append(".");
7587 
7588             path.append(memberName);
7589         }
7590 
7591         if (binary->getOp() == EOpIndexDirect)
7592         {
7593             const TConstUnionArray& indices = binary->getRight()->getAsConstantUnion()->getConstArray();
7594             for (int index = 0; index < indices.size(); ++index)
7595             {
7596                 path.append("[");
7597                 path.append(String(indices[index].getIConst()));
7598                 path.append("]");
7599             }
7600         }
7601 
7602         return true;
7603     }
7604 
visitSymbolglslang::AccessChainTraverser7605     void visitSymbol(TIntermSymbol* symbol) override {
7606         if (!IsAnonymous(symbol->getName()))
7607             path.append(symbol->getName());
7608     }
7609 };
7610 
vkRelaxedRemapFunctionArgument(const TSourceLoc & loc,TFunction * function,TIntermTyped * intermTyped)7611 TIntermNode* TParseContext::vkRelaxedRemapFunctionArgument(const TSourceLoc& loc, TFunction* function, TIntermTyped* intermTyped)
7612 {
7613     AccessChainTraverser accessChainTraverser{};
7614     intermTyped->traverse(&accessChainTraverser);
7615 
7616     TParameter param = { NewPoolTString(accessChainTraverser.path.c_str()), new TType };
7617     param.type->shallowCopy(intermTyped->getType());
7618 
7619     std::vector<int> newParams = {};
7620     vkRelaxedRemapFunctionParameter(function, param, &newParams);
7621 
7622     if (intermTyped->getType().isOpaque())
7623     {
7624         TIntermNode* remappedArgument = intermTyped;
7625         {
7626             TIntermSymbol* intermSymbol = nullptr;
7627             TSymbol* symbol = symbolTable.find(*param.name);
7628             if (symbol && symbol->getAsVariable())
7629                 intermSymbol = intermediate.addSymbol(*symbol->getAsVariable(), loc);
7630             else
7631             {
7632                 TVariable* variable = new TVariable(param.name, *param.type);
7633                 intermSymbol = intermediate.addSymbol(*variable, loc);
7634             }
7635 
7636             remappedArgument = intermSymbol;
7637         }
7638 
7639         return remappedArgument;
7640     }
7641     else if (!(intermTyped->isStruct() && intermTyped->getType().containsOpaque()))
7642         return intermTyped;
7643     else
7644     {
7645         TIntermNode* remappedArgument = intermTyped;
7646         {
7647             TSymbol* symbol = symbolTable.find(*param.name);
7648             if (symbol && symbol->getAsVariable())
7649                 remappedArgument = intermediate.addSymbol(*symbol->getAsVariable(), loc);
7650         }
7651 
7652         if (!newParams.empty())
7653             remappedArgument = intermediate.makeAggregate(remappedArgument, loc);
7654 
7655         for (int paramIndex : newParams)
7656         {
7657             TParameter& newParam = function->operator[](paramIndex);
7658             TIntermSymbol* intermSymbol = nullptr;
7659             TSymbol* symbol = symbolTable.find(*newParam.name);
7660             if (symbol && symbol->getAsVariable())
7661                 intermSymbol = intermediate.addSymbol(*symbol->getAsVariable(), loc);
7662             else
7663             {
7664                 TVariable* variable = new TVariable(newParam.name, *newParam.type);
7665                 intermSymbol = intermediate.addSymbol(*variable, loc);
7666             }
7667 
7668             remappedArgument = intermediate.growAggregate(remappedArgument, intermSymbol);
7669         }
7670 
7671         return remappedArgument;
7672     }
7673 }
7674 
vkRelaxedRemapDotDereference(const TSourceLoc &,TIntermTyped & base,const TType & member,const TString & identifier)7675 TIntermTyped* TParseContext::vkRelaxedRemapDotDereference(const TSourceLoc&, TIntermTyped& base, const TType& member,
7676     const TString& identifier)
7677 {
7678     if (!member.isOpaque())
7679         return &base;
7680 
7681     AccessChainTraverser traverser{};
7682     base.traverse(&traverser);
7683     if (!traverser.path.empty())
7684         traverser.path.append(".");
7685     traverser.path.append(identifier);
7686 
7687     const TSymbol* symbol = symbolTable.find(traverser.path);
7688     if (!symbol)
7689         return &base;
7690 
7691     TIntermTyped* result = intermediate.addSymbol(*symbol->getAsVariable());
7692     result->setType(symbol->getType());
7693     return result;
7694 }
7695 
7696 //
7697 // Do everything necessary to handle a variable (non-block) declaration.
7698 // Either redeclaring a variable, or making a new one, updating the symbol
7699 // table, and all error checking.
7700 //
7701 // Returns a subtree node that computes an initializer, if needed.
7702 // Returns nullptr if there is no code to execute for initialization.
7703 //
7704 // 'publicType' is the type part of the declaration (to the left)
7705 // 'arraySizes' is the arrayness tagged on the identifier (to the right)
7706 //
declareVariable(const TSourceLoc & loc,TString & identifier,const TPublicType & publicType,TArraySizes * arraySizes,TIntermTyped * initializer)7707 TIntermNode* TParseContext::declareVariable(const TSourceLoc& loc, TString& identifier, const TPublicType& publicType,
7708     TArraySizes* arraySizes, TIntermTyped* initializer)
7709 {
7710     // Make a fresh type that combines the characteristics from the individual
7711     // identifier syntax and the declaration-type syntax.
7712     TType type(publicType);
7713     type.transferArraySizes(arraySizes);
7714     type.copyArrayInnerSizes(publicType.arraySizes);
7715     arrayOfArrayVersionCheck(loc, type.getArraySizes());
7716 
7717     if (initializer) {
7718         if (type.getBasicType() == EbtRayQuery) {
7719             error(loc, "ray queries can only be initialized by using the rayQueryInitializeEXT intrinsic:", "=", identifier.c_str());
7720         } else if (type.getBasicType() == EbtHitObjectNV) {
7721             error(loc, "hit objects cannot be initialized using initializers", "=", identifier.c_str());
7722         }
7723 
7724     }
7725 
7726     if (type.isCoopMatKHR()) {
7727         intermediate.setUseVulkanMemoryModel();
7728         intermediate.setUseStorageBuffer();
7729 
7730         if (!publicType.typeParameters || !publicType.typeParameters->arraySizes ||
7731             publicType.typeParameters->arraySizes->getNumDims() != 3) {
7732             error(loc, "unexpected number type parameters", identifier.c_str(), "");
7733         }
7734         if (publicType.typeParameters) {
7735             if (!isTypeFloat(publicType.typeParameters->basicType) && !isTypeInt(publicType.typeParameters->basicType)) {
7736                 error(loc, "expected 8, 16, 32, or 64 bit signed or unsigned integer or 16, 32, or 64 bit float type", identifier.c_str(), "");
7737             }
7738         }
7739     }
7740     else if (type.isCoopMatNV()) {
7741         intermediate.setUseVulkanMemoryModel();
7742         intermediate.setUseStorageBuffer();
7743 
7744         if (!publicType.typeParameters || publicType.typeParameters->arraySizes->getNumDims() != 4) {
7745             error(loc, "expected four type parameters", identifier.c_str(), "");
7746         }
7747         if (publicType.typeParameters) {
7748             if (isTypeFloat(publicType.basicType) &&
7749                 publicType.typeParameters->arraySizes->getDimSize(0) != 16 &&
7750                 publicType.typeParameters->arraySizes->getDimSize(0) != 32 &&
7751                 publicType.typeParameters->arraySizes->getDimSize(0) != 64) {
7752                 error(loc, "expected 16, 32, or 64 bits for first type parameter", identifier.c_str(), "");
7753             }
7754             if (isTypeInt(publicType.basicType) &&
7755                 publicType.typeParameters->arraySizes->getDimSize(0) != 8 &&
7756                 publicType.typeParameters->arraySizes->getDimSize(0) != 16 &&
7757                 publicType.typeParameters->arraySizes->getDimSize(0) != 32) {
7758                 error(loc, "expected 8, 16, or 32 bits for first type parameter", identifier.c_str(), "");
7759             }
7760         }
7761     } else {
7762         if (publicType.typeParameters && publicType.typeParameters->arraySizes->getNumDims() != 0) {
7763             error(loc, "unexpected type parameters", identifier.c_str(), "");
7764         }
7765     }
7766 
7767     if (voidErrorCheck(loc, identifier, type.getBasicType()))
7768         return nullptr;
7769 
7770     if (initializer)
7771         rValueErrorCheck(loc, "initializer", initializer);
7772     else
7773         nonInitConstCheck(loc, identifier, type);
7774 
7775     samplerCheck(loc, type, identifier, initializer);
7776     transparentOpaqueCheck(loc, type, identifier);
7777     atomicUintCheck(loc, type, identifier);
7778     accStructCheck(loc, type, identifier);
7779     checkAndResizeMeshViewDim(loc, type, /*isBlockMember*/ false);
7780     if (type.getQualifier().storage == EvqConst && type.containsReference()) {
7781         error(loc, "variables with reference type can't have qualifier 'const'", "qualifier", "");
7782     }
7783 
7784     if (type.getQualifier().storage != EvqUniform && type.getQualifier().storage != EvqBuffer) {
7785         if (type.contains16BitFloat())
7786             requireFloat16Arithmetic(loc, "qualifier", "float16 types can only be in uniform block or buffer storage");
7787         if (type.contains16BitInt())
7788             requireInt16Arithmetic(loc, "qualifier", "(u)int16 types can only be in uniform block or buffer storage");
7789         if (type.contains8BitInt())
7790             requireInt8Arithmetic(loc, "qualifier", "(u)int8 types can only be in uniform block or buffer storage");
7791     }
7792 
7793     if (type.getQualifier().storage == EvqtaskPayloadSharedEXT)
7794         intermediate.addTaskPayloadEXTCount();
7795     if (type.getQualifier().storage == EvqShared && type.containsCoopMat())
7796         error(loc, "qualifier", "Cooperative matrix types must not be used in shared memory", "");
7797 
7798     if (profile == EEsProfile) {
7799         if (type.getQualifier().isPipeInput() && type.getBasicType() == EbtStruct) {
7800             if (type.getQualifier().isArrayedIo(language)) {
7801                 TType perVertexType(type, 0);
7802                 if (perVertexType.containsArray() && perVertexType.containsBuiltIn() == false) {
7803                     error(loc, "A per vertex structure containing an array is not allowed as input in ES", type.getTypeName().c_str(), "");
7804                 }
7805             }
7806             else if (type.containsArray() && type.containsBuiltIn() == false) {
7807                 error(loc, "A structure containing an array is not allowed as input in ES", type.getTypeName().c_str(), "");
7808             }
7809             if (type.containsStructure())
7810                 error(loc, "A structure containing an struct is not allowed as input in ES", type.getTypeName().c_str(), "");
7811         }
7812     }
7813 
7814     if (identifier != "gl_FragCoord" && (publicType.shaderQualifiers.originUpperLeft || publicType.shaderQualifiers.pixelCenterInteger))
7815         error(loc, "can only apply origin_upper_left and pixel_center_origin to gl_FragCoord", "layout qualifier", "");
7816     if (identifier != "gl_FragDepth" && publicType.shaderQualifiers.getDepth() != EldNone)
7817         error(loc, "can only apply depth layout to gl_FragDepth", "layout qualifier", "");
7818     if (identifier != "gl_FragStencilRefARB" && publicType.shaderQualifiers.getStencil() != ElsNone)
7819         error(loc, "can only apply depth layout to gl_FragStencilRefARB", "layout qualifier", "");
7820 
7821     // Check for redeclaration of built-ins and/or attempting to declare a reserved name
7822     TSymbol* symbol = redeclareBuiltinVariable(loc, identifier, type.getQualifier(), publicType.shaderQualifiers);
7823     if (symbol == nullptr)
7824         reservedErrorCheck(loc, identifier);
7825 
7826     if (symbol == nullptr && spvVersion.vulkan > 0 && spvVersion.vulkanRelaxed) {
7827         bool remapped = vkRelaxedRemapUniformVariable(loc, identifier, publicType, arraySizes, initializer, type);
7828 
7829         if (remapped) {
7830             return nullptr;
7831         }
7832     }
7833 
7834     inheritGlobalDefaults(type.getQualifier());
7835 
7836     // Declare the variable
7837     if (type.isArray()) {
7838         // Check that implicit sizing is only where allowed.
7839         arraySizesCheck(loc, type.getQualifier(), type.getArraySizes(), initializer, false);
7840 
7841         if (! arrayQualifierError(loc, type.getQualifier()) && ! arrayError(loc, type))
7842             declareArray(loc, identifier, type, symbol);
7843 
7844         if (initializer) {
7845             profileRequires(loc, ENoProfile, 120, E_GL_3DL_array_objects, "initializer");
7846             profileRequires(loc, EEsProfile, 300, nullptr, "initializer");
7847         }
7848     } else {
7849         // non-array case
7850         if (symbol == nullptr)
7851             symbol = declareNonArray(loc, identifier, type);
7852         else if (type != symbol->getType())
7853             error(loc, "cannot change the type of", "redeclaration", symbol->getName().c_str());
7854     }
7855 
7856     if (symbol == nullptr)
7857         return nullptr;
7858 
7859     // Deal with initializer
7860     TIntermNode* initNode = nullptr;
7861     if (symbol != nullptr && initializer) {
7862         TVariable* variable = symbol->getAsVariable();
7863         if (! variable) {
7864             error(loc, "initializer requires a variable, not a member", identifier.c_str(), "");
7865             return nullptr;
7866         }
7867         initNode = executeInitializer(loc, initializer, variable);
7868     }
7869 
7870     // look for errors in layout qualifier use
7871     layoutObjectCheck(loc, *symbol);
7872 
7873     // fix up
7874     fixOffset(loc, *symbol);
7875 
7876     return initNode;
7877 }
7878 
7879 // Pick up global defaults from the provide global defaults into dst.
inheritGlobalDefaults(TQualifier & dst) const7880 void TParseContext::inheritGlobalDefaults(TQualifier& dst) const
7881 {
7882     if (dst.storage == EvqVaryingOut) {
7883         if (! dst.hasStream() && language == EShLangGeometry)
7884             dst.layoutStream = globalOutputDefaults.layoutStream;
7885         if (! dst.hasXfbBuffer())
7886             dst.layoutXfbBuffer = globalOutputDefaults.layoutXfbBuffer;
7887     }
7888 }
7889 
7890 //
7891 // Make an internal-only variable whose name is for debug purposes only
7892 // and won't be searched for.  Callers will only use the return value to use
7893 // the variable, not the name to look it up.  It is okay if the name
7894 // is the same as other names; there won't be any conflict.
7895 //
makeInternalVariable(const char * name,const TType & type) const7896 TVariable* TParseContext::makeInternalVariable(const char* name, const TType& type) const
7897 {
7898     TString* nameString = NewPoolTString(name);
7899     TVariable* variable = new TVariable(nameString, type);
7900     symbolTable.makeInternalVariable(*variable);
7901 
7902     return variable;
7903 }
7904 
7905 //
7906 // Declare a non-array variable, the main point being there is no redeclaration
7907 // for resizing allowed.
7908 //
7909 // Return the successfully declared variable.
7910 //
declareNonArray(const TSourceLoc & loc,const TString & identifier,const TType & type)7911 TVariable* TParseContext::declareNonArray(const TSourceLoc& loc, const TString& identifier, const TType& type)
7912 {
7913     // make a new variable
7914     TVariable* variable = new TVariable(&identifier, type);
7915 
7916     ioArrayCheck(loc, type, identifier);
7917 
7918     // add variable to symbol table
7919     if (symbolTable.insert(*variable)) {
7920         if (symbolTable.atGlobalLevel())
7921             trackLinkage(*variable);
7922         return variable;
7923     }
7924 
7925     error(loc, "redefinition", variable->getName().c_str(), "");
7926     return nullptr;
7927 }
7928 
7929 //
7930 // Handle all types of initializers from the grammar.
7931 //
7932 // Returning nullptr just means there is no code to execute to handle the
7933 // initializer, which will, for example, be the case for constant initializers.
7934 //
executeInitializer(const TSourceLoc & loc,TIntermTyped * initializer,TVariable * variable)7935 TIntermNode* TParseContext::executeInitializer(const TSourceLoc& loc, TIntermTyped* initializer, TVariable* variable)
7936 {
7937     // A null initializer is an aggregate that hasn't had an op assigned yet
7938     // (still EOpNull, no relation to nullInit), and has no children.
7939     bool nullInit = initializer->getAsAggregate() && initializer->getAsAggregate()->getOp() == EOpNull &&
7940         initializer->getAsAggregate()->getSequence().size() == 0;
7941 
7942     //
7943     // Identifier must be of type constant, a global, or a temporary, and
7944     // starting at version 120, desktop allows uniforms to have initializers.
7945     //
7946     TStorageQualifier qualifier = variable->getType().getQualifier().storage;
7947     if (! (qualifier == EvqTemporary || qualifier == EvqGlobal || qualifier == EvqConst ||
7948            (qualifier == EvqUniform && !isEsProfile() && version >= 120))) {
7949         if (qualifier == EvqShared) {
7950             // GL_EXT_null_initializer allows this for shared, if it's a null initializer
7951             if (nullInit) {
7952                 const char* feature = "initialization with shared qualifier";
7953                 profileRequires(loc, EEsProfile, 0, E_GL_EXT_null_initializer, feature);
7954                 profileRequires(loc, ~EEsProfile, 0, E_GL_EXT_null_initializer, feature);
7955             } else {
7956                 error(loc, "initializer can only be a null initializer ('{}')", "shared", "");
7957             }
7958         } else {
7959             error(loc, " cannot initialize this type of qualifier ",
7960                   variable->getType().getStorageQualifierString(), "");
7961             return nullptr;
7962         }
7963     }
7964 
7965     if (nullInit) {
7966         // only some types can be null initialized
7967         if (variable->getType().containsUnsizedArray()) {
7968             error(loc, "null initializers can't size unsized arrays", "{}", "");
7969             return nullptr;
7970         }
7971         if (variable->getType().containsOpaque()) {
7972             error(loc, "null initializers can't be used on opaque values", "{}", "");
7973             return nullptr;
7974         }
7975         variable->getWritableType().getQualifier().setNullInit();
7976         return nullptr;
7977     }
7978 
7979     arrayObjectCheck(loc, variable->getType(), "array initializer");
7980 
7981     //
7982     // If the initializer was from braces { ... }, we convert the whole subtree to a
7983     // constructor-style subtree, allowing the rest of the code to operate
7984     // identically for both kinds of initializers.
7985     //
7986     // Type can't be deduced from the initializer list, so a skeletal type to
7987     // follow has to be passed in.  Constness and specialization-constness
7988     // should be deduced bottom up, not dictated by the skeletal type.
7989     //
7990     TType skeletalType;
7991     skeletalType.shallowCopy(variable->getType());
7992     skeletalType.getQualifier().makeTemporary();
7993     initializer = convertInitializerList(loc, skeletalType, initializer);
7994     if (! initializer) {
7995         // error recovery; don't leave const without constant values
7996         if (qualifier == EvqConst)
7997             variable->getWritableType().getQualifier().makeTemporary();
7998         return nullptr;
7999     }
8000 
8001     // Fix outer arrayness if variable is unsized, getting size from the initializer
8002     if (initializer->getType().isSizedArray() && variable->getType().isUnsizedArray())
8003         variable->getWritableType().changeOuterArraySize(initializer->getType().getOuterArraySize());
8004 
8005     // Inner arrayness can also get set by an initializer
8006     if (initializer->getType().isArrayOfArrays() && variable->getType().isArrayOfArrays() &&
8007         initializer->getType().getArraySizes()->getNumDims() ==
8008            variable->getType().getArraySizes()->getNumDims()) {
8009         // adopt unsized sizes from the initializer's sizes
8010         for (int d = 1; d < variable->getType().getArraySizes()->getNumDims(); ++d) {
8011             if (variable->getType().getArraySizes()->getDimSize(d) == UnsizedArraySize) {
8012                 variable->getWritableType().getArraySizes()->setDimSize(d,
8013                     initializer->getType().getArraySizes()->getDimSize(d));
8014             }
8015         }
8016     }
8017 
8018     // Uniforms require a compile-time constant initializer
8019     if (qualifier == EvqUniform && ! initializer->getType().getQualifier().isFrontEndConstant()) {
8020         error(loc, "uniform initializers must be constant", "=", "'%s'",
8021               variable->getType().getCompleteString(intermediate.getEnhancedMsgs()).c_str());
8022         variable->getWritableType().getQualifier().makeTemporary();
8023         return nullptr;
8024     }
8025     // Global consts require a constant initializer (specialization constant is okay)
8026     if (qualifier == EvqConst && symbolTable.atGlobalLevel() && ! initializer->getType().getQualifier().isConstant()) {
8027         error(loc, "global const initializers must be constant", "=", "'%s'",
8028               variable->getType().getCompleteString(intermediate.getEnhancedMsgs()).c_str());
8029         variable->getWritableType().getQualifier().makeTemporary();
8030         return nullptr;
8031     }
8032 
8033     // Const variables require a constant initializer, depending on version
8034     if (qualifier == EvqConst) {
8035         if (! initializer->getType().getQualifier().isConstant()) {
8036             const char* initFeature = "non-constant initializer";
8037             requireProfile(loc, ~EEsProfile, initFeature);
8038             profileRequires(loc, ~EEsProfile, 420, E_GL_ARB_shading_language_420pack, initFeature);
8039             variable->getWritableType().getQualifier().storage = EvqConstReadOnly;
8040             qualifier = EvqConstReadOnly;
8041         }
8042     } else {
8043         // Non-const global variables in ES need a const initializer.
8044         //
8045         // "In declarations of global variables with no storage qualifier or with a const
8046         // qualifier any initializer must be a constant expression."
8047         if (symbolTable.atGlobalLevel() && ! initializer->getType().getQualifier().isConstant()) {
8048             const char* initFeature =
8049                 "non-constant global initializer (needs GL_EXT_shader_non_constant_global_initializers)";
8050             if (isEsProfile()) {
8051                 if (relaxedErrors() && ! extensionTurnedOn(E_GL_EXT_shader_non_constant_global_initializers))
8052                     warn(loc, "not allowed in this version", initFeature, "");
8053                 else
8054                     profileRequires(loc, EEsProfile, 0, E_GL_EXT_shader_non_constant_global_initializers, initFeature);
8055             }
8056         }
8057     }
8058 
8059     if (qualifier == EvqConst || qualifier == EvqUniform) {
8060         // Compile-time tagging of the variable with its constant value...
8061 
8062         initializer = intermediate.addConversion(EOpAssign, variable->getType(), initializer);
8063         if (! initializer || ! initializer->getType().getQualifier().isConstant() ||
8064             variable->getType() != initializer->getType()) {
8065             error(loc, "non-matching or non-convertible constant type for const initializer",
8066                   variable->getType().getStorageQualifierString(), "");
8067             variable->getWritableType().getQualifier().makeTemporary();
8068             return nullptr;
8069         }
8070 
8071         // We either have a folded constant in getAsConstantUnion, or we have to use
8072         // the initializer's subtree in the AST to represent the computation of a
8073         // specialization constant.
8074         assert(initializer->getAsConstantUnion() || initializer->getType().getQualifier().isSpecConstant());
8075         if (initializer->getAsConstantUnion())
8076             variable->setConstArray(initializer->getAsConstantUnion()->getConstArray());
8077         else {
8078             // It's a specialization constant.
8079             variable->getWritableType().getQualifier().makeSpecConstant();
8080 
8081             // Keep the subtree that computes the specialization constant with the variable.
8082             // Later, a symbol node will adopt the subtree from the variable.
8083             variable->setConstSubtree(initializer);
8084         }
8085     } else {
8086         // normal assigning of a value to a variable...
8087         specializationCheck(loc, initializer->getType(), "initializer");
8088         TIntermSymbol* intermSymbol = intermediate.addSymbol(*variable, loc);
8089         TIntermTyped* initNode = intermediate.addAssign(EOpAssign, intermSymbol, initializer, loc);
8090         if (! initNode)
8091             assignError(loc, "=", intermSymbol->getCompleteString(intermediate.getEnhancedMsgs()), initializer->getCompleteString(intermediate.getEnhancedMsgs()));
8092 
8093         return initNode;
8094     }
8095 
8096     return nullptr;
8097 }
8098 
8099 //
8100 // Reprocess any initializer-list (the  "{ ... }" syntax) parts of the
8101 // initializer.
8102 //
8103 // Need to hierarchically assign correct types and implicit
8104 // conversions. Will do this mimicking the same process used for
8105 // creating a constructor-style initializer, ensuring we get the
8106 // same form.  However, it has to in parallel walk the 'type'
8107 // passed in, as type cannot be deduced from an initializer list.
8108 //
convertInitializerList(const TSourceLoc & loc,const TType & type,TIntermTyped * initializer)8109 TIntermTyped* TParseContext::convertInitializerList(const TSourceLoc& loc, const TType& type, TIntermTyped* initializer)
8110 {
8111     // Will operate recursively.  Once a subtree is found that is constructor style,
8112     // everything below it is already good: Only the "top part" of the initializer
8113     // can be an initializer list, where "top part" can extend for several (or all) levels.
8114 
8115     // see if we have bottomed out in the tree within the initializer-list part
8116     TIntermAggregate* initList = initializer->getAsAggregate();
8117     if (! initList || initList->getOp() != EOpNull)
8118         return initializer;
8119 
8120     // Of the initializer-list set of nodes, need to process bottom up,
8121     // so recurse deep, then process on the way up.
8122 
8123     // Go down the tree here...
8124     if (type.isArray()) {
8125         // The type's array might be unsized, which could be okay, so base sizes on the size of the aggregate.
8126         // Later on, initializer execution code will deal with array size logic.
8127         TType arrayType;
8128         arrayType.shallowCopy(type);                     // sharing struct stuff is fine
8129         arrayType.copyArraySizes(*type.getArraySizes());  // but get a fresh copy of the array information, to edit below
8130 
8131         // edit array sizes to fill in unsized dimensions
8132         arrayType.changeOuterArraySize((int)initList->getSequence().size());
8133         TIntermTyped* firstInit = initList->getSequence()[0]->getAsTyped();
8134         if (arrayType.isArrayOfArrays() && firstInit->getType().isArray() &&
8135             arrayType.getArraySizes()->getNumDims() == firstInit->getType().getArraySizes()->getNumDims() + 1) {
8136             for (int d = 1; d < arrayType.getArraySizes()->getNumDims(); ++d) {
8137                 if (arrayType.getArraySizes()->getDimSize(d) == UnsizedArraySize)
8138                     arrayType.getArraySizes()->setDimSize(d, firstInit->getType().getArraySizes()->getDimSize(d - 1));
8139             }
8140         }
8141 
8142         TType elementType(arrayType, 0); // dereferenced type
8143         for (size_t i = 0; i < initList->getSequence().size(); ++i) {
8144             initList->getSequence()[i] = convertInitializerList(loc, elementType, initList->getSequence()[i]->getAsTyped());
8145             if (initList->getSequence()[i] == nullptr)
8146                 return nullptr;
8147         }
8148 
8149         return addConstructor(loc, initList, arrayType);
8150     } else if (type.isStruct()) {
8151         if (type.getStruct()->size() != initList->getSequence().size()) {
8152             error(loc, "wrong number of structure members", "initializer list", "");
8153             return nullptr;
8154         }
8155         for (size_t i = 0; i < type.getStruct()->size(); ++i) {
8156             initList->getSequence()[i] = convertInitializerList(loc, *(*type.getStruct())[i].type, initList->getSequence()[i]->getAsTyped());
8157             if (initList->getSequence()[i] == nullptr)
8158                 return nullptr;
8159         }
8160     } else if (type.isMatrix()) {
8161         if (type.getMatrixCols() != (int)initList->getSequence().size()) {
8162             error(loc, "wrong number of matrix columns:", "initializer list", type.getCompleteString(intermediate.getEnhancedMsgs()).c_str());
8163             return nullptr;
8164         }
8165         TType vectorType(type, 0); // dereferenced type
8166         for (int i = 0; i < type.getMatrixCols(); ++i) {
8167             initList->getSequence()[i] = convertInitializerList(loc, vectorType, initList->getSequence()[i]->getAsTyped());
8168             if (initList->getSequence()[i] == nullptr)
8169                 return nullptr;
8170         }
8171     } else if (type.isVector()) {
8172         if (type.getVectorSize() != (int)initList->getSequence().size()) {
8173             error(loc, "wrong vector size (or rows in a matrix column):", "initializer list", type.getCompleteString(intermediate.getEnhancedMsgs()).c_str());
8174             return nullptr;
8175         }
8176         TBasicType destType = type.getBasicType();
8177         for (int i = 0; i < type.getVectorSize(); ++i) {
8178             TBasicType initType = initList->getSequence()[i]->getAsTyped()->getBasicType();
8179             if (destType != initType && !intermediate.canImplicitlyPromote(initType, destType)) {
8180                 error(loc, "type mismatch in initializer list", "initializer list", type.getCompleteString(intermediate.getEnhancedMsgs()).c_str());
8181                 return nullptr;
8182             }
8183 
8184         }
8185     } else {
8186         error(loc, "unexpected initializer-list type:", "initializer list", type.getCompleteString(intermediate.getEnhancedMsgs()).c_str());
8187         return nullptr;
8188     }
8189 
8190     // Now that the subtree is processed, process this node as if the
8191     // initializer list is a set of arguments to a constructor.
8192     TIntermNode* emulatedConstructorArguments;
8193     if (initList->getSequence().size() == 1)
8194         emulatedConstructorArguments = initList->getSequence()[0];
8195     else
8196         emulatedConstructorArguments = initList;
8197     return addConstructor(loc, emulatedConstructorArguments, type);
8198 }
8199 
8200 //
8201 // Test for the correctness of the parameters passed to various constructor functions
8202 // and also convert them to the right data type, if allowed and required.
8203 //
8204 // 'node' is what to construct from.
8205 // 'type' is what type to construct.
8206 //
8207 // Returns nullptr for an error or the constructed node (aggregate or typed) for no error.
8208 //
addConstructor(const TSourceLoc & loc,TIntermNode * node,const TType & type)8209 TIntermTyped* TParseContext::addConstructor(const TSourceLoc& loc, TIntermNode* node, const TType& type)
8210 {
8211     if (node == nullptr || node->getAsTyped() == nullptr)
8212         return nullptr;
8213     rValueErrorCheck(loc, "constructor", node->getAsTyped());
8214 
8215     TIntermAggregate* aggrNode = node->getAsAggregate();
8216     TOperator op = intermediate.mapTypeToConstructorOp(type);
8217 
8218     // Combined texture-sampler constructors are completely semantic checked
8219     // in constructorTextureSamplerError()
8220     if (op == EOpConstructTextureSampler) {
8221         if (aggrNode != nullptr) {
8222             if (aggrNode->getSequence()[1]->getAsTyped()->getType().getSampler().shadow) {
8223                 // Transfer depth into the texture (SPIR-V image) type, as a hint
8224                 // for tools to know this texture/image is a depth image.
8225                 aggrNode->getSequence()[0]->getAsTyped()->getWritableType().getSampler().shadow = true;
8226             }
8227             return intermediate.setAggregateOperator(aggrNode, op, type, loc);
8228         }
8229     }
8230 
8231     TTypeList::const_iterator memberTypes;
8232     if (op == EOpConstructStruct)
8233         memberTypes = type.getStruct()->begin();
8234 
8235     TType elementType;
8236     if (type.isArray()) {
8237         TType dereferenced(type, 0);
8238         elementType.shallowCopy(dereferenced);
8239     } else
8240         elementType.shallowCopy(type);
8241 
8242     bool singleArg;
8243     if (aggrNode) {
8244         if (aggrNode->getOp() != EOpNull)
8245             singleArg = true;
8246         else
8247             singleArg = false;
8248     } else
8249         singleArg = true;
8250 
8251     TIntermTyped *newNode;
8252     if (singleArg) {
8253         // If structure constructor or array constructor is being called
8254         // for only one parameter inside the structure, we need to call constructAggregate function once.
8255         if (type.isArray())
8256             newNode = constructAggregate(node, elementType, 1, node->getLoc());
8257         else if (op == EOpConstructStruct)
8258             newNode = constructAggregate(node, *(*memberTypes).type, 1, node->getLoc());
8259         else
8260             newNode = constructBuiltIn(type, op, node->getAsTyped(), node->getLoc(), false);
8261 
8262         if (newNode && (type.isArray() || op == EOpConstructStruct))
8263             newNode = intermediate.setAggregateOperator(newNode, EOpConstructStruct, type, loc);
8264 
8265         return newNode;
8266     }
8267 
8268     //
8269     // Handle list of arguments.
8270     //
8271     TIntermSequence &sequenceVector = aggrNode->getSequence();    // Stores the information about the parameter to the constructor
8272     // if the structure constructor contains more than one parameter, then construct
8273     // each parameter
8274 
8275     int paramCount = 0;  // keeps track of the constructor parameter number being checked
8276 
8277     // for each parameter to the constructor call, check to see if the right type is passed or convert them
8278     // to the right type if possible (and allowed).
8279     // for structure constructors, just check if the right type is passed, no conversion is allowed.
8280     for (TIntermSequence::iterator p = sequenceVector.begin();
8281                                    p != sequenceVector.end(); p++, paramCount++) {
8282         if (type.isArray())
8283             newNode = constructAggregate(*p, elementType, paramCount+1, node->getLoc());
8284         else if (op == EOpConstructStruct)
8285             newNode = constructAggregate(*p, *(memberTypes[paramCount]).type, paramCount+1, node->getLoc());
8286         else
8287             newNode = constructBuiltIn(type, op, (*p)->getAsTyped(), node->getLoc(), true);
8288 
8289         if (newNode)
8290             *p = newNode;
8291         else
8292             return nullptr;
8293     }
8294 
8295     TIntermTyped *ret_node = intermediate.setAggregateOperator(aggrNode, op, type, loc);
8296 
8297     TIntermAggregate *agg_node = ret_node->getAsAggregate();
8298     if (agg_node && (agg_node->isVector() || agg_node->isArray() || agg_node->isMatrix()))
8299         agg_node->updatePrecision();
8300 
8301     return ret_node;
8302 }
8303 
8304 // Function for constructor implementation. Calls addUnaryMath with appropriate EOp value
8305 // for the parameter to the constructor (passed to this function). Essentially, it converts
8306 // the parameter types correctly. If a constructor expects an int (like ivec2) and is passed a
8307 // float, then float is converted to int.
8308 //
8309 // Returns nullptr for an error or the constructed node.
8310 //
constructBuiltIn(const TType & type,TOperator op,TIntermTyped * node,const TSourceLoc & loc,bool subset)8311 TIntermTyped* TParseContext::constructBuiltIn(const TType& type, TOperator op, TIntermTyped* node, const TSourceLoc& loc,
8312     bool subset)
8313 {
8314     // If we are changing a matrix in both domain of basic type and to a non matrix,
8315     // do the shape change first (by default, below, basic type is changed before shape).
8316     // This avoids requesting a matrix of a new type that is going to be discarded anyway.
8317     // TODO: This could be generalized to more type combinations, but that would require
8318     // more extensive testing and full algorithm rework. For now, the need to do two changes makes
8319     // the recursive call work, and avoids the most egregious case of creating integer matrices.
8320     if (node->getType().isMatrix() && (type.isScalar() || type.isVector()) &&
8321             type.isFloatingDomain() != node->getType().isFloatingDomain()) {
8322         TType transitionType(node->getBasicType(), glslang::EvqTemporary, type.getVectorSize(), 0, 0, node->isVector());
8323         TOperator transitionOp = intermediate.mapTypeToConstructorOp(transitionType);
8324         node = constructBuiltIn(transitionType, transitionOp, node, loc, false);
8325     }
8326 
8327     TIntermTyped* newNode;
8328     TOperator basicOp;
8329 
8330     //
8331     // First, convert types as needed.
8332     //
8333     switch (op) {
8334     case EOpConstructVec2:
8335     case EOpConstructVec3:
8336     case EOpConstructVec4:
8337     case EOpConstructMat2x2:
8338     case EOpConstructMat2x3:
8339     case EOpConstructMat2x4:
8340     case EOpConstructMat3x2:
8341     case EOpConstructMat3x3:
8342     case EOpConstructMat3x4:
8343     case EOpConstructMat4x2:
8344     case EOpConstructMat4x3:
8345     case EOpConstructMat4x4:
8346     case EOpConstructFloat:
8347         basicOp = EOpConstructFloat;
8348         break;
8349 
8350     case EOpConstructIVec2:
8351     case EOpConstructIVec3:
8352     case EOpConstructIVec4:
8353     case EOpConstructInt:
8354         basicOp = EOpConstructInt;
8355         break;
8356 
8357     case EOpConstructUVec2:
8358         if (node->getType().getBasicType() == EbtReference) {
8359             requireExtensions(loc, 1, &E_GL_EXT_buffer_reference_uvec2, "reference conversion to uvec2");
8360             TIntermTyped* newNode = intermediate.addBuiltInFunctionCall(node->getLoc(), EOpConvPtrToUvec2, true, node,
8361                 type);
8362             return newNode;
8363         } else if (node->getType().getBasicType() == EbtSampler) {
8364             requireExtensions(loc, 1, &E_GL_ARB_bindless_texture, "sampler conversion to uvec2");
8365             // force the basic type of the constructor param to uvec2, otherwise spv builder will
8366             // report some errors
8367             TIntermTyped* newSrcNode = intermediate.createConversion(EbtUint, node);
8368             newSrcNode->getAsTyped()->getWritableType().setVectorSize(2);
8369 
8370             TIntermTyped* newNode =
8371                 intermediate.addBuiltInFunctionCall(node->getLoc(), EOpConstructUVec2, false, newSrcNode, type);
8372             return newNode;
8373         }
8374     case EOpConstructUVec3:
8375     case EOpConstructUVec4:
8376     case EOpConstructUint:
8377         basicOp = EOpConstructUint;
8378         break;
8379 
8380     case EOpConstructBVec2:
8381     case EOpConstructBVec3:
8382     case EOpConstructBVec4:
8383     case EOpConstructBool:
8384         basicOp = EOpConstructBool;
8385         break;
8386     case EOpConstructTextureSampler:
8387         if ((node->getType().getBasicType() == EbtUint || node->getType().getBasicType() == EbtInt) &&
8388             node->getType().getVectorSize() == 2) {
8389             requireExtensions(loc, 1, &E_GL_ARB_bindless_texture, "ivec2/uvec2 convert to texture handle");
8390             // No matter ivec2 or uvec2, Set EOpPackUint2x32 just to generate an opBitcast op code
8391             TIntermTyped* newNode =
8392                 intermediate.addBuiltInFunctionCall(node->getLoc(), EOpPackUint2x32, true, node, type);
8393             return newNode;
8394         }
8395     case EOpConstructDVec2:
8396     case EOpConstructDVec3:
8397     case EOpConstructDVec4:
8398     case EOpConstructDMat2x2:
8399     case EOpConstructDMat2x3:
8400     case EOpConstructDMat2x4:
8401     case EOpConstructDMat3x2:
8402     case EOpConstructDMat3x3:
8403     case EOpConstructDMat3x4:
8404     case EOpConstructDMat4x2:
8405     case EOpConstructDMat4x3:
8406     case EOpConstructDMat4x4:
8407     case EOpConstructDouble:
8408         basicOp = EOpConstructDouble;
8409         break;
8410 
8411     case EOpConstructF16Vec2:
8412     case EOpConstructF16Vec3:
8413     case EOpConstructF16Vec4:
8414     case EOpConstructF16Mat2x2:
8415     case EOpConstructF16Mat2x3:
8416     case EOpConstructF16Mat2x4:
8417     case EOpConstructF16Mat3x2:
8418     case EOpConstructF16Mat3x3:
8419     case EOpConstructF16Mat3x4:
8420     case EOpConstructF16Mat4x2:
8421     case EOpConstructF16Mat4x3:
8422     case EOpConstructF16Mat4x4:
8423     case EOpConstructFloat16:
8424         basicOp = EOpConstructFloat16;
8425         // 8/16-bit storage extensions don't support constructing composites of 8/16-bit types,
8426         // so construct a 32-bit type and convert
8427         if (!intermediate.getArithemeticFloat16Enabled()) {
8428             TType tempType(EbtFloat, EvqTemporary, type.getVectorSize());
8429             newNode = node;
8430             if (tempType != newNode->getType()) {
8431                 TOperator aggregateOp;
8432                 if (op == EOpConstructFloat16)
8433                     aggregateOp = EOpConstructFloat;
8434                 else
8435                     aggregateOp = (TOperator)(EOpConstructVec2 + op - EOpConstructF16Vec2);
8436                 newNode = intermediate.setAggregateOperator(newNode, aggregateOp, tempType, node->getLoc());
8437             }
8438             newNode = intermediate.addConversion(EbtFloat16, newNode);
8439             return newNode;
8440         }
8441         break;
8442 
8443     case EOpConstructI8Vec2:
8444     case EOpConstructI8Vec3:
8445     case EOpConstructI8Vec4:
8446     case EOpConstructInt8:
8447         basicOp = EOpConstructInt8;
8448         // 8/16-bit storage extensions don't support constructing composites of 8/16-bit types,
8449         // so construct a 32-bit type and convert
8450         if (!intermediate.getArithemeticInt8Enabled()) {
8451             TType tempType(EbtInt, EvqTemporary, type.getVectorSize());
8452             newNode = node;
8453             if (tempType != newNode->getType()) {
8454                 TOperator aggregateOp;
8455                 if (op == EOpConstructInt8)
8456                     aggregateOp = EOpConstructInt;
8457                 else
8458                     aggregateOp = (TOperator)(EOpConstructIVec2 + op - EOpConstructI8Vec2);
8459                 newNode = intermediate.setAggregateOperator(newNode, aggregateOp, tempType, node->getLoc());
8460             }
8461             newNode = intermediate.addConversion(EbtInt8, newNode);
8462             return newNode;
8463         }
8464         break;
8465 
8466     case EOpConstructU8Vec2:
8467     case EOpConstructU8Vec3:
8468     case EOpConstructU8Vec4:
8469     case EOpConstructUint8:
8470         basicOp = EOpConstructUint8;
8471         // 8/16-bit storage extensions don't support constructing composites of 8/16-bit types,
8472         // so construct a 32-bit type and convert
8473         if (!intermediate.getArithemeticInt8Enabled()) {
8474             TType tempType(EbtUint, EvqTemporary, type.getVectorSize());
8475             newNode = node;
8476             if (tempType != newNode->getType()) {
8477                 TOperator aggregateOp;
8478                 if (op == EOpConstructUint8)
8479                     aggregateOp = EOpConstructUint;
8480                 else
8481                     aggregateOp = (TOperator)(EOpConstructUVec2 + op - EOpConstructU8Vec2);
8482                 newNode = intermediate.setAggregateOperator(newNode, aggregateOp, tempType, node->getLoc());
8483             }
8484             newNode = intermediate.addConversion(EbtUint8, newNode);
8485             return newNode;
8486         }
8487         break;
8488 
8489     case EOpConstructI16Vec2:
8490     case EOpConstructI16Vec3:
8491     case EOpConstructI16Vec4:
8492     case EOpConstructInt16:
8493         basicOp = EOpConstructInt16;
8494         // 8/16-bit storage extensions don't support constructing composites of 8/16-bit types,
8495         // so construct a 32-bit type and convert
8496         if (!intermediate.getArithemeticInt16Enabled()) {
8497             TType tempType(EbtInt, EvqTemporary, type.getVectorSize());
8498             newNode = node;
8499             if (tempType != newNode->getType()) {
8500                 TOperator aggregateOp;
8501                 if (op == EOpConstructInt16)
8502                     aggregateOp = EOpConstructInt;
8503                 else
8504                     aggregateOp = (TOperator)(EOpConstructIVec2 + op - EOpConstructI16Vec2);
8505                 newNode = intermediate.setAggregateOperator(newNode, aggregateOp, tempType, node->getLoc());
8506             }
8507             newNode = intermediate.addConversion(EbtInt16, newNode);
8508             return newNode;
8509         }
8510         break;
8511 
8512     case EOpConstructU16Vec2:
8513     case EOpConstructU16Vec3:
8514     case EOpConstructU16Vec4:
8515     case EOpConstructUint16:
8516         basicOp = EOpConstructUint16;
8517         // 8/16-bit storage extensions don't support constructing composites of 8/16-bit types,
8518         // so construct a 32-bit type and convert
8519         if (!intermediate.getArithemeticInt16Enabled()) {
8520             TType tempType(EbtUint, EvqTemporary, type.getVectorSize());
8521             newNode = node;
8522             if (tempType != newNode->getType()) {
8523                 TOperator aggregateOp;
8524                 if (op == EOpConstructUint16)
8525                     aggregateOp = EOpConstructUint;
8526                 else
8527                     aggregateOp = (TOperator)(EOpConstructUVec2 + op - EOpConstructU16Vec2);
8528                 newNode = intermediate.setAggregateOperator(newNode, aggregateOp, tempType, node->getLoc());
8529             }
8530             newNode = intermediate.addConversion(EbtUint16, newNode);
8531             return newNode;
8532         }
8533         break;
8534 
8535     case EOpConstructI64Vec2:
8536     case EOpConstructI64Vec3:
8537     case EOpConstructI64Vec4:
8538     case EOpConstructInt64:
8539         basicOp = EOpConstructInt64;
8540         break;
8541 
8542     case EOpConstructUint64:
8543         if (type.isScalar() && node->getType().isReference()) {
8544             TIntermTyped* newNode = intermediate.addBuiltInFunctionCall(node->getLoc(), EOpConvPtrToUint64, true, node, type);
8545             return newNode;
8546         }
8547         // fall through
8548     case EOpConstructU64Vec2:
8549     case EOpConstructU64Vec3:
8550     case EOpConstructU64Vec4:
8551         basicOp = EOpConstructUint64;
8552         break;
8553 
8554     case EOpConstructNonuniform:
8555         // Make a nonuniform copy of node
8556         newNode = intermediate.addBuiltInFunctionCall(node->getLoc(), EOpCopyObject, true, node, type);
8557         return newNode;
8558 
8559     case EOpConstructReference:
8560         // construct reference from reference
8561         if (node->getType().isReference()) {
8562             newNode = intermediate.addBuiltInFunctionCall(node->getLoc(), EOpConstructReference, true, node, type);
8563             return newNode;
8564         // construct reference from uint64
8565         } else if (node->getType().isScalar() && node->getType().getBasicType() == EbtUint64) {
8566             TIntermTyped* newNode = intermediate.addBuiltInFunctionCall(node->getLoc(), EOpConvUint64ToPtr, true, node,
8567                 type);
8568             return newNode;
8569         // construct reference from uvec2
8570         } else if (node->getType().isVector() && node->getType().getBasicType() == EbtUint &&
8571                    node->getVectorSize() == 2) {
8572             requireExtensions(loc, 1, &E_GL_EXT_buffer_reference_uvec2, "uvec2 conversion to reference");
8573             TIntermTyped* newNode = intermediate.addBuiltInFunctionCall(node->getLoc(), EOpConvUvec2ToPtr, true, node,
8574                 type);
8575             return newNode;
8576         } else {
8577             return nullptr;
8578         }
8579 
8580     case EOpConstructCooperativeMatrixNV:
8581     case EOpConstructCooperativeMatrixKHR:
8582         if (node->getType() == type) {
8583             return node;
8584         }
8585         if (!node->getType().isCoopMat()) {
8586             if (type.getBasicType() != node->getType().getBasicType()) {
8587                 node = intermediate.addConversion(type.getBasicType(), node);
8588                 if (node == nullptr)
8589                     return nullptr;
8590             }
8591             node = intermediate.setAggregateOperator(node, op, type, node->getLoc());
8592         } else {
8593             TOperator op = EOpNull;
8594             switch (type.getBasicType()) {
8595             default:
8596                 assert(0);
8597                 break;
8598             case EbtInt:
8599                 switch (node->getType().getBasicType()) {
8600                     case EbtFloat:   op = EOpConvFloatToInt;    break;
8601                     case EbtFloat16: op = EOpConvFloat16ToInt;  break;
8602                     case EbtUint8:   op = EOpConvUint8ToInt;    break;
8603                     case EbtInt8:    op = EOpConvInt8ToInt;     break;
8604                     case EbtUint16:  op = EOpConvUint16ToInt;   break;
8605                     case EbtInt16:   op = EOpConvInt16ToInt;    break;
8606                     case EbtUint:    op = EOpConvUintToInt;     break;
8607                     default: assert(0);
8608                 }
8609                 break;
8610             case EbtUint:
8611                 switch (node->getType().getBasicType()) {
8612                     case EbtFloat:   op = EOpConvFloatToUint;    break;
8613                     case EbtFloat16: op = EOpConvFloat16ToUint;  break;
8614                     case EbtUint8:   op = EOpConvUint8ToUint;    break;
8615                     case EbtInt8:    op = EOpConvInt8ToUint;     break;
8616                     case EbtUint16:  op = EOpConvUint16ToUint;   break;
8617                     case EbtInt16:   op = EOpConvInt16ToUint;    break;
8618                     case EbtInt:     op = EOpConvIntToUint;      break;
8619                     default: assert(0);
8620                 }
8621                 break;
8622             case EbtInt16:
8623                 switch (node->getType().getBasicType()) {
8624                     case EbtFloat:   op = EOpConvFloatToInt16;    break;
8625                     case EbtFloat16: op = EOpConvFloat16ToInt16;  break;
8626                     case EbtUint8:   op = EOpConvUint8ToInt16;    break;
8627                     case EbtInt8:    op = EOpConvInt8ToInt16;     break;
8628                     case EbtUint16:  op = EOpConvUint16ToInt16;   break;
8629                     case EbtInt:     op = EOpConvIntToInt16;      break;
8630                     case EbtUint:    op = EOpConvUintToInt16;     break;
8631                     default: assert(0);
8632                 }
8633                 break;
8634             case EbtUint16:
8635                 switch (node->getType().getBasicType()) {
8636                     case EbtFloat:   op = EOpConvFloatToUint16;   break;
8637                     case EbtFloat16: op = EOpConvFloat16ToUint16; break;
8638                     case EbtUint8:   op = EOpConvUint8ToUint16;   break;
8639                     case EbtInt8:    op = EOpConvInt8ToUint16;    break;
8640                     case EbtInt16:   op = EOpConvInt16ToUint16;   break;
8641                     case EbtInt:     op = EOpConvIntToUint16;     break;
8642                     case EbtUint:    op = EOpConvUintToUint16;    break;
8643                     default: assert(0);
8644                 }
8645                 break;
8646             case EbtInt8:
8647                 switch (node->getType().getBasicType()) {
8648                     case EbtFloat:   op = EOpConvFloatToInt8;    break;
8649                     case EbtFloat16: op = EOpConvFloat16ToInt8;  break;
8650                     case EbtUint8:   op = EOpConvUint8ToInt8;    break;
8651                     case EbtInt16:   op = EOpConvInt16ToInt8;    break;
8652                     case EbtUint16:  op = EOpConvUint16ToInt8;   break;
8653                     case EbtInt:     op = EOpConvIntToInt8;      break;
8654                     case EbtUint:    op = EOpConvUintToInt8;     break;
8655                     default: assert(0);
8656                 }
8657                 break;
8658             case EbtUint8:
8659                 switch (node->getType().getBasicType()) {
8660                     case EbtFloat:   op = EOpConvFloatToUint8;   break;
8661                     case EbtFloat16: op = EOpConvFloat16ToUint8; break;
8662                     case EbtInt8:    op = EOpConvInt8ToUint8;    break;
8663                     case EbtInt16:   op = EOpConvInt16ToUint8;   break;
8664                     case EbtUint16:  op = EOpConvUint16ToUint8;  break;
8665                     case EbtInt:     op = EOpConvIntToUint8;     break;
8666                     case EbtUint:    op = EOpConvUintToUint8;    break;
8667                     default: assert(0);
8668                 }
8669                 break;
8670             case EbtFloat:
8671                 switch (node->getType().getBasicType()) {
8672                     case EbtFloat16: op = EOpConvFloat16ToFloat;  break;
8673                     case EbtInt8:    op = EOpConvInt8ToFloat;     break;
8674                     case EbtUint8:   op = EOpConvUint8ToFloat;    break;
8675                     case EbtInt16:   op = EOpConvInt16ToFloat;    break;
8676                     case EbtUint16:  op = EOpConvUint16ToFloat;   break;
8677                     case EbtInt:     op = EOpConvIntToFloat;      break;
8678                     case EbtUint:    op = EOpConvUintToFloat;     break;
8679                     default: assert(0);
8680                 }
8681                 break;
8682             case EbtFloat16:
8683                 switch (node->getType().getBasicType()) {
8684                     case EbtFloat:  op = EOpConvFloatToFloat16;  break;
8685                     case EbtInt8:   op = EOpConvInt8ToFloat16;   break;
8686                     case EbtUint8:  op = EOpConvUint8ToFloat16;  break;
8687                     case EbtInt16:  op = EOpConvInt16ToFloat16;   break;
8688                     case EbtUint16: op = EOpConvUint16ToFloat16;  break;
8689                     case EbtInt:    op = EOpConvIntToFloat16;    break;
8690                     case EbtUint:   op = EOpConvUintToFloat16;   break;
8691                     default: assert(0);
8692                 }
8693                 break;
8694             }
8695 
8696             node = intermediate.addUnaryNode(op, node, node->getLoc(), type);
8697             // If it's a (non-specialization) constant, it must be folded.
8698             if (node->getAsUnaryNode()->getOperand()->getAsConstantUnion())
8699                 return node->getAsUnaryNode()->getOperand()->getAsConstantUnion()->fold(op, node->getType());
8700         }
8701 
8702         return node;
8703 
8704     case EOpConstructAccStruct:
8705         if ((node->getType().isScalar() && node->getType().getBasicType() == EbtUint64)) {
8706             // construct acceleration structure from uint64
8707             requireExtensions(loc, Num_ray_tracing_EXTs, ray_tracing_EXTs, "uint64_t conversion to acclerationStructureEXT");
8708             return intermediate.addBuiltInFunctionCall(node->getLoc(), EOpConvUint64ToAccStruct, true, node,
8709                 type);
8710         } else if (node->getType().isVector() && node->getType().getBasicType() == EbtUint && node->getVectorSize() == 2) {
8711             // construct acceleration structure from uint64
8712             requireExtensions(loc, Num_ray_tracing_EXTs, ray_tracing_EXTs, "uvec2 conversion to accelerationStructureEXT");
8713             return intermediate.addBuiltInFunctionCall(node->getLoc(), EOpConvUvec2ToAccStruct, true, node,
8714                 type);
8715         } else
8716             return nullptr;
8717 
8718     default:
8719         error(loc, "unsupported construction", "", "");
8720 
8721         return nullptr;
8722     }
8723     newNode = intermediate.addUnaryMath(basicOp, node, node->getLoc());
8724     if (newNode == nullptr) {
8725         error(loc, "can't convert", "constructor", "");
8726         return nullptr;
8727     }
8728 
8729     //
8730     // Now, if there still isn't an operation to do the construction, and we need one, add one.
8731     //
8732 
8733     // Otherwise, skip out early.
8734     if (subset || (newNode != node && newNode->getType() == type))
8735         return newNode;
8736 
8737     // setAggregateOperator will insert a new node for the constructor, as needed.
8738     return intermediate.setAggregateOperator(newNode, op, type, loc);
8739 }
8740 
8741 // This function tests for the type of the parameters to the structure or array constructor. Raises
8742 // an error message if the expected type does not match the parameter passed to the constructor.
8743 //
8744 // Returns nullptr for an error or the input node itself if the expected and the given parameter types match.
8745 //
constructAggregate(TIntermNode * node,const TType & type,int paramCount,const TSourceLoc & loc)8746 TIntermTyped* TParseContext::constructAggregate(TIntermNode* node, const TType& type, int paramCount, const TSourceLoc& loc)
8747 {
8748     TIntermTyped* converted = intermediate.addConversion(EOpConstructStruct, type, node->getAsTyped());
8749     if (! converted || converted->getType() != type) {
8750         bool enhanced = intermediate.getEnhancedMsgs();
8751         error(loc, "", "constructor", "cannot convert parameter %d from '%s' to '%s'", paramCount,
8752               node->getAsTyped()->getType().getCompleteString(enhanced).c_str(), type.getCompleteString(enhanced).c_str());
8753 
8754         return nullptr;
8755     }
8756 
8757     return converted;
8758 }
8759 
8760 // If a memory qualifier is present in 'to', also make it present in 'from'.
inheritMemoryQualifiers(const TQualifier & from,TQualifier & to)8761 void TParseContext::inheritMemoryQualifiers(const TQualifier& from, TQualifier& to)
8762 {
8763     if (from.isReadOnly())
8764         to.readonly = from.readonly;
8765     if (from.isWriteOnly())
8766         to.writeonly = from.writeonly;
8767     if (from.coherent)
8768         to.coherent = from.coherent;
8769     if (from.volatil)
8770         to.volatil = from.volatil;
8771     if (from.restrict)
8772         to.restrict = from.restrict;
8773 }
8774 
8775 //
8776 // Update qualifier layoutBindlessImage & layoutBindlessSampler on block member
8777 //
updateBindlessQualifier(TType & memberType)8778 void TParseContext::updateBindlessQualifier(TType& memberType)
8779 {
8780     if (memberType.containsSampler()) {
8781         if (memberType.isStruct()) {
8782             TTypeList* typeList = memberType.getWritableStruct();
8783             for (unsigned int member = 0; member < typeList->size(); ++member) {
8784                 TType* subMemberType = (*typeList)[member].type;
8785                 updateBindlessQualifier(*subMemberType);
8786             }
8787         }
8788         else if (memberType.getSampler().isImage()) {
8789             intermediate.setBindlessImageMode(currentCaller, AstRefTypeLayout);
8790             memberType.getQualifier().layoutBindlessImage = true;
8791         }
8792         else {
8793             intermediate.setBindlessTextureMode(currentCaller, AstRefTypeLayout);
8794             memberType.getQualifier().layoutBindlessSampler = true;
8795         }
8796     }
8797 }
8798 
8799 //
8800 // Do everything needed to add an interface block.
8801 //
declareBlock(const TSourceLoc & loc,TTypeList & typeList,const TString * instanceName,TArraySizes * arraySizes)8802 void TParseContext::declareBlock(const TSourceLoc& loc, TTypeList& typeList, const TString* instanceName,
8803     TArraySizes* arraySizes)
8804 {
8805     if (spvVersion.vulkan > 0 && spvVersion.vulkanRelaxed)
8806         blockStorageRemap(loc, blockName, currentBlockQualifier);
8807     blockStageIoCheck(loc, currentBlockQualifier);
8808     blockQualifierCheck(loc, currentBlockQualifier, instanceName != nullptr);
8809     if (arraySizes != nullptr) {
8810         arraySizesCheck(loc, currentBlockQualifier, arraySizes, nullptr, false);
8811         arrayOfArrayVersionCheck(loc, arraySizes);
8812         if (arraySizes->getNumDims() > 1)
8813             requireProfile(loc, ~EEsProfile, "array-of-array of block");
8814     }
8815 
8816     // Inherit and check member storage qualifiers WRT to the block-level qualifier.
8817     for (unsigned int member = 0; member < typeList.size(); ++member) {
8818         TType& memberType = *typeList[member].type;
8819         TQualifier& memberQualifier = memberType.getQualifier();
8820         const TSourceLoc& memberLoc = typeList[member].loc;
8821         if (memberQualifier.storage != EvqTemporary && memberQualifier.storage != EvqGlobal && memberQualifier.storage != currentBlockQualifier.storage)
8822             error(memberLoc, "member storage qualifier cannot contradict block storage qualifier", memberType.getFieldName().c_str(), "");
8823         memberQualifier.storage = currentBlockQualifier.storage;
8824         globalQualifierFixCheck(memberLoc, memberQualifier);
8825         inheritMemoryQualifiers(currentBlockQualifier, memberQualifier);
8826         if (currentBlockQualifier.perPrimitiveNV)
8827             memberQualifier.perPrimitiveNV = currentBlockQualifier.perPrimitiveNV;
8828         if (currentBlockQualifier.perViewNV)
8829             memberQualifier.perViewNV = currentBlockQualifier.perViewNV;
8830         if (currentBlockQualifier.perTaskNV)
8831             memberQualifier.perTaskNV = currentBlockQualifier.perTaskNV;
8832         if (currentBlockQualifier.storage == EvqtaskPayloadSharedEXT)
8833             memberQualifier.storage = EvqtaskPayloadSharedEXT;
8834         if (memberQualifier.storage == EvqSpirvStorageClass)
8835             error(memberLoc, "member cannot have a spirv_storage_class qualifier", memberType.getFieldName().c_str(), "");
8836         if (memberQualifier.hasSpirvDecorate() && !memberQualifier.getSpirvDecorate().decorateIds.empty())
8837             error(memberLoc, "member cannot have a spirv_decorate_id qualifier", memberType.getFieldName().c_str(), "");
8838         if ((currentBlockQualifier.storage == EvqUniform || currentBlockQualifier.storage == EvqBuffer) && (memberQualifier.isInterpolation() || memberQualifier.isAuxiliary()))
8839             error(memberLoc, "member of uniform or buffer block cannot have an auxiliary or interpolation qualifier", memberType.getFieldName().c_str(), "");
8840         if (memberType.isArray())
8841             arraySizesCheck(memberLoc, currentBlockQualifier, memberType.getArraySizes(), nullptr, member == typeList.size() - 1);
8842         if (memberQualifier.hasOffset()) {
8843             if (spvVersion.spv == 0) {
8844                 profileRequires(memberLoc, ~EEsProfile, 440, E_GL_ARB_enhanced_layouts, "\"offset\" on block member");
8845                 profileRequires(memberLoc, EEsProfile, 300, E_GL_ARB_enhanced_layouts, "\"offset\" on block member");
8846             }
8847         }
8848 
8849         // For bindless texture, sampler can be declared as uniform/storage block member,
8850         if (memberType.containsOpaque()) {
8851             if (memberType.containsSampler() && extensionTurnedOn(E_GL_ARB_bindless_texture))
8852                 updateBindlessQualifier(memberType);
8853             else
8854                 error(memberLoc, "member of block cannot be or contain a sampler, image, or atomic_uint type", typeList[member].type->getFieldName().c_str(), "");
8855             }
8856 
8857         if (memberType.containsCoopMat())
8858             error(memberLoc, "member of block cannot be or contain a cooperative matrix type", typeList[member].type->getFieldName().c_str(), "");
8859     }
8860 
8861     // This might be a redeclaration of a built-in block.  If so, redeclareBuiltinBlock() will
8862     // do all the rest.
8863     if (! symbolTable.atBuiltInLevel() && builtInName(*blockName)) {
8864         redeclareBuiltinBlock(loc, typeList, *blockName, instanceName, arraySizes);
8865         return;
8866     }
8867 
8868     // Not a redeclaration of a built-in; check that all names are user names.
8869     reservedErrorCheck(loc, *blockName);
8870     if (instanceName)
8871         reservedErrorCheck(loc, *instanceName);
8872     for (unsigned int member = 0; member < typeList.size(); ++member)
8873         reservedErrorCheck(typeList[member].loc, typeList[member].type->getFieldName());
8874 
8875     // Make default block qualification, and adjust the member qualifications
8876 
8877     TQualifier defaultQualification;
8878     switch (currentBlockQualifier.storage) {
8879     case EvqUniform:    defaultQualification = globalUniformDefaults;    break;
8880     case EvqBuffer:     defaultQualification = globalBufferDefaults;     break;
8881     case EvqVaryingIn:  defaultQualification = globalInputDefaults;      break;
8882     case EvqVaryingOut: defaultQualification = globalOutputDefaults;     break;
8883     case EvqShared:     defaultQualification = globalSharedDefaults;     break;
8884     default:            defaultQualification.clear();                    break;
8885     }
8886 
8887     // Special case for "push_constant uniform", which has a default of std430,
8888     // contrary to normal uniform defaults, and can't have a default tracked for it.
8889     if ((currentBlockQualifier.isPushConstant() && !currentBlockQualifier.hasPacking()) ||
8890         (currentBlockQualifier.isShaderRecord() && !currentBlockQualifier.hasPacking()))
8891         currentBlockQualifier.layoutPacking = ElpStd430;
8892 
8893     // Special case for "taskNV in/out", which has a default of std430,
8894     if (currentBlockQualifier.isTaskMemory() && !currentBlockQualifier.hasPacking())
8895         currentBlockQualifier.layoutPacking = ElpStd430;
8896 
8897     // fix and check for member layout qualifiers
8898 
8899     mergeObjectLayoutQualifiers(defaultQualification, currentBlockQualifier, true);
8900 
8901     // "The align qualifier can only be used on blocks or block members, and only for blocks declared with std140 or std430 layouts."
8902     if (currentBlockQualifier.hasAlign()) {
8903         if (defaultQualification.layoutPacking != ElpStd140 &&
8904             defaultQualification.layoutPacking != ElpStd430 &&
8905             defaultQualification.layoutPacking != ElpScalar) {
8906             error(loc, "can only be used with std140, std430, or scalar layout packing", "align", "");
8907             defaultQualification.layoutAlign = -1;
8908         }
8909     }
8910 
8911     bool memberWithLocation = false;
8912     bool memberWithoutLocation = false;
8913     bool memberWithPerViewQualifier = false;
8914     for (unsigned int member = 0; member < typeList.size(); ++member) {
8915         TQualifier& memberQualifier = typeList[member].type->getQualifier();
8916         const TSourceLoc& memberLoc = typeList[member].loc;
8917         if (memberQualifier.hasStream()) {
8918             if (defaultQualification.layoutStream != memberQualifier.layoutStream)
8919                 error(memberLoc, "member cannot contradict block", "stream", "");
8920         }
8921 
8922         // "This includes a block's inheritance of the
8923         // current global default buffer, a block member's inheritance of the block's
8924         // buffer, and the requirement that any *xfb_buffer* declared on a block
8925         // member must match the buffer inherited from the block."
8926         if (memberQualifier.hasXfbBuffer()) {
8927             if (defaultQualification.layoutXfbBuffer != memberQualifier.layoutXfbBuffer)
8928                 error(memberLoc, "member cannot contradict block (or what block inherited from global)", "xfb_buffer", "");
8929         }
8930 
8931         if (memberQualifier.hasPacking())
8932             error(memberLoc, "member of block cannot have a packing layout qualifier", typeList[member].type->getFieldName().c_str(), "");
8933         if (memberQualifier.hasLocation()) {
8934             const char* feature = "location on block member";
8935             switch (currentBlockQualifier.storage) {
8936             case EvqVaryingIn:
8937             case EvqVaryingOut:
8938                 requireProfile(memberLoc, ECoreProfile | ECompatibilityProfile | EEsProfile, feature);
8939                 profileRequires(memberLoc, ECoreProfile | ECompatibilityProfile, 440, E_GL_ARB_enhanced_layouts, feature);
8940                 profileRequires(memberLoc, EEsProfile, 320, Num_AEP_shader_io_blocks, AEP_shader_io_blocks, feature);
8941                 memberWithLocation = true;
8942                 break;
8943             default:
8944                 error(memberLoc, "can only use in an in/out block", feature, "");
8945                 break;
8946             }
8947         } else
8948             memberWithoutLocation = true;
8949 
8950         // "The offset qualifier can only be used on block members of blocks declared with std140 or std430 layouts."
8951         // "The align qualifier can only be used on blocks or block members, and only for blocks declared with std140 or std430 layouts."
8952         if (memberQualifier.hasAlign() || memberQualifier.hasOffset()) {
8953             if (defaultQualification.layoutPacking != ElpStd140 &&
8954                 defaultQualification.layoutPacking != ElpStd430 &&
8955                 defaultQualification.layoutPacking != ElpScalar)
8956                 error(memberLoc, "can only be used with std140, std430, or scalar layout packing", "offset/align", "");
8957         }
8958 
8959         if (memberQualifier.isPerView()) {
8960             memberWithPerViewQualifier = true;
8961         }
8962 
8963         TQualifier newMemberQualification = defaultQualification;
8964         mergeQualifiers(memberLoc, newMemberQualification, memberQualifier, false);
8965         memberQualifier = newMemberQualification;
8966     }
8967 
8968     layoutMemberLocationArrayCheck(loc, memberWithLocation, arraySizes);
8969 
8970     // Ensure that the block has an XfbBuffer assigned. This is needed
8971     // because if the block has a XfbOffset assigned, then it is
8972     // assumed that it has implicitly assigned the current global
8973     // XfbBuffer, and because it's members need to be assigned a
8974     // XfbOffset if they lack it.
8975     if (currentBlockQualifier.storage == EvqVaryingOut && globalOutputDefaults.hasXfbBuffer()) {
8976        if (!currentBlockQualifier.hasXfbBuffer() && currentBlockQualifier.hasXfbOffset())
8977           currentBlockQualifier.layoutXfbBuffer = globalOutputDefaults.layoutXfbBuffer;
8978     }
8979 
8980     // Process the members
8981     fixBlockLocations(loc, currentBlockQualifier, typeList, memberWithLocation, memberWithoutLocation);
8982     fixXfbOffsets(currentBlockQualifier, typeList);
8983     fixBlockUniformOffsets(currentBlockQualifier, typeList);
8984     fixBlockUniformLayoutMatrix(currentBlockQualifier, &typeList, nullptr);
8985     fixBlockUniformLayoutPacking(currentBlockQualifier, &typeList, nullptr);
8986     for (unsigned int member = 0; member < typeList.size(); ++member)
8987         layoutTypeCheck(typeList[member].loc, *typeList[member].type);
8988 
8989     if (memberWithPerViewQualifier) {
8990         for (unsigned int member = 0; member < typeList.size(); ++member) {
8991             checkAndResizeMeshViewDim(typeList[member].loc, *typeList[member].type, /*isBlockMember*/ true);
8992         }
8993     }
8994 
8995     // reverse merge, so that currentBlockQualifier now has all layout information
8996     // (can't use defaultQualification directly, it's missing other non-layout-default-class qualifiers)
8997     mergeObjectLayoutQualifiers(currentBlockQualifier, defaultQualification, true);
8998 
8999     //
9000     // Build and add the interface block as a new type named 'blockName'
9001     //
9002 
9003     TType blockType(&typeList, *blockName, currentBlockQualifier);
9004     if (arraySizes != nullptr)
9005         blockType.transferArraySizes(arraySizes);
9006 
9007     if (arraySizes == nullptr)
9008         ioArrayCheck(loc, blockType, instanceName ? *instanceName : *blockName);
9009     if (currentBlockQualifier.hasBufferReference()) {
9010 
9011         if (currentBlockQualifier.storage != EvqBuffer)
9012             error(loc, "can only be used with buffer", "buffer_reference", "");
9013 
9014         // Create the block reference type. If it was forward-declared, detect that
9015         // as a referent struct type with no members. Replace the referent type with
9016         // blockType.
9017         TType blockNameType(EbtReference, blockType, *blockName);
9018         TVariable* blockNameVar = new TVariable(blockName, blockNameType, true);
9019         if (! symbolTable.insert(*blockNameVar)) {
9020             TSymbol* existingName = symbolTable.find(*blockName);
9021             if (existingName->getType().isReference() &&
9022                 existingName->getType().getReferentType()->getStruct() &&
9023                 existingName->getType().getReferentType()->getStruct()->size() == 0 &&
9024                 existingName->getType().getQualifier().storage == blockType.getQualifier().storage) {
9025                 existingName->getType().getReferentType()->deepCopy(blockType);
9026             } else {
9027                 error(loc, "block name cannot be redefined", blockName->c_str(), "");
9028             }
9029         }
9030         if (!instanceName) {
9031             return;
9032         }
9033     } else {
9034         //
9035         // Don't make a user-defined type out of block name; that will cause an error
9036         // if the same block name gets reused in a different interface.
9037         //
9038         // "Block names have no other use within a shader
9039         // beyond interface matching; it is a compile-time error to use a block name at global scope for anything
9040         // other than as a block name (e.g., use of a block name for a global variable name or function name is
9041         // currently reserved)."
9042         //
9043         // Use the symbol table to prevent normal reuse of the block's name, as a variable entry,
9044         // whose type is EbtBlock, but without all the structure; that will come from the type
9045         // the instances point to.
9046         //
9047         TType blockNameType(EbtBlock, blockType.getQualifier().storage);
9048         TVariable* blockNameVar = new TVariable(blockName, blockNameType);
9049         if (! symbolTable.insert(*blockNameVar)) {
9050             TSymbol* existingName = symbolTable.find(*blockName);
9051             if (existingName->getType().getBasicType() == EbtBlock) {
9052                 if (existingName->getType().getQualifier().storage == blockType.getQualifier().storage) {
9053                     error(loc, "Cannot reuse block name within the same interface:", blockName->c_str(), blockType.getStorageQualifierString());
9054                     return;
9055                 }
9056             } else {
9057                 error(loc, "block name cannot redefine a non-block name", blockName->c_str(), "");
9058                 return;
9059             }
9060         }
9061     }
9062 
9063     // Add the variable, as anonymous or named instanceName.
9064     // Make an anonymous variable if no name was provided.
9065     if (! instanceName)
9066         instanceName = NewPoolTString("");
9067 
9068     TVariable& variable = *new TVariable(instanceName, blockType);
9069     if (! symbolTable.insert(variable)) {
9070         if (*instanceName == "")
9071             error(loc, "nameless block contains a member that already has a name at global scope", blockName->c_str(), "");
9072         else
9073             error(loc, "block instance name redefinition", variable.getName().c_str(), "");
9074 
9075         return;
9076     }
9077 
9078     // Check for general layout qualifier errors
9079     layoutObjectCheck(loc, variable);
9080 
9081     // fix up
9082     if (isIoResizeArray(blockType)) {
9083         ioArraySymbolResizeList.push_back(&variable);
9084         checkIoArraysConsistency(loc, true);
9085     } else
9086         fixIoArraySize(loc, variable.getWritableType());
9087 
9088     // Save it in the AST for linker use.
9089     trackLinkage(variable);
9090 }
9091 
9092 //
9093 // allow storage type of block to be remapped at compile time
9094 //
blockStorageRemap(const TSourceLoc &,const TString * instanceName,TQualifier & qualifier)9095 void TParseContext::blockStorageRemap(const TSourceLoc&, const TString* instanceName, TQualifier& qualifier)
9096 {
9097     TBlockStorageClass type = intermediate.getBlockStorageOverride(instanceName->c_str());
9098     if (type != EbsNone) {
9099         qualifier.setBlockStorage(type);
9100     }
9101 }
9102 
9103 // Do all block-declaration checking regarding the combination of in/out/uniform/buffer
9104 // with a particular stage.
blockStageIoCheck(const TSourceLoc & loc,const TQualifier & qualifier)9105 void TParseContext::blockStageIoCheck(const TSourceLoc& loc, const TQualifier& qualifier)
9106 {
9107     const char *extsrt[2] = { E_GL_NV_ray_tracing, E_GL_EXT_ray_tracing };
9108     switch (qualifier.storage) {
9109     case EvqUniform:
9110         profileRequires(loc, EEsProfile, 300, nullptr, "uniform block");
9111         profileRequires(loc, ENoProfile, 140, E_GL_ARB_uniform_buffer_object, "uniform block");
9112         if (currentBlockQualifier.layoutPacking == ElpStd430 && ! currentBlockQualifier.isPushConstant())
9113             requireExtensions(loc, 1, &E_GL_EXT_scalar_block_layout, "std430 requires the buffer storage qualifier");
9114         break;
9115     case EvqBuffer:
9116         requireProfile(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, "buffer block");
9117         profileRequires(loc, ECoreProfile | ECompatibilityProfile, 430, E_GL_ARB_shader_storage_buffer_object, "buffer block");
9118         profileRequires(loc, EEsProfile, 310, nullptr, "buffer block");
9119         break;
9120     case EvqVaryingIn:
9121         profileRequires(loc, ~EEsProfile, 150, E_GL_ARB_separate_shader_objects, "input block");
9122         // It is a compile-time error to have an input block in a vertex shader or an output block in a fragment shader
9123         // "Compute shaders do not permit user-defined input variables..."
9124         requireStage(loc, (EShLanguageMask)(EShLangTessControlMask|EShLangTessEvaluationMask|EShLangGeometryMask|
9125             EShLangFragmentMask|EShLangMeshMask), "input block");
9126         if (language == EShLangFragment) {
9127             profileRequires(loc, EEsProfile, 320, Num_AEP_shader_io_blocks, AEP_shader_io_blocks, "fragment input block");
9128         } else if (language == EShLangMesh && ! qualifier.isTaskMemory()) {
9129             error(loc, "input blocks cannot be used in a mesh shader", "out", "");
9130         }
9131         break;
9132     case EvqVaryingOut:
9133         profileRequires(loc, ~EEsProfile, 150, E_GL_ARB_separate_shader_objects, "output block");
9134         requireStage(loc, (EShLanguageMask)(EShLangVertexMask|EShLangTessControlMask|EShLangTessEvaluationMask|
9135             EShLangGeometryMask|EShLangMeshMask|EShLangTaskMask), "output block");
9136         // ES 310 can have a block before shader_io is turned on, so skip this test for built-ins
9137         if (language == EShLangVertex && ! parsingBuiltins) {
9138             profileRequires(loc, EEsProfile, 320, Num_AEP_shader_io_blocks, AEP_shader_io_blocks, "vertex output block");
9139         } else if (language == EShLangMesh && qualifier.isTaskMemory()) {
9140             error(loc, "can only use on input blocks in mesh shader", "taskNV", "");
9141         } else if (language == EShLangTask && ! qualifier.isTaskMemory()) {
9142             error(loc, "output blocks cannot be used in a task shader", "out", "");
9143         }
9144         break;
9145     case EvqShared:
9146         if (spvVersion.spv > 0 && spvVersion.spv < EShTargetSpv_1_4) {
9147             error(loc, "shared block requires at least SPIR-V 1.4", "shared block", "");
9148         }
9149         profileRequires(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, 0, E_GL_EXT_shared_memory_block, "shared block");
9150         break;
9151     case EvqPayload:
9152         profileRequires(loc, ~EEsProfile, 460, 2, extsrt, "rayPayloadNV block");
9153         requireStage(loc, (EShLanguageMask)(EShLangRayGenMask | EShLangAnyHitMask | EShLangClosestHitMask | EShLangMissMask),
9154             "rayPayloadNV block");
9155         break;
9156     case EvqPayloadIn:
9157         profileRequires(loc, ~EEsProfile, 460, 2, extsrt, "rayPayloadInNV block");
9158         requireStage(loc, (EShLanguageMask)(EShLangAnyHitMask | EShLangClosestHitMask | EShLangMissMask),
9159             "rayPayloadInNV block");
9160         break;
9161     case EvqHitAttr:
9162         profileRequires(loc, ~EEsProfile, 460, 2, extsrt, "hitAttributeNV block");
9163         requireStage(loc, (EShLanguageMask)(EShLangIntersectMask | EShLangAnyHitMask | EShLangClosestHitMask), "hitAttributeNV block");
9164         break;
9165     case EvqCallableData:
9166         profileRequires(loc, ~EEsProfile, 460, 2, extsrt, "callableDataNV block");
9167         requireStage(loc, (EShLanguageMask)(EShLangRayGenMask | EShLangClosestHitMask | EShLangMissMask | EShLangCallableMask),
9168             "callableDataNV block");
9169         break;
9170     case EvqCallableDataIn:
9171         profileRequires(loc, ~EEsProfile, 460, 2, extsrt, "callableDataInNV block");
9172         requireStage(loc, (EShLanguageMask)(EShLangCallableMask), "callableDataInNV block");
9173         break;
9174     case EvqHitObjectAttrNV:
9175         profileRequires(loc, ~EEsProfile, 460, E_GL_NV_shader_invocation_reorder, "hitObjectAttributeNV block");
9176         requireStage(loc, (EShLanguageMask)(EShLangRayGenMask | EShLangClosestHitMask | EShLangMissMask), "hitObjectAttributeNV block");
9177         break;
9178     default:
9179         error(loc, "only uniform, buffer, in, or out blocks are supported", blockName->c_str(), "");
9180         break;
9181     }
9182 }
9183 
9184 // Do all block-declaration checking regarding its qualifiers.
blockQualifierCheck(const TSourceLoc & loc,const TQualifier & qualifier,bool)9185 void TParseContext::blockQualifierCheck(const TSourceLoc& loc, const TQualifier& qualifier, bool /*instanceName*/)
9186 {
9187     // The 4.5 specification says:
9188     //
9189     // interface-block :
9190     //    layout-qualifieropt interface-qualifier  block-name { member-list } instance-nameopt ;
9191     //
9192     // interface-qualifier :
9193     //    in
9194     //    out
9195     //    patch in
9196     //    patch out
9197     //    uniform
9198     //    buffer
9199     //
9200     // Note however memory qualifiers aren't included, yet the specification also says
9201     //
9202     // "...memory qualifiers may also be used in the declaration of shader storage blocks..."
9203 
9204     if (qualifier.isInterpolation())
9205         error(loc, "cannot use interpolation qualifiers on an interface block", "flat/smooth/noperspective", "");
9206     if (qualifier.centroid)
9207         error(loc, "cannot use centroid qualifier on an interface block", "centroid", "");
9208     if (qualifier.isSample())
9209         error(loc, "cannot use sample qualifier on an interface block", "sample", "");
9210     if (qualifier.invariant)
9211         error(loc, "cannot use invariant qualifier on an interface block", "invariant", "");
9212     if (qualifier.isPushConstant())
9213         intermediate.addPushConstantCount();
9214     if (qualifier.isShaderRecord())
9215         intermediate.addShaderRecordCount();
9216     if (qualifier.isTaskMemory())
9217         intermediate.addTaskNVCount();
9218 }
9219 
9220 //
9221 // "For a block, this process applies to the entire block, or until the first member
9222 // is reached that has a location layout qualifier. When a block member is declared with a location
9223 // qualifier, its location comes from that qualifier: The member's location qualifier overrides the block-level
9224 // declaration. Subsequent members are again assigned consecutive locations, based on the newest location,
9225 // until the next member declared with a location qualifier. The values used for locations do not have to be
9226 // declared in increasing order."
fixBlockLocations(const TSourceLoc & loc,TQualifier & qualifier,TTypeList & typeList,bool memberWithLocation,bool memberWithoutLocation)9227 void TParseContext::fixBlockLocations(const TSourceLoc& loc, TQualifier& qualifier, TTypeList& typeList, bool memberWithLocation, bool memberWithoutLocation)
9228 {
9229     // "If a block has no block-level location layout qualifier, it is required that either all or none of its members
9230     // have a location layout qualifier, or a compile-time error results."
9231     if (! qualifier.hasLocation() && memberWithLocation && memberWithoutLocation)
9232         error(loc, "either the block needs a location, or all members need a location, or no members have a location", "location", "");
9233     else {
9234         if (memberWithLocation) {
9235             // remove any block-level location and make it per *every* member
9236             int nextLocation = 0;  // by the rule above, initial value is not relevant
9237             if (qualifier.hasAnyLocation()) {
9238                 nextLocation = qualifier.layoutLocation;
9239                 qualifier.layoutLocation = TQualifier::layoutLocationEnd;
9240                 if (qualifier.hasComponent()) {
9241                     // "It is a compile-time error to apply the *component* qualifier to a ... block"
9242                     error(loc, "cannot apply to a block", "component", "");
9243                 }
9244                 if (qualifier.hasIndex()) {
9245                     error(loc, "cannot apply to a block", "index", "");
9246                 }
9247             }
9248             for (unsigned int member = 0; member < typeList.size(); ++member) {
9249                 TQualifier& memberQualifier = typeList[member].type->getQualifier();
9250                 const TSourceLoc& memberLoc = typeList[member].loc;
9251                 if (! memberQualifier.hasLocation()) {
9252                     if (nextLocation >= (int)TQualifier::layoutLocationEnd)
9253                         error(memberLoc, "location is too large", "location", "");
9254                     memberQualifier.layoutLocation = nextLocation;
9255                     memberQualifier.layoutComponent = TQualifier::layoutComponentEnd;
9256                 }
9257                 nextLocation = memberQualifier.layoutLocation + intermediate.computeTypeLocationSize(
9258                                     *typeList[member].type, language);
9259             }
9260         }
9261     }
9262 }
9263 
fixXfbOffsets(TQualifier & qualifier,TTypeList & typeList)9264 void TParseContext::fixXfbOffsets(TQualifier& qualifier, TTypeList& typeList)
9265 {
9266     // "If a block is qualified with xfb_offset, all its
9267     // members are assigned transform feedback buffer offsets. If a block is not qualified with xfb_offset, any
9268     // members of that block not qualified with an xfb_offset will not be assigned transform feedback buffer
9269     // offsets."
9270 
9271     if (! qualifier.hasXfbBuffer() || ! qualifier.hasXfbOffset())
9272         return;
9273 
9274     int nextOffset = qualifier.layoutXfbOffset;
9275     for (unsigned int member = 0; member < typeList.size(); ++member) {
9276         TQualifier& memberQualifier = typeList[member].type->getQualifier();
9277         bool contains64BitType = false;
9278         bool contains32BitType = false;
9279         bool contains16BitType = false;
9280         int memberSize = intermediate.computeTypeXfbSize(*typeList[member].type, contains64BitType, contains32BitType, contains16BitType);
9281         // see if we need to auto-assign an offset to this member
9282         if (! memberQualifier.hasXfbOffset()) {
9283             // "if applied to an aggregate containing a double or 64-bit integer, the offset must also be a multiple of 8"
9284             if (contains64BitType)
9285                 RoundToPow2(nextOffset, 8);
9286             else if (contains32BitType)
9287                 RoundToPow2(nextOffset, 4);
9288             else if (contains16BitType)
9289                 RoundToPow2(nextOffset, 2);
9290             memberQualifier.layoutXfbOffset = nextOffset;
9291         } else
9292             nextOffset = memberQualifier.layoutXfbOffset;
9293         nextOffset += memberSize;
9294     }
9295 
9296     // The above gave all block members an offset, so we can take it off the block now,
9297     // which will avoid double counting the offset usage.
9298     qualifier.layoutXfbOffset = TQualifier::layoutXfbOffsetEnd;
9299 }
9300 
9301 // Calculate and save the offset of each block member, using the recursively
9302 // defined block offset rules and the user-provided offset and align.
9303 //
9304 // Also, compute and save the total size of the block. For the block's size, arrayness
9305 // is not taken into account, as each element is backed by a separate buffer.
9306 //
fixBlockUniformOffsets(TQualifier & qualifier,TTypeList & typeList)9307 void TParseContext::fixBlockUniformOffsets(TQualifier& qualifier, TTypeList& typeList)
9308 {
9309     if (!storageCanHaveLayoutInBlock(qualifier.storage) && !qualifier.isTaskMemory())
9310         return;
9311     if (qualifier.layoutPacking != ElpStd140 && qualifier.layoutPacking != ElpStd430 && qualifier.layoutPacking != ElpScalar)
9312         return;
9313 
9314     int offset = 0;
9315     int memberSize;
9316     for (unsigned int member = 0; member < typeList.size(); ++member) {
9317         TQualifier& memberQualifier = typeList[member].type->getQualifier();
9318         const TSourceLoc& memberLoc = typeList[member].loc;
9319 
9320         // "When align is applied to an array, it effects only the start of the array, not the array's internal stride."
9321 
9322         // modify just the children's view of matrix layout, if there is one for this member
9323         TLayoutMatrix subMatrixLayout = typeList[member].type->getQualifier().layoutMatrix;
9324         int dummyStride;
9325         int memberAlignment = intermediate.getMemberAlignment(*typeList[member].type, memberSize, dummyStride, qualifier.layoutPacking,
9326                                                               subMatrixLayout != ElmNone ? subMatrixLayout == ElmRowMajor : qualifier.layoutMatrix == ElmRowMajor);
9327         if (memberQualifier.hasOffset()) {
9328             // "The specified offset must be a multiple
9329             // of the base alignment of the type of the block member it qualifies, or a compile-time error results."
9330             if (! IsMultipleOfPow2(memberQualifier.layoutOffset, memberAlignment))
9331                 error(memberLoc, "must be a multiple of the member's alignment", "offset",
9332                     "(layout offset = %d | member alignment = %d)", memberQualifier.layoutOffset, memberAlignment);
9333 
9334             // GLSL: "It is a compile-time error to specify an offset that is smaller than the offset of the previous
9335             // member in the block or that lies within the previous member of the block"
9336             if (spvVersion.spv == 0) {
9337                 if (memberQualifier.layoutOffset < offset)
9338                     error(memberLoc, "cannot lie in previous members", "offset", "");
9339 
9340                 // "The offset qualifier forces the qualified member to start at or after the specified
9341                 // integral-constant expression, which will be its byte offset from the beginning of the buffer.
9342                 // "The actual offset of a member is computed as
9343                 // follows: If offset was declared, start with that offset, otherwise start with the next available offset."
9344                 offset = std::max(offset, memberQualifier.layoutOffset);
9345             } else {
9346                 // TODO: Vulkan: "It is a compile-time error to have any offset, explicit or assigned,
9347                 // that lies within another member of the block."
9348 
9349                 offset = memberQualifier.layoutOffset;
9350             }
9351         }
9352 
9353         // "The actual alignment of a member will be the greater of the specified align alignment and the standard
9354         // (e.g., std140) base alignment for the member's type."
9355         if (memberQualifier.hasAlign())
9356             memberAlignment = std::max(memberAlignment, memberQualifier.layoutAlign);
9357 
9358         // "If the resulting offset is not a multiple of the actual alignment,
9359         // increase it to the first offset that is a multiple of
9360         // the actual alignment."
9361         RoundToPow2(offset, memberAlignment);
9362         typeList[member].type->getQualifier().layoutOffset = offset;
9363         offset += memberSize;
9364     }
9365 }
9366 
9367 //
9368 // Spread LayoutMatrix to uniform block member, if a uniform block member is a struct,
9369 // we need spread LayoutMatrix to this struct member too. and keep this rule for recursive.
9370 //
fixBlockUniformLayoutMatrix(TQualifier & qualifier,TTypeList * originTypeList,TTypeList * tmpTypeList)9371 void TParseContext::fixBlockUniformLayoutMatrix(TQualifier& qualifier, TTypeList* originTypeList,
9372                                                 TTypeList* tmpTypeList)
9373 {
9374     assert(tmpTypeList == nullptr || originTypeList->size() == tmpTypeList->size());
9375     for (unsigned int member = 0; member < originTypeList->size(); ++member) {
9376         if (qualifier.layoutPacking != ElpNone) {
9377             if (tmpTypeList == nullptr) {
9378                 if (((*originTypeList)[member].type->isMatrix() ||
9379                      (*originTypeList)[member].type->getBasicType() == EbtStruct) &&
9380                     (*originTypeList)[member].type->getQualifier().layoutMatrix == ElmNone) {
9381                     (*originTypeList)[member].type->getQualifier().layoutMatrix = qualifier.layoutMatrix;
9382                 }
9383             } else {
9384                 if (((*tmpTypeList)[member].type->isMatrix() ||
9385                      (*tmpTypeList)[member].type->getBasicType() == EbtStruct) &&
9386                     (*tmpTypeList)[member].type->getQualifier().layoutMatrix == ElmNone) {
9387                     (*tmpTypeList)[member].type->getQualifier().layoutMatrix = qualifier.layoutMatrix;
9388                 }
9389             }
9390         }
9391 
9392         if ((*originTypeList)[member].type->getBasicType() == EbtStruct) {
9393             TQualifier* memberQualifier = nullptr;
9394             // block member can be declare a matrix style, so it should be update to the member's style
9395             if ((*originTypeList)[member].type->getQualifier().layoutMatrix == ElmNone) {
9396                 memberQualifier = &qualifier;
9397             } else {
9398                 memberQualifier = &((*originTypeList)[member].type->getQualifier());
9399             }
9400 
9401             const TType* tmpType = tmpTypeList == nullptr ?
9402                 (*originTypeList)[member].type->clone() : (*tmpTypeList)[member].type;
9403 
9404             fixBlockUniformLayoutMatrix(*memberQualifier, (*originTypeList)[member].type->getWritableStruct(),
9405                                         tmpType->getWritableStruct());
9406 
9407             const TTypeList* structure = recordStructCopy(matrixFixRecord, (*originTypeList)[member].type, tmpType);
9408 
9409             if (tmpTypeList == nullptr) {
9410                 (*originTypeList)[member].type->setStruct(const_cast<TTypeList*>(structure));
9411             }
9412             if (tmpTypeList != nullptr) {
9413                 (*tmpTypeList)[member].type->setStruct(const_cast<TTypeList*>(structure));
9414             }
9415         }
9416     }
9417 }
9418 
9419 //
9420 // Spread LayoutPacking to matrix or aggregate block members. If a block member is a struct or
9421 // array of struct, spread LayoutPacking recursively to its matrix or aggregate members.
9422 //
fixBlockUniformLayoutPacking(TQualifier & qualifier,TTypeList * originTypeList,TTypeList * tmpTypeList)9423 void TParseContext::fixBlockUniformLayoutPacking(TQualifier& qualifier, TTypeList* originTypeList,
9424                                                  TTypeList* tmpTypeList)
9425 {
9426     assert(tmpTypeList == nullptr || originTypeList->size() == tmpTypeList->size());
9427     for (unsigned int member = 0; member < originTypeList->size(); ++member) {
9428         if (qualifier.layoutPacking != ElpNone) {
9429             if (tmpTypeList == nullptr) {
9430                 if ((*originTypeList)[member].type->getQualifier().layoutPacking == ElpNone &&
9431                     !(*originTypeList)[member].type->isScalarOrVector()) {
9432                     (*originTypeList)[member].type->getQualifier().layoutPacking = qualifier.layoutPacking;
9433                 }
9434             } else {
9435                 if ((*tmpTypeList)[member].type->getQualifier().layoutPacking == ElpNone &&
9436                     !(*tmpTypeList)[member].type->isScalarOrVector()) {
9437                     (*tmpTypeList)[member].type->getQualifier().layoutPacking = qualifier.layoutPacking;
9438                 }
9439             }
9440         }
9441 
9442         if ((*originTypeList)[member].type->getBasicType() == EbtStruct) {
9443             // Deep copy the type in pool.
9444             // Because, struct use in different block may have different layout qualifier.
9445             // We have to new a object to distinguish between them.
9446             const TType* tmpType = tmpTypeList == nullptr ?
9447                 (*originTypeList)[member].type->clone() : (*tmpTypeList)[member].type;
9448 
9449             fixBlockUniformLayoutPacking(qualifier, (*originTypeList)[member].type->getWritableStruct(),
9450                                          tmpType->getWritableStruct());
9451 
9452             const TTypeList* structure = recordStructCopy(packingFixRecord, (*originTypeList)[member].type, tmpType);
9453 
9454             if (tmpTypeList == nullptr) {
9455                 (*originTypeList)[member].type->setStruct(const_cast<TTypeList*>(structure));
9456             }
9457             if (tmpTypeList != nullptr) {
9458                 (*tmpTypeList)[member].type->setStruct(const_cast<TTypeList*>(structure));
9459             }
9460         }
9461     }
9462 }
9463 
9464 // For an identifier that is already declared, add more qualification to it.
addQualifierToExisting(const TSourceLoc & loc,TQualifier qualifier,const TString & identifier)9465 void TParseContext::addQualifierToExisting(const TSourceLoc& loc, TQualifier qualifier, const TString& identifier)
9466 {
9467     TSymbol* symbol = symbolTable.find(identifier);
9468 
9469     // A forward declaration of a block reference looks to the grammar like adding
9470     // a qualifier to an existing symbol. Detect this and create the block reference
9471     // type with an empty type list, which will be filled in later in
9472     // TParseContext::declareBlock.
9473     if (!symbol && qualifier.hasBufferReference()) {
9474         TTypeList typeList;
9475         TType blockType(&typeList, identifier, qualifier);
9476         TType blockNameType(EbtReference, blockType, identifier);
9477         TVariable* blockNameVar = new TVariable(&identifier, blockNameType, true);
9478         if (! symbolTable.insert(*blockNameVar)) {
9479             error(loc, "block name cannot redefine a non-block name", blockName->c_str(), "");
9480         }
9481         return;
9482     }
9483 
9484     if (! symbol) {
9485         error(loc, "identifier not previously declared", identifier.c_str(), "");
9486         return;
9487     }
9488     if (symbol->getAsFunction()) {
9489         error(loc, "cannot re-qualify a function name", identifier.c_str(), "");
9490         return;
9491     }
9492 
9493     if (qualifier.isAuxiliary() ||
9494         qualifier.isMemory() ||
9495         qualifier.isInterpolation() ||
9496         qualifier.hasLayout() ||
9497         qualifier.storage != EvqTemporary ||
9498         qualifier.precision != EpqNone) {
9499         error(loc, "cannot add storage, auxiliary, memory, interpolation, layout, or precision qualifier to an existing variable", identifier.c_str(), "");
9500         return;
9501     }
9502 
9503     // For read-only built-ins, add a new symbol for holding the modified qualifier.
9504     // This will bring up an entire block, if a block type has to be modified (e.g., gl_Position inside a block)
9505     if (symbol->isReadOnly())
9506         symbol = symbolTable.copyUp(symbol);
9507 
9508     if (qualifier.invariant) {
9509         if (intermediate.inIoAccessed(identifier))
9510             error(loc, "cannot change qualification after use", "invariant", "");
9511         symbol->getWritableType().getQualifier().invariant = true;
9512         invariantCheck(loc, symbol->getType().getQualifier());
9513     } else if (qualifier.isNoContraction()) {
9514         if (intermediate.inIoAccessed(identifier))
9515             error(loc, "cannot change qualification after use", "precise", "");
9516         symbol->getWritableType().getQualifier().setNoContraction();
9517     } else if (qualifier.specConstant) {
9518         symbol->getWritableType().getQualifier().makeSpecConstant();
9519         if (qualifier.hasSpecConstantId())
9520             symbol->getWritableType().getQualifier().layoutSpecConstantId = qualifier.layoutSpecConstantId;
9521     } else
9522         warn(loc, "unknown requalification", "", "");
9523 }
9524 
addQualifierToExisting(const TSourceLoc & loc,TQualifier qualifier,TIdentifierList & identifiers)9525 void TParseContext::addQualifierToExisting(const TSourceLoc& loc, TQualifier qualifier, TIdentifierList& identifiers)
9526 {
9527     for (unsigned int i = 0; i < identifiers.size(); ++i)
9528         addQualifierToExisting(loc, qualifier, *identifiers[i]);
9529 }
9530 
9531 // Make sure 'invariant' isn't being applied to a non-allowed object.
invariantCheck(const TSourceLoc & loc,const TQualifier & qualifier)9532 void TParseContext::invariantCheck(const TSourceLoc& loc, const TQualifier& qualifier)
9533 {
9534     if (! qualifier.invariant)
9535         return;
9536 
9537     bool pipeOut = qualifier.isPipeOutput();
9538     bool pipeIn = qualifier.isPipeInput();
9539     if ((version >= 300 && isEsProfile()) || (!isEsProfile() && version >= 420)) {
9540         if (! pipeOut)
9541             error(loc, "can only apply to an output", "invariant", "");
9542     } else {
9543         if ((language == EShLangVertex && pipeIn) || (! pipeOut && ! pipeIn))
9544             error(loc, "can only apply to an output, or to an input in a non-vertex stage\n", "invariant", "");
9545     }
9546 }
9547 
9548 //
9549 // Updating default qualifier for the case of a declaration with just a qualifier,
9550 // no type, block, or identifier.
9551 //
updateStandaloneQualifierDefaults(const TSourceLoc & loc,const TPublicType & publicType)9552 void TParseContext::updateStandaloneQualifierDefaults(const TSourceLoc& loc, const TPublicType& publicType)
9553 {
9554     if (publicType.shaderQualifiers.vertices != TQualifier::layoutNotSet) {
9555         assert(language == EShLangTessControl || language == EShLangGeometry || language == EShLangMesh);
9556         const char* id = (language == EShLangTessControl) ? "vertices" : "max_vertices";
9557 
9558         if (publicType.qualifier.storage != EvqVaryingOut)
9559             error(loc, "can only apply to 'out'", id, "");
9560         if (! intermediate.setVertices(publicType.shaderQualifiers.vertices))
9561             error(loc, "cannot change previously set layout value", id, "");
9562 
9563         if (language == EShLangTessControl)
9564             checkIoArraysConsistency(loc);
9565     }
9566     if (publicType.shaderQualifiers.primitives != TQualifier::layoutNotSet) {
9567         assert(language == EShLangMesh);
9568         const char* id = "max_primitives";
9569 
9570         if (publicType.qualifier.storage != EvqVaryingOut)
9571             error(loc, "can only apply to 'out'", id, "");
9572         if (! intermediate.setPrimitives(publicType.shaderQualifiers.primitives))
9573             error(loc, "cannot change previously set layout value", id, "");
9574     }
9575     if (publicType.shaderQualifiers.invocations != TQualifier::layoutNotSet) {
9576         if (publicType.qualifier.storage != EvqVaryingIn)
9577             error(loc, "can only apply to 'in'", "invocations", "");
9578         if (! intermediate.setInvocations(publicType.shaderQualifiers.invocations))
9579             error(loc, "cannot change previously set layout value", "invocations", "");
9580     }
9581     if (publicType.shaderQualifiers.geometry != ElgNone) {
9582         if (publicType.qualifier.storage == EvqVaryingIn) {
9583             switch (publicType.shaderQualifiers.geometry) {
9584             case ElgPoints:
9585             case ElgLines:
9586             case ElgLinesAdjacency:
9587             case ElgTriangles:
9588             case ElgTrianglesAdjacency:
9589             case ElgQuads:
9590             case ElgIsolines:
9591                 if (language == EShLangMesh) {
9592                     error(loc, "cannot apply to input", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
9593                     break;
9594                 }
9595                 if (intermediate.setInputPrimitive(publicType.shaderQualifiers.geometry)) {
9596                     if (language == EShLangGeometry)
9597                         checkIoArraysConsistency(loc);
9598                 } else
9599                     error(loc, "cannot change previously set input primitive", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
9600                 break;
9601             default:
9602                 error(loc, "cannot apply to input", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
9603             }
9604         } else if (publicType.qualifier.storage == EvqVaryingOut) {
9605             switch (publicType.shaderQualifiers.geometry) {
9606             case ElgLines:
9607             case ElgTriangles:
9608                 if (language != EShLangMesh) {
9609                     error(loc, "cannot apply to 'out'", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
9610                     break;
9611                 }
9612                 // Fall through
9613             case ElgPoints:
9614             case ElgLineStrip:
9615             case ElgTriangleStrip:
9616                 if (! intermediate.setOutputPrimitive(publicType.shaderQualifiers.geometry))
9617                     error(loc, "cannot change previously set output primitive", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
9618                 break;
9619             default:
9620                 error(loc, "cannot apply to 'out'", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
9621             }
9622         } else
9623             error(loc, "cannot apply to:", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), GetStorageQualifierString(publicType.qualifier.storage));
9624     }
9625     if (publicType.shaderQualifiers.spacing != EvsNone) {
9626         if (publicType.qualifier.storage == EvqVaryingIn) {
9627             if (! intermediate.setVertexSpacing(publicType.shaderQualifiers.spacing))
9628                 error(loc, "cannot change previously set vertex spacing", TQualifier::getVertexSpacingString(publicType.shaderQualifiers.spacing), "");
9629         } else
9630             error(loc, "can only apply to 'in'", TQualifier::getVertexSpacingString(publicType.shaderQualifiers.spacing), "");
9631     }
9632     if (publicType.shaderQualifiers.order != EvoNone) {
9633         if (publicType.qualifier.storage == EvqVaryingIn) {
9634             if (! intermediate.setVertexOrder(publicType.shaderQualifiers.order))
9635                 error(loc, "cannot change previously set vertex order", TQualifier::getVertexOrderString(publicType.shaderQualifiers.order), "");
9636         } else
9637             error(loc, "can only apply to 'in'", TQualifier::getVertexOrderString(publicType.shaderQualifiers.order), "");
9638     }
9639     if (publicType.shaderQualifiers.pointMode) {
9640         if (publicType.qualifier.storage == EvqVaryingIn)
9641             intermediate.setPointMode();
9642         else
9643             error(loc, "can only apply to 'in'", "point_mode", "");
9644     }
9645 
9646     for (int i = 0; i < 3; ++i) {
9647         if (publicType.shaderQualifiers.localSizeNotDefault[i]) {
9648             if (publicType.qualifier.storage == EvqVaryingIn) {
9649                 if (! intermediate.setLocalSize(i, publicType.shaderQualifiers.localSize[i]))
9650                     error(loc, "cannot change previously set size", "local_size", "");
9651                 else {
9652                     int max = 0;
9653                     if (language == EShLangCompute) {
9654                         switch (i) {
9655                         case 0: max = resources.maxComputeWorkGroupSizeX; break;
9656                         case 1: max = resources.maxComputeWorkGroupSizeY; break;
9657                         case 2: max = resources.maxComputeWorkGroupSizeZ; break;
9658                         default: break;
9659                         }
9660                         if (intermediate.getLocalSize(i) > (unsigned int)max)
9661                             error(loc, "too large; see gl_MaxComputeWorkGroupSize", "local_size", "");
9662                     } else if (language == EShLangMesh) {
9663                         switch (i) {
9664                         case 0:
9665                             max = extensionTurnedOn(E_GL_EXT_mesh_shader) ?
9666                                     resources.maxMeshWorkGroupSizeX_EXT :
9667                                     resources.maxMeshWorkGroupSizeX_NV;
9668                             break;
9669                         case 1:
9670                             max = extensionTurnedOn(E_GL_EXT_mesh_shader) ?
9671                                     resources.maxMeshWorkGroupSizeY_EXT :
9672                                     resources.maxMeshWorkGroupSizeY_NV ;
9673                             break;
9674                         case 2:
9675                             max = extensionTurnedOn(E_GL_EXT_mesh_shader) ?
9676                                     resources.maxMeshWorkGroupSizeZ_EXT :
9677                                     resources.maxMeshWorkGroupSizeZ_NV ;
9678                             break;
9679                         default: break;
9680                         }
9681                         if (intermediate.getLocalSize(i) > (unsigned int)max) {
9682                             TString maxsErrtring = "too large, see ";
9683                             maxsErrtring.append(extensionTurnedOn(E_GL_EXT_mesh_shader) ?
9684                                                     "gl_MaxMeshWorkGroupSizeEXT" : "gl_MaxMeshWorkGroupSizeNV");
9685                             error(loc, maxsErrtring.c_str(), "local_size", "");
9686                         }
9687                     } else if (language == EShLangTask) {
9688                         switch (i) {
9689                         case 0:
9690                             max = extensionTurnedOn(E_GL_EXT_mesh_shader) ?
9691                                     resources.maxTaskWorkGroupSizeX_EXT :
9692                                     resources.maxTaskWorkGroupSizeX_NV;
9693                             break;
9694                         case 1:
9695                             max = extensionTurnedOn(E_GL_EXT_mesh_shader) ?
9696                                     resources.maxTaskWorkGroupSizeY_EXT:
9697                                     resources.maxTaskWorkGroupSizeY_NV;
9698                             break;
9699                         case 2:
9700                             max = extensionTurnedOn(E_GL_EXT_mesh_shader) ?
9701                                     resources.maxTaskWorkGroupSizeZ_EXT:
9702                                     resources.maxTaskWorkGroupSizeZ_NV;
9703                             break;
9704                         default: break;
9705                         }
9706                         if (intermediate.getLocalSize(i) > (unsigned int)max) {
9707                             TString maxsErrtring = "too large, see ";
9708                             maxsErrtring.append(extensionTurnedOn(E_GL_EXT_mesh_shader) ?
9709                                                     "gl_MaxTaskWorkGroupSizeEXT" : "gl_MaxTaskWorkGroupSizeNV");
9710                             error(loc, maxsErrtring.c_str(), "local_size", "");
9711                         }
9712                     } else {
9713                         assert(0);
9714                     }
9715 
9716                     // Fix the existing constant gl_WorkGroupSize with this new information.
9717                     TVariable* workGroupSize = getEditableVariable("gl_WorkGroupSize");
9718                     if (workGroupSize != nullptr)
9719                         workGroupSize->getWritableConstArray()[i].setUConst(intermediate.getLocalSize(i));
9720                 }
9721             } else
9722                 error(loc, "can only apply to 'in'", "local_size", "");
9723         }
9724         if (publicType.shaderQualifiers.localSizeSpecId[i] != TQualifier::layoutNotSet) {
9725             if (publicType.qualifier.storage == EvqVaryingIn) {
9726                 if (! intermediate.setLocalSizeSpecId(i, publicType.shaderQualifiers.localSizeSpecId[i]))
9727                     error(loc, "cannot change previously set size", "local_size", "");
9728             } else
9729                 error(loc, "can only apply to 'in'", "local_size id", "");
9730             // Set the workgroup built-in variable as a specialization constant
9731             TVariable* workGroupSize = getEditableVariable("gl_WorkGroupSize");
9732             if (workGroupSize != nullptr)
9733                 workGroupSize->getWritableType().getQualifier().specConstant = true;
9734         }
9735     }
9736 
9737     if (publicType.shaderQualifiers.earlyFragmentTests) {
9738         if (publicType.qualifier.storage == EvqVaryingIn)
9739             intermediate.setEarlyFragmentTests();
9740         else
9741             error(loc, "can only apply to 'in'", "early_fragment_tests", "");
9742     }
9743     if (publicType.shaderQualifiers.earlyAndLateFragmentTestsAMD) {
9744         if (publicType.qualifier.storage == EvqVaryingIn)
9745             intermediate.setEarlyAndLateFragmentTestsAMD();
9746         else
9747             error(loc, "can only apply to 'in'", "early_and_late_fragment_tests_amd", "");
9748     }
9749     if (publicType.shaderQualifiers.postDepthCoverage) {
9750         if (publicType.qualifier.storage == EvqVaryingIn)
9751             intermediate.setPostDepthCoverage();
9752         else
9753             error(loc, "can only apply to 'in'", "post_coverage_coverage", "");
9754     }
9755     if (publicType.shaderQualifiers.nonCoherentColorAttachmentReadEXT) {
9756         if (publicType.qualifier.storage == EvqVaryingIn)
9757             intermediate.setNonCoherentColorAttachmentReadEXT();
9758         else
9759             error(loc, "can only apply to 'in'", "non_coherent_color_attachment_readEXT", "");
9760     }
9761     if (publicType.shaderQualifiers.nonCoherentDepthAttachmentReadEXT) {
9762         if (publicType.qualifier.storage == EvqVaryingIn)
9763             intermediate.setNonCoherentDepthAttachmentReadEXT();
9764         else
9765             error(loc, "can only apply to 'in'", "non_coherent_depth_attachment_readEXT", "");
9766     }
9767     if (publicType.shaderQualifiers.nonCoherentStencilAttachmentReadEXT) {
9768         if (publicType.qualifier.storage == EvqVaryingIn)
9769             intermediate.setNonCoherentStencilAttachmentReadEXT();
9770         else
9771             error(loc, "can only apply to 'in'", "non_coherent_stencil_attachment_readEXT", "");
9772     }
9773     if (publicType.shaderQualifiers.hasBlendEquation()) {
9774         if (publicType.qualifier.storage != EvqVaryingOut)
9775             error(loc, "can only apply to 'out'", "blend equation", "");
9776     }
9777     if (publicType.shaderQualifiers.interlockOrdering) {
9778         if (publicType.qualifier.storage == EvqVaryingIn) {
9779             if (!intermediate.setInterlockOrdering(publicType.shaderQualifiers.interlockOrdering))
9780                 error(loc, "cannot change previously set fragment shader interlock ordering", TQualifier::getInterlockOrderingString(publicType.shaderQualifiers.interlockOrdering), "");
9781         }
9782         else
9783             error(loc, "can only apply to 'in'", TQualifier::getInterlockOrderingString(publicType.shaderQualifiers.interlockOrdering), "");
9784     }
9785 
9786     if (publicType.shaderQualifiers.layoutDerivativeGroupQuads &&
9787         publicType.shaderQualifiers.layoutDerivativeGroupLinear) {
9788         error(loc, "cannot be both specified", "derivative_group_quadsNV and derivative_group_linearNV", "");
9789     }
9790 
9791     if (publicType.shaderQualifiers.layoutDerivativeGroupQuads) {
9792         if (publicType.qualifier.storage == EvqVaryingIn) {
9793             if ((intermediate.getLocalSize(0) & 1) ||
9794                 (intermediate.getLocalSize(1) & 1))
9795                 error(loc, "requires local_size_x and local_size_y to be multiple of two", "derivative_group_quadsNV", "");
9796             else
9797                 intermediate.setLayoutDerivativeMode(LayoutDerivativeGroupQuads);
9798         }
9799         else
9800             error(loc, "can only apply to 'in'", "derivative_group_quadsNV", "");
9801     }
9802     if (publicType.shaderQualifiers.layoutDerivativeGroupLinear) {
9803         if (publicType.qualifier.storage == EvqVaryingIn) {
9804             if((intermediate.getLocalSize(0) *
9805                 intermediate.getLocalSize(1) *
9806                 intermediate.getLocalSize(2)) % 4 != 0)
9807                 error(loc, "requires total group size to be multiple of four", "derivative_group_linearNV", "");
9808             else
9809                 intermediate.setLayoutDerivativeMode(LayoutDerivativeGroupLinear);
9810         }
9811         else
9812             error(loc, "can only apply to 'in'", "derivative_group_linearNV", "");
9813     }
9814     // Check mesh out array sizes, once all the necessary out qualifiers are defined.
9815     if ((language == EShLangMesh) &&
9816         (intermediate.getVertices() != TQualifier::layoutNotSet) &&
9817         (intermediate.getPrimitives() != TQualifier::layoutNotSet) &&
9818         (intermediate.getOutputPrimitive() != ElgNone))
9819     {
9820         checkIoArraysConsistency(loc);
9821     }
9822 
9823     if (publicType.shaderQualifiers.layoutPrimitiveCulling) {
9824         if (publicType.qualifier.storage != EvqTemporary)
9825             error(loc, "layout qualifier can not have storage qualifiers", "primitive_culling","", "");
9826         else {
9827             intermediate.setLayoutPrimitiveCulling();
9828         }
9829         // Exit early as further checks are not valid
9830         return;
9831     }
9832 
9833     const TQualifier& qualifier = publicType.qualifier;
9834 
9835     if (qualifier.isAuxiliary() ||
9836         qualifier.isMemory() ||
9837         qualifier.isInterpolation() ||
9838         qualifier.precision != EpqNone)
9839         error(loc, "cannot use auxiliary, memory, interpolation, or precision qualifier in a default qualifier declaration (declaration with no type)", "qualifier", "");
9840 
9841     // "The offset qualifier can only be used on block members of blocks..."
9842     // "The align qualifier can only be used on blocks or block members..."
9843     if (qualifier.hasOffset() ||
9844         qualifier.hasAlign())
9845         error(loc, "cannot use offset or align qualifiers in a default qualifier declaration (declaration with no type)", "layout qualifier", "");
9846 
9847     layoutQualifierCheck(loc, qualifier);
9848 
9849     switch (qualifier.storage) {
9850     case EvqUniform:
9851         if (qualifier.hasMatrix())
9852             globalUniformDefaults.layoutMatrix = qualifier.layoutMatrix;
9853         if (qualifier.hasPacking())
9854             globalUniformDefaults.layoutPacking = qualifier.layoutPacking;
9855         break;
9856     case EvqBuffer:
9857         if (qualifier.hasMatrix())
9858             globalBufferDefaults.layoutMatrix = qualifier.layoutMatrix;
9859         if (qualifier.hasPacking())
9860             globalBufferDefaults.layoutPacking = qualifier.layoutPacking;
9861         break;
9862     case EvqVaryingIn:
9863         break;
9864     case EvqVaryingOut:
9865         if (qualifier.hasStream())
9866             globalOutputDefaults.layoutStream = qualifier.layoutStream;
9867         if (qualifier.hasXfbBuffer())
9868             globalOutputDefaults.layoutXfbBuffer = qualifier.layoutXfbBuffer;
9869         if (globalOutputDefaults.hasXfbBuffer() && qualifier.hasXfbStride()) {
9870             if (! intermediate.setXfbBufferStride(globalOutputDefaults.layoutXfbBuffer, qualifier.layoutXfbStride))
9871                 error(loc, "all stride settings must match for xfb buffer", "xfb_stride", "%d", qualifier.layoutXfbBuffer);
9872         }
9873         break;
9874     case EvqShared:
9875         if (qualifier.hasMatrix())
9876             globalSharedDefaults.layoutMatrix = qualifier.layoutMatrix;
9877         if (qualifier.hasPacking())
9878             globalSharedDefaults.layoutPacking = qualifier.layoutPacking;
9879         break;
9880     default:
9881         error(loc, "default qualifier requires 'uniform', 'buffer', 'in', 'out' or 'shared' storage qualification", "", "");
9882         return;
9883     }
9884 
9885     if (qualifier.hasBinding())
9886         error(loc, "cannot declare a default, include a type or full declaration", "binding", "");
9887     if (qualifier.hasAnyLocation())
9888         error(loc, "cannot declare a default, use a full declaration", "location/component/index", "");
9889     if (qualifier.hasXfbOffset())
9890         error(loc, "cannot declare a default, use a full declaration", "xfb_offset", "");
9891     if (qualifier.isPushConstant())
9892         error(loc, "cannot declare a default, can only be used on a block", "push_constant", "");
9893     if (qualifier.hasBufferReference())
9894         error(loc, "cannot declare a default, can only be used on a block", "buffer_reference", "");
9895     if (qualifier.hasSpecConstantId())
9896         error(loc, "cannot declare a default, can only be used on a scalar", "constant_id", "");
9897     if (qualifier.isShaderRecord())
9898         error(loc, "cannot declare a default, can only be used on a block", "shaderRecordNV", "");
9899 }
9900 
9901 //
9902 // Take the sequence of statements that has been built up since the last case/default,
9903 // put it on the list of top-level nodes for the current (inner-most) switch statement,
9904 // and follow that by the case/default we are on now.  (See switch topology comment on
9905 // TIntermSwitch.)
9906 //
wrapupSwitchSubsequence(TIntermAggregate * statements,TIntermNode * branchNode)9907 void TParseContext::wrapupSwitchSubsequence(TIntermAggregate* statements, TIntermNode* branchNode)
9908 {
9909     TIntermSequence* switchSequence = switchSequenceStack.back();
9910 
9911     if (statements) {
9912         if (switchSequence->size() == 0)
9913             error(statements->getLoc(), "cannot have statements before first case/default label", "switch", "");
9914         statements->setOperator(EOpSequence);
9915         switchSequence->push_back(statements);
9916     }
9917     if (branchNode) {
9918         // check all previous cases for the same label (or both are 'default')
9919         for (unsigned int s = 0; s < switchSequence->size(); ++s) {
9920             TIntermBranch* prevBranch = (*switchSequence)[s]->getAsBranchNode();
9921             if (prevBranch) {
9922                 TIntermTyped* prevExpression = prevBranch->getExpression();
9923                 TIntermTyped* newExpression = branchNode->getAsBranchNode()->getExpression();
9924                 if (prevExpression == nullptr && newExpression == nullptr)
9925                     error(branchNode->getLoc(), "duplicate label", "default", "");
9926                 else if (prevExpression != nullptr &&
9927                           newExpression != nullptr &&
9928                          prevExpression->getAsConstantUnion() &&
9929                           newExpression->getAsConstantUnion() &&
9930                          prevExpression->getAsConstantUnion()->getConstArray()[0].getIConst() ==
9931                           newExpression->getAsConstantUnion()->getConstArray()[0].getIConst())
9932                     error(branchNode->getLoc(), "duplicated value", "case", "");
9933             }
9934         }
9935         switchSequence->push_back(branchNode);
9936     }
9937 }
9938 
9939 //
9940 // Turn the top-level node sequence built up of wrapupSwitchSubsequence9)
9941 // into a switch node.
9942 //
addSwitch(const TSourceLoc & loc,TIntermTyped * expression,TIntermAggregate * lastStatements)9943 TIntermNode* TParseContext::addSwitch(const TSourceLoc& loc, TIntermTyped* expression, TIntermAggregate* lastStatements)
9944 {
9945     profileRequires(loc, EEsProfile, 300, nullptr, "switch statements");
9946     profileRequires(loc, ENoProfile, 130, nullptr, "switch statements");
9947 
9948     wrapupSwitchSubsequence(lastStatements, nullptr);
9949 
9950     if (expression == nullptr ||
9951         (expression->getBasicType() != EbtInt && expression->getBasicType() != EbtUint) ||
9952         expression->getType().isArray() || expression->getType().isMatrix() || expression->getType().isVector())
9953             error(loc, "condition must be a scalar integer expression", "switch", "");
9954 
9955     // If there is nothing to do, drop the switch but still execute the expression
9956     TIntermSequence* switchSequence = switchSequenceStack.back();
9957     if (switchSequence->size() == 0)
9958         return expression;
9959 
9960     if (lastStatements == nullptr) {
9961         // This was originally an ERRROR, because early versions of the specification said
9962         // "it is an error to have no statement between a label and the end of the switch statement."
9963         // The specifications were updated to remove this (being ill-defined what a "statement" was),
9964         // so, this became a warning.  However, 3.0 tests still check for the error.
9965         if (isEsProfile() && (version <= 300 || version >= 320) && ! relaxedErrors())
9966             error(loc, "last case/default label not followed by statements", "switch", "");
9967         else if (!isEsProfile() && (version <= 430 || version >= 460))
9968             error(loc, "last case/default label not followed by statements", "switch", "");
9969         else
9970             warn(loc, "last case/default label not followed by statements", "switch", "");
9971 
9972 
9973         // emulate a break for error recovery
9974         lastStatements = intermediate.makeAggregate(intermediate.addBranch(EOpBreak, loc));
9975         lastStatements->setOperator(EOpSequence);
9976         switchSequence->push_back(lastStatements);
9977     }
9978 
9979     TIntermAggregate* body = new TIntermAggregate(EOpSequence);
9980     body->getSequence() = *switchSequenceStack.back();
9981     body->setLoc(loc);
9982 
9983     TIntermSwitch* switchNode = new TIntermSwitch(expression, body);
9984     switchNode->setLoc(loc);
9985 
9986     return switchNode;
9987 }
9988 
9989 //
9990 // When a struct used in block, and has it's own layout packing, layout matrix,
9991 // record the origin structure of a struct to map, and Record the structure copy to the copy table,
9992 //
recordStructCopy(TStructRecord & record,const TType * originType,const TType * tmpType)9993 const TTypeList* TParseContext::recordStructCopy(TStructRecord& record, const TType* originType, const TType* tmpType)
9994 {
9995     size_t memberCount = tmpType->getStruct()->size();
9996     size_t originHash = 0, tmpHash = 0;
9997     std::hash<size_t> hasher;
9998     for (size_t i = 0; i < memberCount; i++) {
9999         size_t originMemberHash = hasher(originType->getStruct()->at(i).type->getQualifier().layoutPacking +
10000                                          originType->getStruct()->at(i).type->getQualifier().layoutMatrix);
10001         size_t tmpMemberHash = hasher(tmpType->getStruct()->at(i).type->getQualifier().layoutPacking +
10002                                       tmpType->getStruct()->at(i).type->getQualifier().layoutMatrix);
10003         originHash = hasher((originHash ^ originMemberHash) << 1);
10004         tmpHash = hasher((tmpHash ^ tmpMemberHash) << 1);
10005     }
10006     const TTypeList* originStruct = originType->getStruct();
10007     const TTypeList* tmpStruct = tmpType->getStruct();
10008     if (originHash != tmpHash) {
10009         auto fixRecords = record.find(originStruct);
10010         if (fixRecords != record.end()) {
10011             auto fixRecord = fixRecords->second.find(tmpHash);
10012             if (fixRecord != fixRecords->second.end()) {
10013                 return fixRecord->second;
10014             } else {
10015                 record[originStruct][tmpHash] = tmpStruct;
10016                 return tmpStruct;
10017             }
10018         } else {
10019             record[originStruct] = std::map<size_t, const TTypeList*>();
10020             record[originStruct][tmpHash] = tmpStruct;
10021             return tmpStruct;
10022         }
10023     }
10024     return originStruct;
10025 }
10026 
mapLegacyLayoutFormat(TLayoutFormat legacyLayoutFormat,TBasicType imageType)10027 TLayoutFormat TParseContext::mapLegacyLayoutFormat(TLayoutFormat legacyLayoutFormat, TBasicType imageType)
10028 {
10029     TLayoutFormat layoutFormat = ElfNone;
10030     if (imageType == EbtFloat) {
10031         switch (legacyLayoutFormat) {
10032         case ElfSize1x16: layoutFormat = ElfR16f; break;
10033         case ElfSize1x32: layoutFormat = ElfR32f; break;
10034         case ElfSize2x32: layoutFormat = ElfRg32f; break;
10035         case ElfSize4x32: layoutFormat = ElfRgba32f; break;
10036         default: break;
10037         }
10038     } else if (imageType == EbtUint) {
10039         switch (legacyLayoutFormat) {
10040         case ElfSize1x8: layoutFormat = ElfR8ui; break;
10041         case ElfSize1x16: layoutFormat = ElfR16ui; break;
10042         case ElfSize1x32: layoutFormat = ElfR32ui; break;
10043         case ElfSize2x32: layoutFormat = ElfRg32ui; break;
10044         case ElfSize4x32: layoutFormat = ElfRgba32ui; break;
10045         default: break;
10046         }
10047     } else if (imageType == EbtInt) {
10048         switch (legacyLayoutFormat) {
10049         case ElfSize1x8: layoutFormat = ElfR8i; break;
10050         case ElfSize1x16: layoutFormat = ElfR16i; break;
10051         case ElfSize1x32: layoutFormat = ElfR32i; break;
10052         case ElfSize2x32: layoutFormat = ElfRg32i; break;
10053         case ElfSize4x32: layoutFormat = ElfRgba32i; break;
10054         default: break;
10055         }
10056     }
10057 
10058     return layoutFormat;
10059 }
10060 
10061 } // end namespace glslang
10062