e2ac43ca19ca2454bf2ecb0a7bfa6aeaefecc9b6
[platform/upstream/glslang.git] / glslang / MachineIndependent / ParseHelper.cpp
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 "Scan.h"
42
43 #include "../OSDependent/osinclude.h"
44 #include <algorithm>
45
46 #include "preprocessor/PpContext.h"
47
48 extern int yyparse(glslang::TParseContext*);
49
50 namespace glslang {
51
52 TParseContext::TParseContext(TSymbolTable& symbolTable, TIntermediate& interm, bool parsingBuiltins,
53                              int version, EProfile profile, const SpvVersion& spvVersion, EShLanguage language,
54                              TInfoSink& infoSink, bool forwardCompatible, EShMessages messages,
55                              const TString* entryPoint) :
56             TParseContextBase(symbolTable, interm, parsingBuiltins, version, profile, spvVersion, language,
57                               infoSink, forwardCompatible, messages, entryPoint),
58             inMain(false),
59             blockName(nullptr),
60             limits(resources.limits)
61 #ifndef GLSLANG_WEB
62             ,
63             atomicUintOffsets(nullptr), anyIndexLimits(false)
64 #endif
65 {
66     // decide whether precision qualifiers should be ignored or respected
67     if (isEsProfile() || spvVersion.vulkan > 0) {
68         precisionManager.respectPrecisionQualifiers();
69         if (! parsingBuiltins && language == EShLangFragment && !isEsProfile() && spvVersion.vulkan > 0)
70             precisionManager.warnAboutDefaults();
71     }
72
73     setPrecisionDefaults();
74
75     globalUniformDefaults.clear();
76     globalUniformDefaults.layoutMatrix = ElmColumnMajor;
77     globalUniformDefaults.layoutPacking = spvVersion.spv != 0 ? ElpStd140 : ElpShared;
78
79     globalBufferDefaults.clear();
80     globalBufferDefaults.layoutMatrix = ElmColumnMajor;
81     globalBufferDefaults.layoutPacking = spvVersion.spv != 0 ? ElpStd430 : ElpShared;
82
83     // use storage buffer on SPIR-V 1.3 and up
84     if (spvVersion.spv >= EShTargetSpv_1_3)
85         intermediate.setUseStorageBuffer();
86
87     globalInputDefaults.clear();
88     globalOutputDefaults.clear();
89
90     globalSharedDefaults.clear();
91     globalSharedDefaults.layoutMatrix = ElmColumnMajor;
92     globalSharedDefaults.layoutPacking = ElpStd430;
93
94 #ifndef GLSLANG_WEB
95     // "Shaders in the transform
96     // feedback capturing mode have an initial global default of
97     //     layout(xfb_buffer = 0) out;"
98     if (language == EShLangVertex ||
99         language == EShLangTessControl ||
100         language == EShLangTessEvaluation ||
101         language == EShLangGeometry)
102         globalOutputDefaults.layoutXfbBuffer = 0;
103
104     if (language == EShLangGeometry)
105         globalOutputDefaults.layoutStream = 0;
106 #endif
107
108     if (entryPoint != nullptr && entryPoint->size() > 0 && *entryPoint != "main")
109         infoSink.info.message(EPrefixError, "Source entry point must be \"main\"");
110 }
111
112 TParseContext::~TParseContext()
113 {
114 #ifndef GLSLANG_WEB
115     delete [] atomicUintOffsets;
116 #endif
117 }
118
119 // Set up all default precisions as needed by the current environment.
120 // Intended just as a TParseContext constructor helper.
121 void TParseContext::setPrecisionDefaults()
122 {
123     // Set all precision defaults to EpqNone, which is correct for all types
124     // when not obeying precision qualifiers, and correct for types that don't
125     // have defaults (thus getting an error on use) when obeying precision
126     // qualifiers.
127
128     for (int type = 0; type < EbtNumTypes; ++type)
129         defaultPrecision[type] = EpqNone;
130
131     for (int type = 0; type < maxSamplerIndex; ++type)
132         defaultSamplerPrecision[type] = EpqNone;
133
134     // replace with real precision defaults for those that have them
135     if (obeyPrecisionQualifiers()) {
136         if (isEsProfile()) {
137             // Most don't have defaults, a few default to lowp.
138             TSampler sampler;
139             sampler.set(EbtFloat, Esd2D);
140             defaultSamplerPrecision[computeSamplerTypeIndex(sampler)] = EpqLow;
141             sampler.set(EbtFloat, EsdCube);
142             defaultSamplerPrecision[computeSamplerTypeIndex(sampler)] = EpqLow;
143             sampler.set(EbtFloat, Esd2D);
144             sampler.setExternal(true);
145             defaultSamplerPrecision[computeSamplerTypeIndex(sampler)] = EpqLow;
146         }
147
148         // If we are parsing built-in computational variables/functions, it is meaningful to record
149         // whether the built-in has no precision qualifier, as that ambiguity
150         // is used to resolve the precision from the supplied arguments/operands instead.
151         // So, we don't actually want to replace EpqNone with a default precision for built-ins.
152         if (! parsingBuiltins) {
153             if (isEsProfile() && language == EShLangFragment) {
154                 defaultPrecision[EbtInt] = EpqMedium;
155                 defaultPrecision[EbtUint] = EpqMedium;
156             } else {
157                 defaultPrecision[EbtInt] = EpqHigh;
158                 defaultPrecision[EbtUint] = EpqHigh;
159                 defaultPrecision[EbtFloat] = EpqHigh;
160             }
161
162             if (!isEsProfile()) {
163                 // Non-ES profile
164                 // All sampler precisions default to highp.
165                 for (int type = 0; type < maxSamplerIndex; ++type)
166                     defaultSamplerPrecision[type] = EpqHigh;
167             }
168         }
169
170         defaultPrecision[EbtSampler] = EpqLow;
171         defaultPrecision[EbtAtomicUint] = EpqHigh;
172     }
173 }
174
175 void TParseContext::setLimits(const TBuiltInResource& r)
176 {
177     resources = r;
178     intermediate.setLimits(r);
179
180 #ifndef GLSLANG_WEB
181     anyIndexLimits = ! limits.generalAttributeMatrixVectorIndexing ||
182                      ! limits.generalConstantMatrixVectorIndexing ||
183                      ! limits.generalSamplerIndexing ||
184                      ! limits.generalUniformIndexing ||
185                      ! limits.generalVariableIndexing ||
186                      ! limits.generalVaryingIndexing;
187
188
189     // "Each binding point tracks its own current default offset for
190     // inheritance of subsequent variables using the same binding. The initial state of compilation is that all
191     // binding points have an offset of 0."
192     atomicUintOffsets = new int[resources.maxAtomicCounterBindings];
193     for (int b = 0; b < resources.maxAtomicCounterBindings; ++b)
194         atomicUintOffsets[b] = 0;
195 #endif
196 }
197
198 //
199 // Parse an array of strings using yyparse, going through the
200 // preprocessor to tokenize the shader strings, then through
201 // the GLSL scanner.
202 //
203 // Returns true for successful acceptance of the shader, false if any errors.
204 //
205 bool TParseContext::parseShaderStrings(TPpContext& ppContext, TInputScanner& input, bool versionWillBeError)
206 {
207     currentScanner = &input;
208     ppContext.setInput(input, versionWillBeError);
209     yyparse(this);
210
211     finish();
212
213     return numErrors == 0;
214 }
215
216 // This is called from bison when it has a parse (syntax) error
217 // Note though that to stop cascading errors, we set EOF, which
218 // will usually cause a syntax error, so be more accurate that
219 // compilation is terminating.
220 void TParseContext::parserError(const char* s)
221 {
222     if (! getScanner()->atEndOfInput() || numErrors == 0)
223         error(getCurrentLoc(), "", "", s, "");
224     else
225         error(getCurrentLoc(), "compilation terminated", "", "");
226 }
227
228 void TParseContext::growGlobalUniformBlock(const TSourceLoc& loc, TType& memberType, const TString& memberName, TTypeList* typeList)
229 {
230     bool createBlock = globalUniformBlock == nullptr;
231
232     if (createBlock) {
233         globalUniformBinding = intermediate.getGlobalUniformBinding();
234         globalUniformSet = intermediate.getGlobalUniformSet();
235     }
236
237     // use base class function to create/expand block
238     TParseContextBase::growGlobalUniformBlock(loc, memberType, memberName, typeList);
239
240     if (spvVersion.vulkan > 0 && spvVersion.vulkanRelaxed) {
241         // check for a block storage override
242         TBlockStorageClass storageOverride = intermediate.getBlockStorageOverride(getGlobalUniformBlockName());
243         TQualifier& qualifier = globalUniformBlock->getWritableType().getQualifier();
244         qualifier.defaultBlock = true;
245
246         if (storageOverride != EbsNone) {
247             if (createBlock) {
248                 // Remap block storage
249                 qualifier.setBlockStorage(storageOverride);
250
251                 // check that the change didn't create errors
252                 blockQualifierCheck(loc, qualifier, false);
253             }
254
255             // remap meber storage as well
256             memberType.getQualifier().setBlockStorage(storageOverride);
257         }
258     }
259 }
260
261 void TParseContext::growAtomicCounterBlock(int binding, const TSourceLoc& loc, TType& memberType, const TString& memberName, TTypeList* typeList)
262 {
263     bool createBlock = atomicCounterBuffers.find(binding) == atomicCounterBuffers.end();
264
265     if (createBlock) {
266         atomicCounterBlockSet = intermediate.getAtomicCounterBlockSet();
267     }
268
269     // use base class function to create/expand block
270     TParseContextBase::growAtomicCounterBlock(binding, loc, memberType, memberName, typeList);
271     TQualifier& qualifier = atomicCounterBuffers[binding]->getWritableType().getQualifier();
272     qualifier.defaultBlock = true;
273
274     if (spvVersion.vulkan > 0 && spvVersion.vulkanRelaxed) {
275         // check for a Block storage override
276         TBlockStorageClass storageOverride = intermediate.getBlockStorageOverride(getAtomicCounterBlockName());
277
278         if (storageOverride != EbsNone) {
279             if (createBlock) {
280                 // Remap block storage
281
282                 qualifier.setBlockStorage(storageOverride);
283
284                 // check that the change didn't create errors
285                 blockQualifierCheck(loc, qualifier, false);
286             }
287
288             // remap meber storage as well
289             memberType.getQualifier().setBlockStorage(storageOverride);
290         }
291     }
292 }
293
294 const char* TParseContext::getGlobalUniformBlockName() const
295 {
296     const char* name = intermediate.getGlobalUniformBlockName();
297     if (std::string(name) == "")
298         return "gl_DefaultUniformBlock";
299     else
300         return name;
301 }
302 void TParseContext::finalizeGlobalUniformBlockLayout(TVariable&)
303 {
304 }
305 void TParseContext::setUniformBlockDefaults(TType& block) const
306 {
307     block.getQualifier().layoutPacking = ElpStd140;
308     block.getQualifier().layoutMatrix = ElmColumnMajor;
309 }
310
311
312 const char* TParseContext::getAtomicCounterBlockName() const
313 {
314     const char* name = intermediate.getAtomicCounterBlockName();
315     if (std::string(name) == "")
316         return "gl_AtomicCounterBlock";
317     else
318         return name;
319 }
320 void TParseContext::finalizeAtomicCounterBlockLayout(TVariable&)
321 {
322 }
323
324 void TParseContext::setAtomicCounterBlockDefaults(TType& block) const
325 {
326     block.getQualifier().layoutPacking = ElpStd430;
327     block.getQualifier().layoutMatrix = ElmRowMajor;
328 }
329
330 void TParseContext::setInvariant(const TSourceLoc& loc, const char* builtin) {
331     TSymbol* symbol = symbolTable.find(builtin);
332     if (symbol && symbol->getType().getQualifier().isPipeOutput()) {
333         if (intermediate.inIoAccessed(builtin))
334             warn(loc, "changing qualification after use", "invariant", builtin);
335         TSymbol* csymbol = symbolTable.copyUp(symbol);
336         csymbol->getWritableType().getQualifier().invariant = true;
337     }
338 }
339
340 void TParseContext::handlePragma(const TSourceLoc& loc, const TVector<TString>& tokens)
341 {
342 #ifndef GLSLANG_WEB
343     if (pragmaCallback)
344         pragmaCallback(loc.line, tokens);
345
346     if (tokens.size() == 0)
347         return;
348
349     if (tokens[0].compare("optimize") == 0) {
350         if (tokens.size() != 4) {
351             error(loc, "optimize pragma syntax is incorrect", "#pragma", "");
352             return;
353         }
354
355         if (tokens[1].compare("(") != 0) {
356             error(loc, "\"(\" expected after 'optimize' keyword", "#pragma", "");
357             return;
358         }
359
360         if (tokens[2].compare("on") == 0)
361             contextPragma.optimize = true;
362         else if (tokens[2].compare("off") == 0)
363             contextPragma.optimize = false;
364         else {
365             if(relaxedErrors())
366                 //  If an implementation does not recognize the tokens following #pragma, then it will ignore that pragma.
367                 warn(loc, "\"on\" or \"off\" expected after '(' for 'optimize' pragma", "#pragma", "");
368             return;
369         }
370
371         if (tokens[3].compare(")") != 0) {
372             error(loc, "\")\" expected to end 'optimize' pragma", "#pragma", "");
373             return;
374         }
375     } else if (tokens[0].compare("debug") == 0) {
376         if (tokens.size() != 4) {
377             error(loc, "debug pragma syntax is incorrect", "#pragma", "");
378             return;
379         }
380
381         if (tokens[1].compare("(") != 0) {
382             error(loc, "\"(\" expected after 'debug' keyword", "#pragma", "");
383             return;
384         }
385
386         if (tokens[2].compare("on") == 0)
387             contextPragma.debug = true;
388         else if (tokens[2].compare("off") == 0)
389             contextPragma.debug = false;
390         else {
391             if(relaxedErrors())
392                 //  If an implementation does not recognize the tokens following #pragma, then it will ignore that pragma.
393                 warn(loc, "\"on\" or \"off\" expected after '(' for 'debug' pragma", "#pragma", "");
394             return;
395         }
396
397         if (tokens[3].compare(")") != 0) {
398             error(loc, "\")\" expected to end 'debug' pragma", "#pragma", "");
399             return;
400         }
401     } else if (spvVersion.spv > 0 && tokens[0].compare("use_storage_buffer") == 0) {
402         if (tokens.size() != 1)
403             error(loc, "extra tokens", "#pragma", "");
404         intermediate.setUseStorageBuffer();
405     } else if (spvVersion.spv > 0 && tokens[0].compare("use_vulkan_memory_model") == 0) {
406         if (tokens.size() != 1)
407             error(loc, "extra tokens", "#pragma", "");
408         intermediate.setUseVulkanMemoryModel();
409     } else if (spvVersion.spv > 0 && tokens[0].compare("use_variable_pointers") == 0) {
410         if (tokens.size() != 1)
411             error(loc, "extra tokens", "#pragma", "");
412         if (spvVersion.spv < glslang::EShTargetSpv_1_3)
413             error(loc, "requires SPIR-V 1.3", "#pragma use_variable_pointers", "");
414         intermediate.setUseVariablePointers();
415     } else if (tokens[0].compare("once") == 0) {
416         warn(loc, "not implemented", "#pragma once", "");
417     } else if (tokens[0].compare("glslang_binary_double_output") == 0) {
418         intermediate.setBinaryDoubleOutput();
419     } else if (spvVersion.spv > 0 && tokens[0].compare("STDGL") == 0 &&
420                tokens[1].compare("invariant") == 0 && tokens[3].compare("all") == 0) {
421         intermediate.setInvariantAll();
422         // Set all builtin out variables invariant if declared
423         setInvariant(loc, "gl_Position");
424         setInvariant(loc, "gl_PointSize");
425         setInvariant(loc, "gl_ClipDistance");
426         setInvariant(loc, "gl_CullDistance");
427         setInvariant(loc, "gl_TessLevelOuter");
428         setInvariant(loc, "gl_TessLevelInner");
429         setInvariant(loc, "gl_PrimitiveID");
430         setInvariant(loc, "gl_Layer");
431         setInvariant(loc, "gl_ViewportIndex");
432         setInvariant(loc, "gl_FragDepth");
433         setInvariant(loc, "gl_SampleMask");
434         setInvariant(loc, "gl_ClipVertex");
435         setInvariant(loc, "gl_FrontColor");
436         setInvariant(loc, "gl_BackColor");
437         setInvariant(loc, "gl_FrontSecondaryColor");
438         setInvariant(loc, "gl_BackSecondaryColor");
439         setInvariant(loc, "gl_TexCoord");
440         setInvariant(loc, "gl_FogFragCoord");
441         setInvariant(loc, "gl_FragColor");
442         setInvariant(loc, "gl_FragData");
443     }
444 #endif
445 }
446
447 //
448 // Handle seeing a variable identifier in the grammar.
449 //
450 TIntermTyped* TParseContext::handleVariable(const TSourceLoc& loc, TSymbol* symbol, const TString* string)
451 {
452     TIntermTyped* node = nullptr;
453
454     // Error check for requiring specific extensions present.
455     if (symbol && symbol->getNumExtensions())
456         requireExtensions(loc, symbol->getNumExtensions(), symbol->getExtensions(), symbol->getName().c_str());
457
458 #ifndef GLSLANG_WEB
459     if (symbol && symbol->isReadOnly()) {
460         // All shared things containing an unsized array must be copied up
461         // on first use, so that all future references will share its array structure,
462         // so that editing the implicit size will effect all nodes consuming it,
463         // and so that editing the implicit size won't change the shared one.
464         //
465         // If this is a variable or a block, check it and all it contains, but if this
466         // is a member of an anonymous block, check the whole block, as the whole block
467         // will need to be copied up if it contains an unsized array.
468         //
469         // This check is being done before the block-name check further down, so guard
470         // for that too.
471         if (!symbol->getType().isUnusableName()) {
472             if (symbol->getType().containsUnsizedArray() ||
473                 (symbol->getAsAnonMember() &&
474                  symbol->getAsAnonMember()->getAnonContainer().getType().containsUnsizedArray()))
475                 makeEditable(symbol);
476         }
477     }
478 #endif
479
480     const TVariable* variable;
481     const TAnonMember* anon = symbol ? symbol->getAsAnonMember() : nullptr;
482     if (anon) {
483         // It was a member of an anonymous container.
484
485         // Create a subtree for its dereference.
486         variable = anon->getAnonContainer().getAsVariable();
487         TIntermTyped* container = intermediate.addSymbol(*variable, loc);
488         TIntermTyped* constNode = intermediate.addConstantUnion(anon->getMemberNumber(), loc);
489         node = intermediate.addIndex(EOpIndexDirectStruct, container, constNode, loc);
490
491         node->setType(*(*variable->getType().getStruct())[anon->getMemberNumber()].type);
492         if (node->getType().hiddenMember())
493             error(loc, "member of nameless block was not redeclared", string->c_str(), "");
494     } else {
495         // Not a member of an anonymous container.
496
497         // The symbol table search was done in the lexical phase.
498         // See if it was a variable.
499         variable = symbol ? symbol->getAsVariable() : nullptr;
500         if (variable) {
501             if (variable->getType().isUnusableName()) {
502                 error(loc, "cannot be used (maybe an instance name is needed)", string->c_str(), "");
503                 variable = nullptr;
504             }
505
506             if (language == EShLangMesh && variable) {
507                 TLayoutGeometry primitiveType = intermediate.getOutputPrimitive();
508                 if ((variable->getMangledName() == "gl_PrimitiveTriangleIndicesEXT" && primitiveType != ElgTriangles) ||
509                     (variable->getMangledName() == "gl_PrimitiveLineIndicesEXT" && primitiveType != ElgLines) ||
510                     (variable->getMangledName() == "gl_PrimitivePointIndicesEXT" && primitiveType != ElgPoints)) {
511                     error(loc, "cannot be used (ouput primitive type mismatch)", string->c_str(), "");
512                     variable = nullptr;
513                 }
514             }
515         } else {
516             if (symbol)
517                 error(loc, "variable name expected", string->c_str(), "");
518         }
519
520         // Recovery, if it wasn't found or was not a variable.
521         if (! variable)
522             variable = new TVariable(string, TType(EbtVoid));
523
524         if (variable->getType().getQualifier().isFrontEndConstant())
525             node = intermediate.addConstantUnion(variable->getConstArray(), variable->getType(), loc);
526         else
527             node = intermediate.addSymbol(*variable, loc);
528     }
529
530     if (variable->getType().getQualifier().isIo())
531         intermediate.addIoAccessed(*string);
532
533     if (variable->getType().isReference() &&
534         variable->getType().getQualifier().bufferReferenceNeedsVulkanMemoryModel()) {
535         intermediate.setUseVulkanMemoryModel();
536     }
537
538     return node;
539 }
540
541 //
542 // Handle seeing a base[index] dereference in the grammar.
543 //
544 TIntermTyped* TParseContext::handleBracketDereference(const TSourceLoc& loc, TIntermTyped* base, TIntermTyped* index)
545 {
546     int indexValue = 0;
547     if (index->getQualifier().isFrontEndConstant())
548         indexValue = index->getAsConstantUnion()->getConstArray()[0].getIConst();
549
550     // basic type checks...
551     variableCheck(base);
552
553     if (! base->isArray() && ! base->isMatrix() && ! base->isVector() && ! base->getType().isCoopMat() &&
554         ! base->isReference()) {
555         if (base->getAsSymbolNode())
556             error(loc, " left of '[' is not of type array, matrix, or vector ", base->getAsSymbolNode()->getName().c_str(), "");
557         else
558             error(loc, " left of '[' is not of type array, matrix, or vector ", "expression", "");
559
560         // Insert dummy error-recovery result
561         return intermediate.addConstantUnion(0.0, EbtFloat, loc);
562     }
563
564     if (!base->isArray() && base->isVector()) {
565         if (base->getType().contains16BitFloat())
566             requireFloat16Arithmetic(loc, "[", "does not operate on types containing float16");
567         if (base->getType().contains16BitInt())
568             requireInt16Arithmetic(loc, "[", "does not operate on types containing (u)int16");
569         if (base->getType().contains8BitInt())
570             requireInt8Arithmetic(loc, "[", "does not operate on types containing (u)int8");
571     }
572
573     // check for constant folding
574     if (base->getType().getQualifier().isFrontEndConstant() && index->getQualifier().isFrontEndConstant()) {
575         // both base and index are front-end constants
576         checkIndex(loc, base->getType(), indexValue);
577         return intermediate.foldDereference(base, indexValue, loc);
578     }
579
580     // at least one of base and index is not a front-end constant variable...
581     TIntermTyped* result = nullptr;
582
583 #ifndef GLSLANG_WEB
584     if (base->isReference() && ! base->isArray()) {
585         requireExtensions(loc, 1, &E_GL_EXT_buffer_reference2, "buffer reference indexing");
586         if (base->getType().getReferentType()->containsUnsizedArray()) {
587             error(loc, "cannot index reference to buffer containing an unsized array", "", "");
588             result = nullptr;
589         } else {
590             result = intermediate.addBinaryMath(EOpAdd, base, index, loc);
591             if (result != nullptr)
592                 result->setType(base->getType());
593         }
594         if (result == nullptr) {
595             error(loc, "cannot index buffer reference", "", "");
596             result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
597         }
598         return result;
599     }
600     if (base->getAsSymbolNode() && isIoResizeArray(base->getType()))
601         handleIoResizeArrayAccess(loc, base);
602 #endif
603
604     if (index->getQualifier().isFrontEndConstant())
605         checkIndex(loc, base->getType(), indexValue);
606
607     if (index->getQualifier().isFrontEndConstant()) {
608 #ifndef GLSLANG_WEB
609         if (base->getType().isUnsizedArray()) {
610             base->getWritableType().updateImplicitArraySize(indexValue + 1);
611             // For 2D per-view builtin arrays, update the inner dimension size in parent type
612             if (base->getQualifier().isPerView() && base->getQualifier().builtIn != EbvNone) {
613                 TIntermBinary* binaryNode = base->getAsBinaryNode();
614                 if (binaryNode) {
615                     TType& leftType = binaryNode->getLeft()->getWritableType();
616                     TArraySizes& arraySizes = *leftType.getArraySizes();
617                     assert(arraySizes.getNumDims() == 2);
618                     arraySizes.setDimSize(1, std::max(arraySizes.getDimSize(1), indexValue + 1));
619                 }
620             }
621         } else
622 #endif
623             checkIndex(loc, base->getType(), indexValue);
624         result = intermediate.addIndex(EOpIndexDirect, base, index, loc);
625     } else {
626 #ifndef GLSLANG_WEB
627         if (base->getType().isUnsizedArray()) {
628             // we have a variable index into an unsized array, which is okay,
629             // depending on the situation
630             if (base->getAsSymbolNode() && isIoResizeArray(base->getType()))
631                 error(loc, "", "[", "array must be sized by a redeclaration or layout qualifier before being indexed with a variable");
632             else {
633                 // it is okay for a run-time sized array
634                 checkRuntimeSizable(loc, *base);
635             }
636             base->getWritableType().setArrayVariablyIndexed();
637         }
638 #endif
639         if (base->getBasicType() == EbtBlock) {
640             if (base->getQualifier().storage == EvqBuffer)
641                 requireProfile(base->getLoc(), ~EEsProfile, "variable indexing buffer block array");
642             else if (base->getQualifier().storage == EvqUniform)
643                 profileRequires(base->getLoc(), EEsProfile, 320, Num_AEP_gpu_shader5, AEP_gpu_shader5,
644                                 "variable indexing uniform block array");
645             else {
646                 // input/output blocks either don't exist or can't be variably indexed
647             }
648         } else if (language == EShLangFragment && base->getQualifier().isPipeOutput())
649             requireProfile(base->getLoc(), ~EEsProfile, "variable indexing fragment shader output array");
650         else if (base->getBasicType() == EbtSampler && version >= 130) {
651             const char* explanation = "variable indexing sampler array";
652             requireProfile(base->getLoc(), EEsProfile | ECoreProfile | ECompatibilityProfile, explanation);
653             profileRequires(base->getLoc(), EEsProfile, 320, Num_AEP_gpu_shader5, AEP_gpu_shader5, explanation);
654             profileRequires(base->getLoc(), ECoreProfile | ECompatibilityProfile, 400, nullptr, explanation);
655         }
656
657         result = intermediate.addIndex(EOpIndexIndirect, base, index, loc);
658     }
659
660     // Insert valid dereferenced result type
661     TType newType(base->getType(), 0);
662     if (base->getType().getQualifier().isConstant() && index->getQualifier().isConstant()) {
663         newType.getQualifier().storage = EvqConst;
664         // If base or index is a specialization constant, the result should also be a specialization constant.
665         if (base->getType().getQualifier().isSpecConstant() || index->getQualifier().isSpecConstant()) {
666             newType.getQualifier().makeSpecConstant();
667         }
668     } else {
669         newType.getQualifier().storage = EvqTemporary;
670         newType.getQualifier().specConstant = false;
671     }
672     result->setType(newType);
673
674 #ifndef GLSLANG_WEB
675     inheritMemoryQualifiers(base->getQualifier(), result->getWritableType().getQualifier());
676
677     // Propagate nonuniform
678     if (base->getQualifier().isNonUniform() || index->getQualifier().isNonUniform())
679         result->getWritableType().getQualifier().nonUniform = true;
680
681     if (anyIndexLimits)
682         handleIndexLimits(loc, base, index);
683 #endif
684
685     return result;
686 }
687
688 #ifndef GLSLANG_WEB
689
690 // for ES 2.0 (version 100) limitations for almost all index operations except vertex-shader uniforms
691 void TParseContext::handleIndexLimits(const TSourceLoc& /*loc*/, TIntermTyped* base, TIntermTyped* index)
692 {
693     if ((! limits.generalSamplerIndexing && base->getBasicType() == EbtSampler) ||
694         (! limits.generalUniformIndexing && base->getQualifier().isUniformOrBuffer() && language != EShLangVertex) ||
695         (! limits.generalAttributeMatrixVectorIndexing && base->getQualifier().isPipeInput() && language == EShLangVertex && (base->getType().isMatrix() || base->getType().isVector())) ||
696         (! limits.generalConstantMatrixVectorIndexing && base->getAsConstantUnion()) ||
697         (! limits.generalVariableIndexing && ! base->getType().getQualifier().isUniformOrBuffer() &&
698                                              ! base->getType().getQualifier().isPipeInput() &&
699                                              ! base->getType().getQualifier().isPipeOutput() &&
700                                              ! base->getType().getQualifier().isConstant()) ||
701         (! limits.generalVaryingIndexing && (base->getType().getQualifier().isPipeInput() ||
702                                                 base->getType().getQualifier().isPipeOutput()))) {
703         // it's too early to know what the inductive variables are, save it for post processing
704         needsIndexLimitationChecking.push_back(index);
705     }
706 }
707
708 // Make a shared symbol have a non-shared version that can be edited by the current
709 // compile, such that editing its type will not change the shared version and will
710 // effect all nodes sharing it.
711 void TParseContext::makeEditable(TSymbol*& symbol)
712 {
713     TParseContextBase::makeEditable(symbol);
714
715     // See if it's tied to IO resizing
716     if (isIoResizeArray(symbol->getType()))
717         ioArraySymbolResizeList.push_back(symbol);
718 }
719
720 // Return true if this is a geometry shader input array or tessellation control output array
721 // or mesh shader output array.
722 bool TParseContext::isIoResizeArray(const TType& type) const
723 {
724     return type.isArray() &&
725            ((language == EShLangGeometry    && type.getQualifier().storage == EvqVaryingIn) ||
726             (language == EShLangTessControl && type.getQualifier().storage == EvqVaryingOut &&
727                 ! type.getQualifier().patch) ||
728             (language == EShLangFragment && type.getQualifier().storage == EvqVaryingIn &&
729                 (type.getQualifier().pervertexNV || type.getQualifier().pervertexEXT)) ||
730             (language == EShLangMesh && type.getQualifier().storage == EvqVaryingOut &&
731                 !type.getQualifier().perTaskNV));
732 }
733
734 // If an array is not isIoResizeArray() but is an io array, make sure it has the right size
735 void TParseContext::fixIoArraySize(const TSourceLoc& loc, TType& type)
736 {
737     if (! type.isArray() || type.getQualifier().patch || symbolTable.atBuiltInLevel())
738         return;
739
740     assert(! isIoResizeArray(type));
741
742     if (type.getQualifier().storage != EvqVaryingIn || type.getQualifier().patch)
743         return;
744
745     if (language == EShLangTessControl || language == EShLangTessEvaluation) {
746         if (type.getOuterArraySize() != resources.maxPatchVertices) {
747             if (type.isSizedArray())
748                 error(loc, "tessellation input array size must be gl_MaxPatchVertices or implicitly sized", "[]", "");
749             type.changeOuterArraySize(resources.maxPatchVertices);
750         }
751     }
752 }
753
754 // Issue any errors if the non-array object is missing arrayness WRT
755 // shader I/O that has array requirements.
756 // All arrayness checking is handled in array paths, this is for
757 void TParseContext::ioArrayCheck(const TSourceLoc& loc, const TType& type, const TString& identifier)
758 {
759     if (! type.isArray() && ! symbolTable.atBuiltInLevel()) {
760         if (type.getQualifier().isArrayedIo(language) && !type.getQualifier().layoutPassthrough)
761             error(loc, "type must be an array:", type.getStorageQualifierString(), identifier.c_str());
762     }
763 }
764
765 // Handle a dereference of a geometry shader input array or tessellation control output array.
766 // See ioArraySymbolResizeList comment in ParseHelper.h.
767 //
768 void TParseContext::handleIoResizeArrayAccess(const TSourceLoc& /*loc*/, TIntermTyped* base)
769 {
770     TIntermSymbol* symbolNode = base->getAsSymbolNode();
771     assert(symbolNode);
772     if (! symbolNode)
773         return;
774
775     // fix array size, if it can be fixed and needs to be fixed (will allow variable indexing)
776     if (symbolNode->getType().isUnsizedArray()) {
777         int newSize = getIoArrayImplicitSize(symbolNode->getType().getQualifier());
778         if (newSize > 0)
779             symbolNode->getWritableType().changeOuterArraySize(newSize);
780     }
781 }
782
783 // If there has been an input primitive declaration (geometry shader) or an output
784 // number of vertices declaration(tessellation shader), make sure all input array types
785 // match it in size.  Types come either from nodes in the AST or symbols in the
786 // symbol table.
787 //
788 // Types without an array size will be given one.
789 // Types already having a size that is wrong will get an error.
790 //
791 void TParseContext::checkIoArraysConsistency(const TSourceLoc &loc, bool tailOnly)
792 {
793     int requiredSize = 0;
794     TString featureString;
795     size_t listSize = ioArraySymbolResizeList.size();
796     size_t i = 0;
797
798     // If tailOnly = true, only check the last array symbol in the list.
799     if (tailOnly) {
800         i = listSize - 1;
801     }
802     for (bool firstIteration = true; i < listSize; ++i) {
803         TType &type = ioArraySymbolResizeList[i]->getWritableType();
804
805         // As I/O array sizes don't change, fetch requiredSize only once,
806         // except for mesh shaders which could have different I/O array sizes based on type qualifiers.
807         if (firstIteration || (language == EShLangMesh)) {
808             requiredSize = getIoArrayImplicitSize(type.getQualifier(), &featureString);
809             if (requiredSize == 0)
810                 break;
811             firstIteration = false;
812         }
813
814         checkIoArrayConsistency(loc, requiredSize, featureString.c_str(), type,
815                                 ioArraySymbolResizeList[i]->getName());
816     }
817 }
818
819 int TParseContext::getIoArrayImplicitSize(const TQualifier &qualifier, TString *featureString) const
820 {
821     int expectedSize = 0;
822     TString str = "unknown";
823     unsigned int maxVertices = intermediate.getVertices() != TQualifier::layoutNotSet ? intermediate.getVertices() : 0;
824
825     if (language == EShLangGeometry) {
826         expectedSize = TQualifier::mapGeometryToSize(intermediate.getInputPrimitive());
827         str = TQualifier::getGeometryString(intermediate.getInputPrimitive());
828     }
829     else if (language == EShLangTessControl) {
830         expectedSize = maxVertices;
831         str = "vertices";
832     } else if (language == EShLangFragment) {
833         // Number of vertices for Fragment shader is always three.
834         expectedSize = 3;
835         str = "vertices";
836     } else if (language == EShLangMesh) {
837         unsigned int maxPrimitives =
838             intermediate.getPrimitives() != TQualifier::layoutNotSet ? intermediate.getPrimitives() : 0;
839         if (qualifier.builtIn == EbvPrimitiveIndicesNV || qualifier.builtIn == EbvPrimitiveTriangleIndicesEXT ||
840             qualifier.builtIn == EbvPrimitiveLineIndicesEXT || qualifier.builtIn == EbvPrimitivePointIndicesEXT) {
841             expectedSize = maxPrimitives * TQualifier::mapGeometryToSize(intermediate.getOutputPrimitive());
842             str = "max_primitives*";
843             str += TQualifier::getGeometryString(intermediate.getOutputPrimitive());
844         }
845         else if (qualifier.isPerPrimitive()) {
846             expectedSize = maxPrimitives;
847             str = "max_primitives";
848         }
849         else {
850             expectedSize = maxVertices;
851             str = "max_vertices";
852         }
853     }
854     if (featureString)
855         *featureString = str;
856     return expectedSize;
857 }
858
859 void TParseContext::checkIoArrayConsistency(const TSourceLoc& loc, int requiredSize, const char* feature, TType& type, const TString& name)
860 {
861     if (type.isUnsizedArray())
862         type.changeOuterArraySize(requiredSize);
863     else if (type.getOuterArraySize() != requiredSize) {
864         if (language == EShLangGeometry)
865             error(loc, "inconsistent input primitive for array size of", feature, name.c_str());
866         else if (language == EShLangTessControl)
867             error(loc, "inconsistent output number of vertices for array size of", feature, name.c_str());
868         else if (language == EShLangFragment) {
869             if (type.getOuterArraySize() > requiredSize)
870                 error(loc, " cannot be greater than 3 for pervertexEXT", feature, name.c_str());
871         }
872         else if (language == EShLangMesh)
873             error(loc, "inconsistent output array size of", feature, name.c_str());
874         else
875             assert(0);
876     }
877 }
878
879 #endif // GLSLANG_WEB
880
881 // Handle seeing a binary node with a math operation.
882 // Returns nullptr if not semantically allowed.
883 TIntermTyped* TParseContext::handleBinaryMath(const TSourceLoc& loc, const char* str, TOperator op, TIntermTyped* left, TIntermTyped* right)
884 {
885     rValueErrorCheck(loc, str, left->getAsTyped());
886     rValueErrorCheck(loc, str, right->getAsTyped());
887
888     bool allowed = true;
889     switch (op) {
890     // TODO: Bring more source language-specific checks up from intermediate.cpp
891     // to the specific parse helpers for that source language.
892     case EOpLessThan:
893     case EOpGreaterThan:
894     case EOpLessThanEqual:
895     case EOpGreaterThanEqual:
896         if (! left->isScalar() || ! right->isScalar())
897             allowed = false;
898         break;
899     default:
900         break;
901     }
902
903     if (((left->getType().contains16BitFloat() || right->getType().contains16BitFloat()) && !float16Arithmetic()) ||
904         ((left->getType().contains16BitInt() || right->getType().contains16BitInt()) && !int16Arithmetic()) ||
905         ((left->getType().contains8BitInt() || right->getType().contains8BitInt()) && !int8Arithmetic())) {
906         allowed = false;
907     }
908
909     TIntermTyped* result = nullptr;
910     if (allowed) {
911         if ((left->isReference() || right->isReference()))
912             requireExtensions(loc, 1, &E_GL_EXT_buffer_reference2, "buffer reference math");
913         result = intermediate.addBinaryMath(op, left, right, loc);
914     }
915
916     if (result == nullptr) {
917         bool enhanced = intermediate.getEnhancedMsgs();
918         binaryOpError(loc, str, left->getCompleteString(enhanced), right->getCompleteString(enhanced));
919     }
920
921     return result;
922 }
923
924 // Handle seeing a unary node with a math operation.
925 TIntermTyped* TParseContext::handleUnaryMath(const TSourceLoc& loc, const char* str, TOperator op, TIntermTyped* childNode)
926 {
927     rValueErrorCheck(loc, str, childNode);
928
929     bool allowed = true;
930     if ((childNode->getType().contains16BitFloat() && !float16Arithmetic()) ||
931         (childNode->getType().contains16BitInt() && !int16Arithmetic()) ||
932         (childNode->getType().contains8BitInt() && !int8Arithmetic())) {
933         allowed = false;
934     }
935
936     TIntermTyped* result = nullptr;
937     if (allowed)
938         result = intermediate.addUnaryMath(op, childNode, loc);
939
940     if (result)
941         return result;
942     else {
943         bool enhanced = intermediate.getEnhancedMsgs();
944         unaryOpError(loc, str, childNode->getCompleteString(enhanced));
945     }
946
947     return childNode;
948 }
949
950 //
951 // Handle seeing a base.field dereference in the grammar.
952 //
953 TIntermTyped* TParseContext::handleDotDereference(const TSourceLoc& loc, TIntermTyped* base, const TString& field)
954 {
955     variableCheck(base);
956
957     //
958     // .length() can't be resolved until we later see the function-calling syntax.
959     // Save away the name in the AST for now.  Processing is completed in
960     // handleLengthMethod().
961     //
962     if (field == "length") {
963         if (base->isArray()) {
964             profileRequires(loc, ENoProfile, 120, E_GL_3DL_array_objects, ".length");
965             profileRequires(loc, EEsProfile, 300, nullptr, ".length");
966         } else if (base->isVector() || base->isMatrix()) {
967             const char* feature = ".length() on vectors and matrices";
968             requireProfile(loc, ~EEsProfile, feature);
969             profileRequires(loc, ~EEsProfile, 420, E_GL_ARB_shading_language_420pack, feature);
970         } else if (!base->getType().isCoopMat()) {
971             bool enhanced = intermediate.getEnhancedMsgs();
972             error(loc, "does not operate on this type:", field.c_str(), base->getType().getCompleteString(enhanced).c_str());
973             return base;
974         }
975
976         return intermediate.addMethod(base, TType(EbtInt), &field, loc);
977     }
978
979     // It's not .length() if we get to here.
980
981     if (base->isArray()) {
982         error(loc, "cannot apply to an array:", ".", field.c_str());
983
984         return base;
985     }
986
987     if (base->getType().isCoopMat()) {
988         error(loc, "cannot apply to a cooperative matrix type:", ".", field.c_str());
989         return base;
990     }
991
992     // It's neither an array nor .length() if we get here,
993     // leaving swizzles and struct/block dereferences.
994
995     TIntermTyped* result = base;
996     if ((base->isVector() || base->isScalar()) &&
997         (base->isFloatingDomain() || base->isIntegerDomain() || base->getBasicType() == EbtBool)) {
998         result = handleDotSwizzle(loc, base, field);
999     } else if (base->isStruct() || base->isReference()) {
1000         const TTypeList* fields = base->isReference() ?
1001                                   base->getType().getReferentType()->getStruct() :
1002                                   base->getType().getStruct();
1003         bool fieldFound = false;
1004         int member;
1005         for (member = 0; member < (int)fields->size(); ++member) {
1006             if ((*fields)[member].type->getFieldName() == field) {
1007                 fieldFound = true;
1008                 break;
1009             }
1010         }
1011         if (fieldFound) {
1012             if (base->getType().getQualifier().isFrontEndConstant())
1013                 result = intermediate.foldDereference(base, member, loc);
1014             else {
1015                 blockMemberExtensionCheck(loc, base, member, field);
1016                 TIntermTyped* index = intermediate.addConstantUnion(member, loc);
1017                 result = intermediate.addIndex(EOpIndexDirectStruct, base, index, loc);
1018                 result->setType(*(*fields)[member].type);
1019                 if ((*fields)[member].type->getQualifier().isIo())
1020                     intermediate.addIoAccessed(field);
1021             }
1022             inheritMemoryQualifiers(base->getQualifier(), result->getWritableType().getQualifier());
1023         } else {
1024             auto baseSymbol = base;
1025             while (baseSymbol->getAsSymbolNode() == nullptr)
1026                 baseSymbol = baseSymbol->getAsBinaryNode()->getLeft();
1027             TString structName;
1028             structName.append("\'").append(baseSymbol->getAsSymbolNode()->getName().c_str()).append( "\'");
1029             error(loc, "no such field in structure", field.c_str(), structName.c_str());
1030         }
1031     } else
1032         error(loc, "does not apply to this type:", field.c_str(), base->getType().getCompleteString(intermediate.getEnhancedMsgs()).c_str());
1033
1034     // Propagate noContraction up the dereference chain
1035     if (base->getQualifier().isNoContraction())
1036         result->getWritableType().getQualifier().setNoContraction();
1037
1038     // Propagate nonuniform
1039     if (base->getQualifier().isNonUniform())
1040         result->getWritableType().getQualifier().nonUniform = true;
1041
1042     return result;
1043 }
1044
1045 //
1046 // Handle seeing a base.swizzle, a subset of base.identifier in the grammar.
1047 //
1048 TIntermTyped* TParseContext::handleDotSwizzle(const TSourceLoc& loc, TIntermTyped* base, const TString& field)
1049 {
1050     TIntermTyped* result = base;
1051     if (base->isScalar()) {
1052         const char* dotFeature = "scalar swizzle";
1053         requireProfile(loc, ~EEsProfile, dotFeature);
1054         profileRequires(loc, ~EEsProfile, 420, E_GL_ARB_shading_language_420pack, dotFeature);
1055     }
1056
1057     TSwizzleSelectors<TVectorSelector> selectors;
1058     parseSwizzleSelector(loc, field, base->getVectorSize(), selectors);
1059
1060     if (base->isVector() && selectors.size() != 1 && base->getType().contains16BitFloat())
1061         requireFloat16Arithmetic(loc, ".", "can't swizzle types containing float16");
1062     if (base->isVector() && selectors.size() != 1 && base->getType().contains16BitInt())
1063         requireInt16Arithmetic(loc, ".", "can't swizzle types containing (u)int16");
1064     if (base->isVector() && selectors.size() != 1 && base->getType().contains8BitInt())
1065         requireInt8Arithmetic(loc, ".", "can't swizzle types containing (u)int8");
1066
1067     if (base->isScalar()) {
1068         if (selectors.size() == 1)
1069             return result;
1070         else {
1071             TType type(base->getBasicType(), EvqTemporary, selectors.size());
1072             // Swizzle operations propagate specialization-constantness
1073             if (base->getQualifier().isSpecConstant())
1074                 type.getQualifier().makeSpecConstant();
1075             return addConstructor(loc, base, type);
1076         }
1077     }
1078
1079     if (base->getType().getQualifier().isFrontEndConstant())
1080         result = intermediate.foldSwizzle(base, selectors, loc);
1081     else {
1082         if (selectors.size() == 1) {
1083             TIntermTyped* index = intermediate.addConstantUnion(selectors[0], loc);
1084             result = intermediate.addIndex(EOpIndexDirect, base, index, loc);
1085             result->setType(TType(base->getBasicType(), EvqTemporary, base->getType().getQualifier().precision));
1086         } else {
1087             TIntermTyped* index = intermediate.addSwizzle(selectors, loc);
1088             result = intermediate.addIndex(EOpVectorSwizzle, base, index, loc);
1089             result->setType(TType(base->getBasicType(), EvqTemporary, base->getType().getQualifier().precision, selectors.size()));
1090         }
1091         // Swizzle operations propagate specialization-constantness
1092         if (base->getType().getQualifier().isSpecConstant())
1093             result->getWritableType().getQualifier().makeSpecConstant();
1094     }
1095
1096     return result;
1097 }
1098
1099 void TParseContext::blockMemberExtensionCheck(const TSourceLoc& loc, const TIntermTyped* base, int member, const TString& memberName)
1100 {
1101     // a block that needs extension checking is either 'base', or if arrayed,
1102     // one level removed to the left
1103     const TIntermSymbol* baseSymbol = nullptr;
1104     if (base->getAsBinaryNode() == nullptr)
1105         baseSymbol = base->getAsSymbolNode();
1106     else
1107         baseSymbol = base->getAsBinaryNode()->getLeft()->getAsSymbolNode();
1108     if (baseSymbol == nullptr)
1109         return;
1110     const TSymbol* symbol = symbolTable.find(baseSymbol->getName());
1111     if (symbol == nullptr)
1112         return;
1113     const TVariable* variable = symbol->getAsVariable();
1114     if (variable == nullptr)
1115         return;
1116     if (!variable->hasMemberExtensions())
1117         return;
1118
1119     // We now have a variable that is the base of a dot reference
1120     // with members that need extension checking.
1121     if (variable->getNumMemberExtensions(member) > 0)
1122         requireExtensions(loc, variable->getNumMemberExtensions(member), variable->getMemberExtensions(member), memberName.c_str());
1123 }
1124
1125 //
1126 // Handle seeing a function declarator in the grammar.  This is the precursor
1127 // to recognizing a function prototype or function definition.
1128 //
1129 TFunction* TParseContext::handleFunctionDeclarator(const TSourceLoc& loc, TFunction& function, bool prototype)
1130 {
1131     // ES can't declare prototypes inside functions
1132     if (! symbolTable.atGlobalLevel())
1133         requireProfile(loc, ~EEsProfile, "local function declaration");
1134
1135     //
1136     // Multiple declarations of the same function name are allowed.
1137     //
1138     // If this is a definition, the definition production code will check for redefinitions
1139     // (we don't know at this point if it's a definition or not).
1140     //
1141     // Redeclarations (full signature match) are allowed.  But, return types and parameter qualifiers must also match.
1142     //  - except ES 100, which only allows a single prototype
1143     //
1144     // ES 100 does not allow redefining, but does allow overloading of built-in functions.
1145     // ES 300 does not allow redefining or overloading of built-in functions.
1146     //
1147     bool builtIn;
1148     TSymbol* symbol = symbolTable.find(function.getMangledName(), &builtIn);
1149     if (symbol && symbol->getAsFunction() && builtIn)
1150         requireProfile(loc, ~EEsProfile, "redefinition of built-in function");
1151 #ifndef GLSLANG_WEB
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 #endif
1164     const TFunction* prevDec = symbol ? symbol->getAsFunction() : 0;
1165     if (prevDec) {
1166         if (prevDec->isPrototyped() && prototype)
1167             profileRequires(loc, EEsProfile, 300, nullptr, "multiple prototypes for same function");
1168         if (prevDec->getType() != function.getType())
1169             error(loc, "overloaded functions must have the same return type", function.getName().c_str(), "");
1170 #ifndef GLSLANG_WEB
1171         if (prevDec->getSpirvInstruction() != function.getSpirvInstruction()) {
1172             error(loc, "overloaded functions must have the same qualifiers", function.getName().c_str(),
1173                   "spirv_instruction");
1174         }
1175 #endif
1176         for (int i = 0; i < prevDec->getParamCount(); ++i) {
1177             if ((*prevDec)[i].type->getQualifier().storage != function[i].type->getQualifier().storage)
1178                 error(loc, "overloaded functions must have the same parameter storage qualifiers for argument", function[i].type->getStorageQualifierString(), "%d", i+1);
1179
1180             if ((*prevDec)[i].type->getQualifier().precision != function[i].type->getQualifier().precision)
1181                 error(loc, "overloaded functions must have the same parameter precision qualifiers for argument", function[i].type->getPrecisionQualifierString(), "%d", i+1);
1182         }
1183     }
1184
1185     arrayObjectCheck(loc, function.getType(), "array in function return type");
1186
1187     if (prototype) {
1188         // All built-in functions are defined, even though they don't have a body.
1189         // Count their prototype as a definition instead.
1190         if (symbolTable.atBuiltInLevel())
1191             function.setDefined();
1192         else {
1193             if (prevDec && ! builtIn)
1194                 symbol->getAsFunction()->setPrototyped();  // need a writable one, but like having prevDec as a const
1195             function.setPrototyped();
1196         }
1197     }
1198
1199     // This insert won't actually insert it if it's a duplicate signature, but it will still check for
1200     // other forms of name collisions.
1201     if (! symbolTable.insert(function))
1202         error(loc, "function name is redeclaration of existing name", function.getName().c_str(), "");
1203
1204     //
1205     // If this is a redeclaration, it could also be a definition,
1206     // in which case, we need to use the parameter names from this one, and not the one that's
1207     // being redeclared.  So, pass back this declaration, not the one in the symbol table.
1208     //
1209     return &function;
1210 }
1211
1212 //
1213 // Handle seeing the function prototype in front of a function definition in the grammar.
1214 // The body is handled after this function returns.
1215 //
1216 TIntermAggregate* TParseContext::handleFunctionDefinition(const TSourceLoc& loc, TFunction& function)
1217 {
1218     currentCaller = function.getMangledName();
1219     TSymbol* symbol = symbolTable.find(function.getMangledName());
1220     TFunction* prevDec = symbol ? symbol->getAsFunction() : nullptr;
1221
1222     if (! prevDec)
1223         error(loc, "can't find function", function.getName().c_str(), "");
1224     // Note:  'prevDec' could be 'function' if this is the first time we've seen function
1225     // as it would have just been put in the symbol table.  Otherwise, we're looking up
1226     // an earlier occurrence.
1227
1228     if (prevDec && prevDec->isDefined()) {
1229         // Then this function already has a body.
1230         error(loc, "function already has a body", function.getName().c_str(), "");
1231     }
1232     if (prevDec && ! prevDec->isDefined()) {
1233         prevDec->setDefined();
1234
1235         // Remember the return type for later checking for RETURN statements.
1236         currentFunctionType = &(prevDec->getType());
1237     } else
1238         currentFunctionType = new TType(EbtVoid);
1239     functionReturnsValue = false;
1240
1241     // Check for entry point
1242     if (function.getName().compare(intermediate.getEntryPointName().c_str()) == 0) {
1243         intermediate.setEntryPointMangledName(function.getMangledName().c_str());
1244         intermediate.incrementEntryPointCount();
1245         inMain = true;
1246     } else
1247         inMain = false;
1248
1249     //
1250     // Raise error message if main function takes any parameters or returns anything other than void
1251     //
1252     if (inMain) {
1253         if (function.getParamCount() > 0)
1254             error(loc, "function cannot take any parameter(s)", function.getName().c_str(), "");
1255         if (function.getType().getBasicType() != EbtVoid)
1256             error(loc, "", function.getType().getBasicTypeString().c_str(), "entry point cannot return a value");
1257     }
1258
1259     //
1260     // New symbol table scope for body of function plus its arguments
1261     //
1262     symbolTable.push();
1263
1264     //
1265     // Insert parameters into the symbol table.
1266     // If the parameter has no name, it's not an error, just don't insert it
1267     // (could be used for unused args).
1268     //
1269     // Also, accumulate the list of parameters into the HIL, so lower level code
1270     // knows where to find parameters.
1271     //
1272     TIntermAggregate* paramNodes = new TIntermAggregate;
1273     for (int i = 0; i < function.getParamCount(); i++) {
1274         TParameter& param = function[i];
1275         if (param.name != nullptr) {
1276             TVariable *variable = new TVariable(param.name, *param.type);
1277
1278             // Insert the parameters with name in the symbol table.
1279             if (! symbolTable.insert(*variable))
1280                 error(loc, "redefinition", variable->getName().c_str(), "");
1281             else {
1282                 // Transfer ownership of name pointer to symbol table.
1283                 param.name = nullptr;
1284
1285                 // Add the parameter to the HIL
1286                 paramNodes = intermediate.growAggregate(paramNodes,
1287                                                         intermediate.addSymbol(*variable, loc),
1288                                                         loc);
1289             }
1290         } else
1291             paramNodes = intermediate.growAggregate(paramNodes, intermediate.addSymbol(*param.type, loc), loc);
1292     }
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 //
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 #ifndef GLSLANG_WEB
1378                     if (formalQualifier.isSpirvLiteral()) {
1379                         if (!arg->getAsTyped()->getQualifier().isFrontEndConstant()) {
1380                             error(arguments->getLoc(),
1381                                   "Non front-end constant expressions cannot be passed for 'spirv_literal' parameters.",
1382                                   "spirv_literal", "");
1383                         }
1384                     }
1385 #endif
1386                     const TType& argType = arg->getAsTyped()->getType();
1387                     const TQualifier& argQualifier = argType.getQualifier();
1388                     if (argQualifier.isMemory() && (argType.containsOpaque() || argType.isReference())) {
1389                         const char* message = "argument cannot drop memory qualifier when passed to formal parameter";
1390 #ifndef GLSLANG_WEB
1391                         if (argQualifier.volatil && ! formalQualifier.volatil)
1392                             error(arguments->getLoc(), message, "volatile", "");
1393                         if (argQualifier.coherent && ! (formalQualifier.devicecoherent || formalQualifier.coherent))
1394                             error(arguments->getLoc(), message, "coherent", "");
1395                         if (argQualifier.devicecoherent && ! (formalQualifier.devicecoherent || formalQualifier.coherent))
1396                             error(arguments->getLoc(), message, "devicecoherent", "");
1397                         if (argQualifier.queuefamilycoherent && ! (formalQualifier.queuefamilycoherent || formalQualifier.devicecoherent || formalQualifier.coherent))
1398                             error(arguments->getLoc(), message, "queuefamilycoherent", "");
1399                         if (argQualifier.workgroupcoherent && ! (formalQualifier.workgroupcoherent || formalQualifier.queuefamilycoherent || formalQualifier.devicecoherent || formalQualifier.coherent))
1400                             error(arguments->getLoc(), message, "workgroupcoherent", "");
1401                         if (argQualifier.subgroupcoherent && ! (formalQualifier.subgroupcoherent || formalQualifier.workgroupcoherent || formalQualifier.queuefamilycoherent || formalQualifier.devicecoherent || formalQualifier.coherent))
1402                             error(arguments->getLoc(), message, "subgroupcoherent", "");
1403                         if (argQualifier.readonly && ! formalQualifier.readonly)
1404                             error(arguments->getLoc(), message, "readonly", "");
1405                         if (argQualifier.writeonly && ! formalQualifier.writeonly)
1406                             error(arguments->getLoc(), message, "writeonly", "");
1407                         // Don't check 'restrict', it is different than the rest:
1408                         // "...but only restrict can be taken away from a calling argument, by a formal parameter that
1409                         // lacks the restrict qualifier..."
1410 #endif
1411                     }
1412                     if (!builtIn && argQualifier.getFormat() != formalQualifier.getFormat()) {
1413                         // we have mismatched formats, which should only be allowed if writeonly
1414                         // and at least one format is unknown
1415                         if (!formalQualifier.isWriteOnly() || (formalQualifier.getFormat() != ElfNone &&
1416                                                                   argQualifier.getFormat() != ElfNone))
1417                             error(arguments->getLoc(), "image formats must match", "format", "");
1418                     }
1419                     if (builtIn && arg->getAsTyped()->getType().contains16BitFloat())
1420                         requireFloat16Arithmetic(arguments->getLoc(), "built-in function", "float16 types can only be in uniform block or buffer storage");
1421                     if (builtIn && arg->getAsTyped()->getType().contains16BitInt())
1422                         requireInt16Arithmetic(arguments->getLoc(), "built-in function", "(u)int16 types can only be in uniform block or buffer storage");
1423                     if (builtIn && arg->getAsTyped()->getType().contains8BitInt())
1424                         requireInt8Arithmetic(arguments->getLoc(), "built-in function", "(u)int8 types can only be in uniform block or buffer storage");
1425
1426                     // TODO 4.5 functionality:  A shader will fail to compile
1427                     // if the value passed to the memargument of an atomic memory function does not correspond to a buffer or
1428                     // shared variable. It is acceptable to pass an element of an array or a single component of a vector to the
1429                     // memargument of an atomic memory function, as long as the underlying array or vector is a buffer or
1430                     // shared variable.
1431                 }
1432
1433                 // Convert 'in' arguments
1434                 addInputArgumentConversions(*fnCandidate, arguments);  // arguments may be modified if it's just a single argument node
1435             }
1436
1437             if (builtIn && fnCandidate->getBuiltInOp() != EOpNull) {
1438                 // A function call mapped to a built-in operation.
1439                 result = handleBuiltInFunctionCall(loc, arguments, *fnCandidate);
1440 #ifndef GLSLANG_WEB
1441             } else if (fnCandidate->getBuiltInOp() == EOpSpirvInst) {
1442                 // When SPIR-V instruction qualifier is specified, the function call is still mapped to a built-in operation.
1443                 result = handleBuiltInFunctionCall(loc, arguments, *fnCandidate);
1444 #endif
1445             } else {
1446                 // This is a function call not mapped to built-in operator.
1447                 // It could still be a built-in function, but only if PureOperatorBuiltins == false.
1448                 result = intermediate.setAggregateOperator(arguments, EOpFunctionCall, fnCandidate->getType(), loc);
1449                 TIntermAggregate* call = result->getAsAggregate();
1450                 call->setName(fnCandidate->getMangledName());
1451
1452                 // this is how we know whether the given function is a built-in function or a user-defined function
1453                 // if builtIn == false, it's a userDefined -> could be an overloaded built-in function also
1454                 // if builtIn == true, it's definitely a built-in function with EOpNull
1455                 if (! builtIn) {
1456                     call->setUserDefined();
1457                     if (symbolTable.atGlobalLevel()) {
1458                         requireProfile(loc, ~EEsProfile, "calling user function from global scope");
1459                         intermediate.addToCallGraph(infoSink, "main(", fnCandidate->getMangledName());
1460                     } else
1461                         intermediate.addToCallGraph(infoSink, currentCaller, fnCandidate->getMangledName());
1462                 }
1463
1464 #ifndef GLSLANG_WEB
1465                 if (builtIn)
1466                     nonOpBuiltInCheck(loc, *fnCandidate, *call);
1467                 else
1468 #endif
1469                     userFunctionCallCheck(loc, *call);
1470             }
1471
1472             // Convert 'out' arguments.  If it was a constant folded built-in, it won't be an aggregate anymore.
1473             // Built-ins with a single argument aren't called with an aggregate, but they also don't have an output.
1474             // Also, build the qualifier list for user function calls, which are always called with an aggregate.
1475             if (result->getAsAggregate()) {
1476                 TQualifierList& qualifierList = result->getAsAggregate()->getQualifierList();
1477                 for (int i = 0; i < fnCandidate->getParamCount(); ++i) {
1478                     TStorageQualifier qual = (*fnCandidate)[i].type->getQualifier().storage;
1479                     qualifierList.push_back(qual);
1480                 }
1481                 result = addOutputArgumentConversions(*fnCandidate, *result->getAsAggregate());
1482             }
1483
1484             if (result->getAsTyped()->getType().isCoopMat() &&
1485                !result->getAsTyped()->getType().isParameterized()) {
1486                 assert(fnCandidate->getBuiltInOp() == EOpCooperativeMatrixMulAdd);
1487
1488                 result->setType(result->getAsAggregate()->getSequence()[2]->getAsTyped()->getType());
1489             }
1490         }
1491     }
1492
1493     // generic error recovery
1494     // TODO: simplification: localize all the error recoveries that look like this, and taking type into account to reduce cascades
1495     if (result == nullptr)
1496         result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
1497
1498     return result;
1499 }
1500
1501 TIntermTyped* TParseContext::handleBuiltInFunctionCall(TSourceLoc loc, TIntermNode* arguments,
1502                                                        const TFunction& function)
1503 {
1504     checkLocation(loc, function.getBuiltInOp());
1505     TIntermTyped *result = intermediate.addBuiltInFunctionCall(loc, function.getBuiltInOp(),
1506                                                                function.getParamCount() == 1,
1507                                                                arguments, function.getType());
1508     if (result != nullptr && obeyPrecisionQualifiers())
1509         computeBuiltinPrecisions(*result, function);
1510
1511     if (result == nullptr) {
1512         if (arguments == nullptr)
1513             error(loc, " wrong operand type", "Internal Error",
1514                                       "built in unary operator function.  Type: %s", "");
1515         else
1516             error(arguments->getLoc(), " wrong operand type", "Internal Error",
1517                                       "built in unary operator function.  Type: %s",
1518                                       static_cast<TIntermTyped*>(arguments)->getCompleteString(intermediate.getEnhancedMsgs()).c_str());
1519     } else if (result->getAsOperator())
1520         builtInOpCheck(loc, function, *result->getAsOperator());
1521
1522 #ifndef GLSLANG_WEB
1523     // Special handling for function call with SPIR-V instruction qualifier specified
1524     if (function.getBuiltInOp() == EOpSpirvInst) {
1525         if (auto agg = result->getAsAggregate()) {
1526             // Propogate spirv_by_reference/spirv_literal from parameters to arguments
1527             auto& sequence = agg->getSequence();
1528             for (unsigned i = 0; i < sequence.size(); ++i) {
1529                 if (function[i].type->getQualifier().isSpirvByReference())
1530                     sequence[i]->getAsTyped()->getQualifier().setSpirvByReference();
1531                 if (function[i].type->getQualifier().isSpirvLiteral())
1532                     sequence[i]->getAsTyped()->getQualifier().setSpirvLiteral();
1533             }
1534
1535             // Attach the function call to SPIR-V intruction
1536             agg->setSpirvInstruction(function.getSpirvInstruction());
1537         } else if (auto unaryNode = result->getAsUnaryNode()) {
1538             // Propogate spirv_by_reference/spirv_literal from parameters to arguments
1539             if (function[0].type->getQualifier().isSpirvByReference())
1540                 unaryNode->getOperand()->getQualifier().setSpirvByReference();
1541             if (function[0].type->getQualifier().isSpirvLiteral())
1542                 unaryNode->getOperand()->getQualifier().setSpirvLiteral();
1543
1544             // Attach the function call to SPIR-V intruction
1545             unaryNode->setSpirvInstruction(function.getSpirvInstruction());
1546         } else
1547             assert(0);
1548     }
1549 #endif
1550
1551     return result;
1552 }
1553
1554 // "The operation of a built-in function can have a different precision
1555 // qualification than the precision qualification of the resulting value.
1556 // These two precision qualifications are established as follows.
1557 //
1558 // The precision qualification of the operation of a built-in function is
1559 // based on the precision qualification of its input arguments and formal
1560 // parameters:  When a formal parameter specifies a precision qualifier,
1561 // that is used, otherwise, the precision qualification of the calling
1562 // argument is used.  The highest precision of these will be the precision
1563 // qualification of the operation of the built-in function. Generally,
1564 // this is applied across all arguments to a built-in function, with the
1565 // exceptions being:
1566 //   - bitfieldExtract and bitfieldInsert ignore the 'offset' and 'bits'
1567 //     arguments.
1568 //   - interpolateAt* functions only look at the 'interpolant' argument.
1569 //
1570 // The precision qualification of the result of a built-in function is
1571 // determined in one of the following ways:
1572 //
1573 //   - For the texture sampling, image load, and image store functions,
1574 //     the precision of the return type matches the precision of the
1575 //     sampler type
1576 //
1577 //   Otherwise:
1578 //
1579 //   - For prototypes that do not specify a resulting precision qualifier,
1580 //     the precision will be the same as the precision of the operation.
1581 //
1582 //   - For prototypes that do specify a resulting precision qualifier,
1583 //     the specified precision qualifier is the precision qualification of
1584 //     the result."
1585 //
1586 void TParseContext::computeBuiltinPrecisions(TIntermTyped& node, const TFunction& function)
1587 {
1588     TPrecisionQualifier operationPrecision = EpqNone;
1589     TPrecisionQualifier resultPrecision = EpqNone;
1590
1591     TIntermOperator* opNode = node.getAsOperator();
1592     if (opNode == nullptr)
1593         return;
1594
1595     if (TIntermUnary* unaryNode = node.getAsUnaryNode()) {
1596         operationPrecision = std::max(function[0].type->getQualifier().precision,
1597                                       unaryNode->getOperand()->getType().getQualifier().precision);
1598         if (function.getType().getBasicType() != EbtBool)
1599             resultPrecision = function.getType().getQualifier().precision == EpqNone ?
1600                                         operationPrecision :
1601                                         function.getType().getQualifier().precision;
1602     } else if (TIntermAggregate* agg = node.getAsAggregate()) {
1603         TIntermSequence& sequence = agg->getSequence();
1604         unsigned int numArgs = (unsigned int)sequence.size();
1605         switch (agg->getOp()) {
1606         case EOpBitfieldExtract:
1607             numArgs = 1;
1608             break;
1609         case EOpBitfieldInsert:
1610             numArgs = 2;
1611             break;
1612         case EOpInterpolateAtCentroid:
1613         case EOpInterpolateAtOffset:
1614         case EOpInterpolateAtSample:
1615             numArgs = 1;
1616             break;
1617         case EOpDebugPrintf:
1618             numArgs = 0;
1619             break;
1620         default:
1621             break;
1622         }
1623         // find the maximum precision from the arguments and parameters
1624         for (unsigned int arg = 0; arg < numArgs; ++arg) {
1625             operationPrecision = std::max(operationPrecision, sequence[arg]->getAsTyped()->getQualifier().precision);
1626             operationPrecision = std::max(operationPrecision, function[arg].type->getQualifier().precision);
1627         }
1628         // compute the result precision
1629         if (agg->isSampling() ||
1630             agg->getOp() == EOpImageLoad || agg->getOp() == EOpImageStore ||
1631             agg->getOp() == EOpImageLoadLod || agg->getOp() == EOpImageStoreLod)
1632             resultPrecision = sequence[0]->getAsTyped()->getQualifier().precision;
1633         else if (function.getType().getBasicType() != EbtBool)
1634             resultPrecision = function.getType().getQualifier().precision == EpqNone ?
1635                                         operationPrecision :
1636                                         function.getType().getQualifier().precision;
1637     }
1638
1639     // Propagate precision through this node and its children. That algorithm stops
1640     // when a precision is found, so start by clearing this subroot precision
1641     opNode->getQualifier().precision = EpqNone;
1642     if (operationPrecision != EpqNone) {
1643         opNode->propagatePrecision(operationPrecision);
1644         opNode->setOperationPrecision(operationPrecision);
1645     }
1646     // Now, set the result precision, which might not match
1647     opNode->getQualifier().precision = resultPrecision;
1648 }
1649
1650 TIntermNode* TParseContext::handleReturnValue(const TSourceLoc& loc, TIntermTyped* value)
1651 {
1652 #ifndef GLSLANG_WEB
1653     storage16BitAssignmentCheck(loc, value->getType(), "return");
1654 #endif
1655
1656     functionReturnsValue = true;
1657     TIntermBranch* branch = nullptr;
1658     if (currentFunctionType->getBasicType() == EbtVoid) {
1659         error(loc, "void function cannot return a value", "return", "");
1660         branch = intermediate.addBranch(EOpReturn, loc);
1661     } else if (*currentFunctionType != value->getType()) {
1662         TIntermTyped* converted = intermediate.addConversion(EOpReturn, *currentFunctionType, value);
1663         if (converted) {
1664             if (*currentFunctionType != converted->getType())
1665                 error(loc, "cannot convert return value to function return type", "return", "");
1666             if (version < 420)
1667                 warn(loc, "type conversion on return values was not explicitly allowed until version 420",
1668                      "return", "");
1669             branch = intermediate.addBranch(EOpReturn, converted, loc);
1670         } else {
1671             error(loc, "type does not match, or is not convertible to, the function's return type", "return", "");
1672             branch = intermediate.addBranch(EOpReturn, value, loc);
1673         }
1674     } else
1675         branch = intermediate.addBranch(EOpReturn, value, loc);
1676
1677     branch->updatePrecision(currentFunctionType->getQualifier().precision);
1678     return branch;
1679 }
1680
1681 // See if the operation is being done in an illegal location.
1682 void TParseContext::checkLocation(const TSourceLoc& loc, TOperator op)
1683 {
1684 #ifndef GLSLANG_WEB
1685     switch (op) {
1686     case EOpBarrier:
1687         if (language == EShLangTessControl) {
1688             if (controlFlowNestingLevel > 0)
1689                 error(loc, "tessellation control barrier() cannot be placed within flow control", "", "");
1690             if (! inMain)
1691                 error(loc, "tessellation control barrier() must be in main()", "", "");
1692             else if (postEntryPointReturn)
1693                 error(loc, "tessellation control barrier() cannot be placed after a return from main()", "", "");
1694         }
1695         break;
1696     case EOpBeginInvocationInterlock:
1697         if (language != EShLangFragment)
1698             error(loc, "beginInvocationInterlockARB() must be in a fragment shader", "", "");
1699         if (! inMain)
1700             error(loc, "beginInvocationInterlockARB() must be in main()", "", "");
1701         else if (postEntryPointReturn)
1702             error(loc, "beginInvocationInterlockARB() cannot be placed after a return from main()", "", "");
1703         if (controlFlowNestingLevel > 0)
1704             error(loc, "beginInvocationInterlockARB() cannot be placed within flow control", "", "");
1705
1706         if (beginInvocationInterlockCount > 0)
1707             error(loc, "beginInvocationInterlockARB() must only be called once", "", "");
1708         if (endInvocationInterlockCount > 0)
1709             error(loc, "beginInvocationInterlockARB() must be called before endInvocationInterlockARB()", "", "");
1710
1711         beginInvocationInterlockCount++;
1712
1713         // default to pixel_interlock_ordered
1714         if (intermediate.getInterlockOrdering() == EioNone)
1715             intermediate.setInterlockOrdering(EioPixelInterlockOrdered);
1716         break;
1717     case EOpEndInvocationInterlock:
1718         if (language != EShLangFragment)
1719             error(loc, "endInvocationInterlockARB() must be in a fragment shader", "", "");
1720         if (! inMain)
1721             error(loc, "endInvocationInterlockARB() must be in main()", "", "");
1722         else if (postEntryPointReturn)
1723             error(loc, "endInvocationInterlockARB() cannot be placed after a return from main()", "", "");
1724         if (controlFlowNestingLevel > 0)
1725             error(loc, "endInvocationInterlockARB() cannot be placed within flow control", "", "");
1726
1727         if (endInvocationInterlockCount > 0)
1728             error(loc, "endInvocationInterlockARB() must only be called once", "", "");
1729         if (beginInvocationInterlockCount == 0)
1730             error(loc, "beginInvocationInterlockARB() must be called before endInvocationInterlockARB()", "", "");
1731
1732         endInvocationInterlockCount++;
1733         break;
1734     default:
1735         break;
1736     }
1737 #endif
1738 }
1739
1740 // Finish processing object.length(). This started earlier in handleDotDereference(), where
1741 // the ".length" part was recognized and semantically checked, and finished here where the
1742 // function syntax "()" is recognized.
1743 //
1744 // Return resulting tree node.
1745 TIntermTyped* TParseContext::handleLengthMethod(const TSourceLoc& loc, TFunction* function, TIntermNode* intermNode)
1746 {
1747     int length = 0;
1748
1749     if (function->getParamCount() > 0)
1750         error(loc, "method does not accept any arguments", function->getName().c_str(), "");
1751     else {
1752         const TType& type = intermNode->getAsTyped()->getType();
1753         if (type.isArray()) {
1754             if (type.isUnsizedArray()) {
1755 #ifndef GLSLANG_WEB
1756                 if (intermNode->getAsSymbolNode() && isIoResizeArray(type)) {
1757                     // We could be between a layout declaration that gives a built-in io array implicit size and
1758                     // a user redeclaration of that array, meaning we have to substitute its implicit size here
1759                     // without actually redeclaring the array.  (It is an error to use a member before the
1760                     // redeclaration, but not an error to use the array name itself.)
1761                     const TString& name = intermNode->getAsSymbolNode()->getName();
1762                     if (name == "gl_in" || name == "gl_out" || name == "gl_MeshVerticesNV" ||
1763                         name == "gl_MeshPrimitivesNV") {
1764                         length = getIoArrayImplicitSize(type.getQualifier());
1765                     }
1766                 }
1767 #endif
1768                 if (length == 0) {
1769 #ifndef GLSLANG_WEB
1770                     if (intermNode->getAsSymbolNode() && isIoResizeArray(type))
1771                         error(loc, "", function->getName().c_str(), "array must first be sized by a redeclaration or layout qualifier");
1772                     else if (isRuntimeLength(*intermNode->getAsTyped())) {
1773                         // Create a unary op and let the back end handle it
1774                         return intermediate.addBuiltInFunctionCall(loc, EOpArrayLength, true, intermNode, TType(EbtInt));
1775                     } else
1776 #endif
1777                         error(loc, "", function->getName().c_str(), "array must be declared with a size before using this method");
1778                 }
1779             } else if (type.getOuterArrayNode()) {
1780                 // If the array's outer size is specified by an intermediate node, it means the array's length
1781                 // was specified by a specialization constant. In such a case, we should return the node of the
1782                 // specialization constants to represent the length.
1783                 return type.getOuterArrayNode();
1784             } else
1785                 length = type.getOuterArraySize();
1786         } else if (type.isMatrix())
1787             length = type.getMatrixCols();
1788         else if (type.isVector())
1789             length = type.getVectorSize();
1790         else if (type.isCoopMat())
1791             return intermediate.addBuiltInFunctionCall(loc, EOpArrayLength, true, intermNode, TType(EbtInt));
1792         else {
1793             // we should not get here, because earlier semantic checking should have prevented this path
1794             error(loc, ".length()", "unexpected use of .length()", "");
1795         }
1796     }
1797
1798     if (length == 0)
1799         length = 1;
1800
1801     return intermediate.addConstantUnion(length, loc);
1802 }
1803
1804 //
1805 // Add any needed implicit conversions for function-call arguments to input parameters.
1806 //
1807 void TParseContext::addInputArgumentConversions(const TFunction& function, TIntermNode*& arguments) const
1808 {
1809 #ifndef GLSLANG_WEB
1810     TIntermAggregate* aggregate = arguments->getAsAggregate();
1811
1812     // Process each argument's conversion
1813     for (int i = 0; i < function.getParamCount(); ++i) {
1814         // At this early point there is a slight ambiguity between whether an aggregate 'arguments'
1815         // is the single argument itself or its children are the arguments.  Only one argument
1816         // means take 'arguments' itself as the one argument.
1817         TIntermTyped* arg = function.getParamCount() == 1 ? arguments->getAsTyped() : (aggregate ? aggregate->getSequence()[i]->getAsTyped() : arguments->getAsTyped());
1818         if (*function[i].type != arg->getType()) {
1819             if (function[i].type->getQualifier().isParamInput() &&
1820                !function[i].type->isCoopMat()) {
1821                 // In-qualified arguments just need an extra node added above the argument to
1822                 // convert to the correct type.
1823                 arg = intermediate.addConversion(EOpFunctionCall, *function[i].type, arg);
1824                 if (arg) {
1825                     if (function.getParamCount() == 1)
1826                         arguments = arg;
1827                     else {
1828                         if (aggregate)
1829                             aggregate->getSequence()[i] = arg;
1830                         else
1831                             arguments = arg;
1832                     }
1833                 }
1834             }
1835         }
1836     }
1837 #endif
1838 }
1839
1840 //
1841 // Add any needed implicit output conversions for function-call arguments.  This
1842 // can require a new tree topology, complicated further by whether the function
1843 // has a return value.
1844 //
1845 // Returns a node of a subtree that evaluates to the return value of the function.
1846 //
1847 TIntermTyped* TParseContext::addOutputArgumentConversions(const TFunction& function, TIntermAggregate& intermNode) const
1848 {
1849 #ifdef GLSLANG_WEB
1850     return &intermNode;
1851 #else
1852     TIntermSequence& arguments = intermNode.getSequence();
1853
1854     // Will there be any output conversions?
1855     bool outputConversions = false;
1856     for (int i = 0; i < function.getParamCount(); ++i) {
1857         if (*function[i].type != arguments[i]->getAsTyped()->getType() && function[i].type->getQualifier().isParamOutput()) {
1858             outputConversions = true;
1859             break;
1860         }
1861     }
1862
1863     if (! outputConversions)
1864         return &intermNode;
1865
1866     // Setup for the new tree, if needed:
1867     //
1868     // Output conversions need a different tree topology.
1869     // Out-qualified arguments need a temporary of the correct type, with the call
1870     // followed by an assignment of the temporary to the original argument:
1871     //     void: function(arg, ...)  ->        (          function(tempArg, ...), arg = tempArg, ...)
1872     //     ret = function(arg, ...)  ->  ret = (tempRet = function(tempArg, ...), arg = tempArg, ..., tempRet)
1873     // Where the "tempArg" type needs no conversion as an argument, but will convert on assignment.
1874     TIntermTyped* conversionTree = nullptr;
1875     TVariable* tempRet = nullptr;
1876     if (intermNode.getBasicType() != EbtVoid) {
1877         // do the "tempRet = function(...), " bit from above
1878         tempRet = makeInternalVariable("tempReturn", intermNode.getType());
1879         TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, intermNode.getLoc());
1880         conversionTree = intermediate.addAssign(EOpAssign, tempRetNode, &intermNode, intermNode.getLoc());
1881     } else
1882         conversionTree = &intermNode;
1883
1884     conversionTree = intermediate.makeAggregate(conversionTree);
1885
1886     // Process each argument's conversion
1887     for (int i = 0; i < function.getParamCount(); ++i) {
1888         if (*function[i].type != arguments[i]->getAsTyped()->getType()) {
1889             if (function[i].type->getQualifier().isParamOutput()) {
1890                 // Out-qualified arguments need to use the topology set up above.
1891                 // do the " ...(tempArg, ...), arg = tempArg" bit from above
1892                 TType paramType;
1893                 paramType.shallowCopy(*function[i].type);
1894                 if (arguments[i]->getAsTyped()->getType().isParameterized() &&
1895                     !paramType.isParameterized()) {
1896                     paramType.shallowCopy(arguments[i]->getAsTyped()->getType());
1897                     paramType.copyTypeParameters(*arguments[i]->getAsTyped()->getType().getTypeParameters());
1898                 }
1899                 TVariable* tempArg = makeInternalVariable("tempArg", paramType);
1900                 tempArg->getWritableType().getQualifier().makeTemporary();
1901                 TIntermSymbol* tempArgNode = intermediate.addSymbol(*tempArg, intermNode.getLoc());
1902                 TIntermTyped* tempAssign = intermediate.addAssign(EOpAssign, arguments[i]->getAsTyped(), tempArgNode, arguments[i]->getLoc());
1903                 conversionTree = intermediate.growAggregate(conversionTree, tempAssign, arguments[i]->getLoc());
1904                 // replace the argument with another node for the same tempArg variable
1905                 arguments[i] = intermediate.addSymbol(*tempArg, intermNode.getLoc());
1906             }
1907         }
1908     }
1909
1910     // Finalize the tree topology (see bigger comment above).
1911     if (tempRet) {
1912         // do the "..., tempRet" bit from above
1913         TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, intermNode.getLoc());
1914         conversionTree = intermediate.growAggregate(conversionTree, tempRetNode, intermNode.getLoc());
1915     }
1916     conversionTree = intermediate.setAggregateOperator(conversionTree, EOpComma, intermNode.getType(), intermNode.getLoc());
1917
1918     return conversionTree;
1919 #endif
1920 }
1921
1922 TIntermTyped* TParseContext::addAssign(const TSourceLoc& loc, TOperator op, TIntermTyped* left, TIntermTyped* right)
1923 {
1924     if ((op == EOpAddAssign || op == EOpSubAssign) && left->isReference())
1925         requireExtensions(loc, 1, &E_GL_EXT_buffer_reference2, "+= and -= on a buffer reference");
1926
1927     return intermediate.addAssign(op, left, right, loc);
1928 }
1929
1930 void TParseContext::memorySemanticsCheck(const TSourceLoc& loc, const TFunction& fnCandidate, const TIntermOperator& callNode)
1931 {
1932     const TIntermSequence* argp = &callNode.getAsAggregate()->getSequence();
1933
1934     //const int gl_SemanticsRelaxed         = 0x0;
1935     const int gl_SemanticsAcquire         = 0x2;
1936     const int gl_SemanticsRelease         = 0x4;
1937     const int gl_SemanticsAcquireRelease  = 0x8;
1938     const int gl_SemanticsMakeAvailable   = 0x2000;
1939     const int gl_SemanticsMakeVisible     = 0x4000;
1940     const int gl_SemanticsVolatile        = 0x8000;
1941
1942     //const int gl_StorageSemanticsNone     = 0x0;
1943     const int gl_StorageSemanticsBuffer   = 0x40;
1944     const int gl_StorageSemanticsShared   = 0x100;
1945     const int gl_StorageSemanticsImage    = 0x800;
1946     const int gl_StorageSemanticsOutput   = 0x1000;
1947
1948
1949     unsigned int semantics = 0, storageClassSemantics = 0;
1950     unsigned int semantics2 = 0, storageClassSemantics2 = 0;
1951
1952     const TIntermTyped* arg0 = (*argp)[0]->getAsTyped();
1953     const bool isMS = arg0->getBasicType() == EbtSampler && arg0->getType().getSampler().isMultiSample();
1954
1955     // Grab the semantics and storage class semantics from the operands, based on opcode
1956     switch (callNode.getOp()) {
1957     case EOpAtomicAdd:
1958     case EOpAtomicSubtract:
1959     case EOpAtomicMin:
1960     case EOpAtomicMax:
1961     case EOpAtomicAnd:
1962     case EOpAtomicOr:
1963     case EOpAtomicXor:
1964     case EOpAtomicExchange:
1965     case EOpAtomicStore:
1966         storageClassSemantics = (*argp)[3]->getAsConstantUnion()->getConstArray()[0].getIConst();
1967         semantics = (*argp)[4]->getAsConstantUnion()->getConstArray()[0].getIConst();
1968         break;
1969     case EOpAtomicLoad:
1970         storageClassSemantics = (*argp)[2]->getAsConstantUnion()->getConstArray()[0].getIConst();
1971         semantics = (*argp)[3]->getAsConstantUnion()->getConstArray()[0].getIConst();
1972         break;
1973     case EOpAtomicCompSwap:
1974         storageClassSemantics = (*argp)[4]->getAsConstantUnion()->getConstArray()[0].getIConst();
1975         semantics = (*argp)[5]->getAsConstantUnion()->getConstArray()[0].getIConst();
1976         storageClassSemantics2 = (*argp)[6]->getAsConstantUnion()->getConstArray()[0].getIConst();
1977         semantics2 = (*argp)[7]->getAsConstantUnion()->getConstArray()[0].getIConst();
1978         break;
1979
1980     case EOpImageAtomicAdd:
1981     case EOpImageAtomicMin:
1982     case EOpImageAtomicMax:
1983     case EOpImageAtomicAnd:
1984     case EOpImageAtomicOr:
1985     case EOpImageAtomicXor:
1986     case EOpImageAtomicExchange:
1987     case EOpImageAtomicStore:
1988         storageClassSemantics = (*argp)[isMS ? 5 : 4]->getAsConstantUnion()->getConstArray()[0].getIConst();
1989         semantics = (*argp)[isMS ? 6 : 5]->getAsConstantUnion()->getConstArray()[0].getIConst();
1990         break;
1991     case EOpImageAtomicLoad:
1992         storageClassSemantics = (*argp)[isMS ? 4 : 3]->getAsConstantUnion()->getConstArray()[0].getIConst();
1993         semantics = (*argp)[isMS ? 5 : 4]->getAsConstantUnion()->getConstArray()[0].getIConst();
1994         break;
1995     case EOpImageAtomicCompSwap:
1996         storageClassSemantics = (*argp)[isMS ? 6 : 5]->getAsConstantUnion()->getConstArray()[0].getIConst();
1997         semantics = (*argp)[isMS ? 7 : 6]->getAsConstantUnion()->getConstArray()[0].getIConst();
1998         storageClassSemantics2 = (*argp)[isMS ? 8 : 7]->getAsConstantUnion()->getConstArray()[0].getIConst();
1999         semantics2 = (*argp)[isMS ? 9 : 8]->getAsConstantUnion()->getConstArray()[0].getIConst();
2000         break;
2001
2002     case EOpBarrier:
2003         storageClassSemantics = (*argp)[2]->getAsConstantUnion()->getConstArray()[0].getIConst();
2004         semantics = (*argp)[3]->getAsConstantUnion()->getConstArray()[0].getIConst();
2005         break;
2006     case EOpMemoryBarrier:
2007         storageClassSemantics = (*argp)[1]->getAsConstantUnion()->getConstArray()[0].getIConst();
2008         semantics = (*argp)[2]->getAsConstantUnion()->getConstArray()[0].getIConst();
2009         break;
2010     default:
2011         break;
2012     }
2013
2014     if ((semantics & gl_SemanticsAcquire) &&
2015         (callNode.getOp() == EOpAtomicStore || callNode.getOp() == EOpImageAtomicStore)) {
2016         error(loc, "gl_SemanticsAcquire must not be used with (image) atomic store",
2017               fnCandidate.getName().c_str(), "");
2018     }
2019     if ((semantics & gl_SemanticsRelease) &&
2020         (callNode.getOp() == EOpAtomicLoad || callNode.getOp() == EOpImageAtomicLoad)) {
2021         error(loc, "gl_SemanticsRelease must not be used with (image) atomic load",
2022               fnCandidate.getName().c_str(), "");
2023     }
2024     if ((semantics & gl_SemanticsAcquireRelease) &&
2025         (callNode.getOp() == EOpAtomicStore || callNode.getOp() == EOpImageAtomicStore ||
2026          callNode.getOp() == EOpAtomicLoad  || callNode.getOp() == EOpImageAtomicLoad)) {
2027         error(loc, "gl_SemanticsAcquireRelease must not be used with (image) atomic load/store",
2028               fnCandidate.getName().c_str(), "");
2029     }
2030     if (((semantics | semantics2) & ~(gl_SemanticsAcquire |
2031                                       gl_SemanticsRelease |
2032                                       gl_SemanticsAcquireRelease |
2033                                       gl_SemanticsMakeAvailable |
2034                                       gl_SemanticsMakeVisible |
2035                                       gl_SemanticsVolatile))) {
2036         error(loc, "Invalid semantics value", fnCandidate.getName().c_str(), "");
2037     }
2038     if (((storageClassSemantics | storageClassSemantics2) & ~(gl_StorageSemanticsBuffer |
2039                                                               gl_StorageSemanticsShared |
2040                                                               gl_StorageSemanticsImage |
2041                                                               gl_StorageSemanticsOutput))) {
2042         error(loc, "Invalid storage class semantics value", fnCandidate.getName().c_str(), "");
2043     }
2044
2045     if (callNode.getOp() == EOpMemoryBarrier) {
2046         if (!IsPow2(semantics & (gl_SemanticsAcquire | gl_SemanticsRelease | gl_SemanticsAcquireRelease))) {
2047             error(loc, "Semantics must include exactly one of gl_SemanticsRelease, gl_SemanticsAcquire, or "
2048                        "gl_SemanticsAcquireRelease", fnCandidate.getName().c_str(), "");
2049         }
2050     } else {
2051         if (semantics & (gl_SemanticsAcquire | gl_SemanticsRelease | gl_SemanticsAcquireRelease)) {
2052             if (!IsPow2(semantics & (gl_SemanticsAcquire | gl_SemanticsRelease | gl_SemanticsAcquireRelease))) {
2053                 error(loc, "Semantics must not include multiple of gl_SemanticsRelease, gl_SemanticsAcquire, or "
2054                            "gl_SemanticsAcquireRelease", fnCandidate.getName().c_str(), "");
2055             }
2056         }
2057         if (semantics2 & (gl_SemanticsAcquire | gl_SemanticsRelease | gl_SemanticsAcquireRelease)) {
2058             if (!IsPow2(semantics2 & (gl_SemanticsAcquire | gl_SemanticsRelease | gl_SemanticsAcquireRelease))) {
2059                 error(loc, "semUnequal must not include multiple of gl_SemanticsRelease, gl_SemanticsAcquire, or "
2060                            "gl_SemanticsAcquireRelease", fnCandidate.getName().c_str(), "");
2061             }
2062         }
2063     }
2064     if (callNode.getOp() == EOpMemoryBarrier) {
2065         if (storageClassSemantics == 0) {
2066             error(loc, "Storage class semantics must not be zero", fnCandidate.getName().c_str(), "");
2067         }
2068     }
2069     if (callNode.getOp() == EOpBarrier && semantics != 0 && storageClassSemantics == 0) {
2070         error(loc, "Storage class semantics must not be zero", fnCandidate.getName().c_str(), "");
2071     }
2072     if ((callNode.getOp() == EOpAtomicCompSwap || callNode.getOp() == EOpImageAtomicCompSwap) &&
2073         (semantics2 & (gl_SemanticsRelease | gl_SemanticsAcquireRelease))) {
2074         error(loc, "semUnequal must not be gl_SemanticsRelease or gl_SemanticsAcquireRelease",
2075               fnCandidate.getName().c_str(), "");
2076     }
2077     if ((semantics & gl_SemanticsMakeAvailable) &&
2078         !(semantics & (gl_SemanticsRelease | gl_SemanticsAcquireRelease))) {
2079         error(loc, "gl_SemanticsMakeAvailable requires gl_SemanticsRelease or gl_SemanticsAcquireRelease",
2080               fnCandidate.getName().c_str(), "");
2081     }
2082     if ((semantics & gl_SemanticsMakeVisible) &&
2083         !(semantics & (gl_SemanticsAcquire | gl_SemanticsAcquireRelease))) {
2084         error(loc, "gl_SemanticsMakeVisible requires gl_SemanticsAcquire or gl_SemanticsAcquireRelease",
2085               fnCandidate.getName().c_str(), "");
2086     }
2087     if ((semantics & gl_SemanticsVolatile) &&
2088         (callNode.getOp() == EOpMemoryBarrier || callNode.getOp() == EOpBarrier)) {
2089         error(loc, "gl_SemanticsVolatile must not be used with memoryBarrier or controlBarrier",
2090               fnCandidate.getName().c_str(), "");
2091     }
2092     if ((callNode.getOp() == EOpAtomicCompSwap || callNode.getOp() == EOpImageAtomicCompSwap) &&
2093         ((semantics ^ semantics2) & gl_SemanticsVolatile)) {
2094         error(loc, "semEqual and semUnequal must either both include gl_SemanticsVolatile or neither",
2095               fnCandidate.getName().c_str(), "");
2096     }
2097 }
2098
2099 //
2100 // Do additional checking of built-in function calls that is not caught
2101 // by normal semantic checks on argument type, extension tagging, etc.
2102 //
2103 // Assumes there has been a semantically correct match to a built-in function prototype.
2104 //
2105 void TParseContext::builtInOpCheck(const TSourceLoc& loc, const TFunction& fnCandidate, TIntermOperator& callNode)
2106 {
2107     // Set up convenience accessors to the argument(s).  There is almost always
2108     // multiple arguments for the cases below, but when there might be one,
2109     // check the unaryArg first.
2110     const TIntermSequence* argp = nullptr;   // confusing to use [] syntax on a pointer, so this is to help get a reference
2111     const TIntermTyped* unaryArg = nullptr;
2112     const TIntermTyped* arg0 = nullptr;
2113     if (callNode.getAsAggregate()) {
2114         argp = &callNode.getAsAggregate()->getSequence();
2115         if (argp->size() > 0)
2116             arg0 = (*argp)[0]->getAsTyped();
2117     } else {
2118         assert(callNode.getAsUnaryNode());
2119         unaryArg = callNode.getAsUnaryNode()->getOperand();
2120         arg0 = unaryArg;
2121     }
2122
2123     TString featureString;
2124     const char* feature = nullptr;
2125     switch (callNode.getOp()) {
2126 #ifndef GLSLANG_WEB
2127     case EOpTextureGather:
2128     case EOpTextureGatherOffset:
2129     case EOpTextureGatherOffsets:
2130     {
2131         // Figure out which variants are allowed by what extensions,
2132         // and what arguments must be constant for which situations.
2133
2134         featureString = fnCandidate.getName();
2135         featureString += "(...)";
2136         feature = featureString.c_str();
2137         profileRequires(loc, EEsProfile, 310, nullptr, feature);
2138         int compArg = -1;  // track which argument, if any, is the constant component argument
2139         switch (callNode.getOp()) {
2140         case EOpTextureGather:
2141             // More than two arguments needs gpu_shader5, and rectangular or shadow needs gpu_shader5,
2142             // otherwise, need GL_ARB_texture_gather.
2143             if (fnCandidate.getParamCount() > 2 || fnCandidate[0].type->getSampler().dim == EsdRect || fnCandidate[0].type->getSampler().shadow) {
2144                 profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_gpu_shader5, feature);
2145                 if (! fnCandidate[0].type->getSampler().shadow)
2146                     compArg = 2;
2147             } else
2148                 profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_texture_gather, feature);
2149             break;
2150         case EOpTextureGatherOffset:
2151             // GL_ARB_texture_gather is good enough for 2D non-shadow textures with no component argument
2152             if (fnCandidate[0].type->getSampler().dim == Esd2D && ! fnCandidate[0].type->getSampler().shadow && fnCandidate.getParamCount() == 3)
2153                 profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_texture_gather, feature);
2154             else
2155                 profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_gpu_shader5, feature);
2156             if (! (*argp)[fnCandidate[0].type->getSampler().shadow ? 3 : 2]->getAsConstantUnion())
2157                 profileRequires(loc, EEsProfile, 320, Num_AEP_gpu_shader5, AEP_gpu_shader5,
2158                                 "non-constant offset argument");
2159             if (! fnCandidate[0].type->getSampler().shadow)
2160                 compArg = 3;
2161             break;
2162         case EOpTextureGatherOffsets:
2163             profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_gpu_shader5, feature);
2164             if (! fnCandidate[0].type->getSampler().shadow)
2165                 compArg = 3;
2166             // check for constant offsets
2167             if (! (*argp)[fnCandidate[0].type->getSampler().shadow ? 3 : 2]->getAsConstantUnion())
2168                 error(loc, "must be a compile-time constant:", feature, "offsets argument");
2169             break;
2170         default:
2171             break;
2172         }
2173
2174         if (compArg > 0 && compArg < fnCandidate.getParamCount()) {
2175             if ((*argp)[compArg]->getAsConstantUnion()) {
2176                 int value = (*argp)[compArg]->getAsConstantUnion()->getConstArray()[0].getIConst();
2177                 if (value < 0 || value > 3)
2178                     error(loc, "must be 0, 1, 2, or 3:", feature, "component argument");
2179             } else
2180                 error(loc, "must be a compile-time constant:", feature, "component argument");
2181         }
2182
2183         bool bias = false;
2184         if (callNode.getOp() == EOpTextureGather)
2185             bias = fnCandidate.getParamCount() > 3;
2186         else if (callNode.getOp() == EOpTextureGatherOffset ||
2187                  callNode.getOp() == EOpTextureGatherOffsets)
2188             bias = fnCandidate.getParamCount() > 4;
2189
2190         if (bias) {
2191             featureString = fnCandidate.getName();
2192             featureString += "with bias argument";
2193             feature = featureString.c_str();
2194             profileRequires(loc, ~EEsProfile, 450, nullptr, feature);
2195             requireExtensions(loc, 1, &E_GL_AMD_texture_gather_bias_lod, feature);
2196         }
2197         break;
2198     }
2199     case EOpSparseTextureGather:
2200     case EOpSparseTextureGatherOffset:
2201     case EOpSparseTextureGatherOffsets:
2202     {
2203         bool bias = false;
2204         if (callNode.getOp() == EOpSparseTextureGather)
2205             bias = fnCandidate.getParamCount() > 4;
2206         else if (callNode.getOp() == EOpSparseTextureGatherOffset ||
2207                  callNode.getOp() == EOpSparseTextureGatherOffsets)
2208             bias = fnCandidate.getParamCount() > 5;
2209
2210         if (bias) {
2211             featureString = fnCandidate.getName();
2212             featureString += "with bias argument";
2213             feature = featureString.c_str();
2214             profileRequires(loc, ~EEsProfile, 450, nullptr, feature);
2215             requireExtensions(loc, 1, &E_GL_AMD_texture_gather_bias_lod, feature);
2216         }
2217         // As per GL_ARB_sparse_texture2 extension "Offsets" parameter must be constant integral expression
2218         // for sparseTextureGatherOffsetsARB just as textureGatherOffsets
2219         if (callNode.getOp() == EOpSparseTextureGatherOffsets) {
2220             int offsetsArg = arg0->getType().getSampler().shadow ? 3 : 2;
2221             if (!(*argp)[offsetsArg]->getAsConstantUnion())
2222                 error(loc, "argument must be compile-time constant", "offsets", "");
2223         }
2224         break;
2225     }
2226
2227     case EOpSparseTextureGatherLod:
2228     case EOpSparseTextureGatherLodOffset:
2229     case EOpSparseTextureGatherLodOffsets:
2230     {
2231         requireExtensions(loc, 1, &E_GL_ARB_sparse_texture2, fnCandidate.getName().c_str());
2232         break;
2233     }
2234
2235     case EOpSwizzleInvocations:
2236     {
2237         if (! (*argp)[1]->getAsConstantUnion())
2238             error(loc, "argument must be compile-time constant", "offset", "");
2239         else {
2240             unsigned offset[4] = {};
2241             offset[0] = (*argp)[1]->getAsConstantUnion()->getConstArray()[0].getUConst();
2242             offset[1] = (*argp)[1]->getAsConstantUnion()->getConstArray()[1].getUConst();
2243             offset[2] = (*argp)[1]->getAsConstantUnion()->getConstArray()[2].getUConst();
2244             offset[3] = (*argp)[1]->getAsConstantUnion()->getConstArray()[3].getUConst();
2245             if (offset[0] > 3 || offset[1] > 3 || offset[2] > 3 || offset[3] > 3)
2246                 error(loc, "components must be in the range [0, 3]", "offset", "");
2247         }
2248
2249         break;
2250     }
2251
2252     case EOpSwizzleInvocationsMasked:
2253     {
2254         if (! (*argp)[1]->getAsConstantUnion())
2255             error(loc, "argument must be compile-time constant", "mask", "");
2256         else {
2257             unsigned mask[3] = {};
2258             mask[0] = (*argp)[1]->getAsConstantUnion()->getConstArray()[0].getUConst();
2259             mask[1] = (*argp)[1]->getAsConstantUnion()->getConstArray()[1].getUConst();
2260             mask[2] = (*argp)[1]->getAsConstantUnion()->getConstArray()[2].getUConst();
2261             if (mask[0] > 31 || mask[1] > 31 || mask[2] > 31)
2262                 error(loc, "components must be in the range [0, 31]", "mask", "");
2263         }
2264
2265         break;
2266     }
2267 #endif
2268
2269     case EOpTextureOffset:
2270     case EOpTextureFetchOffset:
2271     case EOpTextureProjOffset:
2272     case EOpTextureLodOffset:
2273     case EOpTextureProjLodOffset:
2274     case EOpTextureGradOffset:
2275     case EOpTextureProjGradOffset:
2276     {
2277         // Handle texture-offset limits checking
2278         // Pick which argument has to hold constant offsets
2279         int arg = -1;
2280         switch (callNode.getOp()) {
2281         case EOpTextureOffset:          arg = 2;  break;
2282         case EOpTextureFetchOffset:     arg = (arg0->getType().getSampler().isRect()) ? 2 : 3; break;
2283         case EOpTextureProjOffset:      arg = 2;  break;
2284         case EOpTextureLodOffset:       arg = 3;  break;
2285         case EOpTextureProjLodOffset:   arg = 3;  break;
2286         case EOpTextureGradOffset:      arg = 4;  break;
2287         case EOpTextureProjGradOffset:  arg = 4;  break;
2288         default:
2289             assert(0);
2290             break;
2291         }
2292
2293         if (arg > 0) {
2294
2295 #ifndef GLSLANG_WEB
2296             bool f16ShadowCompare = (*argp)[1]->getAsTyped()->getBasicType() == EbtFloat16 &&
2297                                     arg0->getType().getSampler().shadow;
2298             if (f16ShadowCompare)
2299                 ++arg;
2300 #endif
2301             if (! (*argp)[arg]->getAsTyped()->getQualifier().isConstant())
2302                 error(loc, "argument must be compile-time constant", "texel offset", "");
2303             else if ((*argp)[arg]->getAsConstantUnion()) {
2304                 const TType& type = (*argp)[arg]->getAsTyped()->getType();
2305                 for (int c = 0; c < type.getVectorSize(); ++c) {
2306                     int offset = (*argp)[arg]->getAsConstantUnion()->getConstArray()[c].getIConst();
2307                     if (offset > resources.maxProgramTexelOffset || offset < resources.minProgramTexelOffset)
2308                         error(loc, "value is out of range:", "texel offset",
2309                               "[gl_MinProgramTexelOffset, gl_MaxProgramTexelOffset]");
2310                 }
2311             }
2312
2313             if (callNode.getOp() == EOpTextureOffset) {
2314                 TSampler s = arg0->getType().getSampler();
2315                 if (s.is2D() && s.isArrayed() && s.isShadow()) {
2316                     if (isEsProfile())
2317                         error(loc, "TextureOffset does not support sampler2DArrayShadow : ", "sampler", "ES Profile");
2318                     else if (version <= 420)
2319                         error(loc, "TextureOffset does not support sampler2DArrayShadow : ", "sampler", "version <= 420");
2320                 }
2321             }
2322         }
2323
2324         break;
2325     }
2326
2327 #ifndef GLSLANG_WEB
2328     case EOpTraceNV:
2329         if (!(*argp)[10]->getAsConstantUnion())
2330             error(loc, "argument must be compile-time constant", "payload number", "a");
2331         break;
2332     case EOpTraceRayMotionNV:
2333         if (!(*argp)[11]->getAsConstantUnion())
2334             error(loc, "argument must be compile-time constant", "payload number", "a");
2335         break;
2336     case EOpTraceKHR:
2337         if (!(*argp)[10]->getAsConstantUnion())
2338             error(loc, "argument must be compile-time constant", "payload number", "a");
2339         else {
2340             unsigned int location = (*argp)[10]->getAsConstantUnion()->getAsConstantUnion()->getConstArray()[0].getUConst();
2341             if (!extensionTurnedOn(E_GL_EXT_spirv_intrinsics) && intermediate.checkLocationRT(0, location) < 0)
2342                 error(loc, "with layout(location =", "no rayPayloadEXT/rayPayloadInEXT declared", "%d)", location);
2343         }
2344         break;
2345     case EOpExecuteCallableNV:
2346         if (!(*argp)[1]->getAsConstantUnion())
2347             error(loc, "argument must be compile-time constant", "callable data number", "");
2348         break;
2349     case EOpExecuteCallableKHR:
2350         if (!(*argp)[1]->getAsConstantUnion())
2351             error(loc, "argument must be compile-time constant", "callable data number", "");
2352         else {
2353             unsigned int location = (*argp)[1]->getAsConstantUnion()->getAsConstantUnion()->getConstArray()[0].getUConst();
2354             if (!extensionTurnedOn(E_GL_EXT_spirv_intrinsics) && intermediate.checkLocationRT(1, location) < 0)
2355                 error(loc, "with layout(location =", "no callableDataEXT/callableDataInEXT declared", "%d)", location);
2356         }
2357         break;
2358
2359     case EOpRayQueryGetIntersectionType:
2360     case EOpRayQueryGetIntersectionT:
2361     case EOpRayQueryGetIntersectionInstanceCustomIndex:
2362     case EOpRayQueryGetIntersectionInstanceId:
2363     case EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2364     case EOpRayQueryGetIntersectionGeometryIndex:
2365     case EOpRayQueryGetIntersectionPrimitiveIndex:
2366     case EOpRayQueryGetIntersectionBarycentrics:
2367     case EOpRayQueryGetIntersectionFrontFace:
2368     case EOpRayQueryGetIntersectionObjectRayDirection:
2369     case EOpRayQueryGetIntersectionObjectRayOrigin:
2370     case EOpRayQueryGetIntersectionObjectToWorld:
2371     case EOpRayQueryGetIntersectionWorldToObject:
2372         if (!(*argp)[1]->getAsConstantUnion())
2373             error(loc, "argument must be compile-time constant", "committed", "");
2374         break;
2375
2376     case EOpTextureQuerySamples:
2377     case EOpImageQuerySamples:
2378         // GL_ARB_shader_texture_image_samples
2379         profileRequires(loc, ~EEsProfile, 450, E_GL_ARB_shader_texture_image_samples, "textureSamples and imageSamples");
2380         break;
2381
2382     case EOpImageAtomicAdd:
2383     case EOpImageAtomicMin:
2384     case EOpImageAtomicMax:
2385     case EOpImageAtomicAnd:
2386     case EOpImageAtomicOr:
2387     case EOpImageAtomicXor:
2388     case EOpImageAtomicExchange:
2389     case EOpImageAtomicCompSwap:
2390     case EOpImageAtomicLoad:
2391     case EOpImageAtomicStore:
2392     {
2393         // Make sure the image types have the correct layout() format and correct argument types
2394         const TType& imageType = arg0->getType();
2395         if (imageType.getSampler().type == EbtInt || imageType.getSampler().type == EbtUint ||
2396             imageType.getSampler().type == EbtInt64 || imageType.getSampler().type == EbtUint64) {
2397             if (imageType.getQualifier().getFormat() != ElfR32i && imageType.getQualifier().getFormat() != ElfR32ui &&
2398                 imageType.getQualifier().getFormat() != ElfR64i && imageType.getQualifier().getFormat() != ElfR64ui)
2399                 error(loc, "only supported on image with format r32i or r32ui", fnCandidate.getName().c_str(), "");
2400             if (callNode.getType().getBasicType() == EbtInt64 && imageType.getQualifier().getFormat() != ElfR64i)
2401                 error(loc, "only supported on image with format r64i", fnCandidate.getName().c_str(), "");
2402             else if (callNode.getType().getBasicType() == EbtUint64 && imageType.getQualifier().getFormat() != ElfR64ui)
2403                 error(loc, "only supported on image with format r64ui", fnCandidate.getName().c_str(), "");
2404         } else if (imageType.getSampler().type == EbtFloat) {
2405             if (fnCandidate.getName().compare(0, 19, "imageAtomicExchange") == 0) {
2406                 // imageAtomicExchange doesn't require an extension
2407             } else if ((fnCandidate.getName().compare(0, 14, "imageAtomicAdd") == 0) ||
2408                        (fnCandidate.getName().compare(0, 15, "imageAtomicLoad") == 0) ||
2409                        (fnCandidate.getName().compare(0, 16, "imageAtomicStore") == 0)) {
2410                 requireExtensions(loc, 1, &E_GL_EXT_shader_atomic_float, fnCandidate.getName().c_str());
2411             } else if ((fnCandidate.getName().compare(0, 14, "imageAtomicMin") == 0) ||
2412                        (fnCandidate.getName().compare(0, 14, "imageAtomicMax") == 0)) {
2413                 requireExtensions(loc, 1, &E_GL_EXT_shader_atomic_float2, fnCandidate.getName().c_str());
2414             } else {
2415                 error(loc, "only supported on integer images", fnCandidate.getName().c_str(), "");
2416             }
2417             if (imageType.getQualifier().getFormat() != ElfR32f && isEsProfile())
2418                 error(loc, "only supported on image with format r32f", fnCandidate.getName().c_str(), "");
2419         } else {
2420             error(loc, "not supported on this image type", fnCandidate.getName().c_str(), "");
2421         }
2422
2423         const size_t maxArgs = imageType.getSampler().isMultiSample() ? 5 : 4;
2424         if (argp->size() > maxArgs) {
2425             requireExtensions(loc, 1, &E_GL_KHR_memory_scope_semantics, fnCandidate.getName().c_str());
2426             memorySemanticsCheck(loc, fnCandidate, callNode);
2427         }
2428
2429         break;
2430     }
2431
2432     case EOpAtomicAdd:
2433     case EOpAtomicSubtract:
2434     case EOpAtomicMin:
2435     case EOpAtomicMax:
2436     case EOpAtomicAnd:
2437     case EOpAtomicOr:
2438     case EOpAtomicXor:
2439     case EOpAtomicExchange:
2440     case EOpAtomicCompSwap:
2441     case EOpAtomicLoad:
2442     case EOpAtomicStore:
2443     {
2444         if (argp->size() > 3) {
2445             requireExtensions(loc, 1, &E_GL_KHR_memory_scope_semantics, fnCandidate.getName().c_str());
2446             memorySemanticsCheck(loc, fnCandidate, callNode);
2447             if ((callNode.getOp() == EOpAtomicAdd || callNode.getOp() == EOpAtomicExchange ||
2448                 callNode.getOp() == EOpAtomicLoad || callNode.getOp() == EOpAtomicStore) &&
2449                 (arg0->getType().getBasicType() == EbtFloat ||
2450                  arg0->getType().getBasicType() == EbtDouble)) {
2451                 requireExtensions(loc, 1, &E_GL_EXT_shader_atomic_float, fnCandidate.getName().c_str());
2452             } else if ((callNode.getOp() == EOpAtomicAdd || callNode.getOp() == EOpAtomicExchange ||
2453                         callNode.getOp() == EOpAtomicLoad || callNode.getOp() == EOpAtomicStore ||
2454                         callNode.getOp() == EOpAtomicMin || callNode.getOp() == EOpAtomicMax) &&
2455                        arg0->getType().isFloatingDomain()) {
2456                 requireExtensions(loc, 1, &E_GL_EXT_shader_atomic_float2, fnCandidate.getName().c_str());
2457             }
2458         } else if (arg0->getType().getBasicType() == EbtInt64 || arg0->getType().getBasicType() == EbtUint64) {
2459             const char* const extensions[2] = { E_GL_NV_shader_atomic_int64,
2460                                                 E_GL_EXT_shader_atomic_int64 };
2461             requireExtensions(loc, 2, extensions, fnCandidate.getName().c_str());
2462         } else if ((callNode.getOp() == EOpAtomicAdd || callNode.getOp() == EOpAtomicExchange) &&
2463                    (arg0->getType().getBasicType() == EbtFloat ||
2464                     arg0->getType().getBasicType() == EbtDouble)) {
2465             requireExtensions(loc, 1, &E_GL_EXT_shader_atomic_float, fnCandidate.getName().c_str());
2466         } else if ((callNode.getOp() == EOpAtomicAdd || callNode.getOp() == EOpAtomicExchange ||
2467                     callNode.getOp() == EOpAtomicLoad || callNode.getOp() == EOpAtomicStore ||
2468                     callNode.getOp() == EOpAtomicMin || callNode.getOp() == EOpAtomicMax) &&
2469                    arg0->getType().isFloatingDomain()) {
2470             requireExtensions(loc, 1, &E_GL_EXT_shader_atomic_float2, fnCandidate.getName().c_str());
2471         }
2472
2473         const TIntermTyped* base = TIntermediate::findLValueBase(arg0, true , true);
2474         const TType* refType = (base->getType().isReference()) ? base->getType().getReferentType() : nullptr;
2475         const TQualifier& qualifier = (refType != nullptr) ? refType->getQualifier() : base->getType().getQualifier();
2476         if (qualifier.storage != EvqShared && qualifier.storage != EvqBuffer && qualifier.storage != EvqtaskPayloadSharedEXT)
2477             error(loc,"Atomic memory function can only be used for shader storage block member or shared variable.",
2478             fnCandidate.getName().c_str(), "");
2479
2480         break;
2481     }
2482
2483     case EOpInterpolateAtCentroid:
2484     case EOpInterpolateAtSample:
2485     case EOpInterpolateAtOffset:
2486     case EOpInterpolateAtVertex:
2487         // Make sure the first argument is an interpolant, or an array element of an interpolant
2488         if (arg0->getType().getQualifier().storage != EvqVaryingIn) {
2489             // It might still be an array element.
2490             //
2491             // We could check more, but the semantics of the first argument are already met; the
2492             // only way to turn an array into a float/vec* is array dereference and swizzle.
2493             //
2494             // ES and desktop 4.3 and earlier:  swizzles may not be used
2495             // desktop 4.4 and later: swizzles may be used
2496             bool swizzleOkay = (!isEsProfile()) && (version >= 440);
2497             const TIntermTyped* base = TIntermediate::findLValueBase(arg0, swizzleOkay);
2498             if (base == nullptr || base->getType().getQualifier().storage != EvqVaryingIn)
2499                 error(loc, "first argument must be an interpolant, or interpolant-array element", fnCandidate.getName().c_str(), "");
2500         }
2501
2502         if (callNode.getOp() == EOpInterpolateAtVertex) {
2503             if (!arg0->getType().getQualifier().isExplicitInterpolation())
2504                 error(loc, "argument must be qualified as __explicitInterpAMD in", "interpolant", "");
2505             else {
2506                 if (! (*argp)[1]->getAsConstantUnion())
2507                     error(loc, "argument must be compile-time constant", "vertex index", "");
2508                 else {
2509                     unsigned vertexIdx = (*argp)[1]->getAsConstantUnion()->getConstArray()[0].getUConst();
2510                     if (vertexIdx > 2)
2511                         error(loc, "must be in the range [0, 2]", "vertex index", "");
2512                 }
2513             }
2514         }
2515         break;
2516
2517     case EOpEmitStreamVertex:
2518     case EOpEndStreamPrimitive:
2519         if (version == 150)
2520             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");
2521         intermediate.setMultiStream();
2522         break;
2523
2524     case EOpSubgroupClusteredAdd:
2525     case EOpSubgroupClusteredMul:
2526     case EOpSubgroupClusteredMin:
2527     case EOpSubgroupClusteredMax:
2528     case EOpSubgroupClusteredAnd:
2529     case EOpSubgroupClusteredOr:
2530     case EOpSubgroupClusteredXor:
2531         // The <clusterSize> as used in the subgroupClustered<op>() operations must be:
2532         // - An integral constant expression.
2533         // - At least 1.
2534         // - A power of 2.
2535         if ((*argp)[1]->getAsConstantUnion() == nullptr)
2536             error(loc, "argument must be compile-time constant", "cluster size", "");
2537         else {
2538             int size = (*argp)[1]->getAsConstantUnion()->getConstArray()[0].getIConst();
2539             if (size < 1)
2540                 error(loc, "argument must be at least 1", "cluster size", "");
2541             else if (!IsPow2(size))
2542                 error(loc, "argument must be a power of 2", "cluster size", "");
2543         }
2544         break;
2545
2546     case EOpSubgroupBroadcast:
2547     case EOpSubgroupQuadBroadcast:
2548         if (spvVersion.spv < EShTargetSpv_1_5) {
2549             // <id> must be an integral constant expression.
2550             if ((*argp)[1]->getAsConstantUnion() == nullptr)
2551                 error(loc, "argument must be compile-time constant", "id", "");
2552         }
2553         break;
2554
2555     case EOpBarrier:
2556     case EOpMemoryBarrier:
2557         if (argp->size() > 0) {
2558             requireExtensions(loc, 1, &E_GL_KHR_memory_scope_semantics, fnCandidate.getName().c_str());
2559             memorySemanticsCheck(loc, fnCandidate, callNode);
2560         }
2561         break;
2562
2563     case EOpMix:
2564         if (profile == EEsProfile && version < 310) {
2565             // Look for specific signatures
2566             if ((*argp)[0]->getAsTyped()->getBasicType() != EbtFloat &&
2567                 (*argp)[1]->getAsTyped()->getBasicType() != EbtFloat &&
2568                 (*argp)[2]->getAsTyped()->getBasicType() == EbtBool) {
2569                 requireExtensions(loc, 1, &E_GL_EXT_shader_integer_mix, "specific signature of builtin mix");
2570             }
2571         }
2572
2573         if (profile != EEsProfile && version < 450) {
2574             if ((*argp)[0]->getAsTyped()->getBasicType() != EbtFloat &&
2575                 (*argp)[0]->getAsTyped()->getBasicType() != EbtDouble &&
2576                 (*argp)[1]->getAsTyped()->getBasicType() != EbtFloat &&
2577                 (*argp)[1]->getAsTyped()->getBasicType() != EbtDouble &&
2578                 (*argp)[2]->getAsTyped()->getBasicType() == EbtBool) {
2579                 requireExtensions(loc, 1, &E_GL_EXT_shader_integer_mix, fnCandidate.getName().c_str());
2580             }
2581         }
2582
2583         break;
2584 #endif
2585
2586     default:
2587         break;
2588     }
2589
2590     // Texture operations on texture objects (aside from texelFetch on a
2591     // textureBuffer) require EXT_samplerless_texture_functions.
2592     switch (callNode.getOp()) {
2593     case EOpTextureQuerySize:
2594     case EOpTextureQueryLevels:
2595     case EOpTextureQuerySamples:
2596     case EOpTextureFetch:
2597     case EOpTextureFetchOffset:
2598     {
2599         const TSampler& sampler = fnCandidate[0].type->getSampler();
2600
2601         const bool isTexture = sampler.isTexture() && !sampler.isCombined();
2602         const bool isBuffer = sampler.isBuffer();
2603         const bool isFetch = callNode.getOp() == EOpTextureFetch || callNode.getOp() == EOpTextureFetchOffset;
2604
2605         if (isTexture && (!isBuffer || !isFetch))
2606             requireExtensions(loc, 1, &E_GL_EXT_samplerless_texture_functions, fnCandidate.getName().c_str());
2607
2608         break;
2609     }
2610
2611     default:
2612         break;
2613     }
2614
2615     if (callNode.isSubgroup()) {
2616         // these require SPIR-V 1.3
2617         if (spvVersion.spv > 0 && spvVersion.spv < EShTargetSpv_1_3)
2618             error(loc, "requires SPIR-V 1.3", "subgroup op", "");
2619
2620         // Check that if extended types are being used that the correct extensions are enabled.
2621         if (arg0 != nullptr) {
2622             const TType& type = arg0->getType();
2623             bool enhanced = intermediate.getEnhancedMsgs();
2624             switch (type.getBasicType()) {
2625             default:
2626                 break;
2627             case EbtInt8:
2628             case EbtUint8:
2629                 requireExtensions(loc, 1, &E_GL_EXT_shader_subgroup_extended_types_int8, type.getCompleteString(enhanced).c_str());
2630                 break;
2631             case EbtInt16:
2632             case EbtUint16:
2633                 requireExtensions(loc, 1, &E_GL_EXT_shader_subgroup_extended_types_int16, type.getCompleteString(enhanced).c_str());
2634                 break;
2635             case EbtInt64:
2636             case EbtUint64:
2637                 requireExtensions(loc, 1, &E_GL_EXT_shader_subgroup_extended_types_int64, type.getCompleteString(enhanced).c_str());
2638                 break;
2639             case EbtFloat16:
2640                 requireExtensions(loc, 1, &E_GL_EXT_shader_subgroup_extended_types_float16, type.getCompleteString(enhanced).c_str());
2641                 break;
2642             }
2643         }
2644     }
2645 }
2646
2647 #ifndef GLSLANG_WEB
2648
2649 extern bool PureOperatorBuiltins;
2650
2651 // Deprecated!  Use PureOperatorBuiltins == true instead, in which case this
2652 // functionality is handled in builtInOpCheck() instead of here.
2653 //
2654 // Do additional checking of built-in function calls that were not mapped
2655 // to built-in operations (e.g., texturing functions).
2656 //
2657 // Assumes there has been a semantically correct match to a built-in function.
2658 //
2659 void TParseContext::nonOpBuiltInCheck(const TSourceLoc& loc, const TFunction& fnCandidate, TIntermAggregate& callNode)
2660 {
2661     // Further maintenance of this function is deprecated, because the "correct"
2662     // future-oriented design is to not have to do string compares on function names.
2663
2664     // If PureOperatorBuiltins == true, then all built-ins should be mapped
2665     // to a TOperator, and this function would then never get called.
2666
2667     assert(PureOperatorBuiltins == false);
2668
2669     // built-in texturing functions get their return value precision from the precision of the sampler
2670     if (fnCandidate.getType().getQualifier().precision == EpqNone &&
2671         fnCandidate.getParamCount() > 0 && fnCandidate[0].type->getBasicType() == EbtSampler)
2672         callNode.getQualifier().precision = callNode.getSequence()[0]->getAsTyped()->getQualifier().precision;
2673
2674     if (fnCandidate.getName().compare(0, 7, "texture") == 0) {
2675         if (fnCandidate.getName().compare(0, 13, "textureGather") == 0) {
2676             TString featureString = fnCandidate.getName() + "(...)";
2677             const char* feature = featureString.c_str();
2678             profileRequires(loc, EEsProfile, 310, nullptr, feature);
2679
2680             int compArg = -1;  // track which argument, if any, is the constant component argument
2681             if (fnCandidate.getName().compare("textureGatherOffset") == 0) {
2682                 // GL_ARB_texture_gather is good enough for 2D non-shadow textures with no component argument
2683                 if (fnCandidate[0].type->getSampler().dim == Esd2D && ! fnCandidate[0].type->getSampler().shadow && fnCandidate.getParamCount() == 3)
2684                     profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_texture_gather, feature);
2685                 else
2686                     profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_gpu_shader5, feature);
2687                 int offsetArg = fnCandidate[0].type->getSampler().shadow ? 3 : 2;
2688                 if (! callNode.getSequence()[offsetArg]->getAsConstantUnion())
2689                     profileRequires(loc, EEsProfile, 320, Num_AEP_gpu_shader5, AEP_gpu_shader5,
2690                                     "non-constant offset argument");
2691                 if (! fnCandidate[0].type->getSampler().shadow)
2692                     compArg = 3;
2693             } else if (fnCandidate.getName().compare("textureGatherOffsets") == 0) {
2694                 profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_gpu_shader5, feature);
2695                 if (! fnCandidate[0].type->getSampler().shadow)
2696                     compArg = 3;
2697                 // check for constant offsets
2698                 int offsetArg = fnCandidate[0].type->getSampler().shadow ? 3 : 2;
2699                 if (! callNode.getSequence()[offsetArg]->getAsConstantUnion())
2700                     error(loc, "must be a compile-time constant:", feature, "offsets argument");
2701             } else if (fnCandidate.getName().compare("textureGather") == 0) {
2702                 // More than two arguments needs gpu_shader5, and rectangular or shadow needs gpu_shader5,
2703                 // otherwise, need GL_ARB_texture_gather.
2704                 if (fnCandidate.getParamCount() > 2 || fnCandidate[0].type->getSampler().dim == EsdRect || fnCandidate[0].type->getSampler().shadow) {
2705                     profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_gpu_shader5, feature);
2706                     if (! fnCandidate[0].type->getSampler().shadow)
2707                         compArg = 2;
2708                 } else
2709                     profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_texture_gather, feature);
2710             }
2711
2712             if (compArg > 0 && compArg < fnCandidate.getParamCount()) {
2713                 if (callNode.getSequence()[compArg]->getAsConstantUnion()) {
2714                     int value = callNode.getSequence()[compArg]->getAsConstantUnion()->getConstArray()[0].getIConst();
2715                     if (value < 0 || value > 3)
2716                         error(loc, "must be 0, 1, 2, or 3:", feature, "component argument");
2717                 } else
2718                     error(loc, "must be a compile-time constant:", feature, "component argument");
2719             }
2720         } else {
2721             // this is only for functions not starting "textureGather"...
2722             if (fnCandidate.getName().find("Offset") != TString::npos) {
2723
2724                 // Handle texture-offset limits checking
2725                 int arg = -1;
2726                 if (fnCandidate.getName().compare("textureOffset") == 0)
2727                     arg = 2;
2728                 else if (fnCandidate.getName().compare("texelFetchOffset") == 0)
2729                     arg = 3;
2730                 else if (fnCandidate.getName().compare("textureProjOffset") == 0)
2731                     arg = 2;
2732                 else if (fnCandidate.getName().compare("textureLodOffset") == 0)
2733                     arg = 3;
2734                 else if (fnCandidate.getName().compare("textureProjLodOffset") == 0)
2735                     arg = 3;
2736                 else if (fnCandidate.getName().compare("textureGradOffset") == 0)
2737                     arg = 4;
2738                 else if (fnCandidate.getName().compare("textureProjGradOffset") == 0)
2739                     arg = 4;
2740
2741                 if (arg > 0) {
2742                     if (! callNode.getSequence()[arg]->getAsConstantUnion())
2743                         error(loc, "argument must be compile-time constant", "texel offset", "");
2744                     else {
2745                         const TType& type = callNode.getSequence()[arg]->getAsTyped()->getType();
2746                         for (int c = 0; c < type.getVectorSize(); ++c) {
2747                             int offset = callNode.getSequence()[arg]->getAsConstantUnion()->getConstArray()[c].getIConst();
2748                             if (offset > resources.maxProgramTexelOffset || offset < resources.minProgramTexelOffset)
2749                                 error(loc, "value is out of range:", "texel offset", "[gl_MinProgramTexelOffset, gl_MaxProgramTexelOffset]");
2750                         }
2751                     }
2752                 }
2753             }
2754         }
2755     }
2756
2757     // GL_ARB_shader_texture_image_samples
2758     if (fnCandidate.getName().compare(0, 14, "textureSamples") == 0 || fnCandidate.getName().compare(0, 12, "imageSamples") == 0)
2759         profileRequires(loc, ~EEsProfile, 450, E_GL_ARB_shader_texture_image_samples, "textureSamples and imageSamples");
2760
2761     if (fnCandidate.getName().compare(0, 11, "imageAtomic") == 0) {
2762         const TType& imageType = callNode.getSequence()[0]->getAsTyped()->getType();
2763         if (imageType.getSampler().type == EbtInt || imageType.getSampler().type == EbtUint) {
2764             if (imageType.getQualifier().getFormat() != ElfR32i && imageType.getQualifier().getFormat() != ElfR32ui)
2765                 error(loc, "only supported on image with format r32i or r32ui", fnCandidate.getName().c_str(), "");
2766         } else {
2767             if (fnCandidate.getName().compare(0, 19, "imageAtomicExchange") != 0)
2768                 error(loc, "only supported on integer images", fnCandidate.getName().c_str(), "");
2769             else if (imageType.getQualifier().getFormat() != ElfR32f && isEsProfile())
2770                 error(loc, "only supported on image with format r32f", fnCandidate.getName().c_str(), "");
2771         }
2772     }
2773 }
2774
2775 #endif
2776
2777 //
2778 // Do any extra checking for a user function call.
2779 //
2780 void TParseContext::userFunctionCallCheck(const TSourceLoc& loc, TIntermAggregate& callNode)
2781 {
2782     TIntermSequence& arguments = callNode.getSequence();
2783
2784     for (int i = 0; i < (int)arguments.size(); ++i)
2785         samplerConstructorLocationCheck(loc, "call argument", arguments[i]);
2786 }
2787
2788 //
2789 // Emit an error if this is a sampler constructor
2790 //
2791 void TParseContext::samplerConstructorLocationCheck(const TSourceLoc& loc, const char* token, TIntermNode* node)
2792 {
2793     if (node->getAsOperator() && node->getAsOperator()->getOp() == EOpConstructTextureSampler)
2794         error(loc, "sampler constructor must appear at point of use", token, "");
2795 }
2796
2797 //
2798 // Handle seeing a built-in constructor in a grammar production.
2799 //
2800 TFunction* TParseContext::handleConstructorCall(const TSourceLoc& loc, const TPublicType& publicType)
2801 {
2802     TType type(publicType);
2803     type.getQualifier().precision = EpqNone;
2804
2805     if (type.isArray()) {
2806         profileRequires(loc, ENoProfile, 120, E_GL_3DL_array_objects, "arrayed constructor");
2807         profileRequires(loc, EEsProfile, 300, nullptr, "arrayed constructor");
2808     }
2809
2810     TOperator op = intermediate.mapTypeToConstructorOp(type);
2811
2812     if (op == EOpNull) {
2813       if (intermediate.getEnhancedMsgs() && type.getBasicType() == EbtSampler)
2814             error(loc, "function not supported in this version; use texture() instead", "texture*D*", "");
2815         else
2816             error(loc, "cannot construct this type", type.getBasicString(), "");
2817         op = EOpConstructFloat;
2818         TType errorType(EbtFloat);
2819         type.shallowCopy(errorType);
2820     }
2821
2822     TString empty("");
2823
2824     return new TFunction(&empty, type, op);
2825 }
2826
2827 // Handle seeing a precision qualifier in the grammar.
2828 void TParseContext::handlePrecisionQualifier(const TSourceLoc& /*loc*/, TQualifier& qualifier, TPrecisionQualifier precision)
2829 {
2830     if (obeyPrecisionQualifiers())
2831         qualifier.precision = precision;
2832 }
2833
2834 // Check for messages to give on seeing a precision qualifier used in a
2835 // declaration in the grammar.
2836 void TParseContext::checkPrecisionQualifier(const TSourceLoc& loc, TPrecisionQualifier)
2837 {
2838     if (precisionManager.shouldWarnAboutDefaults()) {
2839         warn(loc, "all default precisions are highp; use precision statements to quiet warning, e.g.:\n"
2840                   "         \"precision mediump int; precision highp float;\"", "", "");
2841         precisionManager.defaultWarningGiven();
2842     }
2843 }
2844
2845 //
2846 // Same error message for all places assignments don't work.
2847 //
2848 void TParseContext::assignError(const TSourceLoc& loc, const char* op, TString left, TString right)
2849 {
2850     error(loc, "", op, "cannot convert from '%s' to '%s'",
2851           right.c_str(), left.c_str());
2852 }
2853
2854 //
2855 // Same error message for all places unary operations don't work.
2856 //
2857 void TParseContext::unaryOpError(const TSourceLoc& loc, const char* op, TString operand)
2858 {
2859    error(loc, " wrong operand type", op,
2860           "no operation '%s' exists that takes an operand of type %s (or there is no acceptable conversion)",
2861           op, operand.c_str());
2862 }
2863
2864 //
2865 // Same error message for all binary operations don't work.
2866 //
2867 void TParseContext::binaryOpError(const TSourceLoc& loc, const char* op, TString left, TString right)
2868 {
2869     error(loc, " wrong operand types:", op,
2870             "no operation '%s' exists that takes a left-hand operand of type '%s' and "
2871             "a right operand of type '%s' (or there is no acceptable conversion)",
2872             op, left.c_str(), right.c_str());
2873 }
2874
2875 //
2876 // A basic type of EbtVoid is a key that the name string was seen in the source, but
2877 // it was not found as a variable in the symbol table.  If so, give the error
2878 // message and insert a dummy variable in the symbol table to prevent future errors.
2879 //
2880 void TParseContext::variableCheck(TIntermTyped*& nodePtr)
2881 {
2882     TIntermSymbol* symbol = nodePtr->getAsSymbolNode();
2883     if (! symbol)
2884         return;
2885
2886     if (symbol->getType().getBasicType() == EbtVoid) {
2887         const char *extraInfoFormat = "";
2888         if (spvVersion.vulkan != 0 && symbol->getName() == "gl_VertexID") {
2889           extraInfoFormat = "(Did you mean gl_VertexIndex?)";
2890         } else if (spvVersion.vulkan != 0 && symbol->getName() == "gl_InstanceID") {
2891           extraInfoFormat = "(Did you mean gl_InstanceIndex?)";
2892         }
2893         error(symbol->getLoc(), "undeclared identifier", symbol->getName().c_str(), extraInfoFormat);
2894
2895         // Add to symbol table to prevent future error messages on the same name
2896         if (symbol->getName().size() > 0) {
2897             TVariable* fakeVariable = new TVariable(&symbol->getName(), TType(EbtFloat));
2898             symbolTable.insert(*fakeVariable);
2899
2900             // substitute a symbol node for this new variable
2901             nodePtr = intermediate.addSymbol(*fakeVariable, symbol->getLoc());
2902         }
2903     } else {
2904         switch (symbol->getQualifier().storage) {
2905         case EvqPointCoord:
2906             profileRequires(symbol->getLoc(), ENoProfile, 120, nullptr, "gl_PointCoord");
2907             break;
2908         default: break; // some compilers want this
2909         }
2910     }
2911 }
2912
2913 //
2914 // Both test and if necessary, spit out an error, to see if the node is really
2915 // an l-value that can be operated on this way.
2916 //
2917 // Returns true if there was an error.
2918 //
2919 bool TParseContext::lValueErrorCheck(const TSourceLoc& loc, const char* op, TIntermTyped* node)
2920 {
2921     TIntermBinary* binaryNode = node->getAsBinaryNode();
2922
2923     if (binaryNode) {
2924         bool errorReturn = false;
2925
2926         switch(binaryNode->getOp()) {
2927 #ifndef GLSLANG_WEB
2928         case EOpIndexDirect:
2929         case EOpIndexIndirect:
2930             // ...  tessellation control shader ...
2931             // If a per-vertex output variable is used as an l-value, it is a
2932             // compile-time or link-time error if the expression indicating the
2933             // vertex index is not the identifier gl_InvocationID.
2934             if (language == EShLangTessControl) {
2935                 const TType& leftType = binaryNode->getLeft()->getType();
2936                 if (leftType.getQualifier().storage == EvqVaryingOut && ! leftType.getQualifier().patch && binaryNode->getLeft()->getAsSymbolNode()) {
2937                     // we have a per-vertex output
2938                     const TIntermSymbol* rightSymbol = binaryNode->getRight()->getAsSymbolNode();
2939                     if (! rightSymbol || rightSymbol->getQualifier().builtIn != EbvInvocationId)
2940                         error(loc, "tessellation-control per-vertex output l-value must be indexed with gl_InvocationID", "[]", "");
2941                 }
2942             }
2943             break; // left node is checked by base class
2944 #endif
2945         case EOpVectorSwizzle:
2946             errorReturn = lValueErrorCheck(loc, op, binaryNode->getLeft());
2947             if (!errorReturn) {
2948                 int offset[4] = {0,0,0,0};
2949
2950                 TIntermTyped* rightNode = binaryNode->getRight();
2951                 TIntermAggregate *aggrNode = rightNode->getAsAggregate();
2952
2953                 for (TIntermSequence::iterator p = aggrNode->getSequence().begin();
2954                                                p != aggrNode->getSequence().end(); p++) {
2955                     int value = (*p)->getAsTyped()->getAsConstantUnion()->getConstArray()[0].getIConst();
2956                     offset[value]++;
2957                     if (offset[value] > 1) {
2958                         error(loc, " l-value of swizzle cannot have duplicate components", op, "", "");
2959
2960                         return true;
2961                     }
2962                 }
2963             }
2964
2965             return errorReturn;
2966         default:
2967             break;
2968         }
2969
2970         if (errorReturn) {
2971             error(loc, " l-value required", op, "", "");
2972             return true;
2973         }
2974     }
2975
2976     if (binaryNode && binaryNode->getOp() == EOpIndexDirectStruct && binaryNode->getLeft()->isReference())
2977         return false;
2978
2979     // Let the base class check errors
2980     if (TParseContextBase::lValueErrorCheck(loc, op, node))
2981         return true;
2982
2983     const char* symbol = nullptr;
2984     TIntermSymbol* symNode = node->getAsSymbolNode();
2985     if (symNode != nullptr)
2986         symbol = symNode->getName().c_str();
2987
2988     const char* message = nullptr;
2989     switch (node->getQualifier().storage) {
2990     case EvqVaryingIn:      message = "can't modify shader input";   break;
2991     case EvqInstanceId:     message = "can't modify gl_InstanceID";  break;
2992     case EvqVertexId:       message = "can't modify gl_VertexID";    break;
2993     case EvqFace:           message = "can't modify gl_FrontFace";   break;
2994     case EvqFragCoord:      message = "can't modify gl_FragCoord";   break;
2995     case EvqPointCoord:     message = "can't modify gl_PointCoord";  break;
2996     case EvqFragDepth:
2997         intermediate.setDepthReplacing();
2998         // "In addition, it is an error to statically write to gl_FragDepth in the fragment shader."
2999         if (isEsProfile() && intermediate.getEarlyFragmentTests())
3000             message = "can't modify gl_FragDepth if using early_fragment_tests";
3001         break;
3002     case EvqFragStencil:
3003         intermediate.setStencilReplacing();
3004         // "In addition, it is an error to statically write to gl_FragDepth in the fragment shader."
3005         if (isEsProfile() && intermediate.getEarlyFragmentTests())
3006             message = "can't modify EvqFragStencil if using early_fragment_tests";
3007         break;
3008
3009     case EvqtaskPayloadSharedEXT:
3010         if (language == EShLangMesh)
3011             message = "can't modify variable with storage qualifier taskPayloadSharedEXT in mesh shaders";
3012         break;
3013     default:
3014         break;
3015     }
3016
3017     if (message == nullptr && binaryNode == nullptr && symNode == nullptr) {
3018         error(loc, " l-value required", op, "", "");
3019
3020         return true;
3021     }
3022
3023     //
3024     // Everything else is okay, no error.
3025     //
3026     if (message == nullptr)
3027         return false;
3028
3029     //
3030     // If we get here, we have an error and a message.
3031     //
3032     if (symNode)
3033         error(loc, " l-value required", op, "\"%s\" (%s)", symbol, message);
3034     else
3035         error(loc, " l-value required", op, "(%s)", message);
3036
3037     return true;
3038 }
3039
3040 // Test for and give an error if the node can't be read from.
3041 void TParseContext::rValueErrorCheck(const TSourceLoc& loc, const char* op, TIntermTyped* node)
3042 {
3043     // Let the base class check errors
3044     TParseContextBase::rValueErrorCheck(loc, op, node);
3045
3046     TIntermSymbol* symNode = node->getAsSymbolNode();
3047     if (!(symNode && symNode->getQualifier().isWriteOnly())) // base class checks
3048         if (symNode && symNode->getQualifier().isExplicitInterpolation())
3049             error(loc, "can't read from explicitly-interpolated object: ", op, symNode->getName().c_str());
3050
3051     // local_size_{xyz} must be assigned or specialized before gl_WorkGroupSize can be assigned.
3052     if(node->getQualifier().builtIn == EbvWorkGroupSize &&
3053        !(intermediate.isLocalSizeSet() || intermediate.isLocalSizeSpecialized()))
3054         error(loc, "can't read from gl_WorkGroupSize before a fixed workgroup size has been declared", op, "");
3055 }
3056
3057 //
3058 // Both test, and if necessary spit out an error, to see if the node is really
3059 // a constant.
3060 //
3061 void TParseContext::constantValueCheck(TIntermTyped* node, const char* token)
3062 {
3063     if (! node->getQualifier().isConstant())
3064         error(node->getLoc(), "constant expression required", token, "");
3065 }
3066
3067 //
3068 // Both test, and if necessary spit out an error, to see if the node is really
3069 // a 32-bit integer or can implicitly convert to one.
3070 //
3071 void TParseContext::integerCheck(const TIntermTyped* node, const char* token)
3072 {
3073     auto from_type = node->getBasicType();
3074     if ((from_type == EbtInt || from_type == EbtUint ||
3075          intermediate.canImplicitlyPromote(from_type, EbtInt, EOpNull) ||
3076          intermediate.canImplicitlyPromote(from_type, EbtUint, EOpNull)) && node->isScalar())
3077         return;
3078
3079     error(node->getLoc(), "scalar integer expression required", token, "");
3080 }
3081
3082 //
3083 // Both test, and if necessary spit out an error, to see if we are currently
3084 // globally scoped.
3085 //
3086 void TParseContext::globalCheck(const TSourceLoc& loc, const char* token)
3087 {
3088     if (! symbolTable.atGlobalLevel())
3089         error(loc, "not allowed in nested scope", token, "");
3090 }
3091
3092 //
3093 // Reserved errors for GLSL.
3094 //
3095 void TParseContext::reservedErrorCheck(const TSourceLoc& loc, const TString& identifier)
3096 {
3097     // "Identifiers starting with "gl_" are reserved for use by OpenGL, and may not be
3098     // declared in a shader; this results in a compile-time error."
3099     if (! symbolTable.atBuiltInLevel()) {
3100         if (builtInName(identifier) && !extensionTurnedOn(E_GL_EXT_spirv_intrinsics))
3101             // The extension GL_EXT_spirv_intrinsics allows us to declare identifiers starting with "gl_".
3102             error(loc, "identifiers starting with \"gl_\" are reserved", identifier.c_str(), "");
3103
3104         // "__" are not supposed to be an error.  ES 300 (and desktop) added the clarification:
3105         // "In addition, all identifiers containing two consecutive underscores (__) are
3106         // reserved; using such a name does not itself result in an error, but may result
3107         // in undefined behavior."
3108         // however, before that, ES tests required an error.
3109         if (identifier.find("__") != TString::npos && !extensionTurnedOn(E_GL_EXT_spirv_intrinsics)) {
3110             // The extension GL_EXT_spirv_intrinsics allows us to declare identifiers starting with "__".
3111             if (isEsProfile() && version < 300)
3112                 error(loc, "identifiers containing consecutive underscores (\"__\") are reserved, and an error if version < 300", identifier.c_str(), "");
3113             else
3114                 warn(loc, "identifiers containing consecutive underscores (\"__\") are reserved", identifier.c_str(), "");
3115         }
3116     }
3117 }
3118
3119 //
3120 // Reserved errors for the preprocessor.
3121 //
3122 void TParseContext::reservedPpErrorCheck(const TSourceLoc& loc, const char* identifier, const char* op)
3123 {
3124     // "__" are not supposed to be an error.  ES 300 (and desktop) added the clarification:
3125     // "All macro names containing two consecutive underscores ( __ ) are reserved;
3126     // defining such a name does not itself result in an error, but may result in
3127     // undefined behavior.  All macro names prefixed with "GL_" ("GL" followed by a
3128     // single underscore) are also reserved, and defining such a name results in a
3129     // compile-time error."
3130     // however, before that, ES tests required an error.
3131     if (strncmp(identifier, "GL_", 3) == 0 && !extensionTurnedOn(E_GL_EXT_spirv_intrinsics))
3132         // The extension GL_EXT_spirv_intrinsics allows us to declare macros prefixed with "GL_".
3133         ppError(loc, "names beginning with \"GL_\" can't be (un)defined:", op,  identifier);
3134     else if (strncmp(identifier, "defined", 8) == 0)
3135         if (relaxedErrors())
3136             ppWarn(loc, "\"defined\" is (un)defined:", op,  identifier);
3137         else
3138             ppError(loc, "\"defined\" can't be (un)defined:", op,  identifier);
3139     else if (strstr(identifier, "__") != 0 && !extensionTurnedOn(E_GL_EXT_spirv_intrinsics)) {
3140         // The extension GL_EXT_spirv_intrinsics allows us to declare macros prefixed with "__".
3141         if (isEsProfile() && version >= 300 &&
3142             (strcmp(identifier, "__LINE__") == 0 ||
3143              strcmp(identifier, "__FILE__") == 0 ||
3144              strcmp(identifier, "__VERSION__") == 0))
3145             ppError(loc, "predefined names can't be (un)defined:", op,  identifier);
3146         else {
3147             if (isEsProfile() && version < 300 && !relaxedErrors())
3148                 ppError(loc, "names containing consecutive underscores are reserved, and an error if version < 300:", op, identifier);
3149             else
3150                 ppWarn(loc, "names containing consecutive underscores are reserved:", op, identifier);
3151         }
3152     }
3153 }
3154
3155 //
3156 // See if this version/profile allows use of the line-continuation character '\'.
3157 //
3158 // Returns true if a line continuation should be done.
3159 //
3160 bool TParseContext::lineContinuationCheck(const TSourceLoc& loc, bool endOfComment)
3161 {
3162 #ifdef GLSLANG_WEB
3163     return true;
3164 #endif
3165
3166     const char* message = "line continuation";
3167
3168     bool lineContinuationAllowed = (isEsProfile() && version >= 300) ||
3169                                    (!isEsProfile() && (version >= 420 || extensionTurnedOn(E_GL_ARB_shading_language_420pack)));
3170
3171     if (endOfComment) {
3172         if (lineContinuationAllowed)
3173             warn(loc, "used at end of comment; the following line is still part of the comment", message, "");
3174         else
3175             warn(loc, "used at end of comment, but this version does not provide line continuation", message, "");
3176
3177         return lineContinuationAllowed;
3178     }
3179
3180     if (relaxedErrors()) {
3181         if (! lineContinuationAllowed)
3182             warn(loc, "not allowed in this version", message, "");
3183         return true;
3184     } else {
3185         profileRequires(loc, EEsProfile, 300, nullptr, message);
3186         profileRequires(loc, ~EEsProfile, 420, E_GL_ARB_shading_language_420pack, message);
3187     }
3188
3189     return lineContinuationAllowed;
3190 }
3191
3192 bool TParseContext::builtInName(const TString& identifier)
3193 {
3194     return identifier.compare(0, 3, "gl_") == 0;
3195 }
3196
3197 //
3198 // Make sure there is enough data and not too many arguments provided to the
3199 // constructor to build something of the type of the constructor.  Also returns
3200 // the type of the constructor.
3201 //
3202 // Part of establishing type is establishing specialization-constness.
3203 // We don't yet know "top down" whether type is a specialization constant,
3204 // but a const constructor can becomes a specialization constant if any of
3205 // its children are, subject to KHR_vulkan_glsl rules:
3206 //
3207 //     - int(), uint(), and bool() constructors for type conversions
3208 //       from any of the following types to any of the following types:
3209 //         * int
3210 //         * uint
3211 //         * bool
3212 //     - vector versions of the above conversion constructors
3213 //
3214 // Returns true if there was an error in construction.
3215 //
3216 bool TParseContext::constructorError(const TSourceLoc& loc, TIntermNode* node, TFunction& function, TOperator op, TType& type)
3217 {
3218     // See if the constructor does not establish the main type, only requalifies
3219     // it, in which case the type comes from the argument instead of from the
3220     // constructor function.
3221     switch (op) {
3222 #ifndef GLSLANG_WEB
3223     case EOpConstructNonuniform:
3224         if (node != nullptr && node->getAsTyped() != nullptr) {
3225             type.shallowCopy(node->getAsTyped()->getType());
3226             type.getQualifier().makeTemporary();
3227             type.getQualifier().nonUniform = true;
3228         }
3229         break;
3230 #endif
3231     default:
3232         type.shallowCopy(function.getType());
3233         break;
3234     }
3235
3236     TString constructorString;
3237     if (intermediate.getEnhancedMsgs())
3238         constructorString.append(type.getCompleteString(true, false, false, true)).append(" constructor");
3239     else
3240         constructorString.append("constructor");
3241
3242     // See if it's a matrix
3243     bool constructingMatrix = false;
3244     switch (op) {
3245     case EOpConstructTextureSampler:
3246         return constructorTextureSamplerError(loc, function);
3247     case EOpConstructMat2x2:
3248     case EOpConstructMat2x3:
3249     case EOpConstructMat2x4:
3250     case EOpConstructMat3x2:
3251     case EOpConstructMat3x3:
3252     case EOpConstructMat3x4:
3253     case EOpConstructMat4x2:
3254     case EOpConstructMat4x3:
3255     case EOpConstructMat4x4:
3256 #ifndef GLSLANG_WEB
3257     case EOpConstructDMat2x2:
3258     case EOpConstructDMat2x3:
3259     case EOpConstructDMat2x4:
3260     case EOpConstructDMat3x2:
3261     case EOpConstructDMat3x3:
3262     case EOpConstructDMat3x4:
3263     case EOpConstructDMat4x2:
3264     case EOpConstructDMat4x3:
3265     case EOpConstructDMat4x4:
3266     case EOpConstructF16Mat2x2:
3267     case EOpConstructF16Mat2x3:
3268     case EOpConstructF16Mat2x4:
3269     case EOpConstructF16Mat3x2:
3270     case EOpConstructF16Mat3x3:
3271     case EOpConstructF16Mat3x4:
3272     case EOpConstructF16Mat4x2:
3273     case EOpConstructF16Mat4x3:
3274     case EOpConstructF16Mat4x4:
3275 #endif
3276         constructingMatrix = true;
3277         break;
3278     default:
3279         break;
3280     }
3281
3282     //
3283     // Walk the arguments for first-pass checks and collection of information.
3284     //
3285
3286     int size = 0;
3287     bool constType = true;
3288     bool specConstType = false;   // value is only valid if constType is true
3289     bool full = false;
3290     bool overFull = false;
3291     bool matrixInMatrix = false;
3292     bool arrayArg = false;
3293     bool floatArgument = false;
3294     bool intArgument = false;
3295     for (int arg = 0; arg < function.getParamCount(); ++arg) {
3296         if (function[arg].type->isArray()) {
3297             if (function[arg].type->isUnsizedArray()) {
3298                 // Can't construct from an unsized array.
3299                 error(loc, "array argument must be sized", constructorString.c_str(), "");
3300                 return true;
3301             }
3302             arrayArg = true;
3303         }
3304         if (constructingMatrix && function[arg].type->isMatrix())
3305             matrixInMatrix = true;
3306
3307         // 'full' will go to true when enough args have been seen.  If we loop
3308         // again, there is an extra argument.
3309         if (full) {
3310             // For vectors and matrices, it's okay to have too many components
3311             // available, but not okay to have unused arguments.
3312             overFull = true;
3313         }
3314
3315         size += function[arg].type->computeNumComponents();
3316         if (op != EOpConstructStruct && ! type.isArray() && size >= type.computeNumComponents())
3317             full = true;
3318
3319         if (! function[arg].type->getQualifier().isConstant())
3320             constType = false;
3321         if (function[arg].type->getQualifier().isSpecConstant())
3322             specConstType = true;
3323         if (function[arg].type->isFloatingDomain())
3324             floatArgument = true;
3325         if (function[arg].type->isIntegerDomain())
3326             intArgument = true;
3327         if (type.isStruct()) {
3328             if (function[arg].type->contains16BitFloat()) {
3329                 requireFloat16Arithmetic(loc, constructorString.c_str(), "can't construct structure containing 16-bit type");
3330             }
3331             if (function[arg].type->contains16BitInt()) {
3332                 requireInt16Arithmetic(loc, constructorString.c_str(), "can't construct structure containing 16-bit type");
3333             }
3334             if (function[arg].type->contains8BitInt()) {
3335                 requireInt8Arithmetic(loc, constructorString.c_str(), "can't construct structure containing 8-bit type");
3336             }
3337         }
3338     }
3339     if (op == EOpConstructNonuniform)
3340         constType = false;
3341
3342 #ifndef GLSLANG_WEB
3343     switch (op) {
3344     case EOpConstructFloat16:
3345     case EOpConstructF16Vec2:
3346     case EOpConstructF16Vec3:
3347     case EOpConstructF16Vec4:
3348         if (type.isArray())
3349             requireFloat16Arithmetic(loc, constructorString.c_str(), "16-bit arrays not supported");
3350         if (type.isVector() && function.getParamCount() != 1)
3351             requireFloat16Arithmetic(loc, constructorString.c_str(), "16-bit vectors only take vector types");
3352         break;
3353     case EOpConstructUint16:
3354     case EOpConstructU16Vec2:
3355     case EOpConstructU16Vec3:
3356     case EOpConstructU16Vec4:
3357     case EOpConstructInt16:
3358     case EOpConstructI16Vec2:
3359     case EOpConstructI16Vec3:
3360     case EOpConstructI16Vec4:
3361         if (type.isArray())
3362             requireInt16Arithmetic(loc, constructorString.c_str(), "16-bit arrays not supported");
3363         if (type.isVector() && function.getParamCount() != 1)
3364             requireInt16Arithmetic(loc, constructorString.c_str(), "16-bit vectors only take vector types");
3365         break;
3366     case EOpConstructUint8:
3367     case EOpConstructU8Vec2:
3368     case EOpConstructU8Vec3:
3369     case EOpConstructU8Vec4:
3370     case EOpConstructInt8:
3371     case EOpConstructI8Vec2:
3372     case EOpConstructI8Vec3:
3373     case EOpConstructI8Vec4:
3374         if (type.isArray())
3375             requireInt8Arithmetic(loc, constructorString.c_str(), "8-bit arrays not supported");
3376         if (type.isVector() && function.getParamCount() != 1)
3377             requireInt8Arithmetic(loc, constructorString.c_str(), "8-bit vectors only take vector types");
3378         break;
3379     default:
3380         break;
3381     }
3382 #endif
3383
3384     // inherit constness from children
3385     if (constType) {
3386         bool makeSpecConst;
3387         // Finish pinning down spec-const semantics
3388         if (specConstType) {
3389             switch (op) {
3390             case EOpConstructInt8:
3391             case EOpConstructInt:
3392             case EOpConstructUint:
3393             case EOpConstructBool:
3394             case EOpConstructBVec2:
3395             case EOpConstructBVec3:
3396             case EOpConstructBVec4:
3397             case EOpConstructIVec2:
3398             case EOpConstructIVec3:
3399             case EOpConstructIVec4:
3400             case EOpConstructUVec2:
3401             case EOpConstructUVec3:
3402             case EOpConstructUVec4:
3403 #ifndef GLSLANG_WEB
3404             case EOpConstructUint8:
3405             case EOpConstructInt16:
3406             case EOpConstructUint16:
3407             case EOpConstructInt64:
3408             case EOpConstructUint64:
3409             case EOpConstructI8Vec2:
3410             case EOpConstructI8Vec3:
3411             case EOpConstructI8Vec4:
3412             case EOpConstructU8Vec2:
3413             case EOpConstructU8Vec3:
3414             case EOpConstructU8Vec4:
3415             case EOpConstructI16Vec2:
3416             case EOpConstructI16Vec3:
3417             case EOpConstructI16Vec4:
3418             case EOpConstructU16Vec2:
3419             case EOpConstructU16Vec3:
3420             case EOpConstructU16Vec4:
3421             case EOpConstructI64Vec2:
3422             case EOpConstructI64Vec3:
3423             case EOpConstructI64Vec4:
3424             case EOpConstructU64Vec2:
3425             case EOpConstructU64Vec3:
3426             case EOpConstructU64Vec4:
3427 #endif
3428                 // This was the list of valid ones, if they aren't converting from float
3429                 // and aren't making an array.
3430                 makeSpecConst = ! floatArgument && ! type.isArray();
3431                 break;
3432
3433             case EOpConstructVec2:
3434             case EOpConstructVec3:
3435             case EOpConstructVec4:
3436                 // This was the list of valid ones, if they aren't converting from int
3437                 // and aren't making an array.
3438                 makeSpecConst = ! intArgument && !type.isArray();
3439                 break;
3440
3441             default:
3442                 // anything else wasn't white-listed in the spec as a conversion
3443                 makeSpecConst = false;
3444                 break;
3445             }
3446         } else
3447             makeSpecConst = false;
3448
3449         if (makeSpecConst)
3450             type.getQualifier().makeSpecConstant();
3451         else if (specConstType)
3452             type.getQualifier().makeTemporary();
3453         else
3454             type.getQualifier().storage = EvqConst;
3455     }
3456
3457     if (type.isArray()) {
3458         if (function.getParamCount() == 0) {
3459             error(loc, "array constructor must have at least one argument", constructorString.c_str(), "");
3460             return true;
3461         }
3462
3463         if (type.isUnsizedArray()) {
3464             // auto adapt the constructor type to the number of arguments
3465             type.changeOuterArraySize(function.getParamCount());
3466         } else if (type.getOuterArraySize() != function.getParamCount()) {
3467             error(loc, "array constructor needs one argument per array element", constructorString.c_str(), "");
3468             return true;
3469         }
3470
3471         if (type.isArrayOfArrays()) {
3472             // Types have to match, but we're still making the type.
3473             // Finish making the type, and the comparison is done later
3474             // when checking for conversion.
3475             TArraySizes& arraySizes = *type.getArraySizes();
3476
3477             // At least the dimensionalities have to match.
3478             if (! function[0].type->isArray() ||
3479                     arraySizes.getNumDims() != function[0].type->getArraySizes()->getNumDims() + 1) {
3480                 error(loc, "array constructor argument not correct type to construct array element", constructorString.c_str(), "");
3481                 return true;
3482             }
3483
3484             if (arraySizes.isInnerUnsized()) {
3485                 // "Arrays of arrays ..., and the size for any dimension is optional"
3486                 // That means we need to adopt (from the first argument) the other array sizes into the type.
3487                 for (int d = 1; d < arraySizes.getNumDims(); ++d) {
3488                     if (arraySizes.getDimSize(d) == UnsizedArraySize) {
3489                         arraySizes.setDimSize(d, function[0].type->getArraySizes()->getDimSize(d - 1));
3490                     }
3491                 }
3492             }
3493         }
3494     }
3495
3496     if (arrayArg && op != EOpConstructStruct && ! type.isArrayOfArrays()) {
3497         error(loc, "constructing non-array constituent from array argument", constructorString.c_str(), "");
3498         return true;
3499     }
3500
3501     if (matrixInMatrix && ! type.isArray()) {
3502         profileRequires(loc, ENoProfile, 120, nullptr, "constructing matrix from matrix");
3503
3504         // "If a matrix argument is given to a matrix constructor,
3505         // it is a compile-time error to have any other arguments."
3506         if (function.getParamCount() != 1)
3507             error(loc, "matrix constructed from matrix can only have one argument", constructorString.c_str(), "");
3508         return false;
3509     }
3510
3511     if (overFull) {
3512         error(loc, "too many arguments", constructorString.c_str(), "");
3513         return true;
3514     }
3515
3516     if (op == EOpConstructStruct && ! type.isArray() && (int)type.getStruct()->size() != function.getParamCount()) {
3517         error(loc, "Number of constructor parameters does not match the number of structure fields", constructorString.c_str(), "");
3518         return true;
3519     }
3520
3521     if ((op != EOpConstructStruct && size != 1 && size < type.computeNumComponents()) ||
3522         (op == EOpConstructStruct && size < type.computeNumComponents())) {
3523         error(loc, "not enough data provided for construction", constructorString.c_str(), "");
3524         return true;
3525     }
3526
3527     if (type.isCoopMat() && function.getParamCount() != 1) {
3528         error(loc, "wrong number of arguments", constructorString.c_str(), "");
3529         return true;
3530     }
3531     if (type.isCoopMat() &&
3532         !(function[0].type->isScalar() || function[0].type->isCoopMat())) {
3533         error(loc, "Cooperative matrix constructor argument must be scalar or cooperative matrix", constructorString.c_str(), "");
3534         return true;
3535     }
3536
3537     TIntermTyped* typed = node->getAsTyped();
3538     if (typed == nullptr) {
3539         error(loc, "constructor argument does not have a type", constructorString.c_str(), "");
3540         return true;
3541     }
3542     if (op != EOpConstructStruct && op != EOpConstructNonuniform && typed->getBasicType() == EbtSampler) {
3543         error(loc, "cannot convert a sampler", constructorString.c_str(), "");
3544         return true;
3545     }
3546     if (op != EOpConstructStruct && typed->isAtomic()) {
3547         error(loc, "cannot convert an atomic_uint", constructorString.c_str(), "");
3548         return true;
3549     }
3550     if (typed->getBasicType() == EbtVoid) {
3551         error(loc, "cannot convert a void", constructorString.c_str(), "");
3552         return true;
3553     }
3554
3555     return false;
3556 }
3557
3558 // Verify all the correct semantics for constructing a combined texture/sampler.
3559 // Return true if the semantics are incorrect.
3560 bool TParseContext::constructorTextureSamplerError(const TSourceLoc& loc, const TFunction& function)
3561 {
3562     TString constructorName = function.getType().getBasicTypeString();  // TODO: performance: should not be making copy; interface needs to change
3563     const char* token = constructorName.c_str();
3564
3565     // exactly two arguments needed
3566     if (function.getParamCount() != 2) {
3567         error(loc, "sampler-constructor requires two arguments", token, "");
3568         return true;
3569     }
3570
3571     // For now, not allowing arrayed constructors, the rest of this function
3572     // is set up to allow them, if this test is removed:
3573     if (function.getType().isArray()) {
3574         error(loc, "sampler-constructor cannot make an array of samplers", token, "");
3575         return true;
3576     }
3577
3578     // first argument
3579     //  * the constructor's first argument must be a texture type
3580     //  * the dimensionality (1D, 2D, 3D, Cube, Rect, Buffer, MS, and Array)
3581     //    of the texture type must match that of the constructed sampler type
3582     //    (that is, the suffixes of the type of the first argument and the
3583     //    type of the constructor will be spelled the same way)
3584     if (function[0].type->getBasicType() != EbtSampler ||
3585         ! function[0].type->getSampler().isTexture() ||
3586         function[0].type->isArray()) {
3587         error(loc, "sampler-constructor first argument must be a scalar *texture* type", token, "");
3588         return true;
3589     }
3590     // simulate the first argument's impact on the result type, so it can be compared with the encapsulated operator!=()
3591     TSampler texture = function.getType().getSampler();
3592     texture.setCombined(false);
3593     texture.shadow = false;
3594     if (texture != function[0].type->getSampler()) {
3595         error(loc, "sampler-constructor first argument must be a *texture* type"
3596                    " matching the dimensionality and sampled type of the constructor", token, "");
3597         return true;
3598     }
3599
3600     // second argument
3601     //   * the constructor's second argument must be a scalar of type
3602     //     *sampler* or *samplerShadow*
3603     if (  function[1].type->getBasicType() != EbtSampler ||
3604         ! function[1].type->getSampler().isPureSampler() ||
3605           function[1].type->isArray()) {
3606         error(loc, "sampler-constructor second argument must be a scalar sampler or samplerShadow", token, "");
3607         return true;
3608     }
3609
3610     return false;
3611 }
3612
3613 // Checks to see if a void variable has been declared and raise an error message for such a case
3614 //
3615 // returns true in case of an error
3616 //
3617 bool TParseContext::voidErrorCheck(const TSourceLoc& loc, const TString& identifier, const TBasicType basicType)
3618 {
3619     if (basicType == EbtVoid) {
3620         error(loc, "illegal use of type 'void'", identifier.c_str(), "");
3621         return true;
3622     }
3623
3624     return false;
3625 }
3626
3627 // Checks to see if the node (for the expression) contains a scalar boolean expression or not
3628 void TParseContext::boolCheck(const TSourceLoc& loc, const TIntermTyped* type)
3629 {
3630     if (type->getBasicType() != EbtBool || type->isArray() || type->isMatrix() || type->isVector())
3631         error(loc, "boolean expression expected", "", "");
3632 }
3633
3634 // This function checks to see if the node (for the expression) contains a scalar boolean expression or not
3635 void TParseContext::boolCheck(const TSourceLoc& loc, const TPublicType& pType)
3636 {
3637     if (pType.basicType != EbtBool || pType.arraySizes || pType.matrixCols > 1 || (pType.vectorSize > 1))
3638         error(loc, "boolean expression expected", "", "");
3639 }
3640
3641 void TParseContext::samplerCheck(const TSourceLoc& loc, const TType& type, const TString& identifier, TIntermTyped* /*initializer*/)
3642 {
3643     // Check that the appropriate extension is enabled if external sampler is used.
3644     // There are two extensions. The correct one must be used based on GLSL version.
3645     if (type.getBasicType() == EbtSampler && type.getSampler().isExternal()) {
3646         if (version < 300) {
3647             requireExtensions(loc, 1, &E_GL_OES_EGL_image_external, "samplerExternalOES");
3648         } else {
3649             requireExtensions(loc, 1, &E_GL_OES_EGL_image_external_essl3, "samplerExternalOES");
3650         }
3651     }
3652     if (type.getSampler().isYuv()) {
3653         requireExtensions(loc, 1, &E_GL_EXT_YUV_target, "__samplerExternal2DY2YEXT");
3654     }
3655
3656     if (type.getQualifier().storage == EvqUniform)
3657         return;
3658
3659     if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtSampler))
3660         error(loc, "non-uniform struct contains a sampler or image:", type.getBasicTypeString().c_str(), identifier.c_str());
3661     else if (type.getBasicType() == EbtSampler && type.getQualifier().storage != EvqUniform) {
3662         // non-uniform sampler
3663         // not yet:  okay if it has an initializer
3664         // if (! initializer)
3665         error(loc, "sampler/image types can only be used in uniform variables or function parameters:", type.getBasicTypeString().c_str(), identifier.c_str());
3666     }
3667 }
3668
3669 #ifndef GLSLANG_WEB
3670
3671 void TParseContext::atomicUintCheck(const TSourceLoc& loc, const TType& type, const TString& identifier)
3672 {
3673     if (type.getQualifier().storage == EvqUniform)
3674         return;
3675
3676     if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtAtomicUint))
3677         error(loc, "non-uniform struct contains an atomic_uint:", type.getBasicTypeString().c_str(), identifier.c_str());
3678     else if (type.getBasicType() == EbtAtomicUint && type.getQualifier().storage != EvqUniform)
3679         error(loc, "atomic_uints can only be used in uniform variables or function parameters:", type.getBasicTypeString().c_str(), identifier.c_str());
3680 }
3681
3682 void TParseContext::accStructCheck(const TSourceLoc& loc, const TType& type, const TString& identifier)
3683 {
3684     if (type.getQualifier().storage == EvqUniform)
3685         return;
3686
3687     if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtAccStruct))
3688         error(loc, "non-uniform struct contains an accelerationStructureNV:", type.getBasicTypeString().c_str(), identifier.c_str());
3689     else if (type.getBasicType() == EbtAccStruct && type.getQualifier().storage != EvqUniform)
3690         error(loc, "accelerationStructureNV can only be used in uniform variables or function parameters:",
3691             type.getBasicTypeString().c_str(), identifier.c_str());
3692
3693 }
3694
3695 #endif // GLSLANG_WEB
3696
3697 void TParseContext::transparentOpaqueCheck(const TSourceLoc& loc, const TType& type, const TString& identifier)
3698 {
3699     if (parsingBuiltins)
3700         return;
3701
3702     if (type.getQualifier().storage != EvqUniform)
3703         return;
3704
3705     if (type.containsNonOpaque()) {
3706         // Vulkan doesn't allow transparent uniforms outside of blocks
3707         if (spvVersion.vulkan > 0 && !spvVersion.vulkanRelaxed)
3708             vulkanRemoved(loc, "non-opaque uniforms outside a block");
3709         // OpenGL wants locations on these (unless they are getting automapped)
3710         if (spvVersion.openGl > 0 && !type.getQualifier().hasLocation() && !intermediate.getAutoMapLocations())
3711             error(loc, "non-opaque uniform variables need a layout(location=L)", identifier.c_str(), "");
3712     }
3713 }
3714
3715 //
3716 // Qualifier checks knowing the qualifier and that it is a member of a struct/block.
3717 //
3718 void TParseContext::memberQualifierCheck(glslang::TPublicType& publicType)
3719 {
3720     globalQualifierFixCheck(publicType.loc, publicType.qualifier, true);
3721     checkNoShaderLayouts(publicType.loc, publicType.shaderQualifiers);
3722     if (publicType.qualifier.isNonUniform()) {
3723         error(publicType.loc, "not allowed on block or structure members", "nonuniformEXT", "");
3724         publicType.qualifier.nonUniform = false;
3725     }
3726 }
3727
3728 //
3729 // Check/fix just a full qualifier (no variables or types yet, but qualifier is complete) at global level.
3730 //
3731 void TParseContext::globalQualifierFixCheck(const TSourceLoc& loc, TQualifier& qualifier, bool isMemberCheck)
3732 {
3733     bool nonuniformOkay = false;
3734
3735     // move from parameter/unknown qualifiers to pipeline in/out qualifiers
3736     switch (qualifier.storage) {
3737     case EvqIn:
3738         profileRequires(loc, ENoProfile, 130, nullptr, "in for stage inputs");
3739         profileRequires(loc, EEsProfile, 300, nullptr, "in for stage inputs");
3740         qualifier.storage = EvqVaryingIn;
3741         nonuniformOkay = true;
3742         break;
3743     case EvqOut:
3744         profileRequires(loc, ENoProfile, 130, nullptr, "out for stage outputs");
3745         profileRequires(loc, EEsProfile, 300, nullptr, "out for stage outputs");
3746         qualifier.storage = EvqVaryingOut;
3747         if (intermediate.isInvariantAll())
3748             qualifier.invariant = true;
3749         break;
3750     case EvqInOut:
3751         qualifier.storage = EvqVaryingIn;
3752         error(loc, "cannot use 'inout' at global scope", "", "");
3753         break;
3754     case EvqGlobal:
3755     case EvqTemporary:
3756         nonuniformOkay = true;
3757         break;
3758     case EvqUniform:
3759         // According to GLSL spec: The std430 qualifier is supported only for shader storage blocks; a shader using
3760         // the std430 qualifier on a uniform block will fail to compile.
3761         // Only check the global declaration: layout(std430) uniform;
3762         if (blockName == nullptr &&
3763             qualifier.layoutPacking == ElpStd430)
3764         {
3765             requireExtensions(loc, 1, &E_GL_EXT_scalar_block_layout, "default std430 layout for uniform");
3766         }
3767         break;
3768     default:
3769         break;
3770     }
3771
3772     if (!nonuniformOkay && qualifier.isNonUniform())
3773         error(loc, "for non-parameter, can only apply to 'in' or no storage qualifier", "nonuniformEXT", "");
3774
3775 #ifndef GLSLANG_WEB
3776     if (qualifier.isSpirvByReference())
3777         error(loc, "can only apply to parameter", "spirv_by_reference", "");
3778
3779     if (qualifier.isSpirvLiteral())
3780         error(loc, "can only apply to parameter", "spirv_literal", "");
3781 #endif
3782
3783     // Storage qualifier isn't ready for memberQualifierCheck, we should skip invariantCheck for it.
3784     if (!isMemberCheck || structNestingLevel > 0)
3785         invariantCheck(loc, qualifier);
3786 }
3787
3788 //
3789 // Check a full qualifier and type (no variable yet) at global level.
3790 //
3791 void TParseContext::globalQualifierTypeCheck(const TSourceLoc& loc, const TQualifier& qualifier, const TPublicType& publicType)
3792 {
3793     if (! symbolTable.atGlobalLevel())
3794         return;
3795
3796     if (!(publicType.userDef && publicType.userDef->isReference()) && !parsingBuiltins) {
3797         if (qualifier.isMemoryQualifierImageAndSSBOOnly() && ! publicType.isImage() && publicType.qualifier.storage != EvqBuffer) {
3798             error(loc, "memory qualifiers cannot be used on this type", "", "");
3799         } else if (qualifier.isMemory() && (publicType.basicType != EbtSampler) && !publicType.qualifier.isUniformOrBuffer()) {
3800             error(loc, "memory qualifiers cannot be used on this type", "", "");
3801         }
3802     }
3803
3804     if (qualifier.storage == EvqBuffer &&
3805         publicType.basicType != EbtBlock &&
3806         !qualifier.hasBufferReference())
3807         error(loc, "buffers can be declared only as blocks", "buffer", "");
3808
3809     if (qualifier.storage != EvqVaryingIn && publicType.basicType == EbtDouble &&
3810         extensionTurnedOn(E_GL_ARB_vertex_attrib_64bit) && language == EShLangVertex &&
3811         version < 400) {
3812         profileRequires(loc, ECoreProfile | ECompatibilityProfile, 410, E_GL_ARB_gpu_shader_fp64, "vertex-shader `double` type");
3813     }
3814     if (qualifier.storage != EvqVaryingIn && qualifier.storage != EvqVaryingOut)
3815         return;
3816
3817     if (publicType.shaderQualifiers.hasBlendEquation())
3818         error(loc, "can only be applied to a standalone 'out'", "blend equation", "");
3819
3820     // now, knowing it is a shader in/out, do all the in/out semantic checks
3821
3822     if (publicType.basicType == EbtBool && !parsingBuiltins) {
3823         error(loc, "cannot be bool", GetStorageQualifierString(qualifier.storage), "");
3824         return;
3825     }
3826
3827     if (isTypeInt(publicType.basicType) || publicType.basicType == EbtDouble)
3828         profileRequires(loc, EEsProfile, 300, nullptr, "shader input/output");
3829
3830     if (!qualifier.flat && !qualifier.isExplicitInterpolation() && !qualifier.isPervertexNV() && !qualifier.isPervertexEXT()) {
3831         if (isTypeInt(publicType.basicType) ||
3832             publicType.basicType == EbtDouble ||
3833             (publicType.userDef && (   publicType.userDef->containsBasicType(EbtInt)
3834                                     || publicType.userDef->containsBasicType(EbtUint)
3835                                     || publicType.userDef->contains16BitInt()
3836                                     || publicType.userDef->contains8BitInt()
3837                                     || publicType.userDef->contains64BitInt()
3838                                     || publicType.userDef->containsDouble()))) {
3839             if (qualifier.storage == EvqVaryingIn && language == EShLangFragment)
3840                 error(loc, "must be qualified as flat", TType::getBasicString(publicType.basicType), GetStorageQualifierString(qualifier.storage));
3841             else if (qualifier.storage == EvqVaryingOut && language == EShLangVertex && version == 300)
3842                 error(loc, "must be qualified as flat", TType::getBasicString(publicType.basicType), GetStorageQualifierString(qualifier.storage));
3843         }
3844     }
3845
3846     if (qualifier.isPatch() && qualifier.isInterpolation())
3847         error(loc, "cannot use interpolation qualifiers with patch", "patch", "");
3848
3849     if (qualifier.isTaskPayload() && publicType.basicType == EbtBlock)
3850         error(loc, "taskPayloadSharedEXT variables should not be declared as interface blocks", "taskPayloadSharedEXT", "");
3851
3852     if (qualifier.isTaskMemory() && publicType.basicType != EbtBlock)
3853         error(loc, "taskNV variables can be declared only as blocks", "taskNV", "");
3854
3855     if (qualifier.storage == EvqVaryingIn) {
3856         switch (language) {
3857         case EShLangVertex:
3858             if (publicType.basicType == EbtStruct) {
3859                 error(loc, "cannot be a structure or array", GetStorageQualifierString(qualifier.storage), "");
3860                 return;
3861             }
3862             if (publicType.arraySizes) {
3863                 requireProfile(loc, ~EEsProfile, "vertex input arrays");
3864                 profileRequires(loc, ENoProfile, 150, nullptr, "vertex input arrays");
3865             }
3866             if (publicType.basicType == EbtDouble)
3867                 profileRequires(loc, ~EEsProfile, 410, E_GL_ARB_vertex_attrib_64bit, "vertex-shader `double` type input");
3868             if (qualifier.isAuxiliary() || qualifier.isInterpolation() || qualifier.isMemory() || qualifier.invariant)
3869                 error(loc, "vertex input cannot be further qualified", "", "");
3870             break;
3871         case EShLangFragment:
3872             if (publicType.userDef) {
3873                 profileRequires(loc, EEsProfile, 300, nullptr, "fragment-shader struct input");
3874                 profileRequires(loc, ~EEsProfile, 150, nullptr, "fragment-shader struct input");
3875                 if (publicType.userDef->containsStructure())
3876                     requireProfile(loc, ~EEsProfile, "fragment-shader struct input containing structure");
3877                 if (publicType.userDef->containsArray())
3878                     requireProfile(loc, ~EEsProfile, "fragment-shader struct input containing an array");
3879             }
3880             break;
3881        case EShLangCompute:
3882             if (! symbolTable.atBuiltInLevel())
3883                 error(loc, "global storage input qualifier cannot be used in a compute shader", "in", "");
3884             break;
3885 #ifndef GLSLANG_WEB
3886        case EShLangTessControl:
3887             if (qualifier.patch)
3888                 error(loc, "can only use on output in tessellation-control shader", "patch", "");
3889             break;
3890 #endif
3891         default:
3892             break;
3893         }
3894     } else {
3895         // qualifier.storage == EvqVaryingOut
3896         switch (language) {
3897         case EShLangVertex:
3898             if (publicType.userDef) {
3899                 profileRequires(loc, EEsProfile, 300, nullptr, "vertex-shader struct output");
3900                 profileRequires(loc, ~EEsProfile, 150, nullptr, "vertex-shader struct output");
3901                 if (publicType.userDef->containsStructure())
3902                     requireProfile(loc, ~EEsProfile, "vertex-shader struct output containing structure");
3903                 if (publicType.userDef->containsArray())
3904                     requireProfile(loc, ~EEsProfile, "vertex-shader struct output containing an array");
3905             }
3906
3907             break;
3908         case EShLangFragment:
3909             profileRequires(loc, EEsProfile, 300, nullptr, "fragment shader output");
3910             if (publicType.basicType == EbtStruct) {
3911                 error(loc, "cannot be a structure", GetStorageQualifierString(qualifier.storage), "");
3912                 return;
3913             }
3914             if (publicType.matrixRows > 0) {
3915                 error(loc, "cannot be a matrix", GetStorageQualifierString(qualifier.storage), "");
3916                 return;
3917             }
3918             if (qualifier.isAuxiliary())
3919                 error(loc, "can't use auxiliary qualifier on a fragment output", "centroid/sample/patch", "");
3920             if (qualifier.isInterpolation())
3921                 error(loc, "can't use interpolation qualifier on a fragment output", "flat/smooth/noperspective", "");
3922             if (publicType.basicType == EbtDouble || publicType.basicType == EbtInt64 || publicType.basicType == EbtUint64)
3923                 error(loc, "cannot contain a double, int64, or uint64", GetStorageQualifierString(qualifier.storage), "");
3924         break;
3925
3926         case EShLangCompute:
3927             error(loc, "global storage output qualifier cannot be used in a compute shader", "out", "");
3928             break;
3929 #ifndef GLSLANG_WEB
3930         case EShLangTessEvaluation:
3931             if (qualifier.patch)
3932                 error(loc, "can only use on input in tessellation-evaluation shader", "patch", "");
3933             break;
3934 #endif
3935         default:
3936             break;
3937         }
3938     }
3939 }
3940
3941 //
3942 // Merge characteristics of the 'src' qualifier into the 'dst'.
3943 // If there is duplication, issue error messages, unless 'force'
3944 // is specified, which means to just override default settings.
3945 //
3946 // Also, when force is false, it will be assumed that 'src' follows
3947 // 'dst', for the purpose of error checking order for versions
3948 // that require specific orderings of qualifiers.
3949 //
3950 void TParseContext::mergeQualifiers(const TSourceLoc& loc, TQualifier& dst, const TQualifier& src, bool force)
3951 {
3952     // Multiple auxiliary qualifiers (mostly done later by 'individual qualifiers')
3953     if (src.isAuxiliary() && dst.isAuxiliary())
3954         error(loc, "can only have one auxiliary qualifier (centroid, patch, and sample)", "", "");
3955
3956     // Multiple interpolation qualifiers (mostly done later by 'individual qualifiers')
3957     if (src.isInterpolation() && dst.isInterpolation())
3958         error(loc, "can only have one interpolation qualifier (flat, smooth, noperspective, __explicitInterpAMD)", "", "");
3959
3960     // Ordering
3961     if (! force && ((!isEsProfile() && version < 420) ||
3962                     (isEsProfile() && version < 310))
3963                 && ! extensionTurnedOn(E_GL_ARB_shading_language_420pack)) {
3964         // non-function parameters
3965         if (src.isNoContraction() && (dst.invariant || dst.isInterpolation() || dst.isAuxiliary() || dst.storage != EvqTemporary || dst.precision != EpqNone))
3966             error(loc, "precise qualifier must appear first", "", "");
3967         if (src.invariant && (dst.isInterpolation() || dst.isAuxiliary() || dst.storage != EvqTemporary || dst.precision != EpqNone))
3968             error(loc, "invariant qualifier must appear before interpolation, storage, and precision qualifiers ", "", "");
3969         else if (src.isInterpolation() && (dst.isAuxiliary() || dst.storage != EvqTemporary || dst.precision != EpqNone))
3970             error(loc, "interpolation qualifiers must appear before storage and precision qualifiers", "", "");
3971         else if (src.isAuxiliary() && (dst.storage != EvqTemporary || dst.precision != EpqNone))
3972             error(loc, "Auxiliary qualifiers (centroid, patch, and sample) must appear before storage and precision qualifiers", "", "");
3973         else if (src.storage != EvqTemporary && (dst.precision != EpqNone))
3974             error(loc, "precision qualifier must appear as last qualifier", "", "");
3975
3976         // function parameters
3977         if (src.isNoContraction() && (dst.storage == EvqConst || dst.storage == EvqIn || dst.storage == EvqOut))
3978             error(loc, "precise qualifier must appear first", "", "");
3979         if (src.storage == EvqConst && (dst.storage == EvqIn || dst.storage == EvqOut))
3980             error(loc, "in/out must appear before const", "", "");
3981     }
3982
3983     // Storage qualification
3984     if (dst.storage == EvqTemporary || dst.storage == EvqGlobal)
3985         dst.storage = src.storage;
3986     else if ((dst.storage == EvqIn  && src.storage == EvqOut) ||
3987              (dst.storage == EvqOut && src.storage == EvqIn))
3988         dst.storage = EvqInOut;
3989     else if ((dst.storage == EvqIn    && src.storage == EvqConst) ||
3990              (dst.storage == EvqConst && src.storage == EvqIn))
3991         dst.storage = EvqConstReadOnly;
3992     else if (src.storage != EvqTemporary &&
3993              src.storage != EvqGlobal)
3994         error(loc, "too many storage qualifiers", GetStorageQualifierString(src.storage), "");
3995
3996     // Precision qualifiers
3997     if (! force && src.precision != EpqNone && dst.precision != EpqNone)
3998         error(loc, "only one precision qualifier allowed", GetPrecisionQualifierString(src.precision), "");
3999     if (dst.precision == EpqNone || (force && src.precision != EpqNone))
4000         dst.precision = src.precision;
4001
4002 #ifndef GLSLANG_WEB
4003     if (!force && ((src.coherent && (dst.devicecoherent || dst.queuefamilycoherent || dst.workgroupcoherent || dst.subgroupcoherent || dst.shadercallcoherent)) ||
4004                    (src.devicecoherent && (dst.coherent || dst.queuefamilycoherent || dst.workgroupcoherent || dst.subgroupcoherent || dst.shadercallcoherent)) ||
4005                    (src.queuefamilycoherent && (dst.coherent || dst.devicecoherent || dst.workgroupcoherent || dst.subgroupcoherent || dst.shadercallcoherent)) ||
4006                    (src.workgroupcoherent && (dst.coherent || dst.devicecoherent || dst.queuefamilycoherent || dst.subgroupcoherent || dst.shadercallcoherent)) ||
4007                    (src.subgroupcoherent  && (dst.coherent || dst.devicecoherent || dst.queuefamilycoherent || dst.workgroupcoherent || dst.shadercallcoherent)) ||
4008                    (src.shadercallcoherent && (dst.coherent || dst.devicecoherent || dst.queuefamilycoherent || dst.workgroupcoherent || dst.subgroupcoherent)))) {
4009         error(loc, "only one coherent/devicecoherent/queuefamilycoherent/workgroupcoherent/subgroupcoherent/shadercallcoherent qualifier allowed",
4010             GetPrecisionQualifierString(src.precision), "");
4011     }
4012 #endif
4013     // Layout qualifiers
4014     mergeObjectLayoutQualifiers(dst, src, false);
4015
4016     // individual qualifiers
4017     bool repeated = false;
4018     #define MERGE_SINGLETON(field) repeated |= dst.field && src.field; dst.field |= src.field;
4019     MERGE_SINGLETON(invariant);
4020     MERGE_SINGLETON(centroid);
4021     MERGE_SINGLETON(smooth);
4022     MERGE_SINGLETON(flat);
4023     MERGE_SINGLETON(specConstant);
4024 #ifndef GLSLANG_WEB
4025     MERGE_SINGLETON(noContraction);
4026     MERGE_SINGLETON(nopersp);
4027     MERGE_SINGLETON(explicitInterp);
4028     MERGE_SINGLETON(perPrimitiveNV);
4029     MERGE_SINGLETON(perViewNV);
4030     MERGE_SINGLETON(perTaskNV);
4031     MERGE_SINGLETON(patch);
4032     MERGE_SINGLETON(sample);
4033     MERGE_SINGLETON(coherent);
4034     MERGE_SINGLETON(devicecoherent);
4035     MERGE_SINGLETON(queuefamilycoherent);
4036     MERGE_SINGLETON(workgroupcoherent);
4037     MERGE_SINGLETON(subgroupcoherent);
4038     MERGE_SINGLETON(shadercallcoherent);
4039     MERGE_SINGLETON(nonprivate);
4040     MERGE_SINGLETON(volatil);
4041     MERGE_SINGLETON(restrict);
4042     MERGE_SINGLETON(readonly);
4043     MERGE_SINGLETON(writeonly);
4044     MERGE_SINGLETON(nonUniform);
4045 #endif
4046
4047 #ifndef GLSLANG_WEB
4048     // SPIR-V storage class qualifier (GL_EXT_spirv_intrinsics)
4049     dst.spirvStorageClass = src.spirvStorageClass;
4050
4051     // SPIR-V decorate qualifiers (GL_EXT_spirv_intrinsics)
4052     if (src.hasSprivDecorate()) {
4053         if (dst.hasSprivDecorate()) {
4054             const TSpirvDecorate& srcSpirvDecorate = src.getSpirvDecorate();
4055             TSpirvDecorate& dstSpirvDecorate = dst.getSpirvDecorate();
4056             for (auto& decorate : srcSpirvDecorate.decorates) {
4057                 if (dstSpirvDecorate.decorates.find(decorate.first) != dstSpirvDecorate.decorates.end())
4058                     error(loc, "too many SPIR-V decorate qualifiers", "spirv_decorate", "(decoration=%u)", decorate.first);
4059                 else
4060                     dstSpirvDecorate.decorates.insert(decorate);
4061             }
4062
4063             for (auto& decorateId : srcSpirvDecorate.decorateIds) {
4064                 if (dstSpirvDecorate.decorateIds.find(decorateId.first) != dstSpirvDecorate.decorateIds.end())
4065                     error(loc, "too many SPIR-V decorate qualifiers", "spirv_decorate_id", "(decoration=%u)", decorateId.first);
4066                 else
4067                     dstSpirvDecorate.decorateIds.insert(decorateId);
4068             }
4069
4070             for (auto& decorateString : srcSpirvDecorate.decorateStrings) {
4071                 if (dstSpirvDecorate.decorates.find(decorateString.first) != dstSpirvDecorate.decorates.end())
4072                     error(loc, "too many SPIR-V decorate qualifiers", "spirv_decorate_string", "(decoration=%u)", decorateString.first);
4073                 else
4074                     dstSpirvDecorate.decorates.insert(decorateString);
4075             }
4076         } else {
4077             dst.spirvDecorate = src.spirvDecorate;
4078         }
4079     }
4080 #endif
4081
4082     if (repeated)
4083         error(loc, "replicated qualifiers", "", "");
4084 }
4085
4086 void TParseContext::setDefaultPrecision(const TSourceLoc& loc, TPublicType& publicType, TPrecisionQualifier qualifier)
4087 {
4088     TBasicType basicType = publicType.basicType;
4089
4090     if (basicType == EbtSampler) {
4091         defaultSamplerPrecision[computeSamplerTypeIndex(publicType.sampler)] = qualifier;
4092
4093         return;  // all is well
4094     }
4095
4096     if (basicType == EbtInt || basicType == EbtFloat) {
4097         if (publicType.isScalar()) {
4098             defaultPrecision[basicType] = qualifier;
4099             if (basicType == EbtInt) {
4100                 defaultPrecision[EbtUint] = qualifier;
4101                 precisionManager.explicitIntDefaultSeen();
4102             } else
4103                 precisionManager.explicitFloatDefaultSeen();
4104
4105             return;  // all is well
4106         }
4107     }
4108
4109     if (basicType == EbtAtomicUint) {
4110         if (qualifier != EpqHigh)
4111             error(loc, "can only apply highp to atomic_uint", "precision", "");
4112
4113         return;
4114     }
4115
4116     error(loc, "cannot apply precision statement to this type; use 'float', 'int' or a sampler type", TType::getBasicString(basicType), "");
4117 }
4118
4119 // used to flatten the sampler type space into a single dimension
4120 // correlates with the declaration of defaultSamplerPrecision[]
4121 int TParseContext::computeSamplerTypeIndex(TSampler& sampler)
4122 {
4123     int arrayIndex    = sampler.arrayed         ? 1 : 0;
4124     int shadowIndex   = sampler.shadow          ? 1 : 0;
4125     int externalIndex = sampler.isExternal()    ? 1 : 0;
4126     int imageIndex    = sampler.isImageClass()  ? 1 : 0;
4127     int msIndex       = sampler.isMultiSample() ? 1 : 0;
4128
4129     int flattened = EsdNumDims * (EbtNumTypes * (2 * (2 * (2 * (2 * arrayIndex + msIndex) + imageIndex) + shadowIndex) +
4130                                                  externalIndex) + sampler.type) + sampler.dim;
4131     assert(flattened < maxSamplerIndex);
4132
4133     return flattened;
4134 }
4135
4136 TPrecisionQualifier TParseContext::getDefaultPrecision(TPublicType& publicType)
4137 {
4138     if (publicType.basicType == EbtSampler)
4139         return defaultSamplerPrecision[computeSamplerTypeIndex(publicType.sampler)];
4140     else
4141         return defaultPrecision[publicType.basicType];
4142 }
4143
4144 void TParseContext::precisionQualifierCheck(const TSourceLoc& loc, TBasicType baseType, TQualifier& qualifier)
4145 {
4146     // Built-in symbols are allowed some ambiguous precisions, to be pinned down
4147     // later by context.
4148     if (! obeyPrecisionQualifiers() || parsingBuiltins)
4149         return;
4150
4151 #ifndef GLSLANG_WEB
4152     if (baseType == EbtAtomicUint && qualifier.precision != EpqNone && qualifier.precision != EpqHigh)
4153         error(loc, "atomic counters can only be highp", "atomic_uint", "");
4154 #endif
4155
4156     if (baseType == EbtFloat || baseType == EbtUint || baseType == EbtInt || baseType == EbtSampler || baseType == EbtAtomicUint) {
4157         if (qualifier.precision == EpqNone) {
4158             if (relaxedErrors())
4159                 warn(loc, "type requires declaration of default precision qualifier", TType::getBasicString(baseType), "substituting 'mediump'");
4160             else
4161                 error(loc, "type requires declaration of default precision qualifier", TType::getBasicString(baseType), "");
4162             qualifier.precision = EpqMedium;
4163             defaultPrecision[baseType] = EpqMedium;
4164         }
4165     } else if (qualifier.precision != EpqNone)
4166         error(loc, "type cannot have precision qualifier", TType::getBasicString(baseType), "");
4167 }
4168
4169 void TParseContext::parameterTypeCheck(const TSourceLoc& loc, TStorageQualifier qualifier, const TType& type)
4170 {
4171     if ((qualifier == EvqOut || qualifier == EvqInOut) && type.isOpaque())
4172         error(loc, "samplers and atomic_uints cannot be output parameters", type.getBasicTypeString().c_str(), "");
4173     if (!parsingBuiltins && type.contains16BitFloat())
4174         requireFloat16Arithmetic(loc, type.getBasicTypeString().c_str(), "float16 types can only be in uniform block or buffer storage");
4175     if (!parsingBuiltins && type.contains16BitInt())
4176         requireInt16Arithmetic(loc, type.getBasicTypeString().c_str(), "(u)int16 types can only be in uniform block or buffer storage");
4177     if (!parsingBuiltins && type.contains8BitInt())
4178         requireInt8Arithmetic(loc, type.getBasicTypeString().c_str(), "(u)int8 types can only be in uniform block or buffer storage");
4179 }
4180
4181 bool TParseContext::containsFieldWithBasicType(const TType& type, TBasicType basicType)
4182 {
4183     if (type.getBasicType() == basicType)
4184         return true;
4185
4186     if (type.getBasicType() == EbtStruct) {
4187         const TTypeList& structure = *type.getStruct();
4188         for (unsigned int i = 0; i < structure.size(); ++i) {
4189             if (containsFieldWithBasicType(*structure[i].type, basicType))
4190                 return true;
4191         }
4192     }
4193
4194     return false;
4195 }
4196
4197 //
4198 // Do size checking for an array type's size.
4199 //
4200 void TParseContext::arraySizeCheck(const TSourceLoc& loc, TIntermTyped* expr, TArraySize& sizePair, const char *sizeType)
4201 {
4202     bool isConst = false;
4203     sizePair.node = nullptr;
4204
4205     int size = 1;
4206
4207     TIntermConstantUnion* constant = expr->getAsConstantUnion();
4208     if (constant) {
4209         // handle true (non-specialization) constant
4210         size = constant->getConstArray()[0].getIConst();
4211         isConst = true;
4212     } else {
4213         // see if it's a specialization constant instead
4214         if (expr->getQualifier().isSpecConstant()) {
4215             isConst = true;
4216             sizePair.node = expr;
4217             TIntermSymbol* symbol = expr->getAsSymbolNode();
4218             if (symbol && symbol->getConstArray().size() > 0)
4219                 size = symbol->getConstArray()[0].getIConst();
4220         } else if (expr->getAsUnaryNode() &&
4221                    expr->getAsUnaryNode()->getOp() == glslang::EOpArrayLength &&
4222                    expr->getAsUnaryNode()->getOperand()->getType().isCoopMat()) {
4223             isConst = true;
4224             size = 1;
4225             sizePair.node = expr->getAsUnaryNode();
4226         }
4227     }
4228
4229     sizePair.size = size;
4230
4231     if (! isConst || (expr->getBasicType() != EbtInt && expr->getBasicType() != EbtUint)) {
4232         error(loc, sizeType, "", "must be a constant integer expression");
4233         return;
4234     }
4235
4236     if (size <= 0) {
4237         error(loc, sizeType, "", "must be a positive integer");
4238         return;
4239     }
4240 }
4241
4242 //
4243 // See if this qualifier can be an array.
4244 //
4245 // Returns true if there is an error.
4246 //
4247 bool TParseContext::arrayQualifierError(const TSourceLoc& loc, const TQualifier& qualifier)
4248 {
4249     if (qualifier.storage == EvqConst) {
4250         profileRequires(loc, ENoProfile, 120, E_GL_3DL_array_objects, "const array");
4251         profileRequires(loc, EEsProfile, 300, nullptr, "const array");
4252     }
4253
4254     if (qualifier.storage == EvqVaryingIn && language == EShLangVertex) {
4255         requireProfile(loc, ~EEsProfile, "vertex input arrays");
4256         profileRequires(loc, ENoProfile, 150, nullptr, "vertex input arrays");
4257     }
4258
4259     return false;
4260 }
4261
4262 //
4263 // See if this qualifier and type combination can be an array.
4264 // Assumes arrayQualifierError() was also called to catch the type-invariant tests.
4265 //
4266 // Returns true if there is an error.
4267 //
4268 bool TParseContext::arrayError(const TSourceLoc& loc, const TType& type)
4269 {
4270     if (type.getQualifier().storage == EvqVaryingOut && language == EShLangVertex) {
4271         if (type.isArrayOfArrays())
4272             requireProfile(loc, ~EEsProfile, "vertex-shader array-of-array output");
4273         else if (type.isStruct())
4274             requireProfile(loc, ~EEsProfile, "vertex-shader array-of-struct output");
4275     }
4276     if (type.getQualifier().storage == EvqVaryingIn && language == EShLangFragment) {
4277         if (type.isArrayOfArrays())
4278             requireProfile(loc, ~EEsProfile, "fragment-shader array-of-array input");
4279         else if (type.isStruct())
4280             requireProfile(loc, ~EEsProfile, "fragment-shader array-of-struct input");
4281     }
4282     if (type.getQualifier().storage == EvqVaryingOut && language == EShLangFragment) {
4283         if (type.isArrayOfArrays())
4284             requireProfile(loc, ~EEsProfile, "fragment-shader array-of-array output");
4285     }
4286
4287     return false;
4288 }
4289
4290 //
4291 // Require array to be completely sized
4292 //
4293 void TParseContext::arraySizeRequiredCheck(const TSourceLoc& loc, const TArraySizes& arraySizes)
4294 {
4295     if (!parsingBuiltins && arraySizes.hasUnsized())
4296         error(loc, "array size required", "", "");
4297 }
4298
4299 void TParseContext::structArrayCheck(const TSourceLoc& /*loc*/, const TType& type)
4300 {
4301     const TTypeList& structure = *type.getStruct();
4302     for (int m = 0; m < (int)structure.size(); ++m) {
4303         const TType& member = *structure[m].type;
4304         if (member.isArray())
4305             arraySizeRequiredCheck(structure[m].loc, *member.getArraySizes());
4306     }
4307 }
4308
4309 void TParseContext::arraySizesCheck(const TSourceLoc& loc, const TQualifier& qualifier, TArraySizes* arraySizes,
4310     const TIntermTyped* initializer, bool lastMember)
4311 {
4312     assert(arraySizes);
4313
4314     // always allow special built-in ins/outs sized to topologies
4315     if (parsingBuiltins)
4316         return;
4317
4318     // initializer must be a sized array, in which case
4319     // allow the initializer to set any unknown array sizes
4320     if (initializer != nullptr) {
4321         if (initializer->getType().isUnsizedArray())
4322             error(loc, "array initializer must be sized", "[]", "");
4323         return;
4324     }
4325
4326     // No environment allows any non-outer-dimension to be implicitly sized
4327     if (arraySizes->isInnerUnsized()) {
4328         error(loc, "only outermost dimension of an array of arrays can be implicitly sized", "[]", "");
4329         arraySizes->clearInnerUnsized();
4330     }
4331
4332     if (arraySizes->isInnerSpecialization() &&
4333         (qualifier.storage != EvqTemporary && qualifier.storage != EvqGlobal && qualifier.storage != EvqShared && qualifier.storage != EvqConst))
4334         error(loc, "only outermost dimension of an array of arrays can be a specialization constant", "[]", "");
4335
4336 #ifndef GLSLANG_WEB
4337
4338     // desktop always allows outer-dimension-unsized variable arrays,
4339     if (!isEsProfile())
4340         return;
4341
4342     // for ES, if size isn't coming from an initializer, it has to be explicitly declared now,
4343     // with very few exceptions
4344
4345     // implicitly-sized io exceptions:
4346     switch (language) {
4347     case EShLangGeometry:
4348         if (qualifier.storage == EvqVaryingIn)
4349             if ((isEsProfile() && version >= 320) ||
4350                 extensionsTurnedOn(Num_AEP_geometry_shader, AEP_geometry_shader))
4351                 return;
4352         break;
4353     case EShLangTessControl:
4354         if ( qualifier.storage == EvqVaryingIn ||
4355             (qualifier.storage == EvqVaryingOut && ! qualifier.isPatch()))
4356             if ((isEsProfile() && version >= 320) ||
4357                 extensionsTurnedOn(Num_AEP_tessellation_shader, AEP_tessellation_shader))
4358                 return;
4359         break;
4360     case EShLangTessEvaluation:
4361         if ((qualifier.storage == EvqVaryingIn && ! qualifier.isPatch()) ||
4362              qualifier.storage == EvqVaryingOut)
4363             if ((isEsProfile() && version >= 320) ||
4364                 extensionsTurnedOn(Num_AEP_tessellation_shader, AEP_tessellation_shader))
4365                 return;
4366         break;
4367     case EShLangMesh:
4368         if (qualifier.storage == EvqVaryingOut)
4369             if ((isEsProfile() && version >= 320) ||
4370                 extensionsTurnedOn(Num_AEP_mesh_shader, AEP_mesh_shader))
4371                 return;
4372         break;
4373     default:
4374         break;
4375     }
4376
4377 #endif
4378
4379     // last member of ssbo block exception:
4380     if (qualifier.storage == EvqBuffer && lastMember)
4381         return;
4382
4383     arraySizeRequiredCheck(loc, *arraySizes);
4384 }
4385
4386 void TParseContext::arrayOfArrayVersionCheck(const TSourceLoc& loc, const TArraySizes* sizes)
4387 {
4388     if (sizes == nullptr || sizes->getNumDims() == 1)
4389         return;
4390
4391     const char* feature = "arrays of arrays";
4392
4393     requireProfile(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, feature);
4394     profileRequires(loc, EEsProfile, 310, nullptr, feature);
4395     profileRequires(loc, ECoreProfile | ECompatibilityProfile, 430, nullptr, feature);
4396 }
4397
4398 //
4399 // Do all the semantic checking for declaring or redeclaring an array, with and
4400 // without a size, and make the right changes to the symbol table.
4401 //
4402 void TParseContext::declareArray(const TSourceLoc& loc, const TString& identifier, const TType& type, TSymbol*& symbol)
4403 {
4404     if (symbol == nullptr) {
4405         bool currentScope;
4406         symbol = symbolTable.find(identifier, nullptr, &currentScope);
4407
4408         if (symbol && builtInName(identifier) && ! symbolTable.atBuiltInLevel()) {
4409             // bad shader (errors already reported) trying to redeclare a built-in name as an array
4410             symbol = nullptr;
4411             return;
4412         }
4413         if (symbol == nullptr || ! currentScope) {
4414             //
4415             // Successfully process a new definition.
4416             // (Redeclarations have to take place at the same scope; otherwise they are hiding declarations)
4417             //
4418             symbol = new TVariable(&identifier, type);
4419             symbolTable.insert(*symbol);
4420             if (symbolTable.atGlobalLevel())
4421                 trackLinkage(*symbol);
4422
4423 #ifndef GLSLANG_WEB
4424             if (! symbolTable.atBuiltInLevel()) {
4425                 if (isIoResizeArray(type)) {
4426                     ioArraySymbolResizeList.push_back(symbol);
4427                     checkIoArraysConsistency(loc, true);
4428                 } else
4429                     fixIoArraySize(loc, symbol->getWritableType());
4430             }
4431 #endif
4432
4433             return;
4434         }
4435         if (symbol->getAsAnonMember()) {
4436             error(loc, "cannot redeclare a user-block member array", identifier.c_str(), "");
4437             symbol = nullptr;
4438             return;
4439         }
4440     }
4441
4442     //
4443     // Process a redeclaration.
4444     //
4445
4446     if (symbol == nullptr) {
4447         error(loc, "array variable name expected", identifier.c_str(), "");
4448         return;
4449     }
4450
4451     // redeclareBuiltinVariable() should have already done the copyUp()
4452     TType& existingType = symbol->getWritableType();
4453
4454     if (! existingType.isArray()) {
4455         error(loc, "redeclaring non-array as array", identifier.c_str(), "");
4456         return;
4457     }
4458
4459     if (! existingType.sameElementType(type)) {
4460         error(loc, "redeclaration of array with a different element type", identifier.c_str(), "");
4461         return;
4462     }
4463
4464     if (! existingType.sameInnerArrayness(type)) {
4465         error(loc, "redeclaration of array with a different array dimensions or sizes", identifier.c_str(), "");
4466         return;
4467     }
4468
4469 #ifndef GLSLANG_WEB
4470     if (existingType.isSizedArray()) {
4471         // be more leniant for input arrays to geometry shaders and tessellation control outputs, where the redeclaration is the same size
4472         if (! (isIoResizeArray(type) && existingType.getOuterArraySize() == type.getOuterArraySize()))
4473             error(loc, "redeclaration of array with size", identifier.c_str(), "");
4474         return;
4475     }
4476
4477     arrayLimitCheck(loc, identifier, type.getOuterArraySize());
4478
4479     existingType.updateArraySizes(type);
4480
4481     if (isIoResizeArray(type))
4482         checkIoArraysConsistency(loc);
4483 #endif
4484 }
4485
4486 #ifndef GLSLANG_WEB
4487
4488 // Policy and error check for needing a runtime sized array.
4489 void TParseContext::checkRuntimeSizable(const TSourceLoc& loc, const TIntermTyped& base)
4490 {
4491     // runtime length implies runtime sizeable, so no problem
4492     if (isRuntimeLength(base))
4493         return;
4494
4495     if (base.getType().getQualifier().builtIn == EbvSampleMask)
4496         return;
4497
4498     // Check for last member of a bufferreference type, which is runtime sizeable
4499     // but doesn't support runtime length
4500     if (base.getType().getQualifier().storage == EvqBuffer) {
4501         const TIntermBinary* binary = base.getAsBinaryNode();
4502         if (binary != nullptr &&
4503             binary->getOp() == EOpIndexDirectStruct &&
4504             binary->getLeft()->isReference()) {
4505
4506             const int index = binary->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
4507             const int memberCount = (int)binary->getLeft()->getType().getReferentType()->getStruct()->size();
4508             if (index == memberCount - 1)
4509                 return;
4510         }
4511     }
4512
4513     // check for additional things allowed by GL_EXT_nonuniform_qualifier
4514     if (base.getBasicType() == EbtSampler || base.getBasicType() == EbtAccStruct || base.getBasicType() == EbtRayQuery ||
4515         (base.getBasicType() == EbtBlock && base.getType().getQualifier().isUniformOrBuffer()))
4516         requireExtensions(loc, 1, &E_GL_EXT_nonuniform_qualifier, "variable index");
4517     else
4518         error(loc, "", "[", "array must be redeclared with a size before being indexed with a variable");
4519 }
4520
4521 // Policy decision for whether a run-time .length() is allowed.
4522 bool TParseContext::isRuntimeLength(const TIntermTyped& base) const
4523 {
4524     if (base.getType().getQualifier().storage == EvqBuffer) {
4525         // in a buffer block
4526         const TIntermBinary* binary = base.getAsBinaryNode();
4527         if (binary != nullptr && binary->getOp() == EOpIndexDirectStruct) {
4528             // is it the last member?
4529             const int index = binary->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
4530
4531             if (binary->getLeft()->isReference())
4532                 return false;
4533
4534             const int memberCount = (int)binary->getLeft()->getType().getStruct()->size();
4535             if (index == memberCount - 1)
4536                 return true;
4537         }
4538     }
4539
4540     return false;
4541 }
4542
4543 // Check if mesh perviewNV attributes have a view dimension
4544 // and resize it to gl_MaxMeshViewCountNV when implicitly sized.
4545 void TParseContext::checkAndResizeMeshViewDim(const TSourceLoc& loc, TType& type, bool isBlockMember)
4546 {
4547     // see if member is a per-view attribute
4548     if (!type.getQualifier().isPerView())
4549         return;
4550
4551     if ((isBlockMember && type.isArray()) || (!isBlockMember && type.isArrayOfArrays())) {
4552         // since we don't have the maxMeshViewCountNV set during parsing builtins, we hardcode the value.
4553         int maxViewCount = parsingBuiltins ? 4 : resources.maxMeshViewCountNV;
4554         // For block members, outermost array dimension is the view dimension.
4555         // For non-block members, outermost array dimension is the vertex/primitive dimension
4556         // and 2nd outermost is the view dimension.
4557         int viewDim = isBlockMember ? 0 : 1;
4558         int viewDimSize = type.getArraySizes()->getDimSize(viewDim);
4559
4560         if (viewDimSize != UnsizedArraySize && viewDimSize != maxViewCount)
4561             error(loc, "mesh view output array size must be gl_MaxMeshViewCountNV or implicitly sized", "[]", "");
4562         else if (viewDimSize == UnsizedArraySize)
4563             type.getArraySizes()->setDimSize(viewDim, maxViewCount);
4564     }
4565     else {
4566         error(loc, "requires a view array dimension", "perviewNV", "");
4567     }
4568 }
4569
4570 #endif // GLSLANG_WEB
4571
4572 // Returns true if the first argument to the #line directive is the line number for the next line.
4573 //
4574 // Desktop, pre-version 3.30:  "After processing this directive
4575 // (including its new-line), the implementation will behave as if it is compiling at line number line+1 and
4576 // source string number source-string-number."
4577 //
4578 // Desktop, version 3.30 and later, and ES:  "After processing this directive
4579 // (including its new-line), the implementation will behave as if it is compiling at line number line and
4580 // source string number source-string-number.
4581 bool TParseContext::lineDirectiveShouldSetNextLine() const
4582 {
4583     return isEsProfile() || version >= 330;
4584 }
4585
4586 //
4587 // Enforce non-initializer type/qualifier rules.
4588 //
4589 void TParseContext::nonInitConstCheck(const TSourceLoc& loc, TString& identifier, TType& type)
4590 {
4591     //
4592     // Make the qualifier make sense, given that there is not an initializer.
4593     //
4594     if (type.getQualifier().storage == EvqConst ||
4595         type.getQualifier().storage == EvqConstReadOnly) {
4596         type.getQualifier().makeTemporary();
4597         error(loc, "variables with qualifier 'const' must be initialized", identifier.c_str(), "");
4598     }
4599 }
4600
4601 //
4602 // See if the identifier is a built-in symbol that can be redeclared, and if so,
4603 // copy the symbol table's read-only built-in variable to the current
4604 // global level, where it can be modified based on the passed in type.
4605 //
4606 // Returns nullptr if no redeclaration took place; meaning a normal declaration still
4607 // needs to occur for it, not necessarily an error.
4608 //
4609 // Returns a redeclared and type-modified variable if a redeclarated occurred.
4610 //
4611 TSymbol* TParseContext::redeclareBuiltinVariable(const TSourceLoc& loc, const TString& identifier,
4612                                                  const TQualifier& qualifier, const TShaderQualifiers& publicType)
4613 {
4614 #ifndef GLSLANG_WEB
4615     if (! builtInName(identifier) || symbolTable.atBuiltInLevel() || ! symbolTable.atGlobalLevel())
4616         return nullptr;
4617
4618     bool nonEsRedecls = (!isEsProfile() && (version >= 130 || identifier == "gl_TexCoord"));
4619     bool    esRedecls = (isEsProfile() &&
4620                          (version >= 320 || extensionsTurnedOn(Num_AEP_shader_io_blocks, AEP_shader_io_blocks)));
4621     if (! esRedecls && ! nonEsRedecls)
4622         return nullptr;
4623
4624     // Special case when using GL_ARB_separate_shader_objects
4625     bool ssoPre150 = false;  // means the only reason this variable is redeclared is due to this combination
4626     if (!isEsProfile() && version <= 140 && extensionTurnedOn(E_GL_ARB_separate_shader_objects)) {
4627         if (identifier == "gl_Position"     ||
4628             identifier == "gl_PointSize"    ||
4629             identifier == "gl_ClipVertex"   ||
4630             identifier == "gl_FogFragCoord")
4631             ssoPre150 = true;
4632     }
4633
4634     // Potentially redeclaring a built-in variable...
4635
4636     if (ssoPre150 ||
4637         (identifier == "gl_FragDepth"           && ((nonEsRedecls && version >= 420) || esRedecls)) ||
4638         (identifier == "gl_FragCoord"           && ((nonEsRedecls && version >= 140) || esRedecls)) ||
4639          identifier == "gl_ClipDistance"                                                            ||
4640          identifier == "gl_CullDistance"                                                            ||
4641          identifier == "gl_ShadingRateEXT"                                                          ||
4642          identifier == "gl_PrimitiveShadingRateEXT"                                                 ||
4643          identifier == "gl_FrontColor"                                                              ||
4644          identifier == "gl_BackColor"                                                               ||
4645          identifier == "gl_FrontSecondaryColor"                                                     ||
4646          identifier == "gl_BackSecondaryColor"                                                      ||
4647          identifier == "gl_SecondaryColor"                                                          ||
4648         (identifier == "gl_Color"               && language == EShLangFragment)                     ||
4649         (identifier == "gl_FragStencilRefARB"   && (nonEsRedecls && version >= 140)
4650                                                 && language == EShLangFragment)                     ||
4651          identifier == "gl_SampleMask"                                                              ||
4652          identifier == "gl_Layer"                                                                   ||
4653          identifier == "gl_PrimitiveIndicesNV"                                                      ||
4654          identifier == "gl_PrimitivePointIndicesEXT"                                                ||
4655          identifier == "gl_PrimitiveLineIndicesEXT"                                                 ||
4656          identifier == "gl_PrimitiveTriangleIndicesEXT"                                             ||
4657          identifier == "gl_TexCoord") {
4658
4659         // Find the existing symbol, if any.
4660         bool builtIn;
4661         TSymbol* symbol = symbolTable.find(identifier, &builtIn);
4662
4663         // If the symbol was not found, this must be a version/profile/stage
4664         // that doesn't have it.
4665         if (! symbol)
4666             return nullptr;
4667
4668         // If it wasn't at a built-in level, then it's already been redeclared;
4669         // that is, this is a redeclaration of a redeclaration; reuse that initial
4670         // redeclaration.  Otherwise, make the new one.
4671         if (builtIn) {
4672             makeEditable(symbol);
4673             symbolTable.amendSymbolIdLevel(*symbol);
4674         }
4675
4676         // Now, modify the type of the copy, as per the type of the current redeclaration.
4677
4678         TQualifier& symbolQualifier = symbol->getWritableType().getQualifier();
4679         if (ssoPre150) {
4680             if (intermediate.inIoAccessed(identifier))
4681                 error(loc, "cannot redeclare after use", identifier.c_str(), "");
4682             if (qualifier.hasLayout())
4683                 error(loc, "cannot apply layout qualifier to", "redeclaration", symbol->getName().c_str());
4684             if (qualifier.isMemory() || qualifier.isAuxiliary() || (language == EShLangVertex   && qualifier.storage != EvqVaryingOut) ||
4685                                                                    (language == EShLangFragment && qualifier.storage != EvqVaryingIn))
4686                 error(loc, "cannot change storage, memory, or auxiliary qualification of", "redeclaration", symbol->getName().c_str());
4687             if (! qualifier.smooth)
4688                 error(loc, "cannot change interpolation qualification of", "redeclaration", symbol->getName().c_str());
4689         } else if (identifier == "gl_FrontColor"          ||
4690                    identifier == "gl_BackColor"           ||
4691                    identifier == "gl_FrontSecondaryColor" ||
4692                    identifier == "gl_BackSecondaryColor"  ||
4693                    identifier == "gl_SecondaryColor"      ||
4694                    identifier == "gl_Color") {
4695             symbolQualifier.flat = qualifier.flat;
4696             symbolQualifier.smooth = qualifier.smooth;
4697             symbolQualifier.nopersp = qualifier.nopersp;
4698             if (qualifier.hasLayout())
4699                 error(loc, "cannot apply layout qualifier to", "redeclaration", symbol->getName().c_str());
4700             if (qualifier.isMemory() || qualifier.isAuxiliary() || symbol->getType().getQualifier().storage != qualifier.storage)
4701                 error(loc, "cannot change storage, memory, or auxiliary qualification of", "redeclaration", symbol->getName().c_str());
4702         } else if (identifier == "gl_TexCoord"     ||
4703                    identifier == "gl_ClipDistance" ||
4704                    identifier == "gl_CullDistance") {
4705             if (qualifier.hasLayout() || qualifier.isMemory() || qualifier.isAuxiliary() ||
4706                 qualifier.nopersp != symbolQualifier.nopersp || qualifier.flat != symbolQualifier.flat ||
4707                 symbolQualifier.storage != qualifier.storage)
4708                 error(loc, "cannot change qualification of", "redeclaration", symbol->getName().c_str());
4709         } else if (identifier == "gl_FragCoord") {
4710             if (!intermediate.getTexCoordRedeclared() && intermediate.inIoAccessed("gl_FragCoord"))
4711                 error(loc, "cannot redeclare after use", "gl_FragCoord", "");
4712             if (qualifier.nopersp != symbolQualifier.nopersp || qualifier.flat != symbolQualifier.flat ||
4713                 qualifier.isMemory() || qualifier.isAuxiliary())
4714                 error(loc, "can only change layout qualification of", "redeclaration", symbol->getName().c_str());
4715             if (qualifier.storage != EvqVaryingIn)
4716                 error(loc, "cannot change input storage qualification of", "redeclaration", symbol->getName().c_str());
4717             if (! builtIn && (publicType.pixelCenterInteger != intermediate.getPixelCenterInteger() ||
4718                               publicType.originUpperLeft != intermediate.getOriginUpperLeft()))
4719                 error(loc, "cannot redeclare with different qualification:", "redeclaration", symbol->getName().c_str());
4720
4721
4722             intermediate.setTexCoordRedeclared();
4723             if (publicType.pixelCenterInteger)
4724                 intermediate.setPixelCenterInteger();
4725             if (publicType.originUpperLeft)
4726                 intermediate.setOriginUpperLeft();
4727         } else if (identifier == "gl_FragDepth") {
4728             if (qualifier.nopersp != symbolQualifier.nopersp || qualifier.flat != symbolQualifier.flat ||
4729                 qualifier.isMemory() || qualifier.isAuxiliary())
4730                 error(loc, "can only change layout qualification of", "redeclaration", symbol->getName().c_str());
4731             if (qualifier.storage != EvqVaryingOut)
4732                 error(loc, "cannot change output storage qualification of", "redeclaration", symbol->getName().c_str());
4733             if (publicType.layoutDepth != EldNone) {
4734                 if (intermediate.inIoAccessed("gl_FragDepth"))
4735                     error(loc, "cannot redeclare after use", "gl_FragDepth", "");
4736                 if (! intermediate.setDepth(publicType.layoutDepth))
4737                     error(loc, "all redeclarations must use the same depth layout on", "redeclaration", symbol->getName().c_str());
4738             }
4739         } else if (identifier == "gl_FragStencilRefARB") {
4740             if (qualifier.nopersp != symbolQualifier.nopersp || qualifier.flat != symbolQualifier.flat ||
4741                 qualifier.isMemory() || qualifier.isAuxiliary())
4742                 error(loc, "can only change layout qualification of", "redeclaration", symbol->getName().c_str());
4743             if (qualifier.storage != EvqVaryingOut)
4744                 error(loc, "cannot change output storage qualification of", "redeclaration", symbol->getName().c_str());
4745             if (publicType.layoutStencil != ElsNone) {
4746                 if (intermediate.inIoAccessed("gl_FragStencilRefARB"))
4747                     error(loc, "cannot redeclare after use", "gl_FragStencilRefARB", "");
4748                 if (!intermediate.setStencil(publicType.layoutStencil))
4749                     error(loc, "all redeclarations must use the same stencil layout on", "redeclaration",
4750                           symbol->getName().c_str());
4751             }
4752         }
4753         else if (
4754             identifier == "gl_PrimitiveIndicesNV") {
4755             if (qualifier.hasLayout())
4756                 error(loc, "cannot apply layout qualifier to", "redeclaration", symbol->getName().c_str());
4757             if (qualifier.storage != EvqVaryingOut)
4758                 error(loc, "cannot change output storage qualification of", "redeclaration", symbol->getName().c_str());
4759         }
4760         else if (identifier == "gl_SampleMask") {
4761             if (!publicType.layoutOverrideCoverage) {
4762                 error(loc, "redeclaration only allowed for override_coverage layout", "redeclaration", symbol->getName().c_str());
4763             }
4764             intermediate.setLayoutOverrideCoverage();
4765         }
4766         else if (identifier == "gl_Layer") {
4767             if (!qualifier.layoutViewportRelative && qualifier.layoutSecondaryViewportRelativeOffset == -2048)
4768                 error(loc, "redeclaration only allowed for viewport_relative or secondary_view_offset layout", "redeclaration", symbol->getName().c_str());
4769             symbolQualifier.layoutViewportRelative = qualifier.layoutViewportRelative;
4770             symbolQualifier.layoutSecondaryViewportRelativeOffset = qualifier.layoutSecondaryViewportRelativeOffset;
4771         }
4772
4773         // TODO: semantics quality: separate smooth from nothing declared, then use IsInterpolation for several tests above
4774
4775         return symbol;
4776     }
4777 #endif
4778
4779     return nullptr;
4780 }
4781
4782 //
4783 // Either redeclare the requested block, or give an error message why it can't be done.
4784 //
4785 // TODO: functionality: explicitly sizing members of redeclared blocks is not giving them an explicit size
4786 void TParseContext::redeclareBuiltinBlock(const TSourceLoc& loc, TTypeList& newTypeList, const TString& blockName,
4787     const TString* instanceName, TArraySizes* arraySizes)
4788 {
4789 #ifndef GLSLANG_WEB
4790     const char* feature = "built-in block redeclaration";
4791     profileRequires(loc, EEsProfile, 320, Num_AEP_shader_io_blocks, AEP_shader_io_blocks, feature);
4792     profileRequires(loc, ~EEsProfile, 410, E_GL_ARB_separate_shader_objects, feature);
4793
4794     if (blockName != "gl_PerVertex" && blockName != "gl_PerFragment" &&
4795         blockName != "gl_MeshPerVertexNV" && blockName != "gl_MeshPerPrimitiveNV" &&
4796         blockName != "gl_MeshPerVertexEXT" && blockName != "gl_MeshPerPrimitiveEXT") {
4797         error(loc, "cannot redeclare block: ", "block declaration", blockName.c_str());
4798         return;
4799     }
4800
4801     // Redeclaring a built-in block...
4802
4803     if (instanceName && ! builtInName(*instanceName)) {
4804         error(loc, "cannot redeclare a built-in block with a user name", instanceName->c_str(), "");
4805         return;
4806     }
4807
4808     // Blocks with instance names are easy to find, lookup the instance name,
4809     // Anonymous blocks need to be found via a member.
4810     bool builtIn;
4811     TSymbol* block;
4812     if (instanceName)
4813         block = symbolTable.find(*instanceName, &builtIn);
4814     else
4815         block = symbolTable.find(newTypeList.front().type->getFieldName(), &builtIn);
4816
4817     // If the block was not found, this must be a version/profile/stage
4818     // that doesn't have it, or the instance name is wrong.
4819     const char* errorName = instanceName ? instanceName->c_str() : newTypeList.front().type->getFieldName().c_str();
4820     if (! block) {
4821         error(loc, "no declaration found for redeclaration", errorName, "");
4822         return;
4823     }
4824     // Built-in blocks cannot be redeclared more than once, which if happened,
4825     // we'd be finding the already redeclared one here, rather than the built in.
4826     if (! builtIn) {
4827         error(loc, "can only redeclare a built-in block once, and before any use", blockName.c_str(), "");
4828         return;
4829     }
4830
4831     // Copy the block to make a writable version, to insert into the block table after editing.
4832     block = symbolTable.copyUpDeferredInsert(block);
4833
4834     if (block->getType().getBasicType() != EbtBlock) {
4835         error(loc, "cannot redeclare a non block as a block", errorName, "");
4836         return;
4837     }
4838
4839     // Fix XFB stuff up, it applies to the order of the redeclaration, not
4840     // the order of the original members.
4841     if (currentBlockQualifier.storage == EvqVaryingOut && globalOutputDefaults.hasXfbBuffer()) {
4842         if (!currentBlockQualifier.hasXfbBuffer())
4843             currentBlockQualifier.layoutXfbBuffer = globalOutputDefaults.layoutXfbBuffer;
4844         if (!currentBlockQualifier.hasStream())
4845             currentBlockQualifier.layoutStream = globalOutputDefaults.layoutStream;
4846         fixXfbOffsets(currentBlockQualifier, newTypeList);
4847     }
4848
4849     // Edit and error check the container against the redeclaration
4850     //  - remove unused members
4851     //  - ensure remaining qualifiers/types match
4852
4853     TType& type = block->getWritableType();
4854
4855     // if gl_PerVertex is redeclared for the purpose of passing through "gl_Position"
4856     // for passthrough purpose, the redeclared block should have the same qualifers as
4857     // the current one
4858     if (currentBlockQualifier.layoutPassthrough) {
4859         type.getQualifier().layoutPassthrough = currentBlockQualifier.layoutPassthrough;
4860         type.getQualifier().storage = currentBlockQualifier.storage;
4861         type.getQualifier().layoutStream = currentBlockQualifier.layoutStream;
4862         type.getQualifier().layoutXfbBuffer = currentBlockQualifier.layoutXfbBuffer;
4863     }
4864
4865     TTypeList::iterator member = type.getWritableStruct()->begin();
4866     size_t numOriginalMembersFound = 0;
4867     while (member != type.getStruct()->end()) {
4868         // look for match
4869         bool found = false;
4870         TTypeList::const_iterator newMember;
4871         TSourceLoc memberLoc;
4872         memberLoc.init();
4873         for (newMember = newTypeList.begin(); newMember != newTypeList.end(); ++newMember) {
4874             if (member->type->getFieldName() == newMember->type->getFieldName()) {
4875                 found = true;
4876                 memberLoc = newMember->loc;
4877                 break;
4878             }
4879         }
4880
4881         if (found) {
4882             ++numOriginalMembersFound;
4883             // - ensure match between redeclared members' types
4884             // - check for things that can't be changed
4885             // - update things that can be changed
4886             TType& oldType = *member->type;
4887             const TType& newType = *newMember->type;
4888             if (! newType.sameElementType(oldType))
4889                 error(memberLoc, "cannot redeclare block member with a different type", member->type->getFieldName().c_str(), "");
4890             if (oldType.isArray() != newType.isArray())
4891                 error(memberLoc, "cannot change arrayness of redeclared block member", member->type->getFieldName().c_str(), "");
4892             else if (! oldType.getQualifier().isPerView() && ! oldType.sameArrayness(newType) && oldType.isSizedArray())
4893                 error(memberLoc, "cannot change array size of redeclared block member", member->type->getFieldName().c_str(), "");
4894             else if (! oldType.getQualifier().isPerView() && newType.isArray())
4895                 arrayLimitCheck(loc, member->type->getFieldName(), newType.getOuterArraySize());
4896             if (oldType.getQualifier().isPerView() && ! newType.getQualifier().isPerView())
4897                 error(memberLoc, "missing perviewNV qualifier to redeclared block member", member->type->getFieldName().c_str(), "");
4898             else if (! oldType.getQualifier().isPerView() && newType.getQualifier().isPerView())
4899                 error(memberLoc, "cannot add perviewNV qualifier to redeclared block member", member->type->getFieldName().c_str(), "");
4900             else if (newType.getQualifier().isPerView()) {
4901                 if (oldType.getArraySizes()->getNumDims() != newType.getArraySizes()->getNumDims())
4902                     error(memberLoc, "cannot change arrayness of redeclared block member", member->type->getFieldName().c_str(), "");
4903                 else if (! newType.isUnsizedArray() && newType.getOuterArraySize() != resources.maxMeshViewCountNV)
4904                     error(loc, "mesh view output array size must be gl_MaxMeshViewCountNV or implicitly sized", "[]", "");
4905                 else if (newType.getArraySizes()->getNumDims() == 2) {
4906                     int innerDimSize = newType.getArraySizes()->getDimSize(1);
4907                     arrayLimitCheck(memberLoc, member->type->getFieldName(), innerDimSize);
4908                     oldType.getArraySizes()->setDimSize(1, innerDimSize);
4909                 }
4910             }
4911             if (oldType.getQualifier().isPerPrimitive() && ! newType.getQualifier().isPerPrimitive())
4912                 error(memberLoc, "missing perprimitiveNV qualifier to redeclared block member", member->type->getFieldName().c_str(), "");
4913             else if (! oldType.getQualifier().isPerPrimitive() && newType.getQualifier().isPerPrimitive())
4914                 error(memberLoc, "cannot add perprimitiveNV qualifier to redeclared block member", member->type->getFieldName().c_str(), "");
4915             if (newType.getQualifier().isMemory())
4916                 error(memberLoc, "cannot add memory qualifier to redeclared block member", member->type->getFieldName().c_str(), "");
4917             if (newType.getQualifier().hasNonXfbLayout())
4918                 error(memberLoc, "cannot add non-XFB layout to redeclared block member", member->type->getFieldName().c_str(), "");
4919             if (newType.getQualifier().patch)
4920                 error(memberLoc, "cannot add patch to redeclared block member", member->type->getFieldName().c_str(), "");
4921             if (newType.getQualifier().hasXfbBuffer() &&
4922                 newType.getQualifier().layoutXfbBuffer != currentBlockQualifier.layoutXfbBuffer)
4923                 error(memberLoc, "member cannot contradict block (or what block inherited from global)", "xfb_buffer", "");
4924             if (newType.getQualifier().hasStream() &&
4925                 newType.getQualifier().layoutStream != currentBlockQualifier.layoutStream)
4926                 error(memberLoc, "member cannot contradict block (or what block inherited from global)", "xfb_stream", "");
4927             oldType.getQualifier().centroid = newType.getQualifier().centroid;
4928             oldType.getQualifier().sample = newType.getQualifier().sample;
4929             oldType.getQualifier().invariant = newType.getQualifier().invariant;
4930             oldType.getQualifier().noContraction = newType.getQualifier().noContraction;
4931             oldType.getQualifier().smooth = newType.getQualifier().smooth;
4932             oldType.getQualifier().flat = newType.getQualifier().flat;
4933             oldType.getQualifier().nopersp = newType.getQualifier().nopersp;
4934             oldType.getQualifier().layoutXfbOffset = newType.getQualifier().layoutXfbOffset;
4935             oldType.getQualifier().layoutXfbBuffer = newType.getQualifier().layoutXfbBuffer;
4936             oldType.getQualifier().layoutXfbStride = newType.getQualifier().layoutXfbStride;
4937             if (oldType.getQualifier().layoutXfbOffset != TQualifier::layoutXfbBufferEnd) {
4938                 // If any member has an xfb_offset, then the block's xfb_buffer inherents current xfb_buffer,
4939                 // and for xfb processing, the member needs it as well, along with xfb_stride.
4940                 type.getQualifier().layoutXfbBuffer = currentBlockQualifier.layoutXfbBuffer;
4941                 oldType.getQualifier().layoutXfbBuffer = currentBlockQualifier.layoutXfbBuffer;
4942             }
4943             if (oldType.isUnsizedArray() && newType.isSizedArray())
4944                 oldType.changeOuterArraySize(newType.getOuterArraySize());
4945
4946             //  check and process the member's type, which will include managing xfb information
4947             layoutTypeCheck(loc, oldType);
4948
4949             // go to next member
4950             ++member;
4951         } else {
4952             // For missing members of anonymous blocks that have been redeclared,
4953             // hide the original (shared) declaration.
4954             // Instance-named blocks can just have the member removed.
4955             if (instanceName)
4956                 member = type.getWritableStruct()->erase(member);
4957             else {
4958                 member->type->hideMember();
4959                 ++member;
4960             }
4961         }
4962     }
4963
4964     if (spvVersion.vulkan > 0) {
4965         // ...then streams apply to built-in blocks, instead of them being only on stream 0
4966         type.getQualifier().layoutStream = currentBlockQualifier.layoutStream;
4967     }
4968
4969     if (numOriginalMembersFound < newTypeList.size())
4970         error(loc, "block redeclaration has extra members", blockName.c_str(), "");
4971     if (type.isArray() != (arraySizes != nullptr) ||
4972         (type.isArray() && arraySizes != nullptr && type.getArraySizes()->getNumDims() != arraySizes->getNumDims()))
4973         error(loc, "cannot change arrayness of redeclared block", blockName.c_str(), "");
4974     else if (type.isArray()) {
4975         // At this point, we know both are arrays and both have the same number of dimensions.
4976
4977         // It is okay for a built-in block redeclaration to be unsized, and keep the size of the
4978         // original block declaration.
4979         if (!arraySizes->isSized() && type.isSizedArray())
4980             arraySizes->changeOuterSize(type.getOuterArraySize());
4981
4982         // And, okay to be giving a size to the array, by the redeclaration
4983         if (!type.isSizedArray() && arraySizes->isSized())
4984             type.changeOuterArraySize(arraySizes->getOuterSize());
4985
4986         // Now, they must match in all dimensions.
4987         if (type.isSizedArray() && *type.getArraySizes() != *arraySizes)
4988             error(loc, "cannot change array size of redeclared block", blockName.c_str(), "");
4989     }
4990
4991     symbolTable.insert(*block);
4992
4993     // Check for general layout qualifier errors
4994     layoutObjectCheck(loc, *block);
4995
4996     // Tracking for implicit sizing of array
4997     if (isIoResizeArray(block->getType())) {
4998         ioArraySymbolResizeList.push_back(block);
4999         checkIoArraysConsistency(loc, true);
5000     } else if (block->getType().isArray())
5001         fixIoArraySize(loc, block->getWritableType());
5002
5003     // Save it in the AST for linker use.
5004     trackLinkage(*block);
5005 #endif // GLSLANG_WEB
5006 }
5007
5008 void TParseContext::paramCheckFixStorage(const TSourceLoc& loc, const TStorageQualifier& qualifier, TType& type)
5009 {
5010     switch (qualifier) {
5011     case EvqConst:
5012     case EvqConstReadOnly:
5013         type.getQualifier().storage = EvqConstReadOnly;
5014         break;
5015     case EvqIn:
5016     case EvqOut:
5017     case EvqInOut:
5018         type.getQualifier().storage = qualifier;
5019         break;
5020     case EvqGlobal:
5021     case EvqTemporary:
5022         type.getQualifier().storage = EvqIn;
5023         break;
5024     default:
5025         type.getQualifier().storage = EvqIn;
5026         error(loc, "storage qualifier not allowed on function parameter", GetStorageQualifierString(qualifier), "");
5027         break;
5028     }
5029 }
5030
5031 void TParseContext::paramCheckFix(const TSourceLoc& loc, const TQualifier& qualifier, TType& type)
5032 {
5033 #ifndef GLSLANG_WEB
5034     if (qualifier.isMemory()) {
5035         type.getQualifier().volatil   = qualifier.volatil;
5036         type.getQualifier().coherent  = qualifier.coherent;
5037         type.getQualifier().devicecoherent  = qualifier.devicecoherent ;
5038         type.getQualifier().queuefamilycoherent  = qualifier.queuefamilycoherent;
5039         type.getQualifier().workgroupcoherent  = qualifier.workgroupcoherent;
5040         type.getQualifier().subgroupcoherent  = qualifier.subgroupcoherent;
5041         type.getQualifier().shadercallcoherent = qualifier.shadercallcoherent;
5042         type.getQualifier().nonprivate = qualifier.nonprivate;
5043         type.getQualifier().readonly  = qualifier.readonly;
5044         type.getQualifier().writeonly = qualifier.writeonly;
5045         type.getQualifier().restrict  = qualifier.restrict;
5046     }
5047 #endif
5048
5049     if (qualifier.isAuxiliary() ||
5050         qualifier.isInterpolation())
5051         error(loc, "cannot use auxiliary or interpolation qualifiers on a function parameter", "", "");
5052     if (qualifier.hasLayout())
5053         error(loc, "cannot use layout qualifiers on a function parameter", "", "");
5054     if (qualifier.invariant)
5055         error(loc, "cannot use invariant qualifier on a function parameter", "", "");
5056     if (qualifier.isNoContraction()) {
5057         if (qualifier.isParamOutput())
5058             type.getQualifier().setNoContraction();
5059         else
5060             warn(loc, "qualifier has no effect on non-output parameters", "precise", "");
5061     }
5062     if (qualifier.isNonUniform())
5063         type.getQualifier().nonUniform = qualifier.nonUniform;
5064 #ifndef GLSLANG_WEB
5065     if (qualifier.isSpirvByReference())
5066         type.getQualifier().setSpirvByReference();
5067     if (qualifier.isSpirvLiteral()) {
5068         if (type.getBasicType() == EbtFloat || type.getBasicType() == EbtInt || type.getBasicType() == EbtUint ||
5069             type.getBasicType() == EbtBool)
5070             type.getQualifier().setSpirvLiteral();
5071         else
5072             error(loc, "cannot use spirv_literal qualifier", type.getBasicTypeString().c_str(), "");
5073 #endif
5074     }
5075
5076     paramCheckFixStorage(loc, qualifier.storage, type);
5077 }
5078
5079 void TParseContext::nestedBlockCheck(const TSourceLoc& loc)
5080 {
5081     if (structNestingLevel > 0 || blockNestingLevel > 0)
5082         error(loc, "cannot nest a block definition inside a structure or block", "", "");
5083     ++blockNestingLevel;
5084 }
5085
5086 void TParseContext::nestedStructCheck(const TSourceLoc& loc)
5087 {
5088     if (structNestingLevel > 0 || blockNestingLevel > 0)
5089         error(loc, "cannot nest a structure definition inside a structure or block", "", "");
5090     ++structNestingLevel;
5091 }
5092
5093 void TParseContext::arrayObjectCheck(const TSourceLoc& loc, const TType& type, const char* op)
5094 {
5095     // Some versions don't allow comparing arrays or structures containing arrays
5096     if (type.containsArray()) {
5097         profileRequires(loc, ENoProfile, 120, E_GL_3DL_array_objects, op);
5098         profileRequires(loc, EEsProfile, 300, nullptr, op);
5099     }
5100 }
5101
5102 void TParseContext::opaqueCheck(const TSourceLoc& loc, const TType& type, const char* op)
5103 {
5104     if (containsFieldWithBasicType(type, EbtSampler))
5105         error(loc, "can't use with samplers or structs containing samplers", op, "");
5106 }
5107
5108 void TParseContext::referenceCheck(const TSourceLoc& loc, const TType& type, const char* op)
5109 {
5110 #ifndef GLSLANG_WEB
5111     if (containsFieldWithBasicType(type, EbtReference))
5112         error(loc, "can't use with reference types", op, "");
5113 #endif
5114 }
5115
5116 void TParseContext::storage16BitAssignmentCheck(const TSourceLoc& loc, const TType& type, const char* op)
5117 {
5118 #ifndef GLSLANG_WEB
5119     if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtFloat16))
5120         requireFloat16Arithmetic(loc, op, "can't use with structs containing float16");
5121
5122     if (type.isArray() && type.getBasicType() == EbtFloat16)
5123         requireFloat16Arithmetic(loc, op, "can't use with arrays containing float16");
5124
5125     if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtInt16))
5126         requireInt16Arithmetic(loc, op, "can't use with structs containing int16");
5127
5128     if (type.isArray() && type.getBasicType() == EbtInt16)
5129         requireInt16Arithmetic(loc, op, "can't use with arrays containing int16");
5130
5131     if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtUint16))
5132         requireInt16Arithmetic(loc, op, "can't use with structs containing uint16");
5133
5134     if (type.isArray() && type.getBasicType() == EbtUint16)
5135         requireInt16Arithmetic(loc, op, "can't use with arrays containing uint16");
5136
5137     if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtInt8))
5138         requireInt8Arithmetic(loc, op, "can't use with structs containing int8");
5139
5140     if (type.isArray() && type.getBasicType() == EbtInt8)
5141         requireInt8Arithmetic(loc, op, "can't use with arrays containing int8");
5142
5143     if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtUint8))
5144         requireInt8Arithmetic(loc, op, "can't use with structs containing uint8");
5145
5146     if (type.isArray() && type.getBasicType() == EbtUint8)
5147         requireInt8Arithmetic(loc, op, "can't use with arrays containing uint8");
5148 #endif
5149 }
5150
5151 void TParseContext::specializationCheck(const TSourceLoc& loc, const TType& type, const char* op)
5152 {
5153     if (type.containsSpecializationSize())
5154         error(loc, "can't use with types containing arrays sized with a specialization constant", op, "");
5155 }
5156
5157 void TParseContext::structTypeCheck(const TSourceLoc& /*loc*/, TPublicType& publicType)
5158 {
5159     const TTypeList& typeList = *publicType.userDef->getStruct();
5160
5161     // fix and check for member storage qualifiers and types that don't belong within a structure
5162     for (unsigned int member = 0; member < typeList.size(); ++member) {
5163         TQualifier& memberQualifier = typeList[member].type->getQualifier();
5164         const TSourceLoc& memberLoc = typeList[member].loc;
5165         if (memberQualifier.isAuxiliary() ||
5166             memberQualifier.isInterpolation() ||
5167             (memberQualifier.storage != EvqTemporary && memberQualifier.storage != EvqGlobal))
5168             error(memberLoc, "cannot use storage or interpolation qualifiers on structure members", typeList[member].type->getFieldName().c_str(), "");
5169         if (memberQualifier.isMemory())
5170             error(memberLoc, "cannot use memory qualifiers on structure members", typeList[member].type->getFieldName().c_str(), "");
5171         if (memberQualifier.hasLayout()) {
5172             error(memberLoc, "cannot use layout qualifiers on structure members", typeList[member].type->getFieldName().c_str(), "");
5173             memberQualifier.clearLayout();
5174         }
5175         if (memberQualifier.invariant)
5176             error(memberLoc, "cannot use invariant qualifier on structure members", typeList[member].type->getFieldName().c_str(), "");
5177     }
5178 }
5179
5180 //
5181 // See if this loop satisfies the limitations for ES 2.0 (version 100) for loops in Appendex A:
5182 //
5183 // "The loop index has type int or float.
5184 //
5185 // "The for statement has the form:
5186 //     for ( init-declaration ; condition ; expression )
5187 //     init-declaration has the form: type-specifier identifier = constant-expression
5188 //     condition has the form:  loop-index relational_operator constant-expression
5189 //         where relational_operator is one of: > >= < <= == or !=
5190 //     expression [sic] has one of the following forms:
5191 //         loop-index++
5192 //         loop-index--
5193 //         loop-index += constant-expression
5194 //         loop-index -= constant-expression
5195 //
5196 // The body is handled in an AST traversal.
5197 //
5198 void TParseContext::inductiveLoopCheck(const TSourceLoc& loc, TIntermNode* init, TIntermLoop* loop)
5199 {
5200 #ifndef GLSLANG_WEB
5201     // loop index init must exist and be a declaration, which shows up in the AST as an aggregate of size 1 of the declaration
5202     bool badInit = false;
5203     if (! init || ! init->getAsAggregate() || init->getAsAggregate()->getSequence().size() != 1)
5204         badInit = true;
5205     TIntermBinary* binaryInit = 0;
5206     if (! badInit) {
5207         // get the declaration assignment
5208         binaryInit = init->getAsAggregate()->getSequence()[0]->getAsBinaryNode();
5209         if (! binaryInit)
5210             badInit = true;
5211     }
5212     if (badInit) {
5213         error(loc, "inductive-loop init-declaration requires the form \"type-specifier loop-index = constant-expression\"", "limitations", "");
5214         return;
5215     }
5216
5217     // loop index must be type int or float
5218     if (! binaryInit->getType().isScalar() || (binaryInit->getBasicType() != EbtInt && binaryInit->getBasicType() != EbtFloat)) {
5219         error(loc, "inductive loop requires a scalar 'int' or 'float' loop index", "limitations", "");
5220         return;
5221     }
5222
5223     // init is the form "loop-index = constant"
5224     if (binaryInit->getOp() != EOpAssign || ! binaryInit->getLeft()->getAsSymbolNode() || ! binaryInit->getRight()->getAsConstantUnion()) {
5225         error(loc, "inductive-loop init-declaration requires the form \"type-specifier loop-index = constant-expression\"", "limitations", "");
5226         return;
5227     }
5228
5229     // get the unique id of the loop index
5230     long long loopIndex = binaryInit->getLeft()->getAsSymbolNode()->getId();
5231     inductiveLoopIds.insert(loopIndex);
5232
5233     // condition's form must be "loop-index relational-operator constant-expression"
5234     bool badCond = ! loop->getTest();
5235     if (! badCond) {
5236         TIntermBinary* binaryCond = loop->getTest()->getAsBinaryNode();
5237         badCond = ! binaryCond;
5238         if (! badCond) {
5239             switch (binaryCond->getOp()) {
5240             case EOpGreaterThan:
5241             case EOpGreaterThanEqual:
5242             case EOpLessThan:
5243             case EOpLessThanEqual:
5244             case EOpEqual:
5245             case EOpNotEqual:
5246                 break;
5247             default:
5248                 badCond = true;
5249             }
5250         }
5251         if (binaryCond && (! binaryCond->getLeft()->getAsSymbolNode() ||
5252                            binaryCond->getLeft()->getAsSymbolNode()->getId() != loopIndex ||
5253                            ! binaryCond->getRight()->getAsConstantUnion()))
5254             badCond = true;
5255     }
5256     if (badCond) {
5257         error(loc, "inductive-loop condition requires the form \"loop-index <comparison-op> constant-expression\"", "limitations", "");
5258         return;
5259     }
5260
5261     // loop-index++
5262     // loop-index--
5263     // loop-index += constant-expression
5264     // loop-index -= constant-expression
5265     bool badTerminal = ! loop->getTerminal();
5266     if (! badTerminal) {
5267         TIntermUnary* unaryTerminal = loop->getTerminal()->getAsUnaryNode();
5268         TIntermBinary* binaryTerminal = loop->getTerminal()->getAsBinaryNode();
5269         if (unaryTerminal || binaryTerminal) {
5270             switch(loop->getTerminal()->getAsOperator()->getOp()) {
5271             case EOpPostDecrement:
5272             case EOpPostIncrement:
5273             case EOpAddAssign:
5274             case EOpSubAssign:
5275                 break;
5276             default:
5277                 badTerminal = true;
5278             }
5279         } else
5280             badTerminal = true;
5281         if (binaryTerminal && (! binaryTerminal->getLeft()->getAsSymbolNode() ||
5282                                binaryTerminal->getLeft()->getAsSymbolNode()->getId() != loopIndex ||
5283                                ! binaryTerminal->getRight()->getAsConstantUnion()))
5284             badTerminal = true;
5285         if (unaryTerminal && (! unaryTerminal->getOperand()->getAsSymbolNode() ||
5286                               unaryTerminal->getOperand()->getAsSymbolNode()->getId() != loopIndex))
5287             badTerminal = true;
5288     }
5289     if (badTerminal) {
5290         error(loc, "inductive-loop termination requires the form \"loop-index++, loop-index--, loop-index += constant-expression, or loop-index -= constant-expression\"", "limitations", "");
5291         return;
5292     }
5293
5294     // the body
5295     inductiveLoopBodyCheck(loop->getBody(), loopIndex, symbolTable);
5296 #endif
5297 }
5298
5299 #ifndef GLSLANG_WEB
5300 // Do limit checks for built-in arrays.
5301 void TParseContext::arrayLimitCheck(const TSourceLoc& loc, const TString& identifier, int size)
5302 {
5303     if (identifier.compare("gl_TexCoord") == 0)
5304         limitCheck(loc, size, "gl_MaxTextureCoords", "gl_TexCoord array size");
5305     else if (identifier.compare("gl_ClipDistance") == 0)
5306         limitCheck(loc, size, "gl_MaxClipDistances", "gl_ClipDistance array size");
5307     else if (identifier.compare("gl_CullDistance") == 0)
5308         limitCheck(loc, size, "gl_MaxCullDistances", "gl_CullDistance array size");
5309     else if (identifier.compare("gl_ClipDistancePerViewNV") == 0)
5310         limitCheck(loc, size, "gl_MaxClipDistances", "gl_ClipDistancePerViewNV array size");
5311     else if (identifier.compare("gl_CullDistancePerViewNV") == 0)
5312         limitCheck(loc, size, "gl_MaxCullDistances", "gl_CullDistancePerViewNV array size");
5313 }
5314 #endif // GLSLANG_WEB
5315
5316 // See if the provided value is less than or equal to the symbol indicated by limit,
5317 // which should be a constant in the symbol table.
5318 void TParseContext::limitCheck(const TSourceLoc& loc, int value, const char* limit, const char* feature)
5319 {
5320     TSymbol* symbol = symbolTable.find(limit);
5321     assert(symbol->getAsVariable());
5322     const TConstUnionArray& constArray = symbol->getAsVariable()->getConstArray();
5323     assert(! constArray.empty());
5324     if (value > constArray[0].getIConst())
5325         error(loc, "must be less than or equal to", feature, "%s (%d)", limit, constArray[0].getIConst());
5326 }
5327
5328 #ifndef GLSLANG_WEB
5329
5330 //
5331 // Do any additional error checking, etc., once we know the parsing is done.
5332 //
5333 void TParseContext::finish()
5334 {
5335     TParseContextBase::finish();
5336
5337     if (parsingBuiltins)
5338         return;
5339
5340     // Check on array indexes for ES 2.0 (version 100) limitations.
5341     for (size_t i = 0; i < needsIndexLimitationChecking.size(); ++i)
5342         constantIndexExpressionCheck(needsIndexLimitationChecking[i]);
5343
5344     // Check for stages that are enabled by extension.
5345     // Can't do this at the beginning, it is chicken and egg to add a stage by
5346     // extension.
5347     // Stage-specific features were correctly tested for already, this is just
5348     // about the stage itself.
5349     switch (language) {
5350     case EShLangGeometry:
5351         if (isEsProfile() && version == 310)
5352             requireExtensions(getCurrentLoc(), Num_AEP_geometry_shader, AEP_geometry_shader, "geometry shaders");
5353         break;
5354     case EShLangTessControl:
5355     case EShLangTessEvaluation:
5356         if (isEsProfile() && version == 310)
5357             requireExtensions(getCurrentLoc(), Num_AEP_tessellation_shader, AEP_tessellation_shader, "tessellation shaders");
5358         else if (!isEsProfile() && version < 400)
5359             requireExtensions(getCurrentLoc(), 1, &E_GL_ARB_tessellation_shader, "tessellation shaders");
5360         break;
5361     case EShLangCompute:
5362         if (!isEsProfile() && version < 430)
5363             requireExtensions(getCurrentLoc(), 1, &E_GL_ARB_compute_shader, "compute shaders");
5364         break;
5365     case EShLangTask:
5366         requireExtensions(getCurrentLoc(), Num_AEP_mesh_shader, AEP_mesh_shader, "task shaders");
5367         break;
5368     case EShLangMesh:
5369         requireExtensions(getCurrentLoc(), Num_AEP_mesh_shader, AEP_mesh_shader, "mesh shaders");
5370         break;
5371     default:
5372         break;
5373     }
5374
5375     // Set default outputs for GL_NV_geometry_shader_passthrough
5376     if (language == EShLangGeometry && extensionTurnedOn(E_SPV_NV_geometry_shader_passthrough)) {
5377         if (intermediate.getOutputPrimitive() == ElgNone) {
5378             switch (intermediate.getInputPrimitive()) {
5379             case ElgPoints:      intermediate.setOutputPrimitive(ElgPoints);    break;
5380             case ElgLines:       intermediate.setOutputPrimitive(ElgLineStrip); break;
5381             case ElgTriangles:   intermediate.setOutputPrimitive(ElgTriangleStrip); break;
5382             default: break;
5383             }
5384         }
5385         if (intermediate.getVertices() == TQualifier::layoutNotSet) {
5386             switch (intermediate.getInputPrimitive()) {
5387             case ElgPoints:      intermediate.setVertices(1); break;
5388             case ElgLines:       intermediate.setVertices(2); break;
5389             case ElgTriangles:   intermediate.setVertices(3); break;
5390             default: break;
5391             }
5392         }
5393     }
5394 }
5395 #endif // GLSLANG_WEB
5396
5397 //
5398 // Layout qualifier stuff.
5399 //
5400
5401 // Put the id's layout qualification into the public type, for qualifiers not having a number set.
5402 // This is before we know any type information for error checking.
5403 void TParseContext::setLayoutQualifier(const TSourceLoc& loc, TPublicType& publicType, TString& id)
5404 {
5405     std::transform(id.begin(), id.end(), id.begin(), ::tolower);
5406
5407     if (id == TQualifier::getLayoutMatrixString(ElmColumnMajor)) {
5408         publicType.qualifier.layoutMatrix = ElmColumnMajor;
5409         return;
5410     }
5411     if (id == TQualifier::getLayoutMatrixString(ElmRowMajor)) {
5412         publicType.qualifier.layoutMatrix = ElmRowMajor;
5413         return;
5414     }
5415     if (id == TQualifier::getLayoutPackingString(ElpPacked)) {
5416         if (spvVersion.spv != 0) {
5417             if (spvVersion.vulkanRelaxed)
5418                 return; // silently ignore qualifier
5419             else
5420                 spvRemoved(loc, "packed");
5421         }
5422         publicType.qualifier.layoutPacking = ElpPacked;
5423         return;
5424     }
5425     if (id == TQualifier::getLayoutPackingString(ElpShared)) {
5426         if (spvVersion.spv != 0) {
5427             if (spvVersion.vulkanRelaxed)
5428                 return; // silently ignore qualifier
5429             else
5430                 spvRemoved(loc, "shared");
5431         }
5432         publicType.qualifier.layoutPacking = ElpShared;
5433         return;
5434     }
5435     if (id == TQualifier::getLayoutPackingString(ElpStd140)) {
5436         publicType.qualifier.layoutPacking = ElpStd140;
5437         return;
5438     }
5439 #ifndef GLSLANG_WEB
5440     if (id == TQualifier::getLayoutPackingString(ElpStd430)) {
5441         requireProfile(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, "std430");
5442         profileRequires(loc, ECoreProfile | ECompatibilityProfile, 430, E_GL_ARB_shader_storage_buffer_object, "std430");
5443         profileRequires(loc, EEsProfile, 310, nullptr, "std430");
5444         publicType.qualifier.layoutPacking = ElpStd430;
5445         return;
5446     }
5447     if (id == TQualifier::getLayoutPackingString(ElpScalar)) {
5448         requireVulkan(loc, "scalar");
5449         requireExtensions(loc, 1, &E_GL_EXT_scalar_block_layout, "scalar block layout");
5450         publicType.qualifier.layoutPacking = ElpScalar;
5451         return;
5452     }
5453     // TODO: compile-time performance: may need to stop doing linear searches
5454     for (TLayoutFormat format = (TLayoutFormat)(ElfNone + 1); format < ElfCount; format = (TLayoutFormat)(format + 1)) {
5455         if (id == TQualifier::getLayoutFormatString(format)) {
5456             if ((format > ElfEsFloatGuard && format < ElfFloatGuard) ||
5457                 (format > ElfEsIntGuard && format < ElfIntGuard) ||
5458                 (format > ElfEsUintGuard && format < ElfCount))
5459                 requireProfile(loc, ENoProfile | ECoreProfile | ECompatibilityProfile, "image load-store format");
5460             profileRequires(loc, ENoProfile | ECoreProfile | ECompatibilityProfile, 420, E_GL_ARB_shader_image_load_store, "image load store");
5461             profileRequires(loc, EEsProfile, 310, E_GL_ARB_shader_image_load_store, "image load store");
5462             publicType.qualifier.layoutFormat = format;
5463             return;
5464         }
5465     }
5466     if (id == "push_constant") {
5467         requireVulkan(loc, "push_constant");
5468         publicType.qualifier.layoutPushConstant = true;
5469         return;
5470     }
5471     if (id == "buffer_reference") {
5472         requireVulkan(loc, "buffer_reference");
5473         requireExtensions(loc, 1, &E_GL_EXT_buffer_reference, "buffer_reference");
5474         publicType.qualifier.layoutBufferReference = true;
5475         intermediate.setUseStorageBuffer();
5476         intermediate.setUsePhysicalStorageBuffer();
5477         return;
5478     }
5479     if (language == EShLangGeometry || language == EShLangTessEvaluation || language == EShLangMesh) {
5480         if (id == TQualifier::getGeometryString(ElgTriangles)) {
5481             publicType.shaderQualifiers.geometry = ElgTriangles;
5482             return;
5483         }
5484         if (language == EShLangGeometry || language == EShLangMesh) {
5485             if (id == TQualifier::getGeometryString(ElgPoints)) {
5486                 publicType.shaderQualifiers.geometry = ElgPoints;
5487                 return;
5488             }
5489             if (id == TQualifier::getGeometryString(ElgLines)) {
5490                 publicType.shaderQualifiers.geometry = ElgLines;
5491                 return;
5492             }
5493             if (language == EShLangGeometry) {
5494                 if (id == TQualifier::getGeometryString(ElgLineStrip)) {
5495                     publicType.shaderQualifiers.geometry = ElgLineStrip;
5496                     return;
5497                 }
5498                 if (id == TQualifier::getGeometryString(ElgLinesAdjacency)) {
5499                     publicType.shaderQualifiers.geometry = ElgLinesAdjacency;
5500                     return;
5501                 }
5502                 if (id == TQualifier::getGeometryString(ElgTrianglesAdjacency)) {
5503                     publicType.shaderQualifiers.geometry = ElgTrianglesAdjacency;
5504                     return;
5505                 }
5506                 if (id == TQualifier::getGeometryString(ElgTriangleStrip)) {
5507                     publicType.shaderQualifiers.geometry = ElgTriangleStrip;
5508                     return;
5509                 }
5510                 if (id == "passthrough") {
5511                     requireExtensions(loc, 1, &E_SPV_NV_geometry_shader_passthrough, "geometry shader passthrough");
5512                     publicType.qualifier.layoutPassthrough = true;
5513                     intermediate.setGeoPassthroughEXT();
5514                     return;
5515                 }
5516             }
5517         } else {
5518             assert(language == EShLangTessEvaluation);
5519
5520             // input primitive
5521             if (id == TQualifier::getGeometryString(ElgTriangles)) {
5522                 publicType.shaderQualifiers.geometry = ElgTriangles;
5523                 return;
5524             }
5525             if (id == TQualifier::getGeometryString(ElgQuads)) {
5526                 publicType.shaderQualifiers.geometry = ElgQuads;
5527                 return;
5528             }
5529             if (id == TQualifier::getGeometryString(ElgIsolines)) {
5530                 publicType.shaderQualifiers.geometry = ElgIsolines;
5531                 return;
5532             }
5533
5534             // vertex spacing
5535             if (id == TQualifier::getVertexSpacingString(EvsEqual)) {
5536                 publicType.shaderQualifiers.spacing = EvsEqual;
5537                 return;
5538             }
5539             if (id == TQualifier::getVertexSpacingString(EvsFractionalEven)) {
5540                 publicType.shaderQualifiers.spacing = EvsFractionalEven;
5541                 return;
5542             }
5543             if (id == TQualifier::getVertexSpacingString(EvsFractionalOdd)) {
5544                 publicType.shaderQualifiers.spacing = EvsFractionalOdd;
5545                 return;
5546             }
5547
5548             // triangle order
5549             if (id == TQualifier::getVertexOrderString(EvoCw)) {
5550                 publicType.shaderQualifiers.order = EvoCw;
5551                 return;
5552             }
5553             if (id == TQualifier::getVertexOrderString(EvoCcw)) {
5554                 publicType.shaderQualifiers.order = EvoCcw;
5555                 return;
5556             }
5557
5558             // point mode
5559             if (id == "point_mode") {
5560                 publicType.shaderQualifiers.pointMode = true;
5561                 return;
5562             }
5563         }
5564     }
5565     if (language == EShLangFragment) {
5566         if (id == "origin_upper_left") {
5567             requireProfile(loc, ECoreProfile | ECompatibilityProfile | ENoProfile, "origin_upper_left");
5568             if (profile == ENoProfile) {
5569                 profileRequires(loc,ECoreProfile | ECompatibilityProfile, 140, E_GL_ARB_fragment_coord_conventions, "origin_upper_left");
5570             }
5571
5572             publicType.shaderQualifiers.originUpperLeft = true;
5573             return;
5574         }
5575         if (id == "pixel_center_integer") {
5576             requireProfile(loc, ECoreProfile | ECompatibilityProfile | ENoProfile, "pixel_center_integer");
5577             if (profile == ENoProfile) {
5578                 profileRequires(loc,ECoreProfile | ECompatibilityProfile, 140, E_GL_ARB_fragment_coord_conventions, "pixel_center_integer");
5579             }
5580             publicType.shaderQualifiers.pixelCenterInteger = true;
5581             return;
5582         }
5583         if (id == "early_fragment_tests") {
5584             profileRequires(loc, ENoProfile | ECoreProfile | ECompatibilityProfile, 420, E_GL_ARB_shader_image_load_store, "early_fragment_tests");
5585             profileRequires(loc, EEsProfile, 310, nullptr, "early_fragment_tests");
5586             publicType.shaderQualifiers.earlyFragmentTests = true;
5587             return;
5588         }
5589         if (id == "early_and_late_fragment_tests_amd") {
5590             profileRequires(loc, ENoProfile | ECoreProfile | ECompatibilityProfile, 420, E_GL_AMD_shader_early_and_late_fragment_tests, "early_and_late_fragment_tests_amd");
5591             profileRequires(loc, EEsProfile, 310, nullptr, "early_and_late_fragment_tests_amd");
5592             publicType.shaderQualifiers.earlyAndLateFragmentTestsAMD = true;
5593             return;
5594         }
5595         if (id == "post_depth_coverage") {
5596             requireExtensions(loc, Num_post_depth_coverageEXTs, post_depth_coverageEXTs, "post depth coverage");
5597             if (extensionTurnedOn(E_GL_ARB_post_depth_coverage)) {
5598                 publicType.shaderQualifiers.earlyFragmentTests = true;
5599             }
5600             publicType.shaderQualifiers.postDepthCoverage = true;
5601             return;
5602         }
5603         for (TLayoutDepth depth = (TLayoutDepth)(EldNone + 1); depth < EldCount; depth = (TLayoutDepth)(depth+1)) {
5604             if (id == TQualifier::getLayoutDepthString(depth)) {
5605                 requireProfile(loc, ECoreProfile | ECompatibilityProfile, "depth layout qualifier");
5606                 profileRequires(loc, ECoreProfile | ECompatibilityProfile, 420, nullptr, "depth layout qualifier");
5607                 publicType.shaderQualifiers.layoutDepth = depth;
5608                 return;
5609             }
5610         }
5611         for (TLayoutStencil stencil = (TLayoutStencil)(ElsNone + 1); stencil < ElsCount; stencil = (TLayoutStencil)(stencil+1)) {
5612             if (id == TQualifier::getLayoutStencilString(stencil)) {
5613                 requireProfile(loc, ECoreProfile | ECompatibilityProfile, "stencil layout qualifier");
5614                 profileRequires(loc, ECoreProfile | ECompatibilityProfile, 420, nullptr, "stencil layout qualifier");
5615                 publicType.shaderQualifiers.layoutStencil = stencil;
5616                 return;
5617             }
5618         }
5619         for (TInterlockOrdering order = (TInterlockOrdering)(EioNone + 1); order < EioCount; order = (TInterlockOrdering)(order+1)) {
5620             if (id == TQualifier::getInterlockOrderingString(order)) {
5621                 requireProfile(loc, ECoreProfile | ECompatibilityProfile, "fragment shader interlock layout qualifier");
5622                 profileRequires(loc, ECoreProfile | ECompatibilityProfile, 450, nullptr, "fragment shader interlock layout qualifier");
5623                 requireExtensions(loc, 1, &E_GL_ARB_fragment_shader_interlock, TQualifier::getInterlockOrderingString(order));
5624                 if (order == EioShadingRateInterlockOrdered || order == EioShadingRateInterlockUnordered)
5625                     requireExtensions(loc, 1, &E_GL_NV_shading_rate_image, TQualifier::getInterlockOrderingString(order));
5626                 publicType.shaderQualifiers.interlockOrdering = order;
5627                 return;
5628             }
5629         }
5630         if (id.compare(0, 13, "blend_support") == 0) {
5631             bool found = false;
5632             for (TBlendEquationShift be = (TBlendEquationShift)0; be < EBlendCount; be = (TBlendEquationShift)(be + 1)) {
5633                 if (id == TQualifier::getBlendEquationString(be)) {
5634                     profileRequires(loc, EEsProfile, 320, E_GL_KHR_blend_equation_advanced, "blend equation");
5635                     profileRequires(loc, ~EEsProfile, 0, E_GL_KHR_blend_equation_advanced, "blend equation");
5636                     intermediate.addBlendEquation(be);
5637                     publicType.shaderQualifiers.blendEquation = true;
5638                     found = true;
5639                     break;
5640                 }
5641             }
5642             if (! found)
5643                 error(loc, "unknown blend equation", "blend_support", "");
5644             return;
5645         }
5646         if (id == "override_coverage") {
5647             requireExtensions(loc, 1, &E_GL_NV_sample_mask_override_coverage, "sample mask override coverage");
5648             publicType.shaderQualifiers.layoutOverrideCoverage = true;
5649             return;
5650         }
5651     }
5652     if (language == EShLangVertex ||
5653         language == EShLangTessControl ||
5654         language == EShLangTessEvaluation ||
5655         language == EShLangGeometry ) {
5656         if (id == "viewport_relative") {
5657             requireExtensions(loc, 1, &E_GL_NV_viewport_array2, "view port array2");
5658             publicType.qualifier.layoutViewportRelative = true;
5659             return;
5660         }
5661     } else {
5662         if (language == EShLangRayGen || language == EShLangIntersect ||
5663         language == EShLangAnyHit || language == EShLangClosestHit ||
5664         language == EShLangMiss || language == EShLangCallable) {
5665             if (id == "shaderrecordnv" || id == "shaderrecordext") {
5666                 if (id == "shaderrecordnv") {
5667                     requireExtensions(loc, 1, &E_GL_NV_ray_tracing, "shader record NV");
5668                 } else {
5669                     requireExtensions(loc, 1, &E_GL_EXT_ray_tracing, "shader record EXT");
5670                 }
5671                 publicType.qualifier.layoutShaderRecord = true;
5672                 return;
5673             }
5674
5675         }
5676     }
5677     if (language == EShLangCompute) {
5678         if (id.compare(0, 17, "derivative_group_") == 0) {
5679             requireExtensions(loc, 1, &E_GL_NV_compute_shader_derivatives, "compute shader derivatives");
5680             if (id == "derivative_group_quadsnv") {
5681                 publicType.shaderQualifiers.layoutDerivativeGroupQuads = true;
5682                 return;
5683             } else if (id == "derivative_group_linearnv") {
5684                 publicType.shaderQualifiers.layoutDerivativeGroupLinear = true;
5685                 return;
5686             }
5687         }
5688     }
5689
5690     if (id == "primitive_culling") {
5691         requireExtensions(loc, 1, &E_GL_EXT_ray_flags_primitive_culling, "primitive culling");
5692         publicType.shaderQualifiers.layoutPrimitiveCulling = true;
5693         return;
5694     }
5695 #endif
5696
5697     error(loc, "unrecognized layout identifier, or qualifier requires assignment (e.g., binding = 4)", id.c_str(), "");
5698 }
5699
5700 // Put the id's layout qualifier value into the public type, for qualifiers having a number set.
5701 // This is before we know any type information for error checking.
5702 void TParseContext::setLayoutQualifier(const TSourceLoc& loc, TPublicType& publicType, TString& id, const TIntermTyped* node)
5703 {
5704     const char* feature = "layout-id value";
5705     const char* nonLiteralFeature = "non-literal layout-id value";
5706
5707     integerCheck(node, feature);
5708     const TIntermConstantUnion* constUnion = node->getAsConstantUnion();
5709     int value;
5710     bool nonLiteral = false;
5711     if (constUnion) {
5712         value = constUnion->getConstArray()[0].getIConst();
5713         if (! constUnion->isLiteral()) {
5714             requireProfile(loc, ECoreProfile | ECompatibilityProfile, nonLiteralFeature);
5715             profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, E_GL_ARB_enhanced_layouts, nonLiteralFeature);
5716         }
5717     } else {
5718         // grammar should have give out the error message
5719         value = 0;
5720         nonLiteral = true;
5721     }
5722
5723     if (value < 0) {
5724         error(loc, "cannot be negative", feature, "");
5725         return;
5726     }
5727
5728     std::transform(id.begin(), id.end(), id.begin(), ::tolower);
5729
5730     if (id == "offset") {
5731         // "offset" can be for either
5732         //  - uniform offsets
5733         //  - atomic_uint offsets
5734         const char* feature = "offset";
5735         if (spvVersion.spv == 0) {
5736             requireProfile(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, feature);
5737             const char* exts[2] = { E_GL_ARB_enhanced_layouts, E_GL_ARB_shader_atomic_counters };
5738             profileRequires(loc, ECoreProfile | ECompatibilityProfile, 420, 2, exts, feature);
5739             profileRequires(loc, EEsProfile, 310, nullptr, feature);
5740         }
5741         publicType.qualifier.layoutOffset = value;
5742         publicType.qualifier.explicitOffset = true;
5743         if (nonLiteral)
5744             error(loc, "needs a literal integer", "offset", "");
5745         return;
5746     } else if (id == "align") {
5747         const char* feature = "uniform buffer-member align";
5748         if (spvVersion.spv == 0) {
5749             requireProfile(loc, ECoreProfile | ECompatibilityProfile, feature);
5750             profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, E_GL_ARB_enhanced_layouts, feature);
5751         }
5752         // "The specified alignment must be a power of 2, or a compile-time error results."
5753         if (! IsPow2(value))
5754             error(loc, "must be a power of 2", "align", "");
5755         else
5756             publicType.qualifier.layoutAlign = value;
5757         if (nonLiteral)
5758             error(loc, "needs a literal integer", "align", "");
5759         return;
5760     } else if (id == "location") {
5761         profileRequires(loc, EEsProfile, 300, nullptr, "location");
5762         const char* exts[2] = { E_GL_ARB_separate_shader_objects, E_GL_ARB_explicit_attrib_location };
5763         // GL_ARB_explicit_uniform_location requires 330 or GL_ARB_explicit_attrib_location we do not need to add it here
5764         profileRequires(loc, ~EEsProfile, 330, 2, exts, "location");
5765         if ((unsigned int)value >= TQualifier::layoutLocationEnd)
5766             error(loc, "location is too large", id.c_str(), "");
5767         else
5768             publicType.qualifier.layoutLocation = value;
5769         if (nonLiteral)
5770             error(loc, "needs a literal integer", "location", "");
5771         return;
5772     } else if (id == "set") {
5773         if ((unsigned int)value >= TQualifier::layoutSetEnd)
5774             error(loc, "set is too large", id.c_str(), "");
5775         else
5776             publicType.qualifier.layoutSet = value;
5777         if (value != 0)
5778             requireVulkan(loc, "descriptor set");
5779         if (nonLiteral)
5780             error(loc, "needs a literal integer", "set", "");
5781         return;
5782     } else if (id == "binding") {
5783 #ifndef GLSLANG_WEB
5784         profileRequires(loc, ~EEsProfile, 420, E_GL_ARB_shading_language_420pack, "binding");
5785         profileRequires(loc, EEsProfile, 310, nullptr, "binding");
5786 #endif
5787         if ((unsigned int)value >= TQualifier::layoutBindingEnd)
5788             error(loc, "binding is too large", id.c_str(), "");
5789         else
5790             publicType.qualifier.layoutBinding = value;
5791         if (nonLiteral)
5792             error(loc, "needs a literal integer", "binding", "");
5793         return;
5794     }
5795     if (id == "constant_id") {
5796         requireSpv(loc, "constant_id");
5797         if (value >= (int)TQualifier::layoutSpecConstantIdEnd) {
5798             error(loc, "specialization-constant id is too large", id.c_str(), "");
5799         } else {
5800             publicType.qualifier.layoutSpecConstantId = value;
5801             publicType.qualifier.specConstant = true;
5802             if (! intermediate.addUsedConstantId(value))
5803                 error(loc, "specialization-constant id already used", id.c_str(), "");
5804         }
5805         if (nonLiteral)
5806             error(loc, "needs a literal integer", "constant_id", "");
5807         return;
5808     }
5809 #ifndef GLSLANG_WEB
5810     if (id == "component") {
5811         requireProfile(loc, ECoreProfile | ECompatibilityProfile, "component");
5812         profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, E_GL_ARB_enhanced_layouts, "component");
5813         if ((unsigned)value >= TQualifier::layoutComponentEnd)
5814             error(loc, "component is too large", id.c_str(), "");
5815         else
5816             publicType.qualifier.layoutComponent = value;
5817         if (nonLiteral)
5818             error(loc, "needs a literal integer", "component", "");
5819         return;
5820     }
5821     if (id.compare(0, 4, "xfb_") == 0) {
5822         // "Any shader making any static use (after preprocessing) of any of these
5823         // *xfb_* qualifiers will cause the shader to be in a transform feedback
5824         // capturing mode and hence responsible for describing the transform feedback
5825         // setup."
5826         intermediate.setXfbMode();
5827         const char* feature = "transform feedback qualifier";
5828         requireStage(loc, (EShLanguageMask)(EShLangVertexMask | EShLangGeometryMask | EShLangTessControlMask | EShLangTessEvaluationMask), feature);
5829         requireProfile(loc, ECoreProfile | ECompatibilityProfile, feature);
5830         profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, E_GL_ARB_enhanced_layouts, feature);
5831         if (id == "xfb_buffer") {
5832             // "It is a compile-time error to specify an *xfb_buffer* that is greater than
5833             // the implementation-dependent constant gl_MaxTransformFeedbackBuffers."
5834             if (value >= resources.maxTransformFeedbackBuffers)
5835                 error(loc, "buffer is too large:", id.c_str(), "gl_MaxTransformFeedbackBuffers is %d", resources.maxTransformFeedbackBuffers);
5836             if (value >= (int)TQualifier::layoutXfbBufferEnd)
5837                 error(loc, "buffer is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbBufferEnd-1);
5838             else
5839                 publicType.qualifier.layoutXfbBuffer = value;
5840             if (nonLiteral)
5841                 error(loc, "needs a literal integer", "xfb_buffer", "");
5842             return;
5843         } else if (id == "xfb_offset") {
5844             if (value >= (int)TQualifier::layoutXfbOffsetEnd)
5845                 error(loc, "offset is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbOffsetEnd-1);
5846             else
5847                 publicType.qualifier.layoutXfbOffset = value;
5848             if (nonLiteral)
5849                 error(loc, "needs a literal integer", "xfb_offset", "");
5850             return;
5851         } else if (id == "xfb_stride") {
5852             // "The resulting stride (implicit or explicit), when divided by 4, must be less than or equal to the
5853             // implementation-dependent constant gl_MaxTransformFeedbackInterleavedComponents."
5854             if (value > 4 * resources.maxTransformFeedbackInterleavedComponents) {
5855                 error(loc, "1/4 stride is too large:", id.c_str(), "gl_MaxTransformFeedbackInterleavedComponents is %d",
5856                     resources.maxTransformFeedbackInterleavedComponents);
5857             }
5858             if (value >= (int)TQualifier::layoutXfbStrideEnd)
5859                 error(loc, "stride is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbStrideEnd-1);
5860             else
5861                 publicType.qualifier.layoutXfbStride = value;
5862             if (nonLiteral)
5863                 error(loc, "needs a literal integer", "xfb_stride", "");
5864             return;
5865         }
5866     }
5867     if (id == "input_attachment_index") {
5868         requireVulkan(loc, "input_attachment_index");
5869         if (value >= (int)TQualifier::layoutAttachmentEnd)
5870             error(loc, "attachment index is too large", id.c_str(), "");
5871         else
5872             publicType.qualifier.layoutAttachment = value;
5873         if (nonLiteral)
5874             error(loc, "needs a literal integer", "input_attachment_index", "");
5875         return;
5876     }
5877     if (id == "num_views") {
5878         requireExtensions(loc, Num_OVR_multiview_EXTs, OVR_multiview_EXTs, "num_views");
5879         publicType.shaderQualifiers.numViews = value;
5880         if (nonLiteral)
5881             error(loc, "needs a literal integer", "num_views", "");
5882         return;
5883     }
5884     if (language == EShLangVertex ||
5885         language == EShLangTessControl ||
5886         language == EShLangTessEvaluation ||
5887         language == EShLangGeometry) {
5888         if (id == "secondary_view_offset") {
5889             requireExtensions(loc, 1, &E_GL_NV_stereo_view_rendering, "stereo view rendering");
5890             publicType.qualifier.layoutSecondaryViewportRelativeOffset = value;
5891             if (nonLiteral)
5892                 error(loc, "needs a literal integer", "secondary_view_offset", "");
5893             return;
5894         }
5895     }
5896
5897     if (id == "buffer_reference_align") {
5898         requireExtensions(loc, 1, &E_GL_EXT_buffer_reference, "buffer_reference_align");
5899         if (! IsPow2(value))
5900             error(loc, "must be a power of 2", "buffer_reference_align", "");
5901         else
5902             publicType.qualifier.layoutBufferReferenceAlign = IntLog2(value);
5903         if (nonLiteral)
5904             error(loc, "needs a literal integer", "buffer_reference_align", "");
5905         return;
5906     }
5907 #endif
5908
5909     switch (language) {
5910 #ifndef GLSLANG_WEB
5911     case EShLangTessControl:
5912         if (id == "vertices") {
5913             if (value == 0)
5914                 error(loc, "must be greater than 0", "vertices", "");
5915             else
5916                 publicType.shaderQualifiers.vertices = value;
5917             if (nonLiteral)
5918                 error(loc, "needs a literal integer", "vertices", "");
5919             return;
5920         }
5921         break;
5922
5923     case EShLangGeometry:
5924         if (id == "invocations") {
5925             profileRequires(loc, ECompatibilityProfile | ECoreProfile, 400, nullptr, "invocations");
5926             if (value == 0)
5927                 error(loc, "must be at least 1", "invocations", "");
5928             else
5929                 publicType.shaderQualifiers.invocations = value;
5930             if (nonLiteral)
5931                 error(loc, "needs a literal integer", "invocations", "");
5932             return;
5933         }
5934         if (id == "max_vertices") {
5935             publicType.shaderQualifiers.vertices = value;
5936             if (value > resources.maxGeometryOutputVertices)
5937                 error(loc, "too large, must be less than gl_MaxGeometryOutputVertices", "max_vertices", "");
5938             if (nonLiteral)
5939                 error(loc, "needs a literal integer", "max_vertices", "");
5940             return;
5941         }
5942         if (id == "stream") {
5943             requireProfile(loc, ~EEsProfile, "selecting output stream");
5944             publicType.qualifier.layoutStream = value;
5945             if (value > 0)
5946                 intermediate.setMultiStream();
5947             if (nonLiteral)
5948                 error(loc, "needs a literal integer", "stream", "");
5949             return;
5950         }
5951         break;
5952
5953     case EShLangFragment:
5954         if (id == "index") {
5955             requireProfile(loc, ECompatibilityProfile | ECoreProfile | EEsProfile, "index layout qualifier on fragment output");
5956             const char* exts[2] = { E_GL_ARB_separate_shader_objects, E_GL_ARB_explicit_attrib_location };
5957             profileRequires(loc, ECompatibilityProfile | ECoreProfile, 330, 2, exts, "index layout qualifier on fragment output");
5958             profileRequires(loc, EEsProfile ,310, E_GL_EXT_blend_func_extended, "index layout qualifier on fragment output");
5959             // "It is also a compile-time error if a fragment shader sets a layout index to less than 0 or greater than 1."
5960             if (value < 0 || value > 1) {
5961                 value = 0;
5962                 error(loc, "value must be 0 or 1", "index", "");
5963             }
5964
5965             publicType.qualifier.layoutIndex = value;
5966             if (nonLiteral)
5967                 error(loc, "needs a literal integer", "index", "");
5968             return;
5969         }
5970         break;
5971
5972     case EShLangMesh:
5973         if (id == "max_vertices") {
5974             requireExtensions(loc, Num_AEP_mesh_shader, AEP_mesh_shader, "max_vertices");
5975             publicType.shaderQualifiers.vertices = value;
5976             if (value > resources.maxMeshOutputVerticesNV)
5977                 error(loc, "too large, must be less than gl_MaxMeshOutputVerticesNV", "max_vertices", "");
5978             if (nonLiteral)
5979                 error(loc, "needs a literal integer", "max_vertices", "");
5980             return;
5981         }
5982         if (id == "max_primitives") {
5983             requireExtensions(loc, Num_AEP_mesh_shader, AEP_mesh_shader, "max_primitives");
5984             publicType.shaderQualifiers.primitives = value;
5985             if (value > resources.maxMeshOutputPrimitivesNV)
5986                 error(loc, "too large, must be less than gl_MaxMeshOutputPrimitivesNV", "max_primitives", "");
5987             if (nonLiteral)
5988                 error(loc, "needs a literal integer", "max_primitives", "");
5989             return;
5990         }
5991         // Fall through
5992
5993     case EShLangTask:
5994         // Fall through
5995 #endif
5996     case EShLangCompute:
5997         if (id.compare(0, 11, "local_size_") == 0) {
5998 #ifndef GLSLANG_WEB
5999             if (language == EShLangMesh || language == EShLangTask) {
6000                 requireExtensions(loc, Num_AEP_mesh_shader, AEP_mesh_shader, "gl_WorkGroupSize");
6001             } else {
6002                 profileRequires(loc, EEsProfile, 310, 0, "gl_WorkGroupSize");
6003                 profileRequires(loc, ~EEsProfile, 430, E_GL_ARB_compute_shader, "gl_WorkGroupSize");
6004             }
6005 #endif
6006             if (nonLiteral)
6007                 error(loc, "needs a literal integer", "local_size", "");
6008             if (id.size() == 12 && value == 0) {
6009                 error(loc, "must be at least 1", id.c_str(), "");
6010                 return;
6011             }
6012             if (id == "local_size_x") {
6013                 publicType.shaderQualifiers.localSize[0] = value;
6014                 publicType.shaderQualifiers.localSizeNotDefault[0] = true;
6015                 return;
6016             }
6017             if (id == "local_size_y") {
6018                 publicType.shaderQualifiers.localSize[1] = value;
6019                 publicType.shaderQualifiers.localSizeNotDefault[1] = true;
6020                 return;
6021             }
6022             if (id == "local_size_z") {
6023                 publicType.shaderQualifiers.localSize[2] = value;
6024                 publicType.shaderQualifiers.localSizeNotDefault[2] = true;
6025                 return;
6026             }
6027             if (spvVersion.spv != 0) {
6028                 if (id == "local_size_x_id") {
6029                     publicType.shaderQualifiers.localSizeSpecId[0] = value;
6030                     return;
6031                 }
6032                 if (id == "local_size_y_id") {
6033                     publicType.shaderQualifiers.localSizeSpecId[1] = value;
6034                     return;
6035                 }
6036                 if (id == "local_size_z_id") {
6037                     publicType.shaderQualifiers.localSizeSpecId[2] = value;
6038                     return;
6039                 }
6040             }
6041         }
6042         break;
6043
6044     default:
6045         break;
6046     }
6047
6048     error(loc, "there is no such layout identifier for this stage taking an assigned value", id.c_str(), "");
6049 }
6050
6051 // Merge any layout qualifier information from src into dst, leaving everything else in dst alone
6052 //
6053 // "More than one layout qualifier may appear in a single declaration.
6054 // Additionally, the same layout-qualifier-name can occur multiple times
6055 // within a layout qualifier or across multiple layout qualifiers in the
6056 // same declaration. When the same layout-qualifier-name occurs
6057 // multiple times, in a single declaration, the last occurrence overrides
6058 // the former occurrence(s).  Further, if such a layout-qualifier-name
6059 // will effect subsequent declarations or other observable behavior, it
6060 // is only the last occurrence that will have any effect, behaving as if
6061 // the earlier occurrence(s) within the declaration are not present.
6062 // This is also true for overriding layout-qualifier-names, where one
6063 // overrides the other (e.g., row_major vs. column_major); only the last
6064 // occurrence has any effect."
6065 void TParseContext::mergeObjectLayoutQualifiers(TQualifier& dst, const TQualifier& src, bool inheritOnly)
6066 {
6067     if (src.hasMatrix())
6068         dst.layoutMatrix = src.layoutMatrix;
6069     if (src.hasPacking())
6070         dst.layoutPacking = src.layoutPacking;
6071
6072 #ifndef GLSLANG_WEB
6073     if (src.hasStream())
6074         dst.layoutStream = src.layoutStream;
6075     if (src.hasFormat())
6076         dst.layoutFormat = src.layoutFormat;
6077     if (src.hasXfbBuffer())
6078         dst.layoutXfbBuffer = src.layoutXfbBuffer;
6079     if (src.hasBufferReferenceAlign())
6080         dst.layoutBufferReferenceAlign = src.layoutBufferReferenceAlign;
6081 #endif
6082
6083     if (src.hasAlign())
6084         dst.layoutAlign = src.layoutAlign;
6085
6086     if (! inheritOnly) {
6087         if (src.hasLocation())
6088             dst.layoutLocation = src.layoutLocation;
6089         if (src.hasOffset())
6090             dst.layoutOffset = src.layoutOffset;
6091         if (src.hasSet())
6092             dst.layoutSet = src.layoutSet;
6093         if (src.layoutBinding != TQualifier::layoutBindingEnd)
6094             dst.layoutBinding = src.layoutBinding;
6095
6096         if (src.hasSpecConstantId())
6097             dst.layoutSpecConstantId = src.layoutSpecConstantId;
6098
6099 #ifndef GLSLANG_WEB
6100         if (src.hasComponent())
6101             dst.layoutComponent = src.layoutComponent;
6102         if (src.hasIndex())
6103             dst.layoutIndex = src.layoutIndex;
6104         if (src.hasXfbStride())
6105             dst.layoutXfbStride = src.layoutXfbStride;
6106         if (src.hasXfbOffset())
6107             dst.layoutXfbOffset = src.layoutXfbOffset;
6108         if (src.hasAttachment())
6109             dst.layoutAttachment = src.layoutAttachment;
6110         if (src.layoutPushConstant)
6111             dst.layoutPushConstant = true;
6112
6113         if (src.layoutBufferReference)
6114             dst.layoutBufferReference = true;
6115
6116         if (src.layoutPassthrough)
6117             dst.layoutPassthrough = true;
6118         if (src.layoutViewportRelative)
6119             dst.layoutViewportRelative = true;
6120         if (src.layoutSecondaryViewportRelativeOffset != -2048)
6121             dst.layoutSecondaryViewportRelativeOffset = src.layoutSecondaryViewportRelativeOffset;
6122         if (src.layoutShaderRecord)
6123             dst.layoutShaderRecord = true;
6124         if (src.pervertexNV)
6125             dst.pervertexNV = true;
6126         if (src.pervertexEXT)
6127             dst.pervertexEXT = true;
6128 #endif
6129     }
6130 }
6131
6132 // Do error layout error checking given a full variable/block declaration.
6133 void TParseContext::layoutObjectCheck(const TSourceLoc& loc, const TSymbol& symbol)
6134 {
6135     const TType& type = symbol.getType();
6136     const TQualifier& qualifier = type.getQualifier();
6137
6138     // first, cross check WRT to just the type
6139     layoutTypeCheck(loc, type);
6140
6141     // now, any remaining error checking based on the object itself
6142
6143     if (qualifier.hasAnyLocation()) {
6144         switch (qualifier.storage) {
6145         case EvqUniform:
6146         case EvqBuffer:
6147             if (symbol.getAsVariable() == nullptr)
6148                 error(loc, "can only be used on variable declaration", "location", "");
6149             break;
6150         default:
6151             break;
6152         }
6153     }
6154
6155     // user-variable location check, which are required for SPIR-V in/out:
6156     //  - variables have it directly,
6157     //  - blocks have it on each member (already enforced), so check first one
6158     if (spvVersion.spv > 0 && !parsingBuiltins && qualifier.builtIn == EbvNone &&
6159         !qualifier.hasLocation() && !intermediate.getAutoMapLocations()) {
6160
6161         switch (qualifier.storage) {
6162         case EvqVaryingIn:
6163         case EvqVaryingOut:
6164             if (!type.getQualifier().isTaskMemory() &&
6165 #ifndef GLSLANG_WEB
6166                 !type.getQualifier().hasSprivDecorate() &&
6167 #endif
6168                 (type.getBasicType() != EbtBlock ||
6169                  (!(*type.getStruct())[0].type->getQualifier().hasLocation() &&
6170                    (*type.getStruct())[0].type->getQualifier().builtIn == EbvNone)))
6171                 error(loc, "SPIR-V requires location for user input/output", "location", "");
6172             break;
6173         default:
6174             break;
6175         }
6176     }
6177
6178     // Check packing and matrix
6179     if (qualifier.hasUniformLayout()) {
6180         switch (qualifier.storage) {
6181         case EvqUniform:
6182         case EvqBuffer:
6183             if (type.getBasicType() != EbtBlock) {
6184                 if (qualifier.hasMatrix())
6185                     error(loc, "cannot specify matrix layout on a variable declaration", "layout", "");
6186                 if (qualifier.hasPacking())
6187                     error(loc, "cannot specify packing on a variable declaration", "layout", "");
6188                 // "The offset qualifier can only be used on block members of blocks..."
6189                 if (qualifier.hasOffset() && !type.isAtomic())
6190                     error(loc, "cannot specify on a variable declaration", "offset", "");
6191                 // "The align qualifier can only be used on blocks or block members..."
6192                 if (qualifier.hasAlign())
6193                     error(loc, "cannot specify on a variable declaration", "align", "");
6194                 if (qualifier.isPushConstant())
6195                     error(loc, "can only specify on a uniform block", "push_constant", "");
6196                 if (qualifier.isShaderRecord())
6197                     error(loc, "can only specify on a buffer block", "shaderRecordNV", "");
6198                 if (qualifier.hasLocation() && type.isAtomic())
6199                     error(loc, "cannot specify on atomic counter", "location", "");
6200             }
6201             break;
6202         default:
6203             // these were already filtered by layoutTypeCheck() (or its callees)
6204             break;
6205         }
6206     }
6207 }
6208
6209 // "For some blocks declared as arrays, the location can only be applied at the block level:
6210 // When a block is declared as an array where additional locations are needed for each member
6211 // for each block array element, it is a compile-time error to specify locations on the block
6212 // members.  That is, when locations would be under specified by applying them on block members,
6213 // they are not allowed on block members.  For arrayed interfaces (those generally having an
6214 // extra level of arrayness due to interface expansion), the outer array is stripped before
6215 // applying this rule."
6216 void TParseContext::layoutMemberLocationArrayCheck(const TSourceLoc& loc, bool memberWithLocation,
6217     TArraySizes* arraySizes)
6218 {
6219     if (memberWithLocation && arraySizes != nullptr) {
6220         if (arraySizes->getNumDims() > (currentBlockQualifier.isArrayedIo(language) ? 1 : 0))
6221             error(loc, "cannot use in a block array where new locations are needed for each block element",
6222                        "location", "");
6223     }
6224 }
6225
6226 // Do layout error checking with respect to a type.
6227 void TParseContext::layoutTypeCheck(const TSourceLoc& loc, const TType& type)
6228 {
6229 #ifndef GLSLANG_WEB
6230     if (extensionTurnedOn(E_GL_EXT_spirv_intrinsics))
6231         return; // Skip any check if GL_EXT_spirv_intrinsics is turned on
6232 #endif
6233
6234     const TQualifier& qualifier = type.getQualifier();
6235
6236     // first, intra-layout qualifier-only error checking
6237     layoutQualifierCheck(loc, qualifier);
6238
6239     // now, error checking combining type and qualifier
6240
6241     if (qualifier.hasAnyLocation()) {
6242         if (qualifier.hasLocation()) {
6243             if (qualifier.storage == EvqVaryingOut && language == EShLangFragment) {
6244                 if (qualifier.layoutLocation >= (unsigned int)resources.maxDrawBuffers)
6245                     error(loc, "too large for fragment output", "location", "");
6246             }
6247         }
6248         if (qualifier.hasComponent()) {
6249             // "It is a compile-time error if this sequence of components gets larger than 3."
6250             if (qualifier.layoutComponent + type.getVectorSize() * (type.getBasicType() == EbtDouble ? 2 : 1) > 4)
6251                 error(loc, "type overflows the available 4 components", "component", "");
6252
6253             // "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."
6254             if (type.isMatrix() || type.getBasicType() == EbtBlock || type.getBasicType() == EbtStruct)
6255                 error(loc, "cannot apply to a matrix, structure, or block", "component", "");
6256
6257             // " It is a compile-time error to use component 1 or 3 as the beginning of a double or dvec2."
6258             if (type.getBasicType() == EbtDouble)
6259                 if (qualifier.layoutComponent & 1)
6260                     error(loc, "doubles cannot start on an odd-numbered component", "component", "");
6261         }
6262
6263         switch (qualifier.storage) {
6264         case EvqVaryingIn:
6265         case EvqVaryingOut:
6266             if (type.getBasicType() == EbtBlock)
6267                 profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, E_GL_ARB_enhanced_layouts, "location qualifier on in/out block");
6268             if (type.getQualifier().isTaskMemory())
6269                 error(loc, "cannot apply to taskNV in/out blocks", "location", "");
6270             break;
6271         case EvqUniform:
6272         case EvqBuffer:
6273             if (type.getBasicType() == EbtBlock)
6274                 error(loc, "cannot apply to uniform or buffer block", "location", "");
6275             break;
6276         case EvqtaskPayloadSharedEXT:
6277             error(loc, "cannot apply to taskPayloadSharedEXT", "location", "");
6278             break;
6279 #ifndef GLSLANG_WEB
6280         case EvqPayload:
6281         case EvqPayloadIn:
6282         case EvqHitAttr:
6283         case EvqCallableData:
6284         case EvqCallableDataIn:
6285             break;
6286 #endif
6287         default:
6288             error(loc, "can only apply to uniform, buffer, in, or out storage qualifiers", "location", "");
6289             break;
6290         }
6291
6292         bool typeCollision;
6293         int repeated = intermediate.addUsedLocation(qualifier, type, typeCollision);
6294         if (repeated >= 0 && ! typeCollision)
6295             error(loc, "overlapping use of location", "location", "%d", repeated);
6296         // "fragment-shader outputs ... if two variables are placed within the same
6297         // location, they must have the same underlying type (floating-point or integer)"
6298         if (typeCollision && language == EShLangFragment && qualifier.isPipeOutput())
6299             error(loc, "fragment outputs sharing the same location must be the same basic type", "location", "%d", repeated);
6300     }
6301
6302 #ifndef GLSLANG_WEB
6303     if (qualifier.hasXfbOffset() && qualifier.hasXfbBuffer()) {
6304         if (type.isUnsizedArray()) {
6305             error(loc, "unsized array", "xfb_offset", "in buffer %d", qualifier.layoutXfbBuffer);
6306         } else {
6307             int repeated = intermediate.addXfbBufferOffset(type);
6308             if (repeated >= 0)
6309                 error(loc, "overlapping offsets at", "xfb_offset", "offset %d in buffer %d", repeated, qualifier.layoutXfbBuffer);
6310         }
6311
6312         // "The offset must be a multiple of the size of the first component of the first
6313         // qualified variable or block member, or a compile-time error results. Further, if applied to an aggregate
6314         // containing a double or 64-bit integer, the offset must also be a multiple of 8..."
6315         if ((type.containsBasicType(EbtDouble) || type.containsBasicType(EbtInt64) || type.containsBasicType(EbtUint64)) &&
6316             ! IsMultipleOfPow2(qualifier.layoutXfbOffset, 8))
6317             error(loc, "type contains double or 64-bit integer; xfb_offset must be a multiple of 8", "xfb_offset", "");
6318         else if ((type.containsBasicType(EbtBool) || type.containsBasicType(EbtFloat) ||
6319                   type.containsBasicType(EbtInt) || type.containsBasicType(EbtUint)) &&
6320                  ! IsMultipleOfPow2(qualifier.layoutXfbOffset, 4))
6321             error(loc, "must be a multiple of size of first component", "xfb_offset", "");
6322         // ..., if applied to an aggregate containing a half float or 16-bit integer, the offset must also be a multiple of 2..."
6323         else if ((type.contains16BitFloat() || type.containsBasicType(EbtInt16) || type.containsBasicType(EbtUint16)) &&
6324                  !IsMultipleOfPow2(qualifier.layoutXfbOffset, 2))
6325             error(loc, "type contains half float or 16-bit integer; xfb_offset must be a multiple of 2", "xfb_offset", "");
6326     }
6327     if (qualifier.hasXfbStride() && qualifier.hasXfbBuffer()) {
6328         if (! intermediate.setXfbBufferStride(qualifier.layoutXfbBuffer, qualifier.layoutXfbStride))
6329             error(loc, "all stride settings must match for xfb buffer", "xfb_stride", "%d", qualifier.layoutXfbBuffer);
6330     }
6331 #endif
6332
6333     if (qualifier.hasBinding()) {
6334         // Binding checking, from the spec:
6335         //
6336         // "If the binding point for any uniform or shader storage block instance is less than zero, or greater than or
6337         // equal to the implementation-dependent maximum number of uniform buffer bindings, a compile-time
6338         // error will occur. When the binding identifier is used with a uniform or shader storage block instanced as
6339         // an array of size N, all elements of the array from binding through binding + N - 1 must be within this
6340         // range."
6341         //
6342         if (! type.isOpaque() && type.getBasicType() != EbtBlock)
6343             error(loc, "requires block, or sampler/image, or atomic-counter type", "binding", "");
6344         if (type.getBasicType() == EbtSampler) {
6345             int lastBinding = qualifier.layoutBinding;
6346             if (type.isArray()) {
6347                 if (spvVersion.vulkan == 0) {
6348                     if (type.isSizedArray())
6349                         lastBinding += (type.getCumulativeArraySize() - 1);
6350                     else {
6351 #ifndef GLSLANG_WEB
6352                         warn(loc, "assuming binding count of one for compile-time checking of binding numbers for unsized array", "[]", "");
6353 #endif
6354                     }
6355                 }
6356             }
6357 #ifndef GLSLANG_WEB
6358             if (spvVersion.vulkan == 0 && lastBinding >= resources.maxCombinedTextureImageUnits)
6359                 error(loc, "sampler binding not less than gl_MaxCombinedTextureImageUnits", "binding", type.isArray() ? "(using array)" : "");
6360 #endif
6361         }
6362         if (type.isAtomic() && !spvVersion.vulkanRelaxed) {
6363             if (qualifier.layoutBinding >= (unsigned int)resources.maxAtomicCounterBindings) {
6364                 error(loc, "atomic_uint binding is too large; see gl_MaxAtomicCounterBindings", "binding", "");
6365                 return;
6366             }
6367         }
6368     } else if (!intermediate.getAutoMapBindings()) {
6369         // some types require bindings
6370
6371         // atomic_uint
6372         if (type.isAtomic())
6373             error(loc, "layout(binding=X) is required", "atomic_uint", "");
6374
6375         // SPIR-V
6376         if (spvVersion.spv > 0) {
6377             if (qualifier.isUniformOrBuffer()) {
6378                 if (type.getBasicType() == EbtBlock && !qualifier.isPushConstant() &&
6379                        !qualifier.isShaderRecord() &&
6380                        !qualifier.hasAttachment() &&
6381                        !qualifier.hasBufferReference())
6382                     error(loc, "uniform/buffer blocks require layout(binding=X)", "binding", "");
6383                 else if (spvVersion.vulkan > 0 && type.getBasicType() == EbtSampler)
6384                     error(loc, "sampler/texture/image requires layout(binding=X)", "binding", "");
6385             }
6386         }
6387     }
6388
6389     // some things can't have arrays of arrays
6390     if (type.isArrayOfArrays()) {
6391         if (spvVersion.vulkan > 0) {
6392             if (type.isOpaque() || (type.getQualifier().isUniformOrBuffer() && type.getBasicType() == EbtBlock))
6393                 warn(loc, "Generating SPIR-V array-of-arrays, but Vulkan only supports single array level for this resource", "[][]", "");
6394         }
6395     }
6396
6397     // "The offset qualifier can only be used on block members of blocks..."
6398     if (qualifier.hasOffset()) {
6399         if (type.getBasicType() == EbtBlock)
6400             error(loc, "only applies to block members, not blocks", "offset", "");
6401     }
6402
6403     // Image format
6404     if (qualifier.hasFormat()) {
6405         if (! type.isImage())
6406             error(loc, "only apply to images", TQualifier::getLayoutFormatString(qualifier.getFormat()), "");
6407         else {
6408             if (type.getSampler().type == EbtFloat && qualifier.getFormat() > ElfFloatGuard)
6409                 error(loc, "does not apply to floating point images", TQualifier::getLayoutFormatString(qualifier.getFormat()), "");
6410             if (type.getSampler().type == EbtInt && (qualifier.getFormat() < ElfFloatGuard || qualifier.getFormat() > ElfIntGuard))
6411                 error(loc, "does not apply to signed integer images", TQualifier::getLayoutFormatString(qualifier.getFormat()), "");
6412             if (type.getSampler().type == EbtUint && qualifier.getFormat() < ElfIntGuard)
6413                 error(loc, "does not apply to unsigned integer images", TQualifier::getLayoutFormatString(qualifier.getFormat()), "");
6414
6415             if (isEsProfile()) {
6416                 // "Except for image variables qualified with the format qualifiers r32f, r32i, and r32ui, image variables must
6417                 // specify either memory qualifier readonly or the memory qualifier writeonly."
6418                 if (! (qualifier.getFormat() == ElfR32f || qualifier.getFormat() == ElfR32i || qualifier.getFormat() == ElfR32ui)) {
6419                     if (! qualifier.isReadOnly() && ! qualifier.isWriteOnly())
6420                         error(loc, "format requires readonly or writeonly memory qualifier", TQualifier::getLayoutFormatString(qualifier.getFormat()), "");
6421                 }
6422             }
6423         }
6424     } else if (type.isImage() && ! qualifier.isWriteOnly()) {
6425         const char *explanation = "image variables not declared 'writeonly' and without a format layout qualifier";
6426         requireProfile(loc, ECoreProfile | ECompatibilityProfile, explanation);
6427         profileRequires(loc, ECoreProfile | ECompatibilityProfile, 0, E_GL_EXT_shader_image_load_formatted, explanation);
6428     }
6429
6430     if (qualifier.isPushConstant()) {
6431         if (type.getBasicType() != EbtBlock)
6432             error(loc, "can only be used with a block", "push_constant", "");
6433         if (type.isArray())
6434             error(loc, "Push constants blocks can't be an array", "push_constant", "");
6435     }
6436
6437     if (qualifier.hasBufferReference() && type.getBasicType() != EbtBlock)
6438         error(loc, "can only be used with a block", "buffer_reference", "");
6439
6440     if (qualifier.isShaderRecord() && type.getBasicType() != EbtBlock)
6441         error(loc, "can only be used with a block", "shaderRecordNV", "");
6442
6443     // input attachment
6444     if (type.isSubpass()) {
6445         if (! qualifier.hasAttachment())
6446             error(loc, "requires an input_attachment_index layout qualifier", "subpass", "");
6447     } else {
6448         if (qualifier.hasAttachment())
6449             error(loc, "can only be used with a subpass", "input_attachment_index", "");
6450     }
6451
6452     // specialization-constant id
6453     if (qualifier.hasSpecConstantId()) {
6454         if (type.getQualifier().storage != EvqConst)
6455             error(loc, "can only be applied to 'const'-qualified scalar", "constant_id", "");
6456         if (! type.isScalar())
6457             error(loc, "can only be applied to a scalar", "constant_id", "");
6458         switch (type.getBasicType())
6459         {
6460         case EbtInt8:
6461         case EbtUint8:
6462         case EbtInt16:
6463         case EbtUint16:
6464         case EbtInt:
6465         case EbtUint:
6466         case EbtInt64:
6467         case EbtUint64:
6468         case EbtBool:
6469         case EbtFloat:
6470         case EbtDouble:
6471         case EbtFloat16:
6472             break;
6473         default:
6474             error(loc, "cannot be applied to this type", "constant_id", "");
6475             break;
6476         }
6477     }
6478 }
6479
6480 static bool storageCanHaveLayoutInBlock(const enum TStorageQualifier storage)
6481 {
6482     switch (storage) {
6483     case EvqUniform:
6484     case EvqBuffer:
6485     case EvqShared:
6486         return true;
6487     default:
6488         return false;
6489     }
6490 }
6491
6492 // Do layout error checking that can be done within a layout qualifier proper, not needing to know
6493 // if there are blocks, atomic counters, variables, etc.
6494 void TParseContext::layoutQualifierCheck(const TSourceLoc& loc, const TQualifier& qualifier)
6495 {
6496     if (qualifier.storage == EvqShared && qualifier.hasLayout()) {
6497         if (spvVersion.spv > 0 && spvVersion.spv < EShTargetSpv_1_4) {
6498             error(loc, "shared block requires at least SPIR-V 1.4", "shared block", "");
6499         }
6500         profileRequires(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, 0, E_GL_EXT_shared_memory_block, "shared block");
6501     }
6502
6503     // "It is a compile-time error to use *component* without also specifying the location qualifier (order does not matter)."
6504     if (qualifier.hasComponent() && ! qualifier.hasLocation())
6505         error(loc, "must specify 'location' to use 'component'", "component", "");
6506
6507     if (qualifier.hasAnyLocation()) {
6508
6509         // "As with input layout qualifiers, all shaders except compute shaders
6510         // allow *location* layout qualifiers on output variable declarations,
6511         // output block declarations, and output block member declarations."
6512
6513         switch (qualifier.storage) {
6514 #ifndef GLSLANG_WEB
6515         case EvqVaryingIn:
6516         {
6517             const char* feature = "location qualifier on input";
6518             if (isEsProfile() && version < 310)
6519                 requireStage(loc, EShLangVertex, feature);
6520             else
6521                 requireStage(loc, (EShLanguageMask)~EShLangComputeMask, feature);
6522             if (language == EShLangVertex) {
6523                 const char* exts[2] = { E_GL_ARB_separate_shader_objects, E_GL_ARB_explicit_attrib_location };
6524                 profileRequires(loc, ~EEsProfile, 330, 2, exts, feature);
6525                 profileRequires(loc, EEsProfile, 300, nullptr, feature);
6526             } else {
6527                 profileRequires(loc, ~EEsProfile, 410, E_GL_ARB_separate_shader_objects, feature);
6528                 profileRequires(loc, EEsProfile, 310, nullptr, feature);
6529             }
6530             break;
6531         }
6532         case EvqVaryingOut:
6533         {
6534             const char* feature = "location qualifier on output";
6535             if (isEsProfile() && version < 310)
6536                 requireStage(loc, EShLangFragment, feature);
6537             else
6538                 requireStage(loc, (EShLanguageMask)~EShLangComputeMask, feature);
6539             if (language == EShLangFragment) {
6540                 const char* exts[2] = { E_GL_ARB_separate_shader_objects, E_GL_ARB_explicit_attrib_location };
6541                 profileRequires(loc, ~EEsProfile, 330, 2, exts, feature);
6542                 profileRequires(loc, EEsProfile, 300, nullptr, feature);
6543             } else {
6544                 profileRequires(loc, ~EEsProfile, 410, E_GL_ARB_separate_shader_objects, feature);
6545                 profileRequires(loc, EEsProfile, 310, nullptr, feature);
6546             }
6547             break;
6548         }
6549 #endif
6550         case EvqUniform:
6551         case EvqBuffer:
6552         {
6553             const char* feature = "location qualifier on uniform or buffer";
6554             requireProfile(loc, EEsProfile | ECoreProfile | ECompatibilityProfile | ENoProfile, feature);
6555             profileRequires(loc, ~EEsProfile, 330, E_GL_ARB_explicit_attrib_location, feature);
6556             profileRequires(loc, ~EEsProfile, 430, E_GL_ARB_explicit_uniform_location, feature);
6557             profileRequires(loc, EEsProfile, 310, nullptr, feature);
6558             break;
6559         }
6560         default:
6561             break;
6562         }
6563         if (qualifier.hasIndex()) {
6564             if (qualifier.storage != EvqVaryingOut)
6565                 error(loc, "can only be used on an output", "index", "");
6566             if (! qualifier.hasLocation())
6567                 error(loc, "can only be used with an explicit location", "index", "");
6568         }
6569     }
6570
6571     if (qualifier.hasBinding()) {
6572         if (! qualifier.isUniformOrBuffer() && !qualifier.isTaskMemory())
6573             error(loc, "requires uniform or buffer storage qualifier", "binding", "");
6574     }
6575     if (qualifier.hasStream()) {
6576         if (!qualifier.isPipeOutput())
6577             error(loc, "can only be used on an output", "stream", "");
6578     }
6579     if (qualifier.hasXfb()) {
6580         if (!qualifier.isPipeOutput())
6581             error(loc, "can only be used on an output", "xfb layout qualifier", "");
6582     }
6583     if (qualifier.hasUniformLayout()) {
6584         if (!storageCanHaveLayoutInBlock(qualifier.storage) && !qualifier.isTaskMemory()) {
6585             if (qualifier.hasMatrix() || qualifier.hasPacking())
6586                 error(loc, "matrix or packing qualifiers can only be used on a uniform or buffer", "layout", "");
6587             if (qualifier.hasOffset() || qualifier.hasAlign())
6588                 error(loc, "offset/align can only be used on a uniform or buffer", "layout", "");
6589         }
6590     }
6591     if (qualifier.isPushConstant()) {
6592         if (qualifier.storage != EvqUniform)
6593             error(loc, "can only be used with a uniform", "push_constant", "");
6594         if (qualifier.hasSet())
6595             error(loc, "cannot be used with push_constant", "set", "");
6596         if (qualifier.hasBinding())
6597             error(loc, "cannot be used with push_constant", "binding", "");
6598     }
6599     if (qualifier.hasBufferReference()) {
6600         if (qualifier.storage != EvqBuffer)
6601             error(loc, "can only be used with buffer", "buffer_reference", "");
6602     }
6603     if (qualifier.isShaderRecord()) {
6604         if (qualifier.storage != EvqBuffer)
6605             error(loc, "can only be used with a buffer", "shaderRecordNV", "");
6606         if (qualifier.hasBinding())
6607             error(loc, "cannot be used with shaderRecordNV", "binding", "");
6608         if (qualifier.hasSet())
6609             error(loc, "cannot be used with shaderRecordNV", "set", "");
6610
6611     }
6612     if (qualifier.storage == EvqHitAttr && qualifier.hasLayout()) {
6613         error(loc, "cannot apply layout qualifiers to hitAttributeNV variable", "hitAttributeNV", "");
6614     }
6615 }
6616
6617 // For places that can't have shader-level layout qualifiers
6618 void TParseContext::checkNoShaderLayouts(const TSourceLoc& loc, const TShaderQualifiers& shaderQualifiers)
6619 {
6620 #ifndef GLSLANG_WEB
6621     const char* message = "can only apply to a standalone qualifier";
6622
6623     if (shaderQualifiers.geometry != ElgNone)
6624         error(loc, message, TQualifier::getGeometryString(shaderQualifiers.geometry), "");
6625     if (shaderQualifiers.spacing != EvsNone)
6626         error(loc, message, TQualifier::getVertexSpacingString(shaderQualifiers.spacing), "");
6627     if (shaderQualifiers.order != EvoNone)
6628         error(loc, message, TQualifier::getVertexOrderString(shaderQualifiers.order), "");
6629     if (shaderQualifiers.pointMode)
6630         error(loc, message, "point_mode", "");
6631     if (shaderQualifiers.invocations != TQualifier::layoutNotSet)
6632         error(loc, message, "invocations", "");
6633     for (int i = 0; i < 3; ++i) {
6634         if (shaderQualifiers.localSize[i] > 1)
6635             error(loc, message, "local_size", "");
6636         if (shaderQualifiers.localSizeSpecId[i] != TQualifier::layoutNotSet)
6637             error(loc, message, "local_size id", "");
6638     }
6639     if (shaderQualifiers.vertices != TQualifier::layoutNotSet) {
6640         if (language == EShLangGeometry || language == EShLangMesh)
6641             error(loc, message, "max_vertices", "");
6642         else if (language == EShLangTessControl)
6643             error(loc, message, "vertices", "");
6644         else
6645             assert(0);
6646     }
6647     if (shaderQualifiers.earlyFragmentTests)
6648         error(loc, message, "early_fragment_tests", "");
6649     if (shaderQualifiers.postDepthCoverage)
6650         error(loc, message, "post_depth_coverage", "");
6651     if (shaderQualifiers.primitives != TQualifier::layoutNotSet) {
6652         if (language == EShLangMesh)
6653             error(loc, message, "max_primitives", "");
6654         else
6655             assert(0);
6656     }
6657     if (shaderQualifiers.hasBlendEquation())
6658         error(loc, message, "blend equation", "");
6659     if (shaderQualifiers.numViews != TQualifier::layoutNotSet)
6660         error(loc, message, "num_views", "");
6661     if (shaderQualifiers.interlockOrdering != EioNone)
6662         error(loc, message, TQualifier::getInterlockOrderingString(shaderQualifiers.interlockOrdering), "");
6663     if (shaderQualifiers.layoutPrimitiveCulling)
6664         error(loc, "can only be applied as standalone", "primitive_culling", "");
6665 #endif
6666 }
6667
6668 // Correct and/or advance an object's offset layout qualifier.
6669 void TParseContext::fixOffset(const TSourceLoc& loc, TSymbol& symbol)
6670 {
6671     const TQualifier& qualifier = symbol.getType().getQualifier();
6672 #ifndef GLSLANG_WEB
6673     if (symbol.getType().isAtomic()) {
6674         if (qualifier.hasBinding() && (int)qualifier.layoutBinding < resources.maxAtomicCounterBindings) {
6675
6676             // Set the offset
6677             int offset;
6678             if (qualifier.hasOffset())
6679                 offset = qualifier.layoutOffset;
6680             else
6681                 offset = atomicUintOffsets[qualifier.layoutBinding];
6682
6683             if (offset % 4 != 0)
6684                 error(loc, "atomic counters offset should align based on 4:", "offset", "%d", offset);
6685
6686             symbol.getWritableType().getQualifier().layoutOffset = offset;
6687
6688             // Check for overlap
6689             int numOffsets = 4;
6690             if (symbol.getType().isArray()) {
6691                 if (symbol.getType().isSizedArray() && !symbol.getType().getArraySizes()->isInnerUnsized())
6692                     numOffsets *= symbol.getType().getCumulativeArraySize();
6693                 else {
6694                     // "It is a compile-time error to declare an unsized array of atomic_uint."
6695                     error(loc, "array must be explicitly sized", "atomic_uint", "");
6696                 }
6697             }
6698             int repeated = intermediate.addUsedOffsets(qualifier.layoutBinding, offset, numOffsets);
6699             if (repeated >= 0)
6700                 error(loc, "atomic counters sharing the same offset:", "offset", "%d", repeated);
6701
6702             // Bump the default offset
6703             atomicUintOffsets[qualifier.layoutBinding] = offset + numOffsets;
6704         }
6705     }
6706 #endif
6707 }
6708
6709 //
6710 // Look up a function name in the symbol table, and make sure it is a function.
6711 //
6712 // Return the function symbol if found, otherwise nullptr.
6713 //
6714 const TFunction* TParseContext::findFunction(const TSourceLoc& loc, const TFunction& call, bool& builtIn)
6715 {
6716     if (symbolTable.isFunctionNameVariable(call.getName())) {
6717         error(loc, "can't use function syntax on variable", call.getName().c_str(), "");
6718         return nullptr;
6719     }
6720
6721 #ifdef GLSLANG_WEB
6722     return findFunctionExact(loc, call, builtIn);
6723 #endif
6724
6725     const TFunction* function = nullptr;
6726
6727     // debugPrintfEXT has var args and is in the symbol table as "debugPrintfEXT()",
6728     // mangled to "debugPrintfEXT("
6729     if (call.getName() == "debugPrintfEXT") {
6730         TSymbol* symbol = symbolTable.find("debugPrintfEXT(", &builtIn);
6731         if (symbol)
6732             return symbol->getAsFunction();
6733     }
6734
6735     bool explicitTypesEnabled = extensionTurnedOn(E_GL_EXT_shader_explicit_arithmetic_types) ||
6736                                 extensionTurnedOn(E_GL_EXT_shader_explicit_arithmetic_types_int8) ||
6737                                 extensionTurnedOn(E_GL_EXT_shader_explicit_arithmetic_types_int16) ||
6738                                 extensionTurnedOn(E_GL_EXT_shader_explicit_arithmetic_types_int32) ||
6739                                 extensionTurnedOn(E_GL_EXT_shader_explicit_arithmetic_types_int64) ||
6740                                 extensionTurnedOn(E_GL_EXT_shader_explicit_arithmetic_types_float16) ||
6741                                 extensionTurnedOn(E_GL_EXT_shader_explicit_arithmetic_types_float32) ||
6742                                 extensionTurnedOn(E_GL_EXT_shader_explicit_arithmetic_types_float64);
6743
6744     if (isEsProfile())
6745         function = (explicitTypesEnabled && version >= 310)
6746                    ? findFunctionExplicitTypes(loc, call, builtIn)
6747                    : ((extensionTurnedOn(E_GL_EXT_shader_implicit_conversions) && version >= 310)
6748                       ? findFunction120(loc, call, builtIn)
6749                       : findFunctionExact(loc, call, builtIn));
6750     else if (version < 120)
6751         function = findFunctionExact(loc, call, builtIn);
6752     else if (version < 400) {
6753         bool needfindFunction400 = extensionTurnedOn(E_GL_ARB_gpu_shader_fp64) || extensionTurnedOn(E_GL_ARB_gpu_shader5);
6754         function = needfindFunction400 ? findFunction400(loc, call, builtIn) : findFunction120(loc, call, builtIn);
6755     }
6756     else if (explicitTypesEnabled)
6757         function = findFunctionExplicitTypes(loc, call, builtIn);
6758     else
6759         function = findFunction400(loc, call, builtIn);
6760
6761     return function;
6762 }
6763
6764 // Function finding algorithm for ES and desktop 110.
6765 const TFunction* TParseContext::findFunctionExact(const TSourceLoc& loc, const TFunction& call, bool& builtIn)
6766 {
6767     TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn);
6768     if (symbol == nullptr) {
6769         error(loc, "no matching overloaded function found", call.getName().c_str(), "");
6770
6771         return nullptr;
6772     }
6773
6774     return symbol->getAsFunction();
6775 }
6776
6777 // Function finding algorithm for desktop versions 120 through 330.
6778 const TFunction* TParseContext::findFunction120(const TSourceLoc& loc, const TFunction& call, bool& builtIn)
6779 {
6780     // first, look for an exact match
6781     TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn);
6782     if (symbol)
6783         return symbol->getAsFunction();
6784
6785     // exact match not found, look through a list of overloaded functions of the same name
6786
6787     // "If no exact match is found, then [implicit conversions] will be applied to find a match. Mismatched types
6788     // on input parameters (in or inout or default) must have a conversion from the calling argument type to the
6789     // formal parameter type. Mismatched types on output parameters (out or inout) must have a conversion
6790     // from the formal parameter type to the calling argument type.  When argument conversions are used to find
6791     // a match, it is a semantic error if there are multiple ways to apply these conversions to make the call match
6792     // more than one function."
6793
6794     const TFunction* candidate = nullptr;
6795     TVector<const TFunction*> candidateList;
6796     symbolTable.findFunctionNameList(call.getMangledName(), candidateList, builtIn);
6797
6798     for (auto it = candidateList.begin(); it != candidateList.end(); ++it) {
6799         const TFunction& function = *(*it);
6800
6801         // to even be a potential match, number of arguments has to match
6802         if (call.getParamCount() != function.getParamCount())
6803             continue;
6804
6805         bool possibleMatch = true;
6806         for (int i = 0; i < function.getParamCount(); ++i) {
6807             // same types is easy
6808             if (*function[i].type == *call[i].type)
6809                 continue;
6810
6811             // We have a mismatch in type, see if it is implicitly convertible
6812
6813             if (function[i].type->isArray() || call[i].type->isArray() ||
6814                 ! function[i].type->sameElementShape(*call[i].type))
6815                 possibleMatch = false;
6816             else {
6817                 // do direction-specific checks for conversion of basic type
6818                 if (function[i].type->getQualifier().isParamInput()) {
6819                     if (! intermediate.canImplicitlyPromote(call[i].type->getBasicType(), function[i].type->getBasicType()))
6820                         possibleMatch = false;
6821                 }
6822                 if (function[i].type->getQualifier().isParamOutput()) {
6823                     if (! intermediate.canImplicitlyPromote(function[i].type->getBasicType(), call[i].type->getBasicType()))
6824                         possibleMatch = false;
6825                 }
6826             }
6827             if (! possibleMatch)
6828                 break;
6829         }
6830         if (possibleMatch) {
6831             if (candidate) {
6832                 // our second match, meaning ambiguity
6833                 error(loc, "ambiguous function signature match: multiple signatures match under implicit type conversion", call.getName().c_str(), "");
6834             } else
6835                 candidate = &function;
6836         }
6837     }
6838
6839     if (candidate == nullptr)
6840         error(loc, "no matching overloaded function found", call.getName().c_str(), "");
6841
6842     return candidate;
6843 }
6844
6845 // Function finding algorithm for desktop version 400 and above.
6846 //
6847 // "When function calls are resolved, an exact type match for all the arguments
6848 // is sought. If an exact match is found, all other functions are ignored, and
6849 // the exact match is used. If no exact match is found, then the implicit
6850 // conversions in section 4.1.10 Implicit Conversions will be applied to find
6851 // a match. Mismatched types on input parameters (in or inout or default) must
6852 // have a conversion from the calling argument type to the formal parameter type.
6853 // Mismatched types on output parameters (out or inout) must have a conversion
6854 // from the formal parameter type to the calling argument type.
6855 //
6856 // "If implicit conversions can be used to find more than one matching function,
6857 // a single best-matching function is sought. To determine a best match, the
6858 // conversions between calling argument and formal parameter types are compared
6859 // for each function argument and pair of matching functions. After these
6860 // comparisons are performed, each pair of matching functions are compared.
6861 // A function declaration A is considered a better match than function
6862 // declaration B if
6863 //
6864 //  * for at least one function argument, the conversion for that argument in A
6865 //    is better than the corresponding conversion in B; and
6866 //  * there is no function argument for which the conversion in B is better than
6867 //    the corresponding conversion in A.
6868 //
6869 // "If a single function declaration is considered a better match than every
6870 // other matching function declaration, it will be used. Otherwise, a
6871 // compile-time semantic error for an ambiguous overloaded function call occurs.
6872 //
6873 // "To determine whether the conversion for a single argument in one match is
6874 // better than that for another match, the following rules are applied, in order:
6875 //
6876 //  1. An exact match is better than a match involving any implicit conversion.
6877 //  2. A match involving an implicit conversion from float to double is better
6878 //     than a match involving any other implicit conversion.
6879 //  3. A match involving an implicit conversion from either int or uint to float
6880 //     is better than a match involving an implicit conversion from either int
6881 //     or uint to double.
6882 //
6883 // "If none of the rules above apply to a particular pair of conversions, neither
6884 // conversion is considered better than the other."
6885 //
6886 const TFunction* TParseContext::findFunction400(const TSourceLoc& loc, const TFunction& call, bool& builtIn)
6887 {
6888     // first, look for an exact match
6889     TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn);
6890     if (symbol)
6891         return symbol->getAsFunction();
6892
6893     // no exact match, use the generic selector, parameterized by the GLSL rules
6894
6895     // create list of candidates to send
6896     TVector<const TFunction*> candidateList;
6897     symbolTable.findFunctionNameList(call.getMangledName(), candidateList, builtIn);
6898
6899     // can 'from' convert to 'to'?
6900     const auto convertible = [this,builtIn](const TType& from, const TType& to, TOperator, int) -> bool {
6901         if (from == to)
6902             return true;
6903         if (from.coopMatParameterOK(to))
6904             return true;
6905         // Allow a sized array to be passed through an unsized array parameter, for coopMatLoad/Store functions
6906         if (builtIn && from.isArray() && to.isUnsizedArray()) {
6907             TType fromElementType(from, 0);
6908             TType toElementType(to, 0);
6909             if (fromElementType == toElementType)
6910                 return true;
6911         }
6912         if (from.isArray() || to.isArray() || ! from.sameElementShape(to))
6913             return false;
6914         if (from.isCoopMat() && to.isCoopMat())
6915             return from.sameCoopMatBaseType(to);
6916         return intermediate.canImplicitlyPromote(from.getBasicType(), to.getBasicType());
6917     };
6918
6919     // Is 'to2' a better conversion than 'to1'?
6920     // Ties should not be considered as better.
6921     // Assumes 'convertible' already said true.
6922     const auto better = [](const TType& from, const TType& to1, const TType& to2) -> bool {
6923         // 1. exact match
6924         if (from == to2)
6925             return from != to1;
6926         if (from == to1)
6927             return false;
6928
6929         // 2. float -> double is better
6930         if (from.getBasicType() == EbtFloat) {
6931             if (to2.getBasicType() == EbtDouble && to1.getBasicType() != EbtDouble)
6932                 return true;
6933         }
6934
6935         // 3. -> float is better than -> double
6936         return to2.getBasicType() == EbtFloat && to1.getBasicType() == EbtDouble;
6937     };
6938
6939     // for ambiguity reporting
6940     bool tie = false;
6941
6942     // send to the generic selector
6943     const TFunction* bestMatch = selectFunction(candidateList, call, convertible, better, tie);
6944
6945     if (bestMatch == nullptr)
6946         error(loc, "no matching overloaded function found", call.getName().c_str(), "");
6947     else if (tie)
6948         error(loc, "ambiguous best function under implicit type conversion", call.getName().c_str(), "");
6949
6950     return bestMatch;
6951 }
6952
6953 // "To determine whether the conversion for a single argument in one match
6954 //  is better than that for another match, the conversion is assigned of the
6955 //  three ranks ordered from best to worst:
6956 //   1. Exact match: no conversion.
6957 //    2. Promotion: integral or floating-point promotion.
6958 //    3. Conversion: integral conversion, floating-point conversion,
6959 //       floating-integral conversion.
6960 //  A conversion C1 is better than a conversion C2 if the rank of C1 is
6961 //  better than the rank of C2."
6962 const TFunction* TParseContext::findFunctionExplicitTypes(const TSourceLoc& loc, const TFunction& call, bool& builtIn)
6963 {
6964     // first, look for an exact match
6965     TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn);
6966     if (symbol)
6967         return symbol->getAsFunction();
6968
6969     // no exact match, use the generic selector, parameterized by the GLSL rules
6970
6971     // create list of candidates to send
6972     TVector<const TFunction*> candidateList;
6973     symbolTable.findFunctionNameList(call.getMangledName(), candidateList, builtIn);
6974
6975     // can 'from' convert to 'to'?
6976     const auto convertible = [this,builtIn](const TType& from, const TType& to, TOperator, int) -> bool {
6977         if (from == to)
6978             return true;
6979         if (from.coopMatParameterOK(to))
6980             return true;
6981         // Allow a sized array to be passed through an unsized array parameter, for coopMatLoad/Store functions
6982         if (builtIn && from.isArray() && to.isUnsizedArray()) {
6983             TType fromElementType(from, 0);
6984             TType toElementType(to, 0);
6985             if (fromElementType == toElementType)
6986                 return true;
6987         }
6988         if (from.isArray() || to.isArray() || ! from.sameElementShape(to))
6989             return false;
6990         if (from.isCoopMat() && to.isCoopMat())
6991             return from.sameCoopMatBaseType(to);
6992         return intermediate.canImplicitlyPromote(from.getBasicType(), to.getBasicType());
6993     };
6994
6995     // Is 'to2' a better conversion than 'to1'?
6996     // Ties should not be considered as better.
6997     // Assumes 'convertible' already said true.
6998     const auto better = [this](const TType& from, const TType& to1, const TType& to2) -> bool {
6999         // 1. exact match
7000         if (from == to2)
7001             return from != to1;
7002         if (from == to1)
7003             return false;
7004
7005         // 2. Promotion (integral, floating-point) is better
7006         TBasicType from_type = from.getBasicType();
7007         TBasicType to1_type = to1.getBasicType();
7008         TBasicType to2_type = to2.getBasicType();
7009         bool isPromotion1 = (intermediate.isIntegralPromotion(from_type, to1_type) ||
7010                              intermediate.isFPPromotion(from_type, to1_type));
7011         bool isPromotion2 = (intermediate.isIntegralPromotion(from_type, to2_type) ||
7012                              intermediate.isFPPromotion(from_type, to2_type));
7013         if (isPromotion2)
7014             return !isPromotion1;
7015         if(isPromotion1)
7016             return false;
7017
7018         // 3. Conversion (integral, floating-point , floating-integral)
7019         bool isConversion1 = (intermediate.isIntegralConversion(from_type, to1_type) ||
7020                               intermediate.isFPConversion(from_type, to1_type) ||
7021                               intermediate.isFPIntegralConversion(from_type, to1_type));
7022         bool isConversion2 = (intermediate.isIntegralConversion(from_type, to2_type) ||
7023                               intermediate.isFPConversion(from_type, to2_type) ||
7024                               intermediate.isFPIntegralConversion(from_type, to2_type));
7025
7026         return isConversion2 && !isConversion1;
7027     };
7028
7029     // for ambiguity reporting
7030     bool tie = false;
7031
7032     // send to the generic selector
7033     const TFunction* bestMatch = selectFunction(candidateList, call, convertible, better, tie);
7034
7035     if (bestMatch == nullptr)
7036         error(loc, "no matching overloaded function found", call.getName().c_str(), "");
7037     else if (tie)
7038         error(loc, "ambiguous best function under implicit type conversion", call.getName().c_str(), "");
7039
7040     return bestMatch;
7041 }
7042
7043 //
7044 // Adjust function calls that aren't declared in Vulkan to a
7045 // calls with equivalent effects
7046 //
7047 TIntermTyped* TParseContext::vkRelaxedRemapFunctionCall(const TSourceLoc& loc, TFunction* function, TIntermNode* arguments)
7048 {
7049     TIntermTyped* result = nullptr;
7050
7051 #ifndef GLSLANG_WEB
7052     if (function->getBuiltInOp() != EOpNull) {
7053         return nullptr;
7054     }
7055
7056     if (function->getName() == "atomicCounterIncrement") {
7057         // change atomicCounterIncrement into an atomicAdd of 1
7058         TString name("atomicAdd");
7059         TType uintType(EbtUint);
7060
7061         TFunction realFunc(&name, function->getType());
7062
7063         // Use copyParam to avoid shared ownership of the 'type' field
7064         // of the parameter.
7065         for (int i = 0; i < function->getParamCount(); ++i) {
7066             realFunc.addParameter(TParameter().copyParam((*function)[i]));
7067         }
7068
7069         TParameter tmpP = { 0, &uintType };
7070         realFunc.addParameter(TParameter().copyParam(tmpP));
7071         arguments = intermediate.growAggregate(arguments, intermediate.addConstantUnion(1, loc, true));
7072
7073         result = handleFunctionCall(loc, &realFunc, arguments);
7074     } else if (function->getName() == "atomicCounterDecrement") {
7075         // change atomicCounterDecrement into an atomicAdd with -1
7076         // and subtract 1 from result, to return post-decrement value
7077         TString name("atomicAdd");
7078         TType uintType(EbtUint);
7079
7080         TFunction realFunc(&name, function->getType());
7081
7082         for (int i = 0; i < function->getParamCount(); ++i) {
7083             realFunc.addParameter(TParameter().copyParam((*function)[i]));
7084         }
7085
7086         TParameter tmpP = { 0, &uintType };
7087         realFunc.addParameter(TParameter().copyParam(tmpP));
7088         arguments = intermediate.growAggregate(arguments, intermediate.addConstantUnion(-1, loc, true));
7089
7090         result = handleFunctionCall(loc, &realFunc, arguments);
7091
7092         // post decrement, so that it matches AtomicCounterDecrement semantics
7093         if (result) {
7094             result = handleBinaryMath(loc, "-", EOpSub, result, intermediate.addConstantUnion(1, loc, true));
7095         }
7096     } else if (function->getName() == "atomicCounter") {
7097         // change atomicCounter into a direct read of the variable
7098         if (arguments->getAsTyped()) {
7099             result = arguments->getAsTyped();
7100         }
7101     }
7102 #endif
7103
7104     return result;
7105 }
7106
7107 // When a declaration includes a type, but not a variable name, it can be used
7108 // to establish defaults.
7109 void TParseContext::declareTypeDefaults(const TSourceLoc& loc, const TPublicType& publicType)
7110 {
7111 #ifndef GLSLANG_WEB
7112     if (publicType.basicType == EbtAtomicUint && publicType.qualifier.hasBinding()) {
7113         if (publicType.qualifier.layoutBinding >= (unsigned int)resources.maxAtomicCounterBindings) {
7114             error(loc, "atomic_uint binding is too large", "binding", "");
7115             return;
7116         }
7117         if (publicType.qualifier.hasOffset())
7118             atomicUintOffsets[publicType.qualifier.layoutBinding] = publicType.qualifier.layoutOffset;
7119         return;
7120     }
7121
7122     if (publicType.arraySizes) {
7123         error(loc, "expect an array name", "", "");
7124     }
7125
7126     if (publicType.qualifier.hasLayout() && !publicType.qualifier.hasBufferReference())
7127         warn(loc, "useless application of layout qualifier", "layout", "");
7128 #endif
7129 }
7130
7131 bool TParseContext::vkRelaxedRemapUniformVariable(const TSourceLoc& loc, TString& identifier, const TPublicType&,
7132     TArraySizes*, TIntermTyped* initializer, TType& type)
7133 {
7134     if (parsingBuiltins || symbolTable.atBuiltInLevel() || !symbolTable.atGlobalLevel() ||
7135         type.getQualifier().storage != EvqUniform ||
7136         !(type.containsNonOpaque()
7137 #ifndef GLSLANG_WEB
7138             || type.getBasicType() == EbtAtomicUint
7139 #endif
7140         )) {
7141         return false;
7142     }
7143
7144     if (type.getQualifier().hasLocation()) {
7145         warn(loc, "ignoring layout qualifier for uniform", identifier.c_str(), "location");
7146         type.getQualifier().layoutLocation = TQualifier::layoutLocationEnd;
7147     }
7148
7149     if (initializer) {
7150         warn(loc, "Ignoring initializer for uniform", identifier.c_str(), "");
7151         initializer = nullptr;
7152     }
7153
7154     if (type.isArray()) {
7155         // do array size checks here
7156         arraySizesCheck(loc, type.getQualifier(), type.getArraySizes(), initializer, false);
7157
7158         if (arrayQualifierError(loc, type.getQualifier()) || arrayError(loc, type)) {
7159             error(loc, "array param error", identifier.c_str(), "");
7160         }
7161     }
7162
7163     // do some checking on the type as it was declared
7164     layoutTypeCheck(loc, type);
7165
7166     int bufferBinding = TQualifier::layoutBindingEnd;
7167     TVariable* updatedBlock = nullptr;
7168
7169 #ifndef GLSLANG_WEB
7170     // Convert atomic_uint into members of a buffer block
7171     if (type.isAtomic()) {
7172         type.setBasicType(EbtUint);
7173         type.getQualifier().storage = EvqBuffer;
7174
7175         type.getQualifier().volatil = true;
7176         type.getQualifier().coherent = true;
7177
7178         // xxTODO: use logic from fixOffset() to apply explicit member offset
7179         bufferBinding = type.getQualifier().layoutBinding;
7180         type.getQualifier().layoutBinding = TQualifier::layoutBindingEnd;
7181         type.getQualifier().explicitOffset = false;
7182         growAtomicCounterBlock(bufferBinding, loc, type, identifier, nullptr);
7183         updatedBlock = atomicCounterBuffers[bufferBinding];
7184     }
7185 #endif
7186
7187     if (!updatedBlock) {
7188         growGlobalUniformBlock(loc, type, identifier, nullptr);
7189         updatedBlock = globalUniformBlock;
7190     }
7191
7192     //
7193     //      don't assign explicit member offsets here
7194     //      if any are assigned, need to be updated here and in the merge/link step
7195     // fixBlockUniformOffsets(updatedBlock->getWritableType().getQualifier(), *updatedBlock->getWritableType().getWritableStruct());
7196
7197     // checks on update buffer object
7198     layoutObjectCheck(loc, *updatedBlock);
7199
7200     TSymbol* symbol = symbolTable.find(identifier);
7201
7202     if (!symbol) {
7203         if (updatedBlock == globalUniformBlock)
7204             error(loc, "error adding uniform to default uniform block", identifier.c_str(), "");
7205         else
7206             error(loc, "error adding atomic counter to atomic counter block", identifier.c_str(), "");
7207         return false;
7208     }
7209
7210     // merge qualifiers
7211     mergeObjectLayoutQualifiers(updatedBlock->getWritableType().getQualifier(), type.getQualifier(), true);
7212
7213     return true;
7214 }
7215
7216 //
7217 // Do everything necessary to handle a variable (non-block) declaration.
7218 // Either redeclaring a variable, or making a new one, updating the symbol
7219 // table, and all error checking.
7220 //
7221 // Returns a subtree node that computes an initializer, if needed.
7222 // Returns nullptr if there is no code to execute for initialization.
7223 //
7224 // 'publicType' is the type part of the declaration (to the left)
7225 // 'arraySizes' is the arrayness tagged on the identifier (to the right)
7226 //
7227 TIntermNode* TParseContext::declareVariable(const TSourceLoc& loc, TString& identifier, const TPublicType& publicType,
7228     TArraySizes* arraySizes, TIntermTyped* initializer)
7229 {
7230     // Make a fresh type that combines the characteristics from the individual
7231     // identifier syntax and the declaration-type syntax.
7232     TType type(publicType);
7233     type.transferArraySizes(arraySizes);
7234     type.copyArrayInnerSizes(publicType.arraySizes);
7235     arrayOfArrayVersionCheck(loc, type.getArraySizes());
7236
7237     if (initializer) {
7238         if (type.getBasicType() == EbtRayQuery) {
7239             error(loc, "ray queries can only be initialized by using the rayQueryInitializeEXT intrinsic:", "=", identifier.c_str());
7240         }
7241     }
7242
7243     if (type.isCoopMat()) {
7244         intermediate.setUseVulkanMemoryModel();
7245         intermediate.setUseStorageBuffer();
7246
7247         if (!publicType.typeParameters || publicType.typeParameters->getNumDims() != 4) {
7248             error(loc, "expected four type parameters", identifier.c_str(), "");
7249         }
7250         if (publicType.typeParameters) {
7251             if (isTypeFloat(publicType.basicType) &&
7252                 publicType.typeParameters->getDimSize(0) != 16 &&
7253                 publicType.typeParameters->getDimSize(0) != 32 &&
7254                 publicType.typeParameters->getDimSize(0) != 64) {
7255                 error(loc, "expected 16, 32, or 64 bits for first type parameter", identifier.c_str(), "");
7256             }
7257             if (isTypeInt(publicType.basicType) &&
7258                 publicType.typeParameters->getDimSize(0) != 8 &&
7259                 publicType.typeParameters->getDimSize(0) != 32) {
7260                 error(loc, "expected 8 or 32 bits for first type parameter", identifier.c_str(), "");
7261             }
7262         }
7263
7264     } else {
7265         if (publicType.typeParameters && publicType.typeParameters->getNumDims() != 0) {
7266             error(loc, "unexpected type parameters", identifier.c_str(), "");
7267         }
7268     }
7269
7270     if (voidErrorCheck(loc, identifier, type.getBasicType()))
7271         return nullptr;
7272
7273     if (initializer)
7274         rValueErrorCheck(loc, "initializer", initializer);
7275     else
7276         nonInitConstCheck(loc, identifier, type);
7277
7278     samplerCheck(loc, type, identifier, initializer);
7279     transparentOpaqueCheck(loc, type, identifier);
7280 #ifndef GLSLANG_WEB
7281     atomicUintCheck(loc, type, identifier);
7282     accStructCheck(loc, type, identifier);
7283     checkAndResizeMeshViewDim(loc, type, /*isBlockMember*/ false);
7284 #endif
7285     if (type.getQualifier().storage == EvqConst && type.containsReference()) {
7286         error(loc, "variables with reference type can't have qualifier 'const'", "qualifier", "");
7287     }
7288
7289     if (type.getQualifier().storage != EvqUniform && type.getQualifier().storage != EvqBuffer) {
7290         if (type.contains16BitFloat())
7291             requireFloat16Arithmetic(loc, "qualifier", "float16 types can only be in uniform block or buffer storage");
7292         if (type.contains16BitInt())
7293             requireInt16Arithmetic(loc, "qualifier", "(u)int16 types can only be in uniform block or buffer storage");
7294         if (type.contains8BitInt())
7295             requireInt8Arithmetic(loc, "qualifier", "(u)int8 types can only be in uniform block or buffer storage");
7296     }
7297
7298     if (type.getQualifier().storage == EvqtaskPayloadSharedEXT)
7299         intermediate.addTaskPayloadEXTCount();
7300     if (type.getQualifier().storage == EvqShared && type.containsCoopMat())
7301         error(loc, "qualifier", "Cooperative matrix types must not be used in shared memory", "");
7302
7303     if (profile == EEsProfile) {
7304         if (type.getQualifier().isPipeInput() && type.getBasicType() == EbtStruct) {
7305             if (type.getQualifier().isArrayedIo(language)) {
7306                 TType perVertexType(type, 0);
7307                 if (perVertexType.containsArray() && perVertexType.containsBuiltIn() == false) {
7308                     error(loc, "A per vertex structure containing an array is not allowed as input in ES", type.getTypeName().c_str(), "");
7309                 }
7310             }
7311             else if (type.containsArray() && type.containsBuiltIn() == false) {
7312                 error(loc, "A structure containing an array is not allowed as input in ES", type.getTypeName().c_str(), "");
7313             }
7314             if (type.containsStructure())
7315                 error(loc, "A structure containing an struct is not allowed as input in ES", type.getTypeName().c_str(), "");
7316         }
7317     }
7318
7319     if (identifier != "gl_FragCoord" && (publicType.shaderQualifiers.originUpperLeft || publicType.shaderQualifiers.pixelCenterInteger))
7320         error(loc, "can only apply origin_upper_left and pixel_center_origin to gl_FragCoord", "layout qualifier", "");
7321     if (identifier != "gl_FragDepth" && publicType.shaderQualifiers.getDepth() != EldNone)
7322         error(loc, "can only apply depth layout to gl_FragDepth", "layout qualifier", "");
7323     if (identifier != "gl_FragStencilRefARB" && publicType.shaderQualifiers.getStencil() != ElsNone)
7324         error(loc, "can only apply depth layout to gl_FragStencilRefARB", "layout qualifier", "");
7325
7326     // Check for redeclaration of built-ins and/or attempting to declare a reserved name
7327     TSymbol* symbol = redeclareBuiltinVariable(loc, identifier, type.getQualifier(), publicType.shaderQualifiers);
7328     if (symbol == nullptr)
7329         reservedErrorCheck(loc, identifier);
7330
7331     if (symbol == nullptr && spvVersion.vulkan > 0 && spvVersion.vulkanRelaxed) {
7332         bool remapped = vkRelaxedRemapUniformVariable(loc, identifier, publicType, arraySizes, initializer, type);
7333
7334         if (remapped) {
7335             return nullptr;
7336         }
7337     }
7338
7339     inheritGlobalDefaults(type.getQualifier());
7340
7341     // Declare the variable
7342     if (type.isArray()) {
7343         // Check that implicit sizing is only where allowed.
7344         arraySizesCheck(loc, type.getQualifier(), type.getArraySizes(), initializer, false);
7345
7346         if (! arrayQualifierError(loc, type.getQualifier()) && ! arrayError(loc, type))
7347             declareArray(loc, identifier, type, symbol);
7348
7349         if (initializer) {
7350             profileRequires(loc, ENoProfile, 120, E_GL_3DL_array_objects, "initializer");
7351             profileRequires(loc, EEsProfile, 300, nullptr, "initializer");
7352         }
7353     } else {
7354         // non-array case
7355         if (symbol == nullptr)
7356             symbol = declareNonArray(loc, identifier, type);
7357         else if (type != symbol->getType())
7358             error(loc, "cannot change the type of", "redeclaration", symbol->getName().c_str());
7359     }
7360
7361     if (symbol == nullptr)
7362         return nullptr;
7363
7364     // Deal with initializer
7365     TIntermNode* initNode = nullptr;
7366     if (symbol != nullptr && initializer) {
7367         TVariable* variable = symbol->getAsVariable();
7368         if (! variable) {
7369             error(loc, "initializer requires a variable, not a member", identifier.c_str(), "");
7370             return nullptr;
7371         }
7372         initNode = executeInitializer(loc, initializer, variable);
7373     }
7374
7375     // look for errors in layout qualifier use
7376     layoutObjectCheck(loc, *symbol);
7377
7378     // fix up
7379     fixOffset(loc, *symbol);
7380
7381     return initNode;
7382 }
7383
7384 // Pick up global defaults from the provide global defaults into dst.
7385 void TParseContext::inheritGlobalDefaults(TQualifier& dst) const
7386 {
7387 #ifndef GLSLANG_WEB
7388     if (dst.storage == EvqVaryingOut) {
7389         if (! dst.hasStream() && language == EShLangGeometry)
7390             dst.layoutStream = globalOutputDefaults.layoutStream;
7391         if (! dst.hasXfbBuffer())
7392             dst.layoutXfbBuffer = globalOutputDefaults.layoutXfbBuffer;
7393     }
7394 #endif
7395 }
7396
7397 //
7398 // Make an internal-only variable whose name is for debug purposes only
7399 // and won't be searched for.  Callers will only use the return value to use
7400 // the variable, not the name to look it up.  It is okay if the name
7401 // is the same as other names; there won't be any conflict.
7402 //
7403 TVariable* TParseContext::makeInternalVariable(const char* name, const TType& type) const
7404 {
7405     TString* nameString = NewPoolTString(name);
7406     TVariable* variable = new TVariable(nameString, type);
7407     symbolTable.makeInternalVariable(*variable);
7408
7409     return variable;
7410 }
7411
7412 //
7413 // Declare a non-array variable, the main point being there is no redeclaration
7414 // for resizing allowed.
7415 //
7416 // Return the successfully declared variable.
7417 //
7418 TVariable* TParseContext::declareNonArray(const TSourceLoc& loc, const TString& identifier, const TType& type)
7419 {
7420     // make a new variable
7421     TVariable* variable = new TVariable(&identifier, type);
7422
7423 #ifndef GLSLANG_WEB
7424     ioArrayCheck(loc, type, identifier);
7425 #endif
7426
7427     // add variable to symbol table
7428     if (symbolTable.insert(*variable)) {
7429         if (symbolTable.atGlobalLevel())
7430             trackLinkage(*variable);
7431         return variable;
7432     }
7433
7434     error(loc, "redefinition", variable->getName().c_str(), "");
7435     return nullptr;
7436 }
7437
7438 //
7439 // Handle all types of initializers from the grammar.
7440 //
7441 // Returning nullptr just means there is no code to execute to handle the
7442 // initializer, which will, for example, be the case for constant initializers.
7443 //
7444 TIntermNode* TParseContext::executeInitializer(const TSourceLoc& loc, TIntermTyped* initializer, TVariable* variable)
7445 {
7446     // A null initializer is an aggregate that hasn't had an op assigned yet
7447     // (still EOpNull, no relation to nullInit), and has no children.
7448     bool nullInit = initializer->getAsAggregate() && initializer->getAsAggregate()->getOp() == EOpNull &&
7449         initializer->getAsAggregate()->getSequence().size() == 0;
7450
7451     //
7452     // Identifier must be of type constant, a global, or a temporary, and
7453     // starting at version 120, desktop allows uniforms to have initializers.
7454     //
7455     TStorageQualifier qualifier = variable->getType().getQualifier().storage;
7456     if (! (qualifier == EvqTemporary || qualifier == EvqGlobal || qualifier == EvqConst ||
7457            (qualifier == EvqUniform && !isEsProfile() && version >= 120))) {
7458         if (qualifier == EvqShared) {
7459             // GL_EXT_null_initializer allows this for shared, if it's a null initializer
7460             if (nullInit) {
7461                 const char* feature = "initialization with shared qualifier";
7462                 profileRequires(loc, EEsProfile, 0, E_GL_EXT_null_initializer, feature);
7463                 profileRequires(loc, ~EEsProfile, 0, E_GL_EXT_null_initializer, feature);
7464             } else {
7465                 error(loc, "initializer can only be a null initializer ('{}')", "shared", "");
7466             }
7467         } else {
7468             error(loc, " cannot initialize this type of qualifier ",
7469                   variable->getType().getStorageQualifierString(), "");
7470             return nullptr;
7471         }
7472     }
7473
7474     if (nullInit) {
7475         // only some types can be null initialized
7476         if (variable->getType().containsUnsizedArray()) {
7477             error(loc, "null initializers can't size unsized arrays", "{}", "");
7478             return nullptr;
7479         }
7480         if (variable->getType().containsOpaque()) {
7481             error(loc, "null initializers can't be used on opaque values", "{}", "");
7482             return nullptr;
7483         }
7484         variable->getWritableType().getQualifier().setNullInit();
7485         return nullptr;
7486     }
7487
7488     arrayObjectCheck(loc, variable->getType(), "array initializer");
7489
7490     //
7491     // If the initializer was from braces { ... }, we convert the whole subtree to a
7492     // constructor-style subtree, allowing the rest of the code to operate
7493     // identically for both kinds of initializers.
7494     //
7495     // Type can't be deduced from the initializer list, so a skeletal type to
7496     // follow has to be passed in.  Constness and specialization-constness
7497     // should be deduced bottom up, not dictated by the skeletal type.
7498     //
7499     TType skeletalType;
7500     skeletalType.shallowCopy(variable->getType());
7501     skeletalType.getQualifier().makeTemporary();
7502 #ifndef GLSLANG_WEB
7503     initializer = convertInitializerList(loc, skeletalType, initializer);
7504 #endif
7505     if (! initializer) {
7506         // error recovery; don't leave const without constant values
7507         if (qualifier == EvqConst)
7508             variable->getWritableType().getQualifier().makeTemporary();
7509         return nullptr;
7510     }
7511
7512     // Fix outer arrayness if variable is unsized, getting size from the initializer
7513     if (initializer->getType().isSizedArray() && variable->getType().isUnsizedArray())
7514         variable->getWritableType().changeOuterArraySize(initializer->getType().getOuterArraySize());
7515
7516     // Inner arrayness can also get set by an initializer
7517     if (initializer->getType().isArrayOfArrays() && variable->getType().isArrayOfArrays() &&
7518         initializer->getType().getArraySizes()->getNumDims() ==
7519            variable->getType().getArraySizes()->getNumDims()) {
7520         // adopt unsized sizes from the initializer's sizes
7521         for (int d = 1; d < variable->getType().getArraySizes()->getNumDims(); ++d) {
7522             if (variable->getType().getArraySizes()->getDimSize(d) == UnsizedArraySize) {
7523                 variable->getWritableType().getArraySizes()->setDimSize(d,
7524                     initializer->getType().getArraySizes()->getDimSize(d));
7525             }
7526         }
7527     }
7528
7529     // Uniforms require a compile-time constant initializer
7530     if (qualifier == EvqUniform && ! initializer->getType().getQualifier().isFrontEndConstant()) {
7531         error(loc, "uniform initializers must be constant", "=", "'%s'",
7532               variable->getType().getCompleteString(intermediate.getEnhancedMsgs()).c_str());
7533         variable->getWritableType().getQualifier().makeTemporary();
7534         return nullptr;
7535     }
7536     // Global consts require a constant initializer (specialization constant is okay)
7537     if (qualifier == EvqConst && symbolTable.atGlobalLevel() && ! initializer->getType().getQualifier().isConstant()) {
7538         error(loc, "global const initializers must be constant", "=", "'%s'",
7539               variable->getType().getCompleteString(intermediate.getEnhancedMsgs()).c_str());
7540         variable->getWritableType().getQualifier().makeTemporary();
7541         return nullptr;
7542     }
7543
7544     // Const variables require a constant initializer, depending on version
7545     if (qualifier == EvqConst) {
7546         if (! initializer->getType().getQualifier().isConstant()) {
7547             const char* initFeature = "non-constant initializer";
7548             requireProfile(loc, ~EEsProfile, initFeature);
7549             profileRequires(loc, ~EEsProfile, 420, E_GL_ARB_shading_language_420pack, initFeature);
7550             variable->getWritableType().getQualifier().storage = EvqConstReadOnly;
7551             qualifier = EvqConstReadOnly;
7552         }
7553     } else {
7554         // Non-const global variables in ES need a const initializer.
7555         //
7556         // "In declarations of global variables with no storage qualifier or with a const
7557         // qualifier any initializer must be a constant expression."
7558         if (symbolTable.atGlobalLevel() && ! initializer->getType().getQualifier().isConstant()) {
7559             const char* initFeature =
7560                 "non-constant global initializer (needs GL_EXT_shader_non_constant_global_initializers)";
7561             if (isEsProfile()) {
7562                 if (relaxedErrors() && ! extensionTurnedOn(E_GL_EXT_shader_non_constant_global_initializers))
7563                     warn(loc, "not allowed in this version", initFeature, "");
7564                 else
7565                     profileRequires(loc, EEsProfile, 0, E_GL_EXT_shader_non_constant_global_initializers, initFeature);
7566             }
7567         }
7568     }
7569
7570     if (qualifier == EvqConst || qualifier == EvqUniform) {
7571         // Compile-time tagging of the variable with its constant value...
7572
7573         initializer = intermediate.addConversion(EOpAssign, variable->getType(), initializer);
7574         if (! initializer || ! initializer->getType().getQualifier().isConstant() ||
7575             variable->getType() != initializer->getType()) {
7576             error(loc, "non-matching or non-convertible constant type for const initializer",
7577                   variable->getType().getStorageQualifierString(), "");
7578             variable->getWritableType().getQualifier().makeTemporary();
7579             return nullptr;
7580         }
7581
7582         // We either have a folded constant in getAsConstantUnion, or we have to use
7583         // the initializer's subtree in the AST to represent the computation of a
7584         // specialization constant.
7585         assert(initializer->getAsConstantUnion() || initializer->getType().getQualifier().isSpecConstant());
7586         if (initializer->getAsConstantUnion())
7587             variable->setConstArray(initializer->getAsConstantUnion()->getConstArray());
7588         else {
7589             // It's a specialization constant.
7590             variable->getWritableType().getQualifier().makeSpecConstant();
7591
7592             // Keep the subtree that computes the specialization constant with the variable.
7593             // Later, a symbol node will adopt the subtree from the variable.
7594             variable->setConstSubtree(initializer);
7595         }
7596     } else {
7597         // normal assigning of a value to a variable...
7598         specializationCheck(loc, initializer->getType(), "initializer");
7599         TIntermSymbol* intermSymbol = intermediate.addSymbol(*variable, loc);
7600         TIntermTyped* initNode = intermediate.addAssign(EOpAssign, intermSymbol, initializer, loc);
7601         if (! initNode)
7602             assignError(loc, "=", intermSymbol->getCompleteString(intermediate.getEnhancedMsgs()), initializer->getCompleteString(intermediate.getEnhancedMsgs()));
7603
7604         return initNode;
7605     }
7606
7607     return nullptr;
7608 }
7609
7610 //
7611 // Reprocess any initializer-list (the  "{ ... }" syntax) parts of the
7612 // initializer.
7613 //
7614 // Need to hierarchically assign correct types and implicit
7615 // conversions. Will do this mimicking the same process used for
7616 // creating a constructor-style initializer, ensuring we get the
7617 // same form.  However, it has to in parallel walk the 'type'
7618 // passed in, as type cannot be deduced from an initializer list.
7619 //
7620 TIntermTyped* TParseContext::convertInitializerList(const TSourceLoc& loc, const TType& type, TIntermTyped* initializer)
7621 {
7622     // Will operate recursively.  Once a subtree is found that is constructor style,
7623     // everything below it is already good: Only the "top part" of the initializer
7624     // can be an initializer list, where "top part" can extend for several (or all) levels.
7625
7626     // see if we have bottomed out in the tree within the initializer-list part
7627     TIntermAggregate* initList = initializer->getAsAggregate();
7628     if (! initList || initList->getOp() != EOpNull)
7629         return initializer;
7630
7631     // Of the initializer-list set of nodes, need to process bottom up,
7632     // so recurse deep, then process on the way up.
7633
7634     // Go down the tree here...
7635     if (type.isArray()) {
7636         // The type's array might be unsized, which could be okay, so base sizes on the size of the aggregate.
7637         // Later on, initializer execution code will deal with array size logic.
7638         TType arrayType;
7639         arrayType.shallowCopy(type);                     // sharing struct stuff is fine
7640         arrayType.copyArraySizes(*type.getArraySizes());  // but get a fresh copy of the array information, to edit below
7641
7642         // edit array sizes to fill in unsized dimensions
7643         arrayType.changeOuterArraySize((int)initList->getSequence().size());
7644         TIntermTyped* firstInit = initList->getSequence()[0]->getAsTyped();
7645         if (arrayType.isArrayOfArrays() && firstInit->getType().isArray() &&
7646             arrayType.getArraySizes()->getNumDims() == firstInit->getType().getArraySizes()->getNumDims() + 1) {
7647             for (int d = 1; d < arrayType.getArraySizes()->getNumDims(); ++d) {
7648                 if (arrayType.getArraySizes()->getDimSize(d) == UnsizedArraySize)
7649                     arrayType.getArraySizes()->setDimSize(d, firstInit->getType().getArraySizes()->getDimSize(d - 1));
7650             }
7651         }
7652
7653         TType elementType(arrayType, 0); // dereferenced type
7654         for (size_t i = 0; i < initList->getSequence().size(); ++i) {
7655             initList->getSequence()[i] = convertInitializerList(loc, elementType, initList->getSequence()[i]->getAsTyped());
7656             if (initList->getSequence()[i] == nullptr)
7657                 return nullptr;
7658         }
7659
7660         return addConstructor(loc, initList, arrayType);
7661     } else if (type.isStruct()) {
7662         if (type.getStruct()->size() != initList->getSequence().size()) {
7663             error(loc, "wrong number of structure members", "initializer list", "");
7664             return nullptr;
7665         }
7666         for (size_t i = 0; i < type.getStruct()->size(); ++i) {
7667             initList->getSequence()[i] = convertInitializerList(loc, *(*type.getStruct())[i].type, initList->getSequence()[i]->getAsTyped());
7668             if (initList->getSequence()[i] == nullptr)
7669                 return nullptr;
7670         }
7671     } else if (type.isMatrix()) {
7672         if (type.getMatrixCols() != (int)initList->getSequence().size()) {
7673             error(loc, "wrong number of matrix columns:", "initializer list", type.getCompleteString(intermediate.getEnhancedMsgs()).c_str());
7674             return nullptr;
7675         }
7676         TType vectorType(type, 0); // dereferenced type
7677         for (int i = 0; i < type.getMatrixCols(); ++i) {
7678             initList->getSequence()[i] = convertInitializerList(loc, vectorType, initList->getSequence()[i]->getAsTyped());
7679             if (initList->getSequence()[i] == nullptr)
7680                 return nullptr;
7681         }
7682     } else if (type.isVector()) {
7683         if (type.getVectorSize() != (int)initList->getSequence().size()) {
7684             error(loc, "wrong vector size (or rows in a matrix column):", "initializer list", type.getCompleteString(intermediate.getEnhancedMsgs()).c_str());
7685             return nullptr;
7686         }
7687         TBasicType destType = type.getBasicType();
7688         for (int i = 0; i < type.getVectorSize(); ++i) {
7689             TBasicType initType = initList->getSequence()[i]->getAsTyped()->getBasicType();
7690             if (destType != initType && !intermediate.canImplicitlyPromote(initType, destType)) {
7691                 error(loc, "type mismatch in initializer list", "initializer list", type.getCompleteString(intermediate.getEnhancedMsgs()).c_str());
7692                 return nullptr;
7693             }
7694
7695         }
7696     } else {
7697         error(loc, "unexpected initializer-list type:", "initializer list", type.getCompleteString(intermediate.getEnhancedMsgs()).c_str());
7698         return nullptr;
7699     }
7700
7701     // Now that the subtree is processed, process this node as if the
7702     // initializer list is a set of arguments to a constructor.
7703     TIntermNode* emulatedConstructorArguments;
7704     if (initList->getSequence().size() == 1)
7705         emulatedConstructorArguments = initList->getSequence()[0];
7706     else
7707         emulatedConstructorArguments = initList;
7708     return addConstructor(loc, emulatedConstructorArguments, type);
7709 }
7710
7711 //
7712 // Test for the correctness of the parameters passed to various constructor functions
7713 // and also convert them to the right data type, if allowed and required.
7714 //
7715 // 'node' is what to construct from.
7716 // 'type' is what type to construct.
7717 //
7718 // Returns nullptr for an error or the constructed node (aggregate or typed) for no error.
7719 //
7720 TIntermTyped* TParseContext::addConstructor(const TSourceLoc& loc, TIntermNode* node, const TType& type)
7721 {
7722     if (node == nullptr || node->getAsTyped() == nullptr)
7723         return nullptr;
7724     rValueErrorCheck(loc, "constructor", node->getAsTyped());
7725
7726     TIntermAggregate* aggrNode = node->getAsAggregate();
7727     TOperator op = intermediate.mapTypeToConstructorOp(type);
7728
7729     // Combined texture-sampler constructors are completely semantic checked
7730     // in constructorTextureSamplerError()
7731     if (op == EOpConstructTextureSampler) {
7732         if (aggrNode->getSequence()[1]->getAsTyped()->getType().getSampler().shadow) {
7733             // Transfer depth into the texture (SPIR-V image) type, as a hint
7734             // for tools to know this texture/image is a depth image.
7735             aggrNode->getSequence()[0]->getAsTyped()->getWritableType().getSampler().shadow = true;
7736         }
7737         return intermediate.setAggregateOperator(aggrNode, op, type, loc);
7738     }
7739
7740     TTypeList::const_iterator memberTypes;
7741     if (op == EOpConstructStruct)
7742         memberTypes = type.getStruct()->begin();
7743
7744     TType elementType;
7745     if (type.isArray()) {
7746         TType dereferenced(type, 0);
7747         elementType.shallowCopy(dereferenced);
7748     } else
7749         elementType.shallowCopy(type);
7750
7751     bool singleArg;
7752     if (aggrNode) {
7753         if (aggrNode->getOp() != EOpNull)
7754             singleArg = true;
7755         else
7756             singleArg = false;
7757     } else
7758         singleArg = true;
7759
7760     TIntermTyped *newNode;
7761     if (singleArg) {
7762         // If structure constructor or array constructor is being called
7763         // for only one parameter inside the structure, we need to call constructAggregate function once.
7764         if (type.isArray())
7765             newNode = constructAggregate(node, elementType, 1, node->getLoc());
7766         else if (op == EOpConstructStruct)
7767             newNode = constructAggregate(node, *(*memberTypes).type, 1, node->getLoc());
7768         else
7769             newNode = constructBuiltIn(type, op, node->getAsTyped(), node->getLoc(), false);
7770
7771         if (newNode && (type.isArray() || op == EOpConstructStruct))
7772             newNode = intermediate.setAggregateOperator(newNode, EOpConstructStruct, type, loc);
7773
7774         return newNode;
7775     }
7776
7777     //
7778     // Handle list of arguments.
7779     //
7780     TIntermSequence &sequenceVector = aggrNode->getSequence();    // Stores the information about the parameter to the constructor
7781     // if the structure constructor contains more than one parameter, then construct
7782     // each parameter
7783
7784     int paramCount = 0;  // keeps track of the constructor parameter number being checked
7785
7786     // for each parameter to the constructor call, check to see if the right type is passed or convert them
7787     // to the right type if possible (and allowed).
7788     // for structure constructors, just check if the right type is passed, no conversion is allowed.
7789     for (TIntermSequence::iterator p = sequenceVector.begin();
7790                                    p != sequenceVector.end(); p++, paramCount++) {
7791         if (type.isArray())
7792             newNode = constructAggregate(*p, elementType, paramCount+1, node->getLoc());
7793         else if (op == EOpConstructStruct)
7794             newNode = constructAggregate(*p, *(memberTypes[paramCount]).type, paramCount+1, node->getLoc());
7795         else
7796             newNode = constructBuiltIn(type, op, (*p)->getAsTyped(), node->getLoc(), true);
7797
7798         if (newNode)
7799             *p = newNode;
7800         else
7801             return nullptr;
7802     }
7803
7804     TIntermTyped *ret_node = intermediate.setAggregateOperator(aggrNode, op, type, loc);
7805
7806     TIntermAggregate *agg_node = ret_node->getAsAggregate();
7807     if (agg_node && (agg_node->isVector() || agg_node->isArray() || agg_node->isMatrix()))
7808         agg_node->updatePrecision();
7809
7810     return ret_node;
7811 }
7812
7813 // Function for constructor implementation. Calls addUnaryMath with appropriate EOp value
7814 // for the parameter to the constructor (passed to this function). Essentially, it converts
7815 // the parameter types correctly. If a constructor expects an int (like ivec2) and is passed a
7816 // float, then float is converted to int.
7817 //
7818 // Returns nullptr for an error or the constructed node.
7819 //
7820 TIntermTyped* TParseContext::constructBuiltIn(const TType& type, TOperator op, TIntermTyped* node, const TSourceLoc& loc,
7821     bool subset)
7822 {
7823     // If we are changing a matrix in both domain of basic type and to a non matrix,
7824     // do the shape change first (by default, below, basic type is changed before shape).
7825     // This avoids requesting a matrix of a new type that is going to be discarded anyway.
7826     // TODO: This could be generalized to more type combinations, but that would require
7827     // more extensive testing and full algorithm rework. For now, the need to do two changes makes
7828     // the recursive call work, and avoids the most egregious case of creating integer matrices.
7829     if (node->getType().isMatrix() && (type.isScalar() || type.isVector()) &&
7830             type.isFloatingDomain() != node->getType().isFloatingDomain()) {
7831         TType transitionType(node->getBasicType(), glslang::EvqTemporary, type.getVectorSize(), 0, 0, node->isVector());
7832         TOperator transitionOp = intermediate.mapTypeToConstructorOp(transitionType);
7833         node = constructBuiltIn(transitionType, transitionOp, node, loc, false);
7834     }
7835
7836     TIntermTyped* newNode;
7837     TOperator basicOp;
7838
7839     //
7840     // First, convert types as needed.
7841     //
7842     switch (op) {
7843     case EOpConstructVec2:
7844     case EOpConstructVec3:
7845     case EOpConstructVec4:
7846     case EOpConstructMat2x2:
7847     case EOpConstructMat2x3:
7848     case EOpConstructMat2x4:
7849     case EOpConstructMat3x2:
7850     case EOpConstructMat3x3:
7851     case EOpConstructMat3x4:
7852     case EOpConstructMat4x2:
7853     case EOpConstructMat4x3:
7854     case EOpConstructMat4x4:
7855     case EOpConstructFloat:
7856         basicOp = EOpConstructFloat;
7857         break;
7858
7859     case EOpConstructIVec2:
7860     case EOpConstructIVec3:
7861     case EOpConstructIVec4:
7862     case EOpConstructInt:
7863         basicOp = EOpConstructInt;
7864         break;
7865
7866     case EOpConstructUVec2:
7867         if (node->getType().getBasicType() == EbtReference) {
7868             requireExtensions(loc, 1, &E_GL_EXT_buffer_reference_uvec2, "reference conversion to uvec2");
7869             TIntermTyped* newNode = intermediate.addBuiltInFunctionCall(node->getLoc(), EOpConvPtrToUvec2, true, node,
7870                 type);
7871             return newNode;
7872         }
7873     case EOpConstructUVec3:
7874     case EOpConstructUVec4:
7875     case EOpConstructUint:
7876         basicOp = EOpConstructUint;
7877         break;
7878
7879     case EOpConstructBVec2:
7880     case EOpConstructBVec3:
7881     case EOpConstructBVec4:
7882     case EOpConstructBool:
7883         basicOp = EOpConstructBool;
7884         break;
7885
7886 #ifndef GLSLANG_WEB
7887
7888     case EOpConstructDVec2:
7889     case EOpConstructDVec3:
7890     case EOpConstructDVec4:
7891     case EOpConstructDMat2x2:
7892     case EOpConstructDMat2x3:
7893     case EOpConstructDMat2x4:
7894     case EOpConstructDMat3x2:
7895     case EOpConstructDMat3x3:
7896     case EOpConstructDMat3x4:
7897     case EOpConstructDMat4x2:
7898     case EOpConstructDMat4x3:
7899     case EOpConstructDMat4x4:
7900     case EOpConstructDouble:
7901         basicOp = EOpConstructDouble;
7902         break;
7903
7904     case EOpConstructF16Vec2:
7905     case EOpConstructF16Vec3:
7906     case EOpConstructF16Vec4:
7907     case EOpConstructF16Mat2x2:
7908     case EOpConstructF16Mat2x3:
7909     case EOpConstructF16Mat2x4:
7910     case EOpConstructF16Mat3x2:
7911     case EOpConstructF16Mat3x3:
7912     case EOpConstructF16Mat3x4:
7913     case EOpConstructF16Mat4x2:
7914     case EOpConstructF16Mat4x3:
7915     case EOpConstructF16Mat4x4:
7916     case EOpConstructFloat16:
7917         basicOp = EOpConstructFloat16;
7918         // 8/16-bit storage extensions don't support constructing composites of 8/16-bit types,
7919         // so construct a 32-bit type and convert
7920         if (!intermediate.getArithemeticFloat16Enabled()) {
7921             TType tempType(EbtFloat, EvqTemporary, type.getVectorSize());
7922             newNode = node;
7923             if (tempType != newNode->getType()) {
7924                 TOperator aggregateOp;
7925                 if (op == EOpConstructFloat16)
7926                     aggregateOp = EOpConstructFloat;
7927                 else
7928                     aggregateOp = (TOperator)(EOpConstructVec2 + op - EOpConstructF16Vec2);
7929                 newNode = intermediate.setAggregateOperator(newNode, aggregateOp, tempType, node->getLoc());
7930             }
7931             newNode = intermediate.addConversion(EbtFloat16, newNode);
7932             return newNode;
7933         }
7934         break;
7935
7936     case EOpConstructI8Vec2:
7937     case EOpConstructI8Vec3:
7938     case EOpConstructI8Vec4:
7939     case EOpConstructInt8:
7940         basicOp = EOpConstructInt8;
7941         // 8/16-bit storage extensions don't support constructing composites of 8/16-bit types,
7942         // so construct a 32-bit type and convert
7943         if (!intermediate.getArithemeticInt8Enabled()) {
7944             TType tempType(EbtInt, EvqTemporary, type.getVectorSize());
7945             newNode = node;
7946             if (tempType != newNode->getType()) {
7947                 TOperator aggregateOp;
7948                 if (op == EOpConstructInt8)
7949                     aggregateOp = EOpConstructInt;
7950                 else
7951                     aggregateOp = (TOperator)(EOpConstructIVec2 + op - EOpConstructI8Vec2);
7952                 newNode = intermediate.setAggregateOperator(newNode, aggregateOp, tempType, node->getLoc());
7953             }
7954             newNode = intermediate.addConversion(EbtInt8, newNode);
7955             return newNode;
7956         }
7957         break;
7958
7959     case EOpConstructU8Vec2:
7960     case EOpConstructU8Vec3:
7961     case EOpConstructU8Vec4:
7962     case EOpConstructUint8:
7963         basicOp = EOpConstructUint8;
7964         // 8/16-bit storage extensions don't support constructing composites of 8/16-bit types,
7965         // so construct a 32-bit type and convert
7966         if (!intermediate.getArithemeticInt8Enabled()) {
7967             TType tempType(EbtUint, EvqTemporary, type.getVectorSize());
7968             newNode = node;
7969             if (tempType != newNode->getType()) {
7970                 TOperator aggregateOp;
7971                 if (op == EOpConstructUint8)
7972                     aggregateOp = EOpConstructUint;
7973                 else
7974                     aggregateOp = (TOperator)(EOpConstructUVec2 + op - EOpConstructU8Vec2);
7975                 newNode = intermediate.setAggregateOperator(newNode, aggregateOp, tempType, node->getLoc());
7976             }
7977             newNode = intermediate.addConversion(EbtUint8, newNode);
7978             return newNode;
7979         }
7980         break;
7981
7982     case EOpConstructI16Vec2:
7983     case EOpConstructI16Vec3:
7984     case EOpConstructI16Vec4:
7985     case EOpConstructInt16:
7986         basicOp = EOpConstructInt16;
7987         // 8/16-bit storage extensions don't support constructing composites of 8/16-bit types,
7988         // so construct a 32-bit type and convert
7989         if (!intermediate.getArithemeticInt16Enabled()) {
7990             TType tempType(EbtInt, EvqTemporary, type.getVectorSize());
7991             newNode = node;
7992             if (tempType != newNode->getType()) {
7993                 TOperator aggregateOp;
7994                 if (op == EOpConstructInt16)
7995                     aggregateOp = EOpConstructInt;
7996                 else
7997                     aggregateOp = (TOperator)(EOpConstructIVec2 + op - EOpConstructI16Vec2);
7998                 newNode = intermediate.setAggregateOperator(newNode, aggregateOp, tempType, node->getLoc());
7999             }
8000             newNode = intermediate.addConversion(EbtInt16, newNode);
8001             return newNode;
8002         }
8003         break;
8004
8005     case EOpConstructU16Vec2:
8006     case EOpConstructU16Vec3:
8007     case EOpConstructU16Vec4:
8008     case EOpConstructUint16:
8009         basicOp = EOpConstructUint16;
8010         // 8/16-bit storage extensions don't support constructing composites of 8/16-bit types,
8011         // so construct a 32-bit type and convert
8012         if (!intermediate.getArithemeticInt16Enabled()) {
8013             TType tempType(EbtUint, EvqTemporary, type.getVectorSize());
8014             newNode = node;
8015             if (tempType != newNode->getType()) {
8016                 TOperator aggregateOp;
8017                 if (op == EOpConstructUint16)
8018                     aggregateOp = EOpConstructUint;
8019                 else
8020                     aggregateOp = (TOperator)(EOpConstructUVec2 + op - EOpConstructU16Vec2);
8021                 newNode = intermediate.setAggregateOperator(newNode, aggregateOp, tempType, node->getLoc());
8022             }
8023             newNode = intermediate.addConversion(EbtUint16, newNode);
8024             return newNode;
8025         }
8026         break;
8027
8028     case EOpConstructI64Vec2:
8029     case EOpConstructI64Vec3:
8030     case EOpConstructI64Vec4:
8031     case EOpConstructInt64:
8032         basicOp = EOpConstructInt64;
8033         break;
8034
8035     case EOpConstructUint64:
8036         if (type.isScalar() && node->getType().isReference()) {
8037             TIntermTyped* newNode = intermediate.addBuiltInFunctionCall(node->getLoc(), EOpConvPtrToUint64, true, node, type);
8038             return newNode;
8039         }
8040         // fall through
8041     case EOpConstructU64Vec2:
8042     case EOpConstructU64Vec3:
8043     case EOpConstructU64Vec4:
8044         basicOp = EOpConstructUint64;
8045         break;
8046
8047     case EOpConstructNonuniform:
8048         // Make a nonuniform copy of node
8049         newNode = intermediate.addBuiltInFunctionCall(node->getLoc(), EOpCopyObject, true, node, type);
8050         return newNode;
8051
8052     case EOpConstructReference:
8053         // construct reference from reference
8054         if (node->getType().isReference()) {
8055             newNode = intermediate.addBuiltInFunctionCall(node->getLoc(), EOpConstructReference, true, node, type);
8056             return newNode;
8057         // construct reference from uint64
8058         } else if (node->getType().isScalar() && node->getType().getBasicType() == EbtUint64) {
8059             TIntermTyped* newNode = intermediate.addBuiltInFunctionCall(node->getLoc(), EOpConvUint64ToPtr, true, node,
8060                 type);
8061             return newNode;
8062         // construct reference from uvec2
8063         } else if (node->getType().isVector() && node->getType().getBasicType() == EbtUint &&
8064                    node->getVectorSize() == 2) {
8065             requireExtensions(loc, 1, &E_GL_EXT_buffer_reference_uvec2, "uvec2 conversion to reference");
8066             TIntermTyped* newNode = intermediate.addBuiltInFunctionCall(node->getLoc(), EOpConvUvec2ToPtr, true, node,
8067                 type);
8068             return newNode;
8069         } else {
8070             return nullptr;
8071         }
8072
8073     case EOpConstructCooperativeMatrix:
8074         if (!node->getType().isCoopMat()) {
8075             if (type.getBasicType() != node->getType().getBasicType()) {
8076                 node = intermediate.addConversion(type.getBasicType(), node);
8077                 if (node == nullptr)
8078                     return nullptr;
8079             }
8080             node = intermediate.setAggregateOperator(node, EOpConstructCooperativeMatrix, type, node->getLoc());
8081         } else {
8082             TOperator op = EOpNull;
8083             switch (type.getBasicType()) {
8084             default:
8085                 assert(0);
8086                 break;
8087             case EbtInt:
8088                 switch (node->getType().getBasicType()) {
8089                     case EbtFloat:   op = EOpConvFloatToInt;    break;
8090                     case EbtFloat16: op = EOpConvFloat16ToInt;  break;
8091                     case EbtUint8:   op = EOpConvUint8ToInt;    break;
8092                     case EbtInt8:    op = EOpConvInt8ToInt;     break;
8093                     case EbtUint:    op = EOpConvUintToInt;     break;
8094                     default: assert(0);
8095                 }
8096                 break;
8097             case EbtUint:
8098                 switch (node->getType().getBasicType()) {
8099                     case EbtFloat:   op = EOpConvFloatToUint;    break;
8100                     case EbtFloat16: op = EOpConvFloat16ToUint;  break;
8101                     case EbtUint8:   op = EOpConvUint8ToUint;    break;
8102                     case EbtInt8:    op = EOpConvInt8ToUint;     break;
8103                     case EbtInt:     op = EOpConvIntToUint;      break;
8104                     case EbtUint:    op = EOpConvUintToInt8;     break;
8105                     default: assert(0);
8106                 }
8107                 break;
8108             case EbtInt8:
8109                 switch (node->getType().getBasicType()) {
8110                     case EbtFloat:   op = EOpConvFloatToInt8;    break;
8111                     case EbtFloat16: op = EOpConvFloat16ToInt8;  break;
8112                     case EbtUint8:   op = EOpConvUint8ToInt8;    break;
8113                     case EbtInt:     op = EOpConvIntToInt8;      break;
8114                     case EbtUint:    op = EOpConvUintToInt8;     break;
8115                     default: assert(0);
8116                 }
8117                 break;
8118             case EbtUint8:
8119                 switch (node->getType().getBasicType()) {
8120                     case EbtFloat:   op = EOpConvFloatToUint8;   break;
8121                     case EbtFloat16: op = EOpConvFloat16ToUint8; break;
8122                     case EbtInt8:    op = EOpConvInt8ToUint8;    break;
8123                     case EbtInt:     op = EOpConvIntToUint8;     break;
8124                     case EbtUint:    op = EOpConvUintToUint8;    break;
8125                     default: assert(0);
8126                 }
8127                 break;
8128             case EbtFloat:
8129                 switch (node->getType().getBasicType()) {
8130                     case EbtFloat16: op = EOpConvFloat16ToFloat;  break;
8131                     case EbtInt8:    op = EOpConvInt8ToFloat;     break;
8132                     case EbtUint8:   op = EOpConvUint8ToFloat;    break;
8133                     case EbtInt:     op = EOpConvIntToFloat;      break;
8134                     case EbtUint:    op = EOpConvUintToFloat;     break;
8135                     default: assert(0);
8136                 }
8137                 break;
8138             case EbtFloat16:
8139                 switch (node->getType().getBasicType()) {
8140                     case EbtFloat:  op = EOpConvFloatToFloat16;  break;
8141                     case EbtInt8:   op = EOpConvInt8ToFloat16;   break;
8142                     case EbtUint8:  op = EOpConvUint8ToFloat16;  break;
8143                     case EbtInt:    op = EOpConvIntToFloat16;    break;
8144                     case EbtUint:   op = EOpConvUintToFloat16;   break;
8145                     default: assert(0);
8146                 }
8147                 break;
8148             }
8149
8150             node = intermediate.addUnaryNode(op, node, node->getLoc(), type);
8151             // If it's a (non-specialization) constant, it must be folded.
8152             if (node->getAsUnaryNode()->getOperand()->getAsConstantUnion())
8153                 return node->getAsUnaryNode()->getOperand()->getAsConstantUnion()->fold(op, node->getType());
8154         }
8155
8156         return node;
8157
8158     case EOpConstructAccStruct:
8159         if ((node->getType().isScalar() && node->getType().getBasicType() == EbtUint64)) {
8160             // construct acceleration structure from uint64
8161             requireExtensions(loc, Num_ray_tracing_EXTs, ray_tracing_EXTs, "uint64_t conversion to acclerationStructureEXT");
8162             return intermediate.addBuiltInFunctionCall(node->getLoc(), EOpConvUint64ToAccStruct, true, node,
8163                 type);
8164         } else if (node->getType().isVector() && node->getType().getBasicType() == EbtUint && node->getVectorSize() == 2) {
8165             // construct acceleration structure from uint64
8166             requireExtensions(loc, Num_ray_tracing_EXTs, ray_tracing_EXTs, "uvec2 conversion to accelerationStructureEXT");
8167             return intermediate.addBuiltInFunctionCall(node->getLoc(), EOpConvUvec2ToAccStruct, true, node,
8168                 type);
8169         } else
8170             return nullptr;
8171 #endif // GLSLANG_WEB
8172
8173     default:
8174         error(loc, "unsupported construction", "", "");
8175
8176         return nullptr;
8177     }
8178     newNode = intermediate.addUnaryMath(basicOp, node, node->getLoc());
8179     if (newNode == nullptr) {
8180         error(loc, "can't convert", "constructor", "");
8181         return nullptr;
8182     }
8183
8184     //
8185     // Now, if there still isn't an operation to do the construction, and we need one, add one.
8186     //
8187
8188     // Otherwise, skip out early.
8189     if (subset || (newNode != node && newNode->getType() == type))
8190         return newNode;
8191
8192     // setAggregateOperator will insert a new node for the constructor, as needed.
8193     return intermediate.setAggregateOperator(newNode, op, type, loc);
8194 }
8195
8196 // This function tests for the type of the parameters to the structure or array constructor. Raises
8197 // an error message if the expected type does not match the parameter passed to the constructor.
8198 //
8199 // Returns nullptr for an error or the input node itself if the expected and the given parameter types match.
8200 //
8201 TIntermTyped* TParseContext::constructAggregate(TIntermNode* node, const TType& type, int paramCount, const TSourceLoc& loc)
8202 {
8203     TIntermTyped* converted = intermediate.addConversion(EOpConstructStruct, type, node->getAsTyped());
8204     if (! converted || converted->getType() != type) {
8205         bool enhanced = intermediate.getEnhancedMsgs();
8206         error(loc, "", "constructor", "cannot convert parameter %d from '%s' to '%s'", paramCount,
8207               node->getAsTyped()->getType().getCompleteString(enhanced).c_str(), type.getCompleteString(enhanced).c_str());
8208
8209         return nullptr;
8210     }
8211
8212     return converted;
8213 }
8214
8215 // If a memory qualifier is present in 'to', also make it present in 'from'.
8216 void TParseContext::inheritMemoryQualifiers(const TQualifier& from, TQualifier& to)
8217 {
8218 #ifndef GLSLANG_WEB
8219     if (from.isReadOnly())
8220         to.readonly = from.readonly;
8221     if (from.isWriteOnly())
8222         to.writeonly = from.writeonly;
8223     if (from.coherent)
8224         to.coherent = from.coherent;
8225     if (from.volatil)
8226         to.volatil = from.volatil;
8227     if (from.restrict)
8228         to.restrict = from.restrict;
8229 #endif
8230 }
8231
8232 //
8233 // Do everything needed to add an interface block.
8234 //
8235 void TParseContext::declareBlock(const TSourceLoc& loc, TTypeList& typeList, const TString* instanceName,
8236     TArraySizes* arraySizes)
8237 {
8238     if (spvVersion.vulkan > 0 && spvVersion.vulkanRelaxed)
8239         blockStorageRemap(loc, blockName, currentBlockQualifier);
8240     blockStageIoCheck(loc, currentBlockQualifier);
8241     blockQualifierCheck(loc, currentBlockQualifier, instanceName != nullptr);
8242     if (arraySizes != nullptr) {
8243         arraySizesCheck(loc, currentBlockQualifier, arraySizes, nullptr, false);
8244         arrayOfArrayVersionCheck(loc, arraySizes);
8245         if (arraySizes->getNumDims() > 1)
8246             requireProfile(loc, ~EEsProfile, "array-of-array of block");
8247     }
8248
8249     // Inherit and check member storage qualifiers WRT to the block-level qualifier.
8250     for (unsigned int member = 0; member < typeList.size(); ++member) {
8251         TType& memberType = *typeList[member].type;
8252         TQualifier& memberQualifier = memberType.getQualifier();
8253         const TSourceLoc& memberLoc = typeList[member].loc;
8254         if (memberQualifier.storage != EvqTemporary && memberQualifier.storage != EvqGlobal && memberQualifier.storage != currentBlockQualifier.storage)
8255             error(memberLoc, "member storage qualifier cannot contradict block storage qualifier", memberType.getFieldName().c_str(), "");
8256         memberQualifier.storage = currentBlockQualifier.storage;
8257         globalQualifierFixCheck(memberLoc, memberQualifier);
8258 #ifndef GLSLANG_WEB
8259         inheritMemoryQualifiers(currentBlockQualifier, memberQualifier);
8260         if (currentBlockQualifier.perPrimitiveNV)
8261             memberQualifier.perPrimitiveNV = currentBlockQualifier.perPrimitiveNV;
8262         if (currentBlockQualifier.perViewNV)
8263             memberQualifier.perViewNV = currentBlockQualifier.perViewNV;
8264         if (currentBlockQualifier.perTaskNV)
8265             memberQualifier.perTaskNV = currentBlockQualifier.perTaskNV;
8266         if (currentBlockQualifier.storage == EvqtaskPayloadSharedEXT)
8267             memberQualifier.storage = EvqtaskPayloadSharedEXT;
8268         if (memberQualifier.storage == EvqSpirvStorageClass)
8269             error(memberLoc, "member cannot have a spirv_storage_class qualifier", memberType.getFieldName().c_str(), "");
8270         if (memberQualifier.hasSprivDecorate() && !memberQualifier.getSpirvDecorate().decorateIds.empty())
8271             error(memberLoc, "member cannot have a spirv_decorate_id qualifier", memberType.getFieldName().c_str(), "");
8272 #endif
8273         if ((currentBlockQualifier.storage == EvqUniform || currentBlockQualifier.storage == EvqBuffer) && (memberQualifier.isInterpolation() || memberQualifier.isAuxiliary()))
8274             error(memberLoc, "member of uniform or buffer block cannot have an auxiliary or interpolation qualifier", memberType.getFieldName().c_str(), "");
8275         if (memberType.isArray())
8276             arraySizesCheck(memberLoc, currentBlockQualifier, memberType.getArraySizes(), nullptr, member == typeList.size() - 1);
8277         if (memberQualifier.hasOffset()) {
8278             if (spvVersion.spv == 0) {
8279                 profileRequires(memberLoc, ~EEsProfile, 440, E_GL_ARB_enhanced_layouts, "\"offset\" on block member");
8280                 profileRequires(memberLoc, EEsProfile, 300, E_GL_ARB_enhanced_layouts, "\"offset\" on block member");
8281             }
8282         }
8283
8284         if (memberType.containsOpaque())
8285             error(memberLoc, "member of block cannot be or contain a sampler, image, or atomic_uint type", typeList[member].type->getFieldName().c_str(), "");
8286
8287         if (memberType.containsCoopMat())
8288             error(memberLoc, "member of block cannot be or contain a cooperative matrix type", typeList[member].type->getFieldName().c_str(), "");
8289     }
8290
8291     // This might be a redeclaration of a built-in block.  If so, redeclareBuiltinBlock() will
8292     // do all the rest.
8293     if (! symbolTable.atBuiltInLevel() && builtInName(*blockName)) {
8294         redeclareBuiltinBlock(loc, typeList, *blockName, instanceName, arraySizes);
8295         return;
8296     }
8297
8298     // Not a redeclaration of a built-in; check that all names are user names.
8299     reservedErrorCheck(loc, *blockName);
8300     if (instanceName)
8301         reservedErrorCheck(loc, *instanceName);
8302     for (unsigned int member = 0; member < typeList.size(); ++member)
8303         reservedErrorCheck(typeList[member].loc, typeList[member].type->getFieldName());
8304
8305     // Make default block qualification, and adjust the member qualifications
8306
8307     TQualifier defaultQualification;
8308     switch (currentBlockQualifier.storage) {
8309     case EvqUniform:    defaultQualification = globalUniformDefaults;    break;
8310     case EvqBuffer:     defaultQualification = globalBufferDefaults;     break;
8311     case EvqVaryingIn:  defaultQualification = globalInputDefaults;      break;
8312     case EvqVaryingOut: defaultQualification = globalOutputDefaults;     break;
8313     case EvqShared:     defaultQualification = globalSharedDefaults;     break;
8314     default:            defaultQualification.clear();                    break;
8315     }
8316
8317     // Special case for "push_constant uniform", which has a default of std430,
8318     // contrary to normal uniform defaults, and can't have a default tracked for it.
8319     if ((currentBlockQualifier.isPushConstant() && !currentBlockQualifier.hasPacking()) ||
8320         (currentBlockQualifier.isShaderRecord() && !currentBlockQualifier.hasPacking()))
8321         currentBlockQualifier.layoutPacking = ElpStd430;
8322
8323     // Special case for "taskNV in/out", which has a default of std430,
8324     if (currentBlockQualifier.isTaskMemory() && !currentBlockQualifier.hasPacking())
8325         currentBlockQualifier.layoutPacking = ElpStd430;
8326
8327     // fix and check for member layout qualifiers
8328
8329     mergeObjectLayoutQualifiers(defaultQualification, currentBlockQualifier, true);
8330
8331     // "The align qualifier can only be used on blocks or block members, and only for blocks declared with std140 or std430 layouts."
8332     if (currentBlockQualifier.hasAlign()) {
8333         if (defaultQualification.layoutPacking != ElpStd140 &&
8334             defaultQualification.layoutPacking != ElpStd430 &&
8335             defaultQualification.layoutPacking != ElpScalar) {
8336             error(loc, "can only be used with std140, std430, or scalar layout packing", "align", "");
8337             defaultQualification.layoutAlign = -1;
8338         }
8339     }
8340
8341     bool memberWithLocation = false;
8342     bool memberWithoutLocation = false;
8343     bool memberWithPerViewQualifier = false;
8344     for (unsigned int member = 0; member < typeList.size(); ++member) {
8345         TQualifier& memberQualifier = typeList[member].type->getQualifier();
8346         const TSourceLoc& memberLoc = typeList[member].loc;
8347 #ifndef GLSLANG_WEB
8348         if (memberQualifier.hasStream()) {
8349             if (defaultQualification.layoutStream != memberQualifier.layoutStream)
8350                 error(memberLoc, "member cannot contradict block", "stream", "");
8351         }
8352
8353         // "This includes a block's inheritance of the
8354         // current global default buffer, a block member's inheritance of the block's
8355         // buffer, and the requirement that any *xfb_buffer* declared on a block
8356         // member must match the buffer inherited from the block."
8357         if (memberQualifier.hasXfbBuffer()) {
8358             if (defaultQualification.layoutXfbBuffer != memberQualifier.layoutXfbBuffer)
8359                 error(memberLoc, "member cannot contradict block (or what block inherited from global)", "xfb_buffer", "");
8360         }
8361 #endif
8362
8363         if (memberQualifier.hasPacking())
8364             error(memberLoc, "member of block cannot have a packing layout qualifier", typeList[member].type->getFieldName().c_str(), "");
8365         if (memberQualifier.hasLocation()) {
8366             const char* feature = "location on block member";
8367             switch (currentBlockQualifier.storage) {
8368 #ifndef GLSLANG_WEB
8369             case EvqVaryingIn:
8370             case EvqVaryingOut:
8371                 requireProfile(memberLoc, ECoreProfile | ECompatibilityProfile | EEsProfile, feature);
8372                 profileRequires(memberLoc, ECoreProfile | ECompatibilityProfile, 440, E_GL_ARB_enhanced_layouts, feature);
8373                 profileRequires(memberLoc, EEsProfile, 320, Num_AEP_shader_io_blocks, AEP_shader_io_blocks, feature);
8374                 memberWithLocation = true;
8375                 break;
8376 #endif
8377             default:
8378                 error(memberLoc, "can only use in an in/out block", feature, "");
8379                 break;
8380             }
8381         } else
8382             memberWithoutLocation = true;
8383
8384         // "The offset qualifier can only be used on block members of blocks declared with std140 or std430 layouts."
8385         // "The align qualifier can only be used on blocks or block members, and only for blocks declared with std140 or std430 layouts."
8386         if (memberQualifier.hasAlign() || memberQualifier.hasOffset()) {
8387             if (defaultQualification.layoutPacking != ElpStd140 &&
8388                 defaultQualification.layoutPacking != ElpStd430 &&
8389                 defaultQualification.layoutPacking != ElpScalar)
8390                 error(memberLoc, "can only be used with std140, std430, or scalar layout packing", "offset/align", "");
8391         }
8392
8393         if (memberQualifier.isPerView()) {
8394             memberWithPerViewQualifier = true;
8395         }
8396
8397         TQualifier newMemberQualification = defaultQualification;
8398         mergeQualifiers(memberLoc, newMemberQualification, memberQualifier, false);
8399         memberQualifier = newMemberQualification;
8400     }
8401
8402     layoutMemberLocationArrayCheck(loc, memberWithLocation, arraySizes);
8403
8404 #ifndef GLSLANG_WEB
8405     // Ensure that the block has an XfbBuffer assigned. This is needed
8406     // because if the block has a XfbOffset assigned, then it is
8407     // assumed that it has implicitly assigned the current global
8408     // XfbBuffer, and because it's members need to be assigned a
8409     // XfbOffset if they lack it.
8410     if (currentBlockQualifier.storage == EvqVaryingOut && globalOutputDefaults.hasXfbBuffer()) {
8411        if (!currentBlockQualifier.hasXfbBuffer() && currentBlockQualifier.hasXfbOffset())
8412           currentBlockQualifier.layoutXfbBuffer = globalOutputDefaults.layoutXfbBuffer;
8413     }
8414 #endif
8415
8416     // Process the members
8417     fixBlockLocations(loc, currentBlockQualifier, typeList, memberWithLocation, memberWithoutLocation);
8418     fixXfbOffsets(currentBlockQualifier, typeList);
8419     fixBlockUniformOffsets(currentBlockQualifier, typeList);
8420     fixBlockUniformLayoutMatrix(currentBlockQualifier, &typeList, nullptr);
8421     fixBlockUniformLayoutPacking(currentBlockQualifier, &typeList, nullptr);
8422     for (unsigned int member = 0; member < typeList.size(); ++member)
8423         layoutTypeCheck(typeList[member].loc, *typeList[member].type);
8424
8425 #ifndef GLSLANG_WEB
8426     if (memberWithPerViewQualifier) {
8427         for (unsigned int member = 0; member < typeList.size(); ++member) {
8428             checkAndResizeMeshViewDim(typeList[member].loc, *typeList[member].type, /*isBlockMember*/ true);
8429         }
8430     }
8431 #endif
8432
8433     // reverse merge, so that currentBlockQualifier now has all layout information
8434     // (can't use defaultQualification directly, it's missing other non-layout-default-class qualifiers)
8435     mergeObjectLayoutQualifiers(currentBlockQualifier, defaultQualification, true);
8436
8437     //
8438     // Build and add the interface block as a new type named 'blockName'
8439     //
8440
8441     TType blockType(&typeList, *blockName, currentBlockQualifier);
8442     if (arraySizes != nullptr)
8443         blockType.transferArraySizes(arraySizes);
8444
8445 #ifndef GLSLANG_WEB
8446     if (arraySizes == nullptr)
8447         ioArrayCheck(loc, blockType, instanceName ? *instanceName : *blockName);
8448     if (currentBlockQualifier.hasBufferReference()) {
8449
8450         if (currentBlockQualifier.storage != EvqBuffer)
8451             error(loc, "can only be used with buffer", "buffer_reference", "");
8452
8453         // Create the block reference type. If it was forward-declared, detect that
8454         // as a referent struct type with no members. Replace the referent type with
8455         // blockType.
8456         TType blockNameType(EbtReference, blockType, *blockName);
8457         TVariable* blockNameVar = new TVariable(blockName, blockNameType, true);
8458         if (! symbolTable.insert(*blockNameVar)) {
8459             TSymbol* existingName = symbolTable.find(*blockName);
8460             if (existingName->getType().isReference() &&
8461                 existingName->getType().getReferentType()->getStruct() &&
8462                 existingName->getType().getReferentType()->getStruct()->size() == 0 &&
8463                 existingName->getType().getQualifier().storage == blockType.getQualifier().storage) {
8464                 existingName->getType().getReferentType()->deepCopy(blockType);
8465             } else {
8466                 error(loc, "block name cannot be redefined", blockName->c_str(), "");
8467             }
8468         }
8469         if (!instanceName) {
8470             return;
8471         }
8472     } else
8473 #endif
8474     {
8475         //
8476         // Don't make a user-defined type out of block name; that will cause an error
8477         // if the same block name gets reused in a different interface.
8478         //
8479         // "Block names have no other use within a shader
8480         // beyond interface matching; it is a compile-time error to use a block name at global scope for anything
8481         // other than as a block name (e.g., use of a block name for a global variable name or function name is
8482         // currently reserved)."
8483         //
8484         // Use the symbol table to prevent normal reuse of the block's name, as a variable entry,
8485         // whose type is EbtBlock, but without all the structure; that will come from the type
8486         // the instances point to.
8487         //
8488         TType blockNameType(EbtBlock, blockType.getQualifier().storage);
8489         TVariable* blockNameVar = new TVariable(blockName, blockNameType);
8490         if (! symbolTable.insert(*blockNameVar)) {
8491             TSymbol* existingName = symbolTable.find(*blockName);
8492             if (existingName->getType().getBasicType() == EbtBlock) {
8493                 if (existingName->getType().getQualifier().storage == blockType.getQualifier().storage) {
8494                     error(loc, "Cannot reuse block name within the same interface:", blockName->c_str(), blockType.getStorageQualifierString());
8495                     return;
8496                 }
8497             } else {
8498                 error(loc, "block name cannot redefine a non-block name", blockName->c_str(), "");
8499                 return;
8500             }
8501         }
8502     }
8503
8504     // Add the variable, as anonymous or named instanceName.
8505     // Make an anonymous variable if no name was provided.
8506     if (! instanceName)
8507         instanceName = NewPoolTString("");
8508
8509     TVariable& variable = *new TVariable(instanceName, blockType);
8510     if (! symbolTable.insert(variable)) {
8511         if (*instanceName == "")
8512             error(loc, "nameless block contains a member that already has a name at global scope", blockName->c_str(), "");
8513         else
8514             error(loc, "block instance name redefinition", variable.getName().c_str(), "");
8515
8516         return;
8517     }
8518
8519     // Check for general layout qualifier errors
8520     layoutObjectCheck(loc, variable);
8521
8522 #ifndef GLSLANG_WEB
8523     // fix up
8524     if (isIoResizeArray(blockType)) {
8525         ioArraySymbolResizeList.push_back(&variable);
8526         checkIoArraysConsistency(loc, true);
8527     } else
8528         fixIoArraySize(loc, variable.getWritableType());
8529 #endif
8530
8531     // Save it in the AST for linker use.
8532     trackLinkage(variable);
8533 }
8534
8535 //
8536 // allow storage type of block to be remapped at compile time
8537 //
8538 void TParseContext::blockStorageRemap(const TSourceLoc&, const TString* instanceName, TQualifier& qualifier)
8539 {
8540     TBlockStorageClass type = intermediate.getBlockStorageOverride(instanceName->c_str());
8541     if (type != EbsNone) {
8542         qualifier.setBlockStorage(type);
8543     }
8544 }
8545
8546 // Do all block-declaration checking regarding the combination of in/out/uniform/buffer
8547 // with a particular stage.
8548 void TParseContext::blockStageIoCheck(const TSourceLoc& loc, const TQualifier& qualifier)
8549 {
8550     const char *extsrt[2] = { E_GL_NV_ray_tracing, E_GL_EXT_ray_tracing };
8551     switch (qualifier.storage) {
8552     case EvqUniform:
8553         profileRequires(loc, EEsProfile, 300, nullptr, "uniform block");
8554         profileRequires(loc, ENoProfile, 140, E_GL_ARB_uniform_buffer_object, "uniform block");
8555         if (currentBlockQualifier.layoutPacking == ElpStd430 && ! currentBlockQualifier.isPushConstant())
8556             requireExtensions(loc, 1, &E_GL_EXT_scalar_block_layout, "std430 requires the buffer storage qualifier");
8557         break;
8558     case EvqBuffer:
8559         requireProfile(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, "buffer block");
8560         profileRequires(loc, ECoreProfile | ECompatibilityProfile, 430, E_GL_ARB_shader_storage_buffer_object, "buffer block");
8561         profileRequires(loc, EEsProfile, 310, nullptr, "buffer block");
8562         break;
8563     case EvqVaryingIn:
8564         profileRequires(loc, ~EEsProfile, 150, E_GL_ARB_separate_shader_objects, "input block");
8565         // It is a compile-time error to have an input block in a vertex shader or an output block in a fragment shader
8566         // "Compute shaders do not permit user-defined input variables..."
8567         requireStage(loc, (EShLanguageMask)(EShLangTessControlMask|EShLangTessEvaluationMask|EShLangGeometryMask|
8568             EShLangFragmentMask|EShLangMeshMask), "input block");
8569         if (language == EShLangFragment) {
8570             profileRequires(loc, EEsProfile, 320, Num_AEP_shader_io_blocks, AEP_shader_io_blocks, "fragment input block");
8571         } else if (language == EShLangMesh && ! qualifier.isTaskMemory()) {
8572             error(loc, "input blocks cannot be used in a mesh shader", "out", "");
8573         }
8574         break;
8575     case EvqVaryingOut:
8576         profileRequires(loc, ~EEsProfile, 150, E_GL_ARB_separate_shader_objects, "output block");
8577         requireStage(loc, (EShLanguageMask)(EShLangVertexMask|EShLangTessControlMask|EShLangTessEvaluationMask|
8578             EShLangGeometryMask|EShLangMeshMask|EShLangTaskMask), "output block");
8579         // ES 310 can have a block before shader_io is turned on, so skip this test for built-ins
8580         if (language == EShLangVertex && ! parsingBuiltins) {
8581             profileRequires(loc, EEsProfile, 320, Num_AEP_shader_io_blocks, AEP_shader_io_blocks, "vertex output block");
8582         } else if (language == EShLangMesh && qualifier.isTaskMemory()) {
8583             error(loc, "can only use on input blocks in mesh shader", "taskNV", "");
8584         } else if (language == EShLangTask && ! qualifier.isTaskMemory()) {
8585             error(loc, "output blocks cannot be used in a task shader", "out", "");
8586         }
8587         break;
8588     case EvqShared:
8589         if (spvVersion.spv > 0 && spvVersion.spv < EShTargetSpv_1_4) {
8590             error(loc, "shared block requires at least SPIR-V 1.4", "shared block", "");
8591         }
8592         profileRequires(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, 0, E_GL_EXT_shared_memory_block, "shared block");
8593         break;
8594 #ifndef GLSLANG_WEB
8595     case EvqPayload:
8596         profileRequires(loc, ~EEsProfile, 460, 2, extsrt, "rayPayloadNV block");
8597         requireStage(loc, (EShLanguageMask)(EShLangRayGenMask | EShLangAnyHitMask | EShLangClosestHitMask | EShLangMissMask),
8598             "rayPayloadNV block");
8599         break;
8600     case EvqPayloadIn:
8601         profileRequires(loc, ~EEsProfile, 460, 2, extsrt, "rayPayloadInNV block");
8602         requireStage(loc, (EShLanguageMask)(EShLangAnyHitMask | EShLangClosestHitMask | EShLangMissMask),
8603             "rayPayloadInNV block");
8604         break;
8605     case EvqHitAttr:
8606         profileRequires(loc, ~EEsProfile, 460, 2, extsrt, "hitAttributeNV block");
8607         requireStage(loc, (EShLanguageMask)(EShLangIntersectMask | EShLangAnyHitMask | EShLangClosestHitMask), "hitAttributeNV block");
8608         break;
8609     case EvqCallableData:
8610         profileRequires(loc, ~EEsProfile, 460, 2, extsrt, "callableDataNV block");
8611         requireStage(loc, (EShLanguageMask)(EShLangRayGenMask | EShLangClosestHitMask | EShLangMissMask | EShLangCallableMask),
8612             "callableDataNV block");
8613         break;
8614     case EvqCallableDataIn:
8615         profileRequires(loc, ~EEsProfile, 460, 2, extsrt, "callableDataInNV block");
8616         requireStage(loc, (EShLanguageMask)(EShLangCallableMask), "callableDataInNV block");
8617         break;
8618 #endif
8619     default:
8620         error(loc, "only uniform, buffer, in, or out blocks are supported", blockName->c_str(), "");
8621         break;
8622     }
8623 }
8624
8625 // Do all block-declaration checking regarding its qualifiers.
8626 void TParseContext::blockQualifierCheck(const TSourceLoc& loc, const TQualifier& qualifier, bool /*instanceName*/)
8627 {
8628     // The 4.5 specification says:
8629     //
8630     // interface-block :
8631     //    layout-qualifieropt interface-qualifier  block-name { member-list } instance-nameopt ;
8632     //
8633     // interface-qualifier :
8634     //    in
8635     //    out
8636     //    patch in
8637     //    patch out
8638     //    uniform
8639     //    buffer
8640     //
8641     // Note however memory qualifiers aren't included, yet the specification also says
8642     //
8643     // "...memory qualifiers may also be used in the declaration of shader storage blocks..."
8644
8645     if (qualifier.isInterpolation())
8646         error(loc, "cannot use interpolation qualifiers on an interface block", "flat/smooth/noperspective", "");
8647     if (qualifier.centroid)
8648         error(loc, "cannot use centroid qualifier on an interface block", "centroid", "");
8649     if (qualifier.isSample())
8650         error(loc, "cannot use sample qualifier on an interface block", "sample", "");
8651     if (qualifier.invariant)
8652         error(loc, "cannot use invariant qualifier on an interface block", "invariant", "");
8653     if (qualifier.isPushConstant())
8654         intermediate.addPushConstantCount();
8655     if (qualifier.isShaderRecord())
8656         intermediate.addShaderRecordCount();
8657     if (qualifier.isTaskMemory())
8658         intermediate.addTaskNVCount();
8659 }
8660
8661 //
8662 // "For a block, this process applies to the entire block, or until the first member
8663 // is reached that has a location layout qualifier. When a block member is declared with a location
8664 // qualifier, its location comes from that qualifier: The member's location qualifier overrides the block-level
8665 // declaration. Subsequent members are again assigned consecutive locations, based on the newest location,
8666 // until the next member declared with a location qualifier. The values used for locations do not have to be
8667 // declared in increasing order."
8668 void TParseContext::fixBlockLocations(const TSourceLoc& loc, TQualifier& qualifier, TTypeList& typeList, bool memberWithLocation, bool memberWithoutLocation)
8669 {
8670     // "If a block has no block-level location layout qualifier, it is required that either all or none of its members
8671     // have a location layout qualifier, or a compile-time error results."
8672     if (! qualifier.hasLocation() && memberWithLocation && memberWithoutLocation)
8673         error(loc, "either the block needs a location, or all members need a location, or no members have a location", "location", "");
8674     else {
8675         if (memberWithLocation) {
8676             // remove any block-level location and make it per *every* member
8677             int nextLocation = 0;  // by the rule above, initial value is not relevant
8678             if (qualifier.hasAnyLocation()) {
8679                 nextLocation = qualifier.layoutLocation;
8680                 qualifier.layoutLocation = TQualifier::layoutLocationEnd;
8681                 if (qualifier.hasComponent()) {
8682                     // "It is a compile-time error to apply the *component* qualifier to a ... block"
8683                     error(loc, "cannot apply to a block", "component", "");
8684                 }
8685                 if (qualifier.hasIndex()) {
8686                     error(loc, "cannot apply to a block", "index", "");
8687                 }
8688             }
8689             for (unsigned int member = 0; member < typeList.size(); ++member) {
8690                 TQualifier& memberQualifier = typeList[member].type->getQualifier();
8691                 const TSourceLoc& memberLoc = typeList[member].loc;
8692                 if (! memberQualifier.hasLocation()) {
8693                     if (nextLocation >= (int)TQualifier::layoutLocationEnd)
8694                         error(memberLoc, "location is too large", "location", "");
8695                     memberQualifier.layoutLocation = nextLocation;
8696                     memberQualifier.layoutComponent = TQualifier::layoutComponentEnd;
8697                 }
8698                 nextLocation = memberQualifier.layoutLocation + intermediate.computeTypeLocationSize(
8699                                     *typeList[member].type, language);
8700             }
8701         }
8702     }
8703 }
8704
8705 void TParseContext::fixXfbOffsets(TQualifier& qualifier, TTypeList& typeList)
8706 {
8707 #ifndef GLSLANG_WEB
8708     // "If a block is qualified with xfb_offset, all its
8709     // members are assigned transform feedback buffer offsets. If a block is not qualified with xfb_offset, any
8710     // members of that block not qualified with an xfb_offset will not be assigned transform feedback buffer
8711     // offsets."
8712
8713     if (! qualifier.hasXfbBuffer() || ! qualifier.hasXfbOffset())
8714         return;
8715
8716     int nextOffset = qualifier.layoutXfbOffset;
8717     for (unsigned int member = 0; member < typeList.size(); ++member) {
8718         TQualifier& memberQualifier = typeList[member].type->getQualifier();
8719         bool contains64BitType = false;
8720         bool contains32BitType = false;
8721         bool contains16BitType = false;
8722         int memberSize = intermediate.computeTypeXfbSize(*typeList[member].type, contains64BitType, contains32BitType, contains16BitType);
8723         // see if we need to auto-assign an offset to this member
8724         if (! memberQualifier.hasXfbOffset()) {
8725             // "if applied to an aggregate containing a double or 64-bit integer, the offset must also be a multiple of 8"
8726             if (contains64BitType)
8727                 RoundToPow2(nextOffset, 8);
8728             else if (contains32BitType)
8729                 RoundToPow2(nextOffset, 4);
8730             else if (contains16BitType)
8731                 RoundToPow2(nextOffset, 2);
8732             memberQualifier.layoutXfbOffset = nextOffset;
8733         } else
8734             nextOffset = memberQualifier.layoutXfbOffset;
8735         nextOffset += memberSize;
8736     }
8737
8738     // The above gave all block members an offset, so we can take it off the block now,
8739     // which will avoid double counting the offset usage.
8740     qualifier.layoutXfbOffset = TQualifier::layoutXfbOffsetEnd;
8741 #endif
8742 }
8743
8744 // Calculate and save the offset of each block member, using the recursively
8745 // defined block offset rules and the user-provided offset and align.
8746 //
8747 // Also, compute and save the total size of the block. For the block's size, arrayness
8748 // is not taken into account, as each element is backed by a separate buffer.
8749 //
8750 void TParseContext::fixBlockUniformOffsets(TQualifier& qualifier, TTypeList& typeList)
8751 {
8752     if (!storageCanHaveLayoutInBlock(qualifier.storage) && !qualifier.isTaskMemory())
8753         return;
8754     if (qualifier.layoutPacking != ElpStd140 && qualifier.layoutPacking != ElpStd430 && qualifier.layoutPacking != ElpScalar)
8755         return;
8756
8757     int offset = 0;
8758     int memberSize;
8759     for (unsigned int member = 0; member < typeList.size(); ++member) {
8760         TQualifier& memberQualifier = typeList[member].type->getQualifier();
8761         const TSourceLoc& memberLoc = typeList[member].loc;
8762
8763         // "When align is applied to an array, it effects only the start of the array, not the array's internal stride."
8764
8765         // modify just the children's view of matrix layout, if there is one for this member
8766         TLayoutMatrix subMatrixLayout = typeList[member].type->getQualifier().layoutMatrix;
8767         int dummyStride;
8768         int memberAlignment = intermediate.getMemberAlignment(*typeList[member].type, memberSize, dummyStride, qualifier.layoutPacking,
8769                                                               subMatrixLayout != ElmNone ? subMatrixLayout == ElmRowMajor : qualifier.layoutMatrix == ElmRowMajor);
8770         if (memberQualifier.hasOffset()) {
8771             // "The specified offset must be a multiple
8772             // of the base alignment of the type of the block member it qualifies, or a compile-time error results."
8773             if (! IsMultipleOfPow2(memberQualifier.layoutOffset, memberAlignment))
8774                 error(memberLoc, "must be a multiple of the member's alignment", "offset", "");
8775
8776             // GLSL: "It is a compile-time error to specify an offset that is smaller than the offset of the previous
8777             // member in the block or that lies within the previous member of the block"
8778             if (spvVersion.spv == 0) {
8779                 if (memberQualifier.layoutOffset < offset)
8780                     error(memberLoc, "cannot lie in previous members", "offset", "");
8781
8782                 // "The offset qualifier forces the qualified member to start at or after the specified
8783                 // integral-constant expression, which will be its byte offset from the beginning of the buffer.
8784                 // "The actual offset of a member is computed as
8785                 // follows: If offset was declared, start with that offset, otherwise start with the next available offset."
8786                 offset = std::max(offset, memberQualifier.layoutOffset);
8787             } else {
8788                 // TODO: Vulkan: "It is a compile-time error to have any offset, explicit or assigned,
8789                 // that lies within another member of the block."
8790
8791                 offset = memberQualifier.layoutOffset;
8792             }
8793         }
8794
8795         // "The actual alignment of a member will be the greater of the specified align alignment and the standard
8796         // (e.g., std140) base alignment for the member's type."
8797         if (memberQualifier.hasAlign())
8798             memberAlignment = std::max(memberAlignment, memberQualifier.layoutAlign);
8799
8800         // "If the resulting offset is not a multiple of the actual alignment,
8801         // increase it to the first offset that is a multiple of
8802         // the actual alignment."
8803         RoundToPow2(offset, memberAlignment);
8804         typeList[member].type->getQualifier().layoutOffset = offset;
8805         offset += memberSize;
8806     }
8807 }
8808
8809 //
8810 // Spread LayoutMatrix to uniform block member, if a uniform block member is a struct,
8811 // we need spread LayoutMatrix to this struct member too. and keep this rule for recursive.
8812 //
8813 void TParseContext::fixBlockUniformLayoutMatrix(TQualifier& qualifier, TTypeList* originTypeList,
8814                                                 TTypeList* tmpTypeList)
8815 {
8816     assert(tmpTypeList == nullptr || originTypeList->size() == tmpTypeList->size());
8817     for (unsigned int member = 0; member < originTypeList->size(); ++member) {
8818         if (qualifier.layoutPacking != ElpNone) {
8819             if (tmpTypeList == nullptr) {
8820                 if (((*originTypeList)[member].type->isMatrix() ||
8821                      (*originTypeList)[member].type->getBasicType() == EbtStruct) &&
8822                     (*originTypeList)[member].type->getQualifier().layoutMatrix == ElmNone) {
8823                     (*originTypeList)[member].type->getQualifier().layoutMatrix = qualifier.layoutMatrix;
8824                 }
8825             } else {
8826                 if (((*tmpTypeList)[member].type->isMatrix() ||
8827                      (*tmpTypeList)[member].type->getBasicType() == EbtStruct) &&
8828                     (*tmpTypeList)[member].type->getQualifier().layoutMatrix == ElmNone) {
8829                     (*tmpTypeList)[member].type->getQualifier().layoutMatrix = qualifier.layoutMatrix;
8830                 }
8831             }
8832         }
8833
8834         if ((*originTypeList)[member].type->getBasicType() == EbtStruct) {
8835             TQualifier* memberQualifier = nullptr;
8836             // block member can be declare a matrix style, so it should be update to the member's style
8837             if ((*originTypeList)[member].type->getQualifier().layoutMatrix == ElmNone) {
8838                 memberQualifier = &qualifier;
8839             } else {
8840                 memberQualifier = &((*originTypeList)[member].type->getQualifier());
8841             }
8842
8843             const TType* tmpType = tmpTypeList == nullptr ?
8844                 (*originTypeList)[member].type->clone() : (*tmpTypeList)[member].type;
8845
8846             fixBlockUniformLayoutMatrix(*memberQualifier, (*originTypeList)[member].type->getWritableStruct(),
8847                                         tmpType->getWritableStruct());
8848
8849             const TTypeList* structure = recordStructCopy(matrixFixRecord, (*originTypeList)[member].type, tmpType);
8850
8851             if (tmpTypeList == nullptr) {
8852                 (*originTypeList)[member].type->setStruct(const_cast<TTypeList*>(structure));
8853             }
8854             if (tmpTypeList != nullptr) {
8855                 (*tmpTypeList)[member].type->setStruct(const_cast<TTypeList*>(structure));
8856             }
8857         }
8858     }
8859 }
8860
8861 //
8862 // Spread LayoutPacking to matrix or aggregate block members. If a block member is a struct or
8863 // array of struct, spread LayoutPacking recursively to its matrix or aggregate members.
8864 //
8865 void TParseContext::fixBlockUniformLayoutPacking(TQualifier& qualifier, TTypeList* originTypeList,
8866                                                  TTypeList* tmpTypeList)
8867 {
8868     assert(tmpTypeList == nullptr || originTypeList->size() == tmpTypeList->size());
8869     for (unsigned int member = 0; member < originTypeList->size(); ++member) {
8870         if (qualifier.layoutPacking != ElpNone) {
8871             if (tmpTypeList == nullptr) {
8872                 if ((*originTypeList)[member].type->getQualifier().layoutPacking == ElpNone &&
8873                     !(*originTypeList)[member].type->isScalarOrVector()) {
8874                     (*originTypeList)[member].type->getQualifier().layoutPacking = qualifier.layoutPacking;
8875                 }
8876             } else {
8877                 if ((*tmpTypeList)[member].type->getQualifier().layoutPacking == ElpNone &&
8878                     !(*tmpTypeList)[member].type->isScalarOrVector()) {
8879                     (*tmpTypeList)[member].type->getQualifier().layoutPacking = qualifier.layoutPacking;
8880                 }
8881             }
8882         }
8883
8884         if ((*originTypeList)[member].type->getBasicType() == EbtStruct) {
8885             // Deep copy the type in pool.
8886             // Because, struct use in different block may have different layout qualifier.
8887             // We have to new a object to distinguish between them.
8888             const TType* tmpType = tmpTypeList == nullptr ?
8889                 (*originTypeList)[member].type->clone() : (*tmpTypeList)[member].type;
8890
8891             fixBlockUniformLayoutPacking(qualifier, (*originTypeList)[member].type->getWritableStruct(),
8892                                          tmpType->getWritableStruct());
8893
8894             const TTypeList* structure = recordStructCopy(packingFixRecord, (*originTypeList)[member].type, tmpType);
8895
8896             if (tmpTypeList == nullptr) {
8897                 (*originTypeList)[member].type->setStruct(const_cast<TTypeList*>(structure));
8898             }
8899             if (tmpTypeList != nullptr) {
8900                 (*tmpTypeList)[member].type->setStruct(const_cast<TTypeList*>(structure));
8901             }
8902         }
8903     }
8904 }
8905
8906 // For an identifier that is already declared, add more qualification to it.
8907 void TParseContext::addQualifierToExisting(const TSourceLoc& loc, TQualifier qualifier, const TString& identifier)
8908 {
8909     TSymbol* symbol = symbolTable.find(identifier);
8910
8911     // A forward declaration of a block reference looks to the grammar like adding
8912     // a qualifier to an existing symbol. Detect this and create the block reference
8913     // type with an empty type list, which will be filled in later in
8914     // TParseContext::declareBlock.
8915     if (!symbol && qualifier.hasBufferReference()) {
8916         TTypeList typeList;
8917         TType blockType(&typeList, identifier, qualifier);;
8918         TType blockNameType(EbtReference, blockType, identifier);
8919         TVariable* blockNameVar = new TVariable(&identifier, blockNameType, true);
8920         if (! symbolTable.insert(*blockNameVar)) {
8921             error(loc, "block name cannot redefine a non-block name", blockName->c_str(), "");
8922         }
8923         return;
8924     }
8925
8926     if (! symbol) {
8927         error(loc, "identifier not previously declared", identifier.c_str(), "");
8928         return;
8929     }
8930     if (symbol->getAsFunction()) {
8931         error(loc, "cannot re-qualify a function name", identifier.c_str(), "");
8932         return;
8933     }
8934
8935     if (qualifier.isAuxiliary() ||
8936         qualifier.isMemory() ||
8937         qualifier.isInterpolation() ||
8938         qualifier.hasLayout() ||
8939         qualifier.storage != EvqTemporary ||
8940         qualifier.precision != EpqNone) {
8941         error(loc, "cannot add storage, auxiliary, memory, interpolation, layout, or precision qualifier to an existing variable", identifier.c_str(), "");
8942         return;
8943     }
8944
8945     // For read-only built-ins, add a new symbol for holding the modified qualifier.
8946     // This will bring up an entire block, if a block type has to be modified (e.g., gl_Position inside a block)
8947     if (symbol->isReadOnly())
8948         symbol = symbolTable.copyUp(symbol);
8949
8950     if (qualifier.invariant) {
8951         if (intermediate.inIoAccessed(identifier))
8952             error(loc, "cannot change qualification after use", "invariant", "");
8953         symbol->getWritableType().getQualifier().invariant = true;
8954         invariantCheck(loc, symbol->getType().getQualifier());
8955     } else if (qualifier.isNoContraction()) {
8956         if (intermediate.inIoAccessed(identifier))
8957             error(loc, "cannot change qualification after use", "precise", "");
8958         symbol->getWritableType().getQualifier().setNoContraction();
8959     } else if (qualifier.specConstant) {
8960         symbol->getWritableType().getQualifier().makeSpecConstant();
8961         if (qualifier.hasSpecConstantId())
8962             symbol->getWritableType().getQualifier().layoutSpecConstantId = qualifier.layoutSpecConstantId;
8963     } else
8964         warn(loc, "unknown requalification", "", "");
8965 }
8966
8967 void TParseContext::addQualifierToExisting(const TSourceLoc& loc, TQualifier qualifier, TIdentifierList& identifiers)
8968 {
8969     for (unsigned int i = 0; i < identifiers.size(); ++i)
8970         addQualifierToExisting(loc, qualifier, *identifiers[i]);
8971 }
8972
8973 // Make sure 'invariant' isn't being applied to a non-allowed object.
8974 void TParseContext::invariantCheck(const TSourceLoc& loc, const TQualifier& qualifier)
8975 {
8976     if (! qualifier.invariant)
8977         return;
8978
8979     bool pipeOut = qualifier.isPipeOutput();
8980     bool pipeIn = qualifier.isPipeInput();
8981     if ((version >= 300 && isEsProfile()) || (!isEsProfile() && version >= 420)) {
8982         if (! pipeOut)
8983             error(loc, "can only apply to an output", "invariant", "");
8984     } else {
8985         if ((language == EShLangVertex && pipeIn) || (! pipeOut && ! pipeIn))
8986             error(loc, "can only apply to an output, or to an input in a non-vertex stage\n", "invariant", "");
8987     }
8988 }
8989
8990 //
8991 // Updating default qualifier for the case of a declaration with just a qualifier,
8992 // no type, block, or identifier.
8993 //
8994 void TParseContext::updateStandaloneQualifierDefaults(const TSourceLoc& loc, const TPublicType& publicType)
8995 {
8996 #ifndef GLSLANG_WEB
8997     if (publicType.shaderQualifiers.vertices != TQualifier::layoutNotSet) {
8998         assert(language == EShLangTessControl || language == EShLangGeometry || language == EShLangMesh);
8999         const char* id = (language == EShLangTessControl) ? "vertices" : "max_vertices";
9000
9001         if (publicType.qualifier.storage != EvqVaryingOut)
9002             error(loc, "can only apply to 'out'", id, "");
9003         if (! intermediate.setVertices(publicType.shaderQualifiers.vertices))
9004             error(loc, "cannot change previously set layout value", id, "");
9005
9006         if (language == EShLangTessControl)
9007             checkIoArraysConsistency(loc);
9008     }
9009     if (publicType.shaderQualifiers.primitives != TQualifier::layoutNotSet) {
9010         assert(language == EShLangMesh);
9011         const char* id = "max_primitives";
9012
9013         if (publicType.qualifier.storage != EvqVaryingOut)
9014             error(loc, "can only apply to 'out'", id, "");
9015         if (! intermediate.setPrimitives(publicType.shaderQualifiers.primitives))
9016             error(loc, "cannot change previously set layout value", id, "");
9017     }
9018     if (publicType.shaderQualifiers.invocations != TQualifier::layoutNotSet) {
9019         if (publicType.qualifier.storage != EvqVaryingIn)
9020             error(loc, "can only apply to 'in'", "invocations", "");
9021         if (! intermediate.setInvocations(publicType.shaderQualifiers.invocations))
9022             error(loc, "cannot change previously set layout value", "invocations", "");
9023     }
9024     if (publicType.shaderQualifiers.geometry != ElgNone) {
9025         if (publicType.qualifier.storage == EvqVaryingIn) {
9026             switch (publicType.shaderQualifiers.geometry) {
9027             case ElgPoints:
9028             case ElgLines:
9029             case ElgLinesAdjacency:
9030             case ElgTriangles:
9031             case ElgTrianglesAdjacency:
9032             case ElgQuads:
9033             case ElgIsolines:
9034                 if (language == EShLangMesh) {
9035                     error(loc, "cannot apply to input", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
9036                     break;
9037                 }
9038                 if (intermediate.setInputPrimitive(publicType.shaderQualifiers.geometry)) {
9039                     if (language == EShLangGeometry)
9040                         checkIoArraysConsistency(loc);
9041                 } else
9042                     error(loc, "cannot change previously set input primitive", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
9043                 break;
9044             default:
9045                 error(loc, "cannot apply to input", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
9046             }
9047         } else if (publicType.qualifier.storage == EvqVaryingOut) {
9048             switch (publicType.shaderQualifiers.geometry) {
9049             case ElgLines:
9050             case ElgTriangles:
9051                 if (language != EShLangMesh) {
9052                     error(loc, "cannot apply to 'out'", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
9053                     break;
9054                 }
9055                 // Fall through
9056             case ElgPoints:
9057             case ElgLineStrip:
9058             case ElgTriangleStrip:
9059                 if (! intermediate.setOutputPrimitive(publicType.shaderQualifiers.geometry))
9060                     error(loc, "cannot change previously set output primitive", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
9061                 break;
9062             default:
9063                 error(loc, "cannot apply to 'out'", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
9064             }
9065         } else
9066             error(loc, "cannot apply to:", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), GetStorageQualifierString(publicType.qualifier.storage));
9067     }
9068     if (publicType.shaderQualifiers.spacing != EvsNone) {
9069         if (publicType.qualifier.storage == EvqVaryingIn) {
9070             if (! intermediate.setVertexSpacing(publicType.shaderQualifiers.spacing))
9071                 error(loc, "cannot change previously set vertex spacing", TQualifier::getVertexSpacingString(publicType.shaderQualifiers.spacing), "");
9072         } else
9073             error(loc, "can only apply to 'in'", TQualifier::getVertexSpacingString(publicType.shaderQualifiers.spacing), "");
9074     }
9075     if (publicType.shaderQualifiers.order != EvoNone) {
9076         if (publicType.qualifier.storage == EvqVaryingIn) {
9077             if (! intermediate.setVertexOrder(publicType.shaderQualifiers.order))
9078                 error(loc, "cannot change previously set vertex order", TQualifier::getVertexOrderString(publicType.shaderQualifiers.order), "");
9079         } else
9080             error(loc, "can only apply to 'in'", TQualifier::getVertexOrderString(publicType.shaderQualifiers.order), "");
9081     }
9082     if (publicType.shaderQualifiers.pointMode) {
9083         if (publicType.qualifier.storage == EvqVaryingIn)
9084             intermediate.setPointMode();
9085         else
9086             error(loc, "can only apply to 'in'", "point_mode", "");
9087     }
9088 #endif
9089     for (int i = 0; i < 3; ++i) {
9090         if (publicType.shaderQualifiers.localSizeNotDefault[i]) {
9091             if (publicType.qualifier.storage == EvqVaryingIn) {
9092                 if (! intermediate.setLocalSize(i, publicType.shaderQualifiers.localSize[i]))
9093                     error(loc, "cannot change previously set size", "local_size", "");
9094                 else {
9095                     int max = 0;
9096                     if (language == EShLangCompute) {
9097                         switch (i) {
9098                         case 0: max = resources.maxComputeWorkGroupSizeX; break;
9099                         case 1: max = resources.maxComputeWorkGroupSizeY; break;
9100                         case 2: max = resources.maxComputeWorkGroupSizeZ; break;
9101                         default: break;
9102                         }
9103                         if (intermediate.getLocalSize(i) > (unsigned int)max)
9104                             error(loc, "too large; see gl_MaxComputeWorkGroupSize", "local_size", "");
9105                     }
9106 #ifndef GLSLANG_WEB
9107                     else if (language == EShLangMesh) {
9108                         switch (i) {
9109                         case 0:
9110                             max = extensionTurnedOn(E_GL_EXT_mesh_shader) ?
9111                                     resources.maxMeshWorkGroupSizeX_EXT :
9112                                     resources.maxMeshWorkGroupSizeX_NV;
9113                             break;
9114                         case 1:
9115                             max = extensionTurnedOn(E_GL_EXT_mesh_shader) ?
9116                                     resources.maxMeshWorkGroupSizeY_EXT :
9117                                     resources.maxMeshWorkGroupSizeY_NV ;
9118                             break;
9119                         case 2:
9120                             max = extensionTurnedOn(E_GL_EXT_mesh_shader) ?
9121                                     resources.maxMeshWorkGroupSizeZ_EXT :
9122                                     resources.maxMeshWorkGroupSizeZ_NV ;
9123                             break;
9124                         default: break;
9125                         }
9126                         if (intermediate.getLocalSize(i) > (unsigned int)max) {
9127                             TString maxsErrtring = "too large, see ";
9128                             maxsErrtring.append(extensionTurnedOn(E_GL_EXT_mesh_shader) ?
9129                                                     "gl_MaxMeshWorkGroupSizeEXT" : "gl_MaxMeshWorkGroupSizeNV");
9130                             error(loc, maxsErrtring.c_str(), "local_size", "");
9131                         }
9132                     } else if (language == EShLangTask) {
9133                         switch (i) {
9134                         case 0:
9135                             max = extensionTurnedOn(E_GL_EXT_mesh_shader) ?
9136                                     resources.maxTaskWorkGroupSizeX_EXT :
9137                                     resources.maxTaskWorkGroupSizeX_NV;
9138                             break;
9139                         case 1:
9140                             max = extensionTurnedOn(E_GL_EXT_mesh_shader) ?
9141                                     resources.maxTaskWorkGroupSizeY_EXT:
9142                                     resources.maxTaskWorkGroupSizeY_NV;
9143                             break;
9144                         case 2:
9145                             max = extensionTurnedOn(E_GL_EXT_mesh_shader) ?
9146                                     resources.maxTaskWorkGroupSizeZ_EXT:
9147                                     resources.maxTaskWorkGroupSizeZ_NV;
9148                             break;
9149                         default: break;
9150                         }
9151                         if (intermediate.getLocalSize(i) > (unsigned int)max) {
9152                             TString maxsErrtring = "too large, see ";
9153                             maxsErrtring.append(extensionTurnedOn(E_GL_EXT_mesh_shader) ?
9154                                                     "gl_MaxTaskWorkGroupSizeEXT" : "gl_MaxTaskWorkGroupSizeNV");
9155                             error(loc, maxsErrtring.c_str(), "local_size", "");
9156                         }
9157                     }
9158 #endif
9159                     else {
9160                         assert(0);
9161                     }
9162
9163                     // Fix the existing constant gl_WorkGroupSize with this new information.
9164                     TVariable* workGroupSize = getEditableVariable("gl_WorkGroupSize");
9165                     if (workGroupSize != nullptr)
9166                         workGroupSize->getWritableConstArray()[i].setUConst(intermediate.getLocalSize(i));
9167                 }
9168             } else
9169                 error(loc, "can only apply to 'in'", "local_size", "");
9170         }
9171         if (publicType.shaderQualifiers.localSizeSpecId[i] != TQualifier::layoutNotSet) {
9172             if (publicType.qualifier.storage == EvqVaryingIn) {
9173                 if (! intermediate.setLocalSizeSpecId(i, publicType.shaderQualifiers.localSizeSpecId[i]))
9174                     error(loc, "cannot change previously set size", "local_size", "");
9175             } else
9176                 error(loc, "can only apply to 'in'", "local_size id", "");
9177             // Set the workgroup built-in variable as a specialization constant
9178             TVariable* workGroupSize = getEditableVariable("gl_WorkGroupSize");
9179             if (workGroupSize != nullptr)
9180                 workGroupSize->getWritableType().getQualifier().specConstant = true;
9181         }
9182     }
9183
9184 #ifndef GLSLANG_WEB
9185     if (publicType.shaderQualifiers.earlyFragmentTests) {
9186         if (publicType.qualifier.storage == EvqVaryingIn)
9187             intermediate.setEarlyFragmentTests();
9188         else
9189             error(loc, "can only apply to 'in'", "early_fragment_tests", "");
9190     }
9191     if (publicType.shaderQualifiers.earlyAndLateFragmentTestsAMD) {
9192         if (publicType.qualifier.storage == EvqVaryingIn)
9193             intermediate.setEarlyAndLateFragmentTestsAMD();
9194         else
9195             error(loc, "can only apply to 'in'", "early_and_late_fragment_tests_amd", "");
9196     }
9197     if (publicType.shaderQualifiers.postDepthCoverage) {
9198         if (publicType.qualifier.storage == EvqVaryingIn)
9199             intermediate.setPostDepthCoverage();
9200         else
9201             error(loc, "can only apply to 'in'", "post_coverage_coverage", "");
9202     }
9203     if (publicType.shaderQualifiers.hasBlendEquation()) {
9204         if (publicType.qualifier.storage != EvqVaryingOut)
9205             error(loc, "can only apply to 'out'", "blend equation", "");
9206     }
9207     if (publicType.shaderQualifiers.interlockOrdering) {
9208         if (publicType.qualifier.storage == EvqVaryingIn) {
9209             if (!intermediate.setInterlockOrdering(publicType.shaderQualifiers.interlockOrdering))
9210                 error(loc, "cannot change previously set fragment shader interlock ordering", TQualifier::getInterlockOrderingString(publicType.shaderQualifiers.interlockOrdering), "");
9211         }
9212         else
9213             error(loc, "can only apply to 'in'", TQualifier::getInterlockOrderingString(publicType.shaderQualifiers.interlockOrdering), "");
9214     }
9215
9216     if (publicType.shaderQualifiers.layoutDerivativeGroupQuads &&
9217         publicType.shaderQualifiers.layoutDerivativeGroupLinear) {
9218         error(loc, "cannot be both specified", "derivative_group_quadsNV and derivative_group_linearNV", "");
9219     }
9220
9221     if (publicType.shaderQualifiers.layoutDerivativeGroupQuads) {
9222         if (publicType.qualifier.storage == EvqVaryingIn) {
9223             if ((intermediate.getLocalSize(0) & 1) ||
9224                 (intermediate.getLocalSize(1) & 1))
9225                 error(loc, "requires local_size_x and local_size_y to be multiple of two", "derivative_group_quadsNV", "");
9226             else
9227                 intermediate.setLayoutDerivativeMode(LayoutDerivativeGroupQuads);
9228         }
9229         else
9230             error(loc, "can only apply to 'in'", "derivative_group_quadsNV", "");
9231     }
9232     if (publicType.shaderQualifiers.layoutDerivativeGroupLinear) {
9233         if (publicType.qualifier.storage == EvqVaryingIn) {
9234             if((intermediate.getLocalSize(0) *
9235                 intermediate.getLocalSize(1) *
9236                 intermediate.getLocalSize(2)) % 4 != 0)
9237                 error(loc, "requires total group size to be multiple of four", "derivative_group_linearNV", "");
9238             else
9239                 intermediate.setLayoutDerivativeMode(LayoutDerivativeGroupLinear);
9240         }
9241         else
9242             error(loc, "can only apply to 'in'", "derivative_group_linearNV", "");
9243     }
9244     // Check mesh out array sizes, once all the necessary out qualifiers are defined.
9245     if ((language == EShLangMesh) &&
9246         (intermediate.getVertices() != TQualifier::layoutNotSet) &&
9247         (intermediate.getPrimitives() != TQualifier::layoutNotSet) &&
9248         (intermediate.getOutputPrimitive() != ElgNone))
9249     {
9250         checkIoArraysConsistency(loc);
9251     }
9252
9253     if (publicType.shaderQualifiers.layoutPrimitiveCulling) {
9254         if (publicType.qualifier.storage != EvqTemporary)
9255             error(loc, "layout qualifier can not have storage qualifiers", "primitive_culling","", "");
9256         else {
9257             intermediate.setLayoutPrimitiveCulling();
9258         }
9259         // Exit early as further checks are not valid
9260         return;
9261     }
9262 #endif
9263     const TQualifier& qualifier = publicType.qualifier;
9264
9265     if (qualifier.isAuxiliary() ||
9266         qualifier.isMemory() ||
9267         qualifier.isInterpolation() ||
9268         qualifier.precision != EpqNone)
9269         error(loc, "cannot use auxiliary, memory, interpolation, or precision qualifier in a default qualifier declaration (declaration with no type)", "qualifier", "");
9270
9271     // "The offset qualifier can only be used on block members of blocks..."
9272     // "The align qualifier can only be used on blocks or block members..."
9273     if (qualifier.hasOffset() ||
9274         qualifier.hasAlign())
9275         error(loc, "cannot use offset or align qualifiers in a default qualifier declaration (declaration with no type)", "layout qualifier", "");
9276
9277     layoutQualifierCheck(loc, qualifier);
9278
9279     switch (qualifier.storage) {
9280     case EvqUniform:
9281         if (qualifier.hasMatrix())
9282             globalUniformDefaults.layoutMatrix = qualifier.layoutMatrix;
9283         if (qualifier.hasPacking())
9284             globalUniformDefaults.layoutPacking = qualifier.layoutPacking;
9285         break;
9286     case EvqBuffer:
9287         if (qualifier.hasMatrix())
9288             globalBufferDefaults.layoutMatrix = qualifier.layoutMatrix;
9289         if (qualifier.hasPacking())
9290             globalBufferDefaults.layoutPacking = qualifier.layoutPacking;
9291         break;
9292     case EvqVaryingIn:
9293         break;
9294     case EvqVaryingOut:
9295 #ifndef GLSLANG_WEB
9296         if (qualifier.hasStream())
9297             globalOutputDefaults.layoutStream = qualifier.layoutStream;
9298         if (qualifier.hasXfbBuffer())
9299             globalOutputDefaults.layoutXfbBuffer = qualifier.layoutXfbBuffer;
9300         if (globalOutputDefaults.hasXfbBuffer() && qualifier.hasXfbStride()) {
9301             if (! intermediate.setXfbBufferStride(globalOutputDefaults.layoutXfbBuffer, qualifier.layoutXfbStride))
9302                 error(loc, "all stride settings must match for xfb buffer", "xfb_stride", "%d", qualifier.layoutXfbBuffer);
9303         }
9304 #endif
9305         break;
9306     case EvqShared:
9307         if (qualifier.hasMatrix())
9308             globalSharedDefaults.layoutMatrix = qualifier.layoutMatrix;
9309         if (qualifier.hasPacking())
9310             globalSharedDefaults.layoutPacking = qualifier.layoutPacking;
9311         break;
9312     default:
9313         error(loc, "default qualifier requires 'uniform', 'buffer', 'in', 'out' or 'shared' storage qualification", "", "");
9314         return;
9315     }
9316
9317     if (qualifier.hasBinding())
9318         error(loc, "cannot declare a default, include a type or full declaration", "binding", "");
9319     if (qualifier.hasAnyLocation())
9320         error(loc, "cannot declare a default, use a full declaration", "location/component/index", "");
9321     if (qualifier.hasXfbOffset())
9322         error(loc, "cannot declare a default, use a full declaration", "xfb_offset", "");
9323     if (qualifier.isPushConstant())
9324         error(loc, "cannot declare a default, can only be used on a block", "push_constant", "");
9325     if (qualifier.hasBufferReference())
9326         error(loc, "cannot declare a default, can only be used on a block", "buffer_reference", "");
9327     if (qualifier.hasSpecConstantId())
9328         error(loc, "cannot declare a default, can only be used on a scalar", "constant_id", "");
9329     if (qualifier.isShaderRecord())
9330         error(loc, "cannot declare a default, can only be used on a block", "shaderRecordNV", "");
9331 }
9332
9333 //
9334 // Take the sequence of statements that has been built up since the last case/default,
9335 // put it on the list of top-level nodes for the current (inner-most) switch statement,
9336 // and follow that by the case/default we are on now.  (See switch topology comment on
9337 // TIntermSwitch.)
9338 //
9339 void TParseContext::wrapupSwitchSubsequence(TIntermAggregate* statements, TIntermNode* branchNode)
9340 {
9341     TIntermSequence* switchSequence = switchSequenceStack.back();
9342
9343     if (statements) {
9344         if (switchSequence->size() == 0)
9345             error(statements->getLoc(), "cannot have statements before first case/default label", "switch", "");
9346         statements->setOperator(EOpSequence);
9347         switchSequence->push_back(statements);
9348     }
9349     if (branchNode) {
9350         // check all previous cases for the same label (or both are 'default')
9351         for (unsigned int s = 0; s < switchSequence->size(); ++s) {
9352             TIntermBranch* prevBranch = (*switchSequence)[s]->getAsBranchNode();
9353             if (prevBranch) {
9354                 TIntermTyped* prevExpression = prevBranch->getExpression();
9355                 TIntermTyped* newExpression = branchNode->getAsBranchNode()->getExpression();
9356                 if (prevExpression == nullptr && newExpression == nullptr)
9357                     error(branchNode->getLoc(), "duplicate label", "default", "");
9358                 else if (prevExpression != nullptr &&
9359                           newExpression != nullptr &&
9360                          prevExpression->getAsConstantUnion() &&
9361                           newExpression->getAsConstantUnion() &&
9362                          prevExpression->getAsConstantUnion()->getConstArray()[0].getIConst() ==
9363                           newExpression->getAsConstantUnion()->getConstArray()[0].getIConst())
9364                     error(branchNode->getLoc(), "duplicated value", "case", "");
9365             }
9366         }
9367         switchSequence->push_back(branchNode);
9368     }
9369 }
9370
9371 //
9372 // Turn the top-level node sequence built up of wrapupSwitchSubsequence9)
9373 // into a switch node.
9374 //
9375 TIntermNode* TParseContext::addSwitch(const TSourceLoc& loc, TIntermTyped* expression, TIntermAggregate* lastStatements)
9376 {
9377     profileRequires(loc, EEsProfile, 300, nullptr, "switch statements");
9378     profileRequires(loc, ENoProfile, 130, nullptr, "switch statements");
9379
9380     wrapupSwitchSubsequence(lastStatements, nullptr);
9381
9382     if (expression == nullptr ||
9383         (expression->getBasicType() != EbtInt && expression->getBasicType() != EbtUint) ||
9384         expression->getType().isArray() || expression->getType().isMatrix() || expression->getType().isVector())
9385             error(loc, "condition must be a scalar integer expression", "switch", "");
9386
9387     // If there is nothing to do, drop the switch but still execute the expression
9388     TIntermSequence* switchSequence = switchSequenceStack.back();
9389     if (switchSequence->size() == 0)
9390         return expression;
9391
9392     if (lastStatements == nullptr) {
9393         // This was originally an ERRROR, because early versions of the specification said
9394         // "it is an error to have no statement between a label and the end of the switch statement."
9395         // The specifications were updated to remove this (being ill-defined what a "statement" was),
9396         // so, this became a warning.  However, 3.0 tests still check for the error.
9397         if (isEsProfile() && (version <= 300 || version >= 320) && ! relaxedErrors())
9398             error(loc, "last case/default label not followed by statements", "switch", "");
9399         else if (!isEsProfile() && (version <= 430 || version >= 460))
9400             error(loc, "last case/default label not followed by statements", "switch", "");
9401         else
9402             warn(loc, "last case/default label not followed by statements", "switch", "");
9403
9404
9405         // emulate a break for error recovery
9406         lastStatements = intermediate.makeAggregate(intermediate.addBranch(EOpBreak, loc));
9407         lastStatements->setOperator(EOpSequence);
9408         switchSequence->push_back(lastStatements);
9409     }
9410
9411     TIntermAggregate* body = new TIntermAggregate(EOpSequence);
9412     body->getSequence() = *switchSequenceStack.back();
9413     body->setLoc(loc);
9414
9415     TIntermSwitch* switchNode = new TIntermSwitch(expression, body);
9416     switchNode->setLoc(loc);
9417
9418     return switchNode;
9419 }
9420
9421 //
9422 // When a struct used in block, and has it's own layout packing, layout matrix,
9423 // record the origin structure of a struct to map, and Record the structure copy to the copy table,
9424 //
9425 const TTypeList* TParseContext::recordStructCopy(TStructRecord& record, const TType* originType, const TType* tmpType)
9426 {
9427     size_t memberCount = tmpType->getStruct()->size();
9428     size_t originHash = 0, tmpHash = 0;
9429     std::hash<size_t> hasher;
9430     for (size_t i = 0; i < memberCount; i++) {
9431         size_t originMemberHash = hasher(originType->getStruct()->at(i).type->getQualifier().layoutPacking +
9432                                          originType->getStruct()->at(i).type->getQualifier().layoutMatrix);
9433         size_t tmpMemberHash = hasher(tmpType->getStruct()->at(i).type->getQualifier().layoutPacking +
9434                                       tmpType->getStruct()->at(i).type->getQualifier().layoutMatrix);
9435         originHash = hasher((originHash ^ originMemberHash) << 1);
9436         tmpHash = hasher((tmpHash ^ tmpMemberHash) << 1);
9437     }
9438     const TTypeList* originStruct = originType->getStruct();
9439     const TTypeList* tmpStruct = tmpType->getStruct();
9440     if (originHash != tmpHash) {
9441         auto fixRecords = record.find(originStruct);
9442         if (fixRecords != record.end()) {
9443             auto fixRecord = fixRecords->second.find(tmpHash);
9444             if (fixRecord != fixRecords->second.end()) {
9445                 return fixRecord->second;
9446             } else {
9447                 record[originStruct][tmpHash] = tmpStruct;
9448                 return tmpStruct;
9449             }
9450         } else {
9451             record[originStruct] = std::map<size_t, const TTypeList*>();
9452             record[originStruct][tmpHash] = tmpStruct;
9453             return tmpStruct;
9454         }
9455     }
9456     return originStruct;
9457 }
9458
9459 } // end namespace glslang