For GL_NV_geometry_shader_passthrough extension, the Inferred output primitive for...
[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-2016 Google, Inc.
5 // Copyright (C) 2017 ARM Limited.
6 //
7 // All rights reserved.
8 //
9 // Redistribution and use in source and binary forms, with or without
10 // modification, are permitted provided that the following conditions
11 // are met:
12 //
13 //    Redistributions of source code must retain the above copyright
14 //    notice, this list of conditions and the following disclaimer.
15 //
16 //    Redistributions in binary form must reproduce the above
17 //    copyright notice, this list of conditions and the following
18 //    disclaimer in the documentation and/or other materials provided
19 //    with the distribution.
20 //
21 //    Neither the name of 3Dlabs Inc. Ltd. nor the names of its
22 //    contributors may be used to endorse or promote products derived
23 //    from this software without specific prior written permission.
24 //
25 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
28 // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
29 // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
30 // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
31 // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
32 // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
33 // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34 // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36 // POSSIBILITY OF SUCH DAMAGE.
37 //
38
39 #include "ParseHelper.h"
40 #include "Scan.h"
41
42 #include "../OSDependent/osinclude.h"
43 #include <algorithm>
44
45 #include "preprocessor/PpContext.h"
46
47 extern int yyparse(glslang::TParseContext*);
48
49 namespace glslang {
50
51 TParseContext::TParseContext(TSymbolTable& symbolTable, TIntermediate& interm, bool parsingBuiltins,
52                              int version, EProfile profile, const SpvVersion& spvVersion, EShLanguage language,
53                              TInfoSink& infoSink, bool forwardCompatible, EShMessages messages,
54                              const TString* entryPoint) :
55             TParseContextBase(symbolTable, interm, parsingBuiltins, version, profile, spvVersion, language,
56                               infoSink, forwardCompatible, messages, entryPoint),
57             inMain(false),
58             blockName(nullptr),
59             limits(resources.limits),
60             atomicUintOffsets(nullptr), anyIndexLimits(false)
61 {
62     // decide whether precision qualifiers should be ignored or respected
63     if (profile == EEsProfile || spvVersion.vulkan > 0) {
64         precisionManager.respectPrecisionQualifiers();
65         if (! parsingBuiltins && language == EShLangFragment && profile != EEsProfile && spvVersion.vulkan > 0)
66             precisionManager.warnAboutDefaults();
67     }
68
69     setPrecisionDefaults();
70
71     globalUniformDefaults.clear();
72     globalUniformDefaults.layoutMatrix = ElmColumnMajor;
73     globalUniformDefaults.layoutPacking = spvVersion.spv != 0 ? ElpStd140 : ElpShared;
74
75     globalBufferDefaults.clear();
76     globalBufferDefaults.layoutMatrix = ElmColumnMajor;
77     globalBufferDefaults.layoutPacking = spvVersion.spv != 0 ? ElpStd430 : ElpShared;
78
79     globalInputDefaults.clear();
80     globalOutputDefaults.clear();
81
82     // "Shaders in the transform
83     // feedback capturing mode have an initial global default of
84     //     layout(xfb_buffer = 0) out;"
85     if (language == EShLangVertex ||
86         language == EShLangTessControl ||
87         language == EShLangTessEvaluation ||
88         language == EShLangGeometry)
89         globalOutputDefaults.layoutXfbBuffer = 0;
90
91     if (language == EShLangGeometry)
92         globalOutputDefaults.layoutStream = 0;
93
94     if (entryPoint != nullptr && entryPoint->size() > 0 && *entryPoint != "main")
95         infoSink.info.message(EPrefixError, "Source entry point must be \"main\"");
96 }
97
98 TParseContext::~TParseContext()
99 {
100     delete [] atomicUintOffsets;
101 }
102
103 // Set up all default precisions as needed by the current environment.
104 // Intended just as a TParseContext constructor helper.
105 void TParseContext::setPrecisionDefaults()
106 {
107     // Set all precision defaults to EpqNone, which is correct for all types
108     // when not obeying precision qualifiers, and correct for types that don't
109     // have defaults (thus getting an error on use) when obeying precision
110     // qualifiers.
111
112     for (int type = 0; type < EbtNumTypes; ++type)
113         defaultPrecision[type] = EpqNone;
114
115     for (int type = 0; type < maxSamplerIndex; ++type)
116         defaultSamplerPrecision[type] = EpqNone;
117
118     // replace with real precision defaults for those that have them
119     if (obeyPrecisionQualifiers()) {
120         if (profile == EEsProfile) {
121             // Most don't have defaults, a few default to lowp.
122             TSampler sampler;
123             sampler.set(EbtFloat, Esd2D);
124             defaultSamplerPrecision[computeSamplerTypeIndex(sampler)] = EpqLow;
125             sampler.set(EbtFloat, EsdCube);
126             defaultSamplerPrecision[computeSamplerTypeIndex(sampler)] = EpqLow;
127             sampler.set(EbtFloat, Esd2D);
128             sampler.external = true;
129             defaultSamplerPrecision[computeSamplerTypeIndex(sampler)] = EpqLow;
130         }
131
132         // If we are parsing built-in computational variables/functions, it is meaningful to record
133         // whether the built-in has no precision qualifier, as that ambiguity
134         // is used to resolve the precision from the supplied arguments/operands instead.
135         // So, we don't actually want to replace EpqNone with a default precision for built-ins.
136         if (! parsingBuiltins) {
137             if (profile == EEsProfile && language == EShLangFragment) {
138                 defaultPrecision[EbtInt] = EpqMedium;
139                 defaultPrecision[EbtUint] = EpqMedium;
140             } else {
141                 defaultPrecision[EbtInt] = EpqHigh;
142                 defaultPrecision[EbtUint] = EpqHigh;
143                 defaultPrecision[EbtFloat] = EpqHigh;
144             }
145
146             if (profile != EEsProfile) {
147                 // Non-ES profile
148                 // All sampler precisions default to highp.
149                 for (int type = 0; type < maxSamplerIndex; ++type)
150                     defaultSamplerPrecision[type] = EpqHigh;
151             }
152         }
153
154         defaultPrecision[EbtSampler] = EpqLow;
155         defaultPrecision[EbtAtomicUint] = EpqHigh;
156     }
157 }
158
159 void TParseContext::setLimits(const TBuiltInResource& r)
160 {
161     resources = r;
162
163     anyIndexLimits = ! limits.generalAttributeMatrixVectorIndexing ||
164                      ! limits.generalConstantMatrixVectorIndexing ||
165                      ! limits.generalSamplerIndexing ||
166                      ! limits.generalUniformIndexing ||
167                      ! limits.generalVariableIndexing ||
168                      ! limits.generalVaryingIndexing;
169
170     intermediate.setLimits(resources);
171
172     // "Each binding point tracks its own current default offset for
173     // inheritance of subsequent variables using the same binding. The initial state of compilation is that all
174     // binding points have an offset of 0."
175     atomicUintOffsets = new int[resources.maxAtomicCounterBindings];
176     for (int b = 0; b < resources.maxAtomicCounterBindings; ++b)
177         atomicUintOffsets[b] = 0;
178 }
179
180 //
181 // Parse an array of strings using yyparse, going through the
182 // preprocessor to tokenize the shader strings, then through
183 // the GLSL scanner.
184 //
185 // Returns true for successful acceptance of the shader, false if any errors.
186 //
187 bool TParseContext::parseShaderStrings(TPpContext& ppContext, TInputScanner& input, bool versionWillBeError)
188 {
189     currentScanner = &input;
190     ppContext.setInput(input, versionWillBeError);
191     yyparse(this);
192
193     finish();
194
195     return numErrors == 0;
196 }
197
198 // This is called from bison when it has a parse (syntax) error
199 // Note though that to stop cascading errors, we set EOF, which
200 // will usually cause a syntax error, so be more accurate that
201 // compilation is terminating.
202 void TParseContext::parserError(const char* s)
203 {
204     if (! getScanner()->atEndOfInput() || numErrors == 0)
205         error(getCurrentLoc(), "", "", s, "");
206     else
207         error(getCurrentLoc(), "compilation terminated", "", "");
208 }
209
210 void TParseContext::handlePragma(const TSourceLoc& loc, const TVector<TString>& tokens)
211 {
212     if (pragmaCallback)
213         pragmaCallback(loc.line, tokens);
214
215     if (tokens.size() == 0)
216         return;
217
218     if (tokens[0].compare("optimize") == 0) {
219         if (tokens.size() != 4) {
220             error(loc, "optimize pragma syntax is incorrect", "#pragma", "");
221             return;
222         }
223
224         if (tokens[1].compare("(") != 0) {
225             error(loc, "\"(\" expected after 'optimize' keyword", "#pragma", "");
226             return;
227         }
228
229         if (tokens[2].compare("on") == 0)
230             contextPragma.optimize = true;
231         else if (tokens[2].compare("off") == 0)
232             contextPragma.optimize = false;
233         else {
234             error(loc, "\"on\" or \"off\" expected after '(' for 'optimize' pragma", "#pragma", "");
235             return;
236         }
237
238         if (tokens[3].compare(")") != 0) {
239             error(loc, "\")\" expected to end 'optimize' pragma", "#pragma", "");
240             return;
241         }
242     } else if (tokens[0].compare("debug") == 0) {
243         if (tokens.size() != 4) {
244             error(loc, "debug pragma syntax is incorrect", "#pragma", "");
245             return;
246         }
247
248         if (tokens[1].compare("(") != 0) {
249             error(loc, "\"(\" expected after 'debug' keyword", "#pragma", "");
250             return;
251         }
252
253         if (tokens[2].compare("on") == 0)
254             contextPragma.debug = true;
255         else if (tokens[2].compare("off") == 0)
256             contextPragma.debug = false;
257         else {
258             error(loc, "\"on\" or \"off\" expected after '(' for 'debug' pragma", "#pragma", "");
259             return;
260         }
261
262         if (tokens[3].compare(")") != 0) {
263             error(loc, "\")\" expected to end 'debug' pragma", "#pragma", "");
264             return;
265         }
266     } else if (spvVersion.spv > 0 && tokens[0].compare("use_storage_buffer") == 0) {
267         if (tokens.size() != 1)
268             error(loc, "extra tokens", "#pragma", "");
269         intermediate.setUseStorageBuffer();
270     } else if (spvVersion.spv > 0 && tokens[0].compare("use_vulkan_memory_model") == 0) {
271         if (tokens.size() != 1)
272             error(loc, "extra tokens", "#pragma", "");
273         intermediate.setUseVulkanMemoryModel();
274     } else if (tokens[0].compare("once") == 0) {
275         warn(loc, "not implemented", "#pragma once", "");
276     } else if (tokens[0].compare("glslang_binary_double_output") == 0)
277         intermediate.setBinaryDoubleOutput();
278 }
279
280 //
281 // Handle seeing a variable identifier in the grammar.
282 //
283 TIntermTyped* TParseContext::handleVariable(const TSourceLoc& loc, TSymbol* symbol, const TString* string)
284 {
285     TIntermTyped* node = nullptr;
286
287     // Error check for requiring specific extensions present.
288     if (symbol && symbol->getNumExtensions())
289         requireExtensions(loc, symbol->getNumExtensions(), symbol->getExtensions(), symbol->getName().c_str());
290
291     if (symbol && symbol->isReadOnly()) {
292         // All shared things containing an unsized array must be copied up
293         // on first use, so that all future references will share its array structure,
294         // so that editing the implicit size will effect all nodes consuming it,
295         // and so that editing the implicit size won't change the shared one.
296         //
297         // If this is a variable or a block, check it and all it contains, but if this
298         // is a member of an anonymous block, check the whole block, as the whole block
299         // will need to be copied up if it contains an unsized array.
300         if (symbol->getType().containsUnsizedArray() ||
301             (symbol->getAsAnonMember() &&
302              symbol->getAsAnonMember()->getAnonContainer().getType().containsUnsizedArray()))
303             makeEditable(symbol);
304     }
305
306     const TVariable* variable;
307     const TAnonMember* anon = symbol ? symbol->getAsAnonMember() : nullptr;
308     if (anon) {
309         // It was a member of an anonymous container.
310
311         // The "getNumExtensions()" mechanism above doesn't yet work for block members
312         blockMemberExtensionCheck(loc, nullptr, *string);
313
314         // Create a subtree for its dereference.
315         variable = anon->getAnonContainer().getAsVariable();
316         TIntermTyped* container = intermediate.addSymbol(*variable, loc);
317         TIntermTyped* constNode = intermediate.addConstantUnion(anon->getMemberNumber(), loc);
318         node = intermediate.addIndex(EOpIndexDirectStruct, container, constNode, loc);
319
320         node->setType(*(*variable->getType().getStruct())[anon->getMemberNumber()].type);
321         if (node->getType().hiddenMember())
322             error(loc, "member of nameless block was not redeclared", string->c_str(), "");
323     } else {
324         // Not a member of an anonymous container.
325
326         // The symbol table search was done in the lexical phase.
327         // See if it was a variable.
328         variable = symbol ? symbol->getAsVariable() : nullptr;
329         if (variable) {
330             if ((variable->getType().getBasicType() == EbtBlock ||
331                  variable->getType().getBasicType() == EbtStruct) && variable->getType().getStruct() == nullptr) {
332                 error(loc, "cannot be used (maybe an instance name is needed)", string->c_str(), "");
333                 variable = nullptr;
334             }
335         } else {
336             if (symbol)
337                 error(loc, "variable name expected", string->c_str(), "");
338         }
339
340         // Recovery, if it wasn't found or was not a variable.
341         if (! variable)
342             variable = new TVariable(string, TType(EbtVoid));
343
344         if (variable->getType().getQualifier().isFrontEndConstant())
345             node = intermediate.addConstantUnion(variable->getConstArray(), variable->getType(), loc);
346         else
347             node = intermediate.addSymbol(*variable, loc);
348     }
349
350     if (variable->getType().getQualifier().isIo())
351         intermediate.addIoAccessed(*string);
352
353     return node;
354 }
355
356 //
357 // Handle seeing a base[index] dereference in the grammar.
358 //
359 TIntermTyped* TParseContext::handleBracketDereference(const TSourceLoc& loc, TIntermTyped* base, TIntermTyped* index)
360 {
361     int indexValue = 0;
362     if (index->getQualifier().isFrontEndConstant())
363         indexValue = index->getAsConstantUnion()->getConstArray()[0].getIConst();
364
365     // basic type checks...
366     variableCheck(base);
367
368     if (! base->isArray() && ! base->isMatrix() && ! base->isVector()) {
369         if (base->getAsSymbolNode())
370             error(loc, " left of '[' is not of type array, matrix, or vector ", base->getAsSymbolNode()->getName().c_str(), "");
371         else
372             error(loc, " left of '[' is not of type array, matrix, or vector ", "expression", "");
373
374         // Insert dummy error-recovery result
375         return intermediate.addConstantUnion(0.0, EbtFloat, loc);
376     }
377
378     if (!base->isArray() && base->isVector()) {
379         if (base->getType().containsBasicType(EbtFloat16))
380             requireFloat16Arithmetic(loc, "[", "does not operate on types containing float16");
381         if (base->getType().contains16BitInt())
382             requireInt16Arithmetic(loc, "[", "does not operate on types containing (u)int16");
383         if (base->getType().contains8BitInt())
384             requireInt8Arithmetic(loc, "[", "does not operate on types containing (u)int8");
385     }
386
387     // check for constant folding
388     if (base->getType().getQualifier().isFrontEndConstant() && index->getQualifier().isFrontEndConstant()) {
389         // both base and index are front-end constants
390         checkIndex(loc, base->getType(), indexValue);
391         return intermediate.foldDereference(base, indexValue, loc);
392     }
393
394     // at least one of base and index is not a front-end constant variable...
395     TIntermTyped* result = nullptr;
396     if (index->getQualifier().isFrontEndConstant())
397         checkIndex(loc, base->getType(), indexValue);
398
399     if (base->getAsSymbolNode() && isIoResizeArray(base->getType()))
400         handleIoResizeArrayAccess(loc, base);
401
402     if (index->getQualifier().isFrontEndConstant()) {
403         if (base->getType().isUnsizedArray())
404             base->getWritableType().updateImplicitArraySize(indexValue + 1);
405         else
406             checkIndex(loc, base->getType(), indexValue);
407         result = intermediate.addIndex(EOpIndexDirect, base, index, loc);
408     } else {
409         if (base->getType().isUnsizedArray()) {
410             // we have a variable index into an unsized array, which is okay,
411             // depending on the situation
412             if (base->getAsSymbolNode() && isIoResizeArray(base->getType()))
413                 error(loc, "", "[", "array must be sized by a redeclaration or layout qualifier before being indexed with a variable");
414             else {
415                 // it is okay for a run-time sized array
416                 checkRuntimeSizable(loc, *base);
417             }
418             base->getWritableType().setArrayVariablyIndexed();
419         }
420         if (base->getBasicType() == EbtBlock) {
421             if (base->getQualifier().storage == EvqBuffer)
422                 requireProfile(base->getLoc(), ~EEsProfile, "variable indexing buffer block array");
423             else if (base->getQualifier().storage == EvqUniform)
424                 profileRequires(base->getLoc(), EEsProfile, 320, Num_AEP_gpu_shader5, AEP_gpu_shader5,
425                                 "variable indexing uniform block array");
426             else {
427                 // input/output blocks either don't exist or can be variable indexed
428             }
429         } else if (language == EShLangFragment && base->getQualifier().isPipeOutput())
430             requireProfile(base->getLoc(), ~EEsProfile, "variable indexing fragment shader output array");
431         else if (base->getBasicType() == EbtSampler && version >= 130) {
432             const char* explanation = "variable indexing sampler array";
433             requireProfile(base->getLoc(), EEsProfile | ECoreProfile | ECompatibilityProfile, explanation);
434             profileRequires(base->getLoc(), EEsProfile, 320, Num_AEP_gpu_shader5, AEP_gpu_shader5, explanation);
435             profileRequires(base->getLoc(), ECoreProfile | ECompatibilityProfile, 400, nullptr, explanation);
436         }
437
438         result = intermediate.addIndex(EOpIndexIndirect, base, index, loc);
439     }
440
441     // Insert valid dereferenced result
442     TType newType(base->getType(), 0);  // dereferenced type
443     if (base->getType().getQualifier().isConstant() && index->getQualifier().isConstant()) {
444         newType.getQualifier().storage = EvqConst;
445         // If base or index is a specialization constant, the result should also be a specialization constant.
446         if (base->getType().getQualifier().isSpecConstant() || index->getQualifier().isSpecConstant()) {
447             newType.getQualifier().makeSpecConstant();
448         }
449     } else {
450         newType.getQualifier().makePartialTemporary();
451     }
452     result->setType(newType);
453
454     // Propagate nonuniform
455     if (base->getQualifier().isNonUniform() || index->getQualifier().isNonUniform())
456         result->getWritableType().getQualifier().nonUniform = true;
457
458     if (anyIndexLimits)
459         handleIndexLimits(loc, base, index);
460
461     return result;
462 }
463
464 // for ES 2.0 (version 100) limitations for almost all index operations except vertex-shader uniforms
465 void TParseContext::handleIndexLimits(const TSourceLoc& /*loc*/, TIntermTyped* base, TIntermTyped* index)
466 {
467     if ((! limits.generalSamplerIndexing && base->getBasicType() == EbtSampler) ||
468         (! limits.generalUniformIndexing && base->getQualifier().isUniformOrBuffer() && language != EShLangVertex) ||
469         (! limits.generalAttributeMatrixVectorIndexing && base->getQualifier().isPipeInput() && language == EShLangVertex && (base->getType().isMatrix() || base->getType().isVector())) ||
470         (! limits.generalConstantMatrixVectorIndexing && base->getAsConstantUnion()) ||
471         (! limits.generalVariableIndexing && ! base->getType().getQualifier().isUniformOrBuffer() &&
472                                              ! base->getType().getQualifier().isPipeInput() &&
473                                              ! base->getType().getQualifier().isPipeOutput() &&
474                                              ! base->getType().getQualifier().isConstant()) ||
475         (! limits.generalVaryingIndexing && (base->getType().getQualifier().isPipeInput() ||
476                                                 base->getType().getQualifier().isPipeOutput()))) {
477         // it's too early to know what the inductive variables are, save it for post processing
478         needsIndexLimitationChecking.push_back(index);
479     }
480 }
481
482 // Make a shared symbol have a non-shared version that can be edited by the current
483 // compile, such that editing its type will not change the shared version and will
484 // effect all nodes sharing it.
485 void TParseContext::makeEditable(TSymbol*& symbol)
486 {
487     TParseContextBase::makeEditable(symbol);
488
489     // See if it's tied to IO resizing
490     if (isIoResizeArray(symbol->getType()))
491         ioArraySymbolResizeList.push_back(symbol);
492 }
493
494 // Return true if this is a geometry shader input array or tessellation control output array
495 // or mesh shader output array.
496 bool TParseContext::isIoResizeArray(const TType& type) const
497 {
498     return type.isArray() &&
499            ((language == EShLangGeometry    && type.getQualifier().storage == EvqVaryingIn) ||
500             (language == EShLangTessControl && type.getQualifier().storage == EvqVaryingOut && ! type.getQualifier().patch)
501 #ifdef NV_EXTENSIONS
502             ||
503             (language == EShLangFragment && type.getQualifier().storage == EvqVaryingIn &&  type.getQualifier().pervertexNV) ||
504             (language == EShLangMeshNV && type.getQualifier().storage == EvqVaryingOut && !type.getQualifier().perTaskNV)
505
506 #endif
507             );
508 }
509
510 // If an array is not isIoResizeArray() but is an io array, make sure it has the right size
511 void TParseContext::fixIoArraySize(const TSourceLoc& loc, TType& type)
512 {
513     if (! type.isArray() || type.getQualifier().patch || symbolTable.atBuiltInLevel())
514         return;
515
516     assert(! isIoResizeArray(type));
517
518     if (type.getQualifier().storage != EvqVaryingIn || type.getQualifier().patch)
519         return;
520
521     if (language == EShLangTessControl || language == EShLangTessEvaluation) {
522         if (type.getOuterArraySize() != resources.maxPatchVertices) {
523             if (type.isSizedArray())
524                 error(loc, "tessellation input array size must be gl_MaxPatchVertices or implicitly sized", "[]", "");
525             type.changeOuterArraySize(resources.maxPatchVertices);
526         }
527     }
528 }
529
530 // Issue any errors if the non-array object is missing arrayness WRT
531 // shader I/O that has array requirements.
532 // All arrayness checking is handled in array paths, this is for
533 void TParseContext::ioArrayCheck(const TSourceLoc& loc, const TType& type, const TString& identifier)
534 {
535     if (! type.isArray() && ! symbolTable.atBuiltInLevel()) {
536         if (type.getQualifier().isArrayedIo(language)
537 #ifdef NV_EXTENSIONS
538             && !type.getQualifier().layoutPassthrough
539 #endif
540            )
541             error(loc, "type must be an array:", type.getStorageQualifierString(), identifier.c_str());
542     }
543 }
544
545 // Handle a dereference of a geometry shader input array or tessellation control output array.
546 // See ioArraySymbolResizeList comment in ParseHelper.h.
547 //
548 void TParseContext::handleIoResizeArrayAccess(const TSourceLoc& /*loc*/, TIntermTyped* base)
549 {
550     TIntermSymbol* symbolNode = base->getAsSymbolNode();
551     assert(symbolNode);
552     if (! symbolNode)
553         return;
554
555     // fix array size, if it can be fixed and needs to be fixed (will allow variable indexing)
556     if (symbolNode->getType().isUnsizedArray()) {
557         int newSize = getIoArrayImplicitSize(symbolNode->getType().getQualifier().isPerPrimitive());
558         if (newSize > 0)
559             symbolNode->getWritableType().changeOuterArraySize(newSize);
560     }
561 }
562
563 // If there has been an input primitive declaration (geometry shader) or an output
564 // number of vertices declaration(tessellation shader), make sure all input array types
565 // match it in size.  Types come either from nodes in the AST or symbols in the
566 // symbol table.
567 //
568 // Types without an array size will be given one.
569 // Types already having a size that is wrong will get an error.
570 //
571 void TParseContext::checkIoArraysConsistency(const TSourceLoc& loc, bool tailOnly, bool isPerPrimitive)
572 {
573     int requiredSize = getIoArrayImplicitSize(isPerPrimitive);
574     if (requiredSize == 0)
575         return;
576
577     const char* feature;
578     if (language == EShLangGeometry)
579         feature = TQualifier::getGeometryString(intermediate.getInputPrimitive());
580     else if (language == EShLangTessControl
581 #ifdef NV_EXTENSIONS
582           || language == EShLangFragment
583 #endif
584         )
585
586         feature = "vertices";
587 #ifdef NV_EXTENSIONS
588      else if (language == EShLangMeshNV) {
589         feature = isPerPrimitive ? "max_primitives" : "max_vertices";
590      }
591 #endif
592     else
593         feature = "unknown";
594
595     if (tailOnly) {
596         checkIoArrayConsistency(loc, requiredSize, feature, ioArraySymbolResizeList.back()->getWritableType(), ioArraySymbolResizeList.back()->getName());
597         return;
598     }
599
600     for (size_t i = 0; i < ioArraySymbolResizeList.size(); ++i)
601         checkIoArrayConsistency(loc, requiredSize, feature, ioArraySymbolResizeList[i]->getWritableType(), ioArraySymbolResizeList[i]->getName());
602 }
603
604 int TParseContext::getIoArrayImplicitSize(bool isPerPrimitive) const
605 {
606     if (language == EShLangGeometry)
607         return TQualifier::mapGeometryToSize(intermediate.getInputPrimitive());
608     else if (language == EShLangTessControl)
609         return intermediate.getVertices() != TQualifier::layoutNotSet ? intermediate.getVertices() : 0;
610 #ifdef NV_EXTENSIONS
611     else if (language == EShLangFragment)
612         return 3; //Number of vertices for Fragment shader is always three.
613     else if (language == EShLangMeshNV) {
614         if (isPerPrimitive) {
615             return intermediate.getPrimitives() != TQualifier::layoutNotSet ? intermediate.getPrimitives() : 0;
616         } else {
617             return intermediate.getVertices() != TQualifier::layoutNotSet ? intermediate.getVertices() : 0;
618         }
619     }
620 #endif
621
622     else
623         return 0;
624 }
625
626 void TParseContext::checkIoArrayConsistency(const TSourceLoc& loc, int requiredSize, const char* feature, TType& type, const TString& name)
627 {
628     if (type.isUnsizedArray())
629         type.changeOuterArraySize(requiredSize);
630     else if (type.getOuterArraySize() != requiredSize) {
631         if (language == EShLangGeometry)
632             error(loc, "inconsistent input primitive for array size of", feature, name.c_str());
633         else if (language == EShLangTessControl)
634             error(loc, "inconsistent output number of vertices for array size of", feature, name.c_str());
635 #ifdef NV_EXTENSIONS
636         else if (language == EShLangFragment) {
637             if (type.getOuterArraySize() > requiredSize)
638                 error(loc, " cannot be greater than 3 for pervertexNV", feature, name.c_str());
639         }
640         else if (language == EShLangMeshNV)
641             error(loc, "inconsistent output array size of", feature, name.c_str());
642 #endif
643         else
644             assert(0);
645     }
646 }
647
648 // Handle seeing a binary node with a math operation.
649 // Returns nullptr if not semantically allowed.
650 TIntermTyped* TParseContext::handleBinaryMath(const TSourceLoc& loc, const char* str, TOperator op, TIntermTyped* left, TIntermTyped* right)
651 {
652     rValueErrorCheck(loc, str, left->getAsTyped());
653     rValueErrorCheck(loc, str, right->getAsTyped());
654
655     bool allowed = true;
656     switch (op) {
657     // TODO: Bring more source language-specific checks up from intermediate.cpp
658     // to the specific parse helpers for that source language.
659     case EOpLessThan:
660     case EOpGreaterThan:
661     case EOpLessThanEqual:
662     case EOpGreaterThanEqual:
663         if (! left->isScalar() || ! right->isScalar())
664             allowed = false;
665         break;
666     default:
667         break;
668     }
669
670     if (((left->getType().containsBasicType(EbtFloat16) || right->getType().containsBasicType(EbtFloat16)) && !float16Arithmetic()) ||
671         ((left->getType().contains16BitInt() || right->getType().contains16BitInt()) && !int16Arithmetic()) ||
672         ((left->getType().contains8BitInt() || right->getType().contains8BitInt()) && !int8Arithmetic())) {
673         allowed = false;
674     }
675
676     TIntermTyped* result = nullptr;
677     if (allowed)
678         result = intermediate.addBinaryMath(op, left, right, loc);
679
680     if (result == nullptr)
681         binaryOpError(loc, str, left->getCompleteString(), right->getCompleteString());
682
683     return result;
684 }
685
686 // Handle seeing a unary node with a math operation.
687 TIntermTyped* TParseContext::handleUnaryMath(const TSourceLoc& loc, const char* str, TOperator op, TIntermTyped* childNode)
688 {
689     rValueErrorCheck(loc, str, childNode);
690
691     bool allowed = true;
692     if ((childNode->getType().containsBasicType(EbtFloat16) && !float16Arithmetic()) ||
693         (childNode->getType().contains16BitInt() && !int16Arithmetic()) ||
694         (childNode->getType().contains8BitInt() && !int8Arithmetic())) {
695         allowed = false;
696     }
697
698     TIntermTyped* result = nullptr;
699     
700     if (allowed)
701         result = intermediate.addUnaryMath(op, childNode, loc);
702
703     if (result)
704         return result;
705     else
706         unaryOpError(loc, str, childNode->getCompleteString());
707
708     return childNode;
709 }
710
711 //
712 // Handle seeing a base.field dereference in the grammar.
713 //
714 TIntermTyped* TParseContext::handleDotDereference(const TSourceLoc& loc, TIntermTyped* base, const TString& field)
715 {
716     variableCheck(base);
717
718     //
719     // .length() can't be resolved until we later see the function-calling syntax.
720     // Save away the name in the AST for now.  Processing is completed in
721     // handleLengthMethod().
722     //
723     if (field == "length") {
724         if (base->isArray()) {
725             profileRequires(loc, ENoProfile, 120, E_GL_3DL_array_objects, ".length");
726             profileRequires(loc, EEsProfile, 300, nullptr, ".length");
727         } else if (base->isVector() || base->isMatrix()) {
728             const char* feature = ".length() on vectors and matrices";
729             requireProfile(loc, ~EEsProfile, feature);
730             profileRequires(loc, ~EEsProfile, 420, E_GL_ARB_shading_language_420pack, feature);
731         } else {
732             error(loc, "does not operate on this type:", field.c_str(), base->getType().getCompleteString().c_str());
733
734             return base;
735         }
736
737         return intermediate.addMethod(base, TType(EbtInt), &field, loc);
738     }
739
740     // It's not .length() if we get to here.
741
742     if (base->isArray()) {
743         error(loc, "cannot apply to an array:", ".", field.c_str());
744
745         return base;
746     }
747
748     // It's neither an array nor .length() if we get here,
749     // leaving swizzles and struct/block dereferences.
750
751     TIntermTyped* result = base;
752     if ((base->isVector() || base->isScalar()) &&
753         (base->isFloatingDomain() || base->isIntegerDomain() || base->getBasicType() == EbtBool)) {
754         if (base->isScalar()) {
755             const char* dotFeature = "scalar swizzle";
756             requireProfile(loc, ~EEsProfile, dotFeature);
757             profileRequires(loc, ~EEsProfile, 420, E_GL_ARB_shading_language_420pack, dotFeature);
758         }
759
760         TSwizzleSelectors<TVectorSelector> selectors;
761         parseSwizzleSelector(loc, field, base->getVectorSize(), selectors);
762
763         if (base->isVector() && selectors.size() != 1 && base->getType().containsBasicType(EbtFloat16))
764             requireFloat16Arithmetic(loc, ".", "can't swizzle types containing float16");
765         if (base->isVector() && selectors.size() != 1 && base->getType().contains16BitInt())
766             requireInt16Arithmetic(loc, ".", "can't swizzle types containing (u)int16");
767         if (base->isVector() && selectors.size() != 1 && base->getType().contains8BitInt())
768             requireInt8Arithmetic(loc, ".", "can't swizzle types containing (u)int8");
769
770         if (base->isScalar()) {
771             if (selectors.size() == 1)
772                 return result;
773             else {
774                 TType type(base->getBasicType(), EvqTemporary, selectors.size());
775                 // Swizzle operations propagate specialization-constantness
776                 if (base->getQualifier().isSpecConstant())
777                     type.getQualifier().makeSpecConstant();
778                 return addConstructor(loc, base, type);
779             }
780         }
781
782         if (base->getType().getQualifier().isFrontEndConstant())
783             result = intermediate.foldSwizzle(base, selectors, loc);
784         else {
785             if (selectors.size() == 1) {
786                 TIntermTyped* index = intermediate.addConstantUnion(selectors[0], loc);
787                 result = intermediate.addIndex(EOpIndexDirect, base, index, loc);
788                 result->setType(TType(base->getBasicType(), EvqTemporary, base->getType().getQualifier().precision));
789             } else {
790                 TIntermTyped* index = intermediate.addSwizzle(selectors, loc);
791                 result = intermediate.addIndex(EOpVectorSwizzle, base, index, loc);
792                 result->setType(TType(base->getBasicType(), EvqTemporary, base->getType().getQualifier().precision, selectors.size()));
793             }
794             // Swizzle operations propagate specialization-constantness
795             if (base->getType().getQualifier().isSpecConstant())
796                 result->getWritableType().getQualifier().makeSpecConstant();
797         }
798     } else if (base->getBasicType() == EbtStruct || base->getBasicType() == EbtBlock) {
799         const TTypeList* fields = base->getType().getStruct();
800         bool fieldFound = false;
801         int member;
802         for (member = 0; member < (int)fields->size(); ++member) {
803             if ((*fields)[member].type->getFieldName() == field) {
804                 fieldFound = true;
805                 break;
806             }
807         }
808         if (fieldFound) {
809             if (base->getType().getQualifier().isFrontEndConstant())
810                 result = intermediate.foldDereference(base, member, loc);
811             else {
812                 blockMemberExtensionCheck(loc, base, field);
813                 TIntermTyped* index = intermediate.addConstantUnion(member, loc);
814                 result = intermediate.addIndex(EOpIndexDirectStruct, base, index, loc);
815                 result->setType(*(*fields)[member].type);
816             }
817         } else
818             error(loc, "no such field in structure", field.c_str(), "");
819     } else
820         error(loc, "does not apply to this type:", field.c_str(), base->getType().getCompleteString().c_str());
821
822     // Propagate noContraction up the dereference chain
823     if (base->getQualifier().noContraction)
824         result->getWritableType().getQualifier().noContraction = true;
825
826     // Propagate nonuniform
827     if (base->getQualifier().isNonUniform())
828         result->getWritableType().getQualifier().nonUniform = true;
829
830     return result;
831 }
832
833 void TParseContext::blockMemberExtensionCheck(const TSourceLoc& loc, const TIntermTyped* /*base*/, const TString& field)
834 {
835     if (profile == EEsProfile && field == "gl_PointSize") {
836         if (language == EShLangGeometry)
837             requireExtensions(loc, Num_AEP_geometry_point_size, AEP_geometry_point_size, "gl_PointSize");
838         else if (language == EShLangTessControl || language == EShLangTessEvaluation)
839             requireExtensions(loc, Num_AEP_tessellation_point_size, AEP_tessellation_point_size, "gl_PointSize");
840     }
841 }
842
843 //
844 // Handle seeing a function declarator in the grammar.  This is the precursor
845 // to recognizing a function prototype or function definition.
846 //
847 TFunction* TParseContext::handleFunctionDeclarator(const TSourceLoc& loc, TFunction& function, bool prototype)
848 {
849     // ES can't declare prototypes inside functions
850     if (! symbolTable.atGlobalLevel())
851         requireProfile(loc, ~EEsProfile, "local function declaration");
852
853     //
854     // Multiple declarations of the same function name are allowed.
855     //
856     // If this is a definition, the definition production code will check for redefinitions
857     // (we don't know at this point if it's a definition or not).
858     //
859     // Redeclarations (full signature match) are allowed.  But, return types and parameter qualifiers must also match.
860     //  - except ES 100, which only allows a single prototype
861     //
862     // ES 100 does not allow redefining, but does allow overloading of built-in functions.
863     // ES 300 does not allow redefining or overloading of built-in functions.
864     //
865     bool builtIn;
866     TSymbol* symbol = symbolTable.find(function.getMangledName(), &builtIn);
867     if (symbol && symbol->getAsFunction() && builtIn)
868         requireProfile(loc, ~EEsProfile, "redefinition of built-in function");
869     const TFunction* prevDec = symbol ? symbol->getAsFunction() : 0;
870     if (prevDec) {
871         if (prevDec->isPrototyped() && prototype)
872             profileRequires(loc, EEsProfile, 300, nullptr, "multiple prototypes for same function");
873         if (prevDec->getType() != function.getType())
874             error(loc, "overloaded functions must have the same return type", function.getName().c_str(), "");
875         for (int i = 0; i < prevDec->getParamCount(); ++i) {
876             if ((*prevDec)[i].type->getQualifier().storage != function[i].type->getQualifier().storage)
877                 error(loc, "overloaded functions must have the same parameter storage qualifiers for argument", function[i].type->getStorageQualifierString(), "%d", i+1);
878
879             if ((*prevDec)[i].type->getQualifier().precision != function[i].type->getQualifier().precision)
880                 error(loc, "overloaded functions must have the same parameter precision qualifiers for argument", function[i].type->getPrecisionQualifierString(), "%d", i+1);
881         }
882     }
883
884     arrayObjectCheck(loc, function.getType(), "array in function return type");
885
886     if (prototype) {
887         // All built-in functions are defined, even though they don't have a body.
888         // Count their prototype as a definition instead.
889         if (symbolTable.atBuiltInLevel())
890             function.setDefined();
891         else {
892             if (prevDec && ! builtIn)
893                 symbol->getAsFunction()->setPrototyped();  // need a writable one, but like having prevDec as a const
894             function.setPrototyped();
895         }
896     }
897
898     // This insert won't actually insert it if it's a duplicate signature, but it will still check for
899     // other forms of name collisions.
900     if (! symbolTable.insert(function))
901         error(loc, "function name is redeclaration of existing name", function.getName().c_str(), "");
902
903     //
904     // If this is a redeclaration, it could also be a definition,
905     // in which case, we need to use the parameter names from this one, and not the one that's
906     // being redeclared.  So, pass back this declaration, not the one in the symbol table.
907     //
908     return &function;
909 }
910
911 //
912 // Handle seeing the function prototype in front of a function definition in the grammar.
913 // The body is handled after this function returns.
914 //
915 TIntermAggregate* TParseContext::handleFunctionDefinition(const TSourceLoc& loc, TFunction& function)
916 {
917     currentCaller = function.getMangledName();
918     TSymbol* symbol = symbolTable.find(function.getMangledName());
919     TFunction* prevDec = symbol ? symbol->getAsFunction() : nullptr;
920
921     if (! prevDec)
922         error(loc, "can't find function", function.getName().c_str(), "");
923     // Note:  'prevDec' could be 'function' if this is the first time we've seen function
924     // as it would have just been put in the symbol table.  Otherwise, we're looking up
925     // an earlier occurrence.
926
927     if (prevDec && prevDec->isDefined()) {
928         // Then this function already has a body.
929         error(loc, "function already has a body", function.getName().c_str(), "");
930     }
931     if (prevDec && ! prevDec->isDefined()) {
932         prevDec->setDefined();
933
934         // Remember the return type for later checking for RETURN statements.
935         currentFunctionType = &(prevDec->getType());
936     } else
937         currentFunctionType = new TType(EbtVoid);
938     functionReturnsValue = false;
939
940     // Check for entry point
941     if (function.getName().compare(intermediate.getEntryPointName().c_str()) == 0) {
942         intermediate.setEntryPointMangledName(function.getMangledName().c_str());
943         intermediate.incrementEntryPointCount();
944         inMain = true;
945     } else
946         inMain = false;
947
948     //
949     // Raise error message if main function takes any parameters or returns anything other than void
950     //
951     if (inMain) {
952         if (function.getParamCount() > 0)
953             error(loc, "function cannot take any parameter(s)", function.getName().c_str(), "");
954         if (function.getType().getBasicType() != EbtVoid)
955             error(loc, "", function.getType().getBasicTypeString().c_str(), "entry point cannot return a value");
956     }
957
958     //
959     // New symbol table scope for body of function plus its arguments
960     //
961     symbolTable.push();
962
963     //
964     // Insert parameters into the symbol table.
965     // If the parameter has no name, it's not an error, just don't insert it
966     // (could be used for unused args).
967     //
968     // Also, accumulate the list of parameters into the HIL, so lower level code
969     // knows where to find parameters.
970     //
971     TIntermAggregate* paramNodes = new TIntermAggregate;
972     for (int i = 0; i < function.getParamCount(); i++) {
973         TParameter& param = function[i];
974         if (param.name != nullptr) {
975             TVariable *variable = new TVariable(param.name, *param.type);
976
977             // Insert the parameters with name in the symbol table.
978             if (! symbolTable.insert(*variable))
979                 error(loc, "redefinition", variable->getName().c_str(), "");
980             else {
981                 // Transfer ownership of name pointer to symbol table.
982                 param.name = nullptr;
983
984                 // Add the parameter to the HIL
985                 paramNodes = intermediate.growAggregate(paramNodes,
986                                                         intermediate.addSymbol(*variable, loc),
987                                                         loc);
988             }
989         } else
990             paramNodes = intermediate.growAggregate(paramNodes, intermediate.addSymbol(*param.type, loc), loc);
991     }
992     intermediate.setAggregateOperator(paramNodes, EOpParameters, TType(EbtVoid), loc);
993     loopNestingLevel = 0;
994     statementNestingLevel = 0;
995     controlFlowNestingLevel = 0;
996     postEntryPointReturn = false;
997
998     return paramNodes;
999 }
1000
1001 //
1002 // Handle seeing function call syntax in the grammar, which could be any of
1003 //  - .length() method
1004 //  - constructor
1005 //  - a call to a built-in function mapped to an operator
1006 //  - a call to a built-in function that will remain a function call (e.g., texturing)
1007 //  - user function
1008 //  - subroutine call (not implemented yet)
1009 //
1010 TIntermTyped* TParseContext::handleFunctionCall(const TSourceLoc& loc, TFunction* function, TIntermNode* arguments)
1011 {
1012     TIntermTyped* result = nullptr;
1013
1014     if (function->getBuiltInOp() == EOpArrayLength)
1015         result = handleLengthMethod(loc, function, arguments);
1016     else if (function->getBuiltInOp() != EOpNull) {
1017         //
1018         // Then this should be a constructor.
1019         // Don't go through the symbol table for constructors.
1020         // Their parameters will be verified algorithmically.
1021         //
1022         TType type(EbtVoid);  // use this to get the type back
1023         if (! constructorError(loc, arguments, *function, function->getBuiltInOp(), type)) {
1024             //
1025             // It's a constructor, of type 'type'.
1026             //
1027             result = addConstructor(loc, arguments, type);
1028             if (result == nullptr)
1029                 error(loc, "cannot construct with these arguments", type.getCompleteString().c_str(), "");
1030         }
1031     } else {
1032         //
1033         // Find it in the symbol table.
1034         //
1035         const TFunction* fnCandidate;
1036         bool builtIn;
1037         fnCandidate = findFunction(loc, *function, builtIn);
1038         if (fnCandidate) {
1039             // This is a declared function that might map to
1040             //  - a built-in operator,
1041             //  - a built-in function not mapped to an operator, or
1042             //  - a user function.
1043
1044             // Error check for a function requiring specific extensions present.
1045             if (builtIn && fnCandidate->getNumExtensions())
1046                 requireExtensions(loc, fnCandidate->getNumExtensions(), fnCandidate->getExtensions(), fnCandidate->getName().c_str());
1047
1048             if (builtIn && fnCandidate->getType().containsBasicType(EbtFloat16))
1049                 requireFloat16Arithmetic(loc, "built-in function", "float16 types can only be in uniform block or buffer storage");
1050             if (builtIn && fnCandidate->getType().contains16BitInt())
1051                 requireInt16Arithmetic(loc, "built-in function", "(u)int16 types can only be in uniform block or buffer storage");
1052             if (builtIn && fnCandidate->getType().contains8BitInt())
1053                 requireInt8Arithmetic(loc, "built-in function", "(u)int8 types can only be in uniform block or buffer storage");
1054
1055             if (arguments != nullptr) {
1056                 // Make sure qualifications work for these arguments.
1057                 TIntermAggregate* aggregate = arguments->getAsAggregate();
1058                 for (int i = 0; i < fnCandidate->getParamCount(); ++i) {
1059                     // At this early point there is a slight ambiguity between whether an aggregate 'arguments'
1060                     // is the single argument itself or its children are the arguments.  Only one argument
1061                     // means take 'arguments' itself as the one argument.
1062                     TIntermNode* arg = fnCandidate->getParamCount() == 1 ? arguments : (aggregate ? aggregate->getSequence()[i] : arguments);
1063                     TQualifier& formalQualifier = (*fnCandidate)[i].type->getQualifier();
1064                     if (formalQualifier.isParamOutput()) {
1065                         if (lValueErrorCheck(arguments->getLoc(), "assign", arg->getAsTyped()))
1066                             error(arguments->getLoc(), "Non-L-value cannot be passed for 'out' or 'inout' parameters.", "out", "");
1067                     }
1068                     TQualifier& argQualifier = arg->getAsTyped()->getQualifier();
1069                     if (argQualifier.isMemory()) {
1070                         const char* message = "argument cannot drop memory qualifier when passed to formal parameter";
1071                         if (argQualifier.volatil && ! formalQualifier.volatil)
1072                             error(arguments->getLoc(), message, "volatile", "");
1073                         if (argQualifier.coherent && ! (formalQualifier.devicecoherent || formalQualifier.coherent))
1074                             error(arguments->getLoc(), message, "coherent", "");
1075                         if (argQualifier.devicecoherent && ! (formalQualifier.devicecoherent || formalQualifier.coherent))
1076                             error(arguments->getLoc(), message, "devicecoherent", "");
1077                         if (argQualifier.queuefamilycoherent && ! (formalQualifier.queuefamilycoherent || formalQualifier.devicecoherent || formalQualifier.coherent))
1078                             error(arguments->getLoc(), message, "queuefamilycoherent", "");
1079                         if (argQualifier.workgroupcoherent && ! (formalQualifier.workgroupcoherent || formalQualifier.queuefamilycoherent || formalQualifier.devicecoherent || formalQualifier.coherent))
1080                             error(arguments->getLoc(), message, "workgroupcoherent", "");
1081                         if (argQualifier.subgroupcoherent && ! (formalQualifier.subgroupcoherent || formalQualifier.workgroupcoherent || formalQualifier.queuefamilycoherent || formalQualifier.devicecoherent || formalQualifier.coherent))
1082                             error(arguments->getLoc(), message, "subgroupcoherent", "");
1083                         if (argQualifier.readonly && ! formalQualifier.readonly)
1084                             error(arguments->getLoc(), message, "readonly", "");
1085                         if (argQualifier.writeonly && ! formalQualifier.writeonly)
1086                             error(arguments->getLoc(), message, "writeonly", "");
1087                     }
1088
1089                     if (builtIn && arg->getAsTyped()->getType().containsBasicType(EbtFloat16))
1090                         requireFloat16Arithmetic(arguments->getLoc(), "built-in function", "float16 types can only be in uniform block or buffer storage");
1091                     if (builtIn && arg->getAsTyped()->getType().contains16BitInt())
1092                         requireInt16Arithmetic(arguments->getLoc(), "built-in function", "(u)int16 types can only be in uniform block or buffer storage");
1093                     if (builtIn && arg->getAsTyped()->getType().contains8BitInt())
1094                         requireInt8Arithmetic(arguments->getLoc(), "built-in function", "(u)int8 types can only be in uniform block or buffer storage");
1095
1096                     // TODO 4.5 functionality:  A shader will fail to compile
1097                     // if the value passed to the memargument of an atomic memory function does not correspond to a buffer or
1098                     // shared variable. It is acceptable to pass an element of an array or a single component of a vector to the
1099                     // memargument of an atomic memory function, as long as the underlying array or vector is a buffer or
1100                     // shared variable.
1101                 }
1102
1103                 // Convert 'in' arguments
1104                 addInputArgumentConversions(*fnCandidate, arguments);  // arguments may be modified if it's just a single argument node
1105             }
1106
1107             if (builtIn && fnCandidate->getBuiltInOp() != EOpNull) {
1108                 // A function call mapped to a built-in operation.
1109                 result = handleBuiltInFunctionCall(loc, arguments, *fnCandidate);
1110             } else {
1111                 // This is a function call not mapped to built-in operator.
1112                 // It could still be a built-in function, but only if PureOperatorBuiltins == false.
1113                 result = intermediate.setAggregateOperator(arguments, EOpFunctionCall, fnCandidate->getType(), loc);
1114                 TIntermAggregate* call = result->getAsAggregate();
1115                 call->setName(fnCandidate->getMangledName());
1116
1117                 // this is how we know whether the given function is a built-in function or a user-defined function
1118                 // if builtIn == false, it's a userDefined -> could be an overloaded built-in function also
1119                 // if builtIn == true, it's definitely a built-in function with EOpNull
1120                 if (! builtIn) {
1121                     call->setUserDefined();
1122                     if (symbolTable.atGlobalLevel()) {
1123                         requireProfile(loc, ~EEsProfile, "calling user function from global scope");
1124                         intermediate.addToCallGraph(infoSink, "main(", fnCandidate->getMangledName());
1125                     } else
1126                         intermediate.addToCallGraph(infoSink, currentCaller, fnCandidate->getMangledName());
1127                 }
1128
1129                 if (builtIn)
1130                     nonOpBuiltInCheck(loc, *fnCandidate, *call);
1131                 else
1132                     userFunctionCallCheck(loc, *call);
1133             }
1134
1135             // Convert 'out' arguments.  If it was a constant folded built-in, it won't be an aggregate anymore.
1136             // Built-ins with a single argument aren't called with an aggregate, but they also don't have an output.
1137             // Also, build the qualifier list for user function calls, which are always called with an aggregate.
1138             if (result->getAsAggregate()) {
1139                 TQualifierList& qualifierList = result->getAsAggregate()->getQualifierList();
1140                 for (int i = 0; i < fnCandidate->getParamCount(); ++i) {
1141                     TStorageQualifier qual = (*fnCandidate)[i].type->getQualifier().storage;
1142                     qualifierList.push_back(qual);
1143                 }
1144                 result = addOutputArgumentConversions(*fnCandidate, *result->getAsAggregate());
1145             }
1146         }
1147     }
1148
1149     // generic error recovery
1150     // TODO: simplification: localize all the error recoveries that look like this, and taking type into account to reduce cascades
1151     if (result == nullptr)
1152         result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
1153
1154     return result;
1155 }
1156
1157 TIntermTyped* TParseContext::handleBuiltInFunctionCall(TSourceLoc loc, TIntermNode* arguments,
1158                                                        const TFunction& function)
1159 {
1160     checkLocation(loc, function.getBuiltInOp());
1161     TIntermTyped *result = intermediate.addBuiltInFunctionCall(loc, function.getBuiltInOp(),
1162                                                                function.getParamCount() == 1,
1163                                                                arguments, function.getType());
1164     if (obeyPrecisionQualifiers())
1165         computeBuiltinPrecisions(*result, function);
1166
1167     if (result == nullptr) {
1168         if (arguments == nullptr)
1169             error(loc, " wrong operand type", "Internal Error",
1170                                       "built in unary operator function.  Type: %s", "");
1171         else
1172             error(arguments->getLoc(), " wrong operand type", "Internal Error",
1173                                       "built in unary operator function.  Type: %s",
1174                                       static_cast<TIntermTyped*>(arguments)->getCompleteString().c_str());
1175     } else if (result->getAsOperator())
1176         builtInOpCheck(loc, function, *result->getAsOperator());
1177
1178     return result;
1179 }
1180
1181 // "The operation of a built-in function can have a different precision
1182 // qualification than the precision qualification of the resulting value.
1183 // These two precision qualifications are established as follows.
1184 //
1185 // The precision qualification of the operation of a built-in function is
1186 // based on the precision qualification of its input arguments and formal
1187 // parameters:  When a formal parameter specifies a precision qualifier,
1188 // that is used, otherwise, the precision qualification of the calling
1189 // argument is used.  The highest precision of these will be the precision
1190 // qualification of the operation of the built-in function. Generally,
1191 // this is applied across all arguments to a built-in function, with the
1192 // exceptions being:
1193 //   - bitfieldExtract and bitfieldInsert ignore the 'offset' and 'bits'
1194 //     arguments.
1195 //   - interpolateAt* functions only look at the 'interpolant' argument.
1196 //
1197 // The precision qualification of the result of a built-in function is
1198 // determined in one of the following ways:
1199 //
1200 //   - For the texture sampling, image load, and image store functions,
1201 //     the precision of the return type matches the precision of the
1202 //     sampler type
1203 //
1204 //   Otherwise:
1205 //
1206 //   - For prototypes that do not specify a resulting precision qualifier,
1207 //     the precision will be the same as the precision of the operation.
1208 //
1209 //   - For prototypes that do specify a resulting precision qualifier,
1210 //     the specified precision qualifier is the precision qualification of
1211 //     the result."
1212 //
1213 void TParseContext::computeBuiltinPrecisions(TIntermTyped& node, const TFunction& function)
1214 {
1215     TPrecisionQualifier operationPrecision = EpqNone;
1216     TPrecisionQualifier resultPrecision = EpqNone;
1217
1218     TIntermOperator* opNode = node.getAsOperator();
1219     if (opNode == nullptr)
1220         return;
1221
1222     if (TIntermUnary* unaryNode = node.getAsUnaryNode()) {
1223         operationPrecision = std::max(function[0].type->getQualifier().precision,
1224                                       unaryNode->getOperand()->getType().getQualifier().precision);
1225         if (function.getType().getBasicType() != EbtBool)
1226             resultPrecision = function.getType().getQualifier().precision == EpqNone ?
1227                                         operationPrecision :
1228                                         function.getType().getQualifier().precision;
1229     } else if (TIntermAggregate* agg = node.getAsAggregate()) {
1230         TIntermSequence& sequence = agg->getSequence();
1231         unsigned int numArgs = (unsigned int)sequence.size();
1232         switch (agg->getOp()) {
1233         case EOpBitfieldExtract:
1234             numArgs = 1;
1235             break;
1236         case EOpBitfieldInsert:
1237             numArgs = 2;
1238             break;
1239         case EOpInterpolateAtCentroid:
1240         case EOpInterpolateAtOffset:
1241         case EOpInterpolateAtSample:
1242             numArgs = 1;
1243             break;
1244         default:
1245             break;
1246         }
1247         // find the maximum precision from the arguments and parameters
1248         for (unsigned int arg = 0; arg < numArgs; ++arg) {
1249             operationPrecision = std::max(operationPrecision, sequence[arg]->getAsTyped()->getQualifier().precision);
1250             operationPrecision = std::max(operationPrecision, function[arg].type->getQualifier().precision);
1251         }
1252         // compute the result precision
1253 #ifdef AMD_EXTENSIONS
1254         if (agg->isSampling() ||
1255             agg->getOp() == EOpImageLoad || agg->getOp() == EOpImageStore ||
1256             agg->getOp() == EOpImageLoadLod || agg->getOp() == EOpImageStoreLod)
1257 #else
1258         if (agg->isSampling() || agg->getOp() == EOpImageLoad || agg->getOp() == EOpImageStore)
1259 #endif
1260             resultPrecision = sequence[0]->getAsTyped()->getQualifier().precision;
1261         else if (function.getType().getBasicType() != EbtBool)
1262             resultPrecision = function.getType().getQualifier().precision == EpqNone ?
1263                                         operationPrecision :
1264                                         function.getType().getQualifier().precision;
1265     }
1266
1267     // Propagate precision through this node and its children. That algorithm stops
1268     // when a precision is found, so start by clearing this subroot precision
1269     opNode->getQualifier().precision = EpqNone;
1270     if (operationPrecision != EpqNone) {
1271         opNode->propagatePrecision(operationPrecision);
1272         opNode->setOperationPrecision(operationPrecision);
1273     }
1274     // Now, set the result precision, which might not match
1275     opNode->getQualifier().precision = resultPrecision;
1276 }
1277
1278 TIntermNode* TParseContext::handleReturnValue(const TSourceLoc& loc, TIntermTyped* value)
1279 {
1280     storage16BitAssignmentCheck(loc, value->getType(), "return");
1281
1282     functionReturnsValue = true;
1283     if (currentFunctionType->getBasicType() == EbtVoid) {
1284         error(loc, "void function cannot return a value", "return", "");
1285         return intermediate.addBranch(EOpReturn, loc);
1286     } else if (*currentFunctionType != value->getType()) {
1287         TIntermTyped* converted = intermediate.addConversion(EOpReturn, *currentFunctionType, value);
1288         if (converted) {
1289             if (*currentFunctionType != converted->getType())
1290                 error(loc, "cannot convert return value to function return type", "return", "");
1291             if (version < 420)
1292                 warn(loc, "type conversion on return values was not explicitly allowed until version 420", "return", "");
1293             return intermediate.addBranch(EOpReturn, converted, loc);
1294         } else {
1295             error(loc, "type does not match, or is not convertible to, the function's return type", "return", "");
1296             return intermediate.addBranch(EOpReturn, value, loc);
1297         }
1298     } else
1299         return intermediate.addBranch(EOpReturn, value, loc);
1300 }
1301
1302 // See if the operation is being done in an illegal location.
1303 void TParseContext::checkLocation(const TSourceLoc& loc, TOperator op)
1304 {
1305     switch (op) {
1306     case EOpBarrier:
1307         if (language == EShLangTessControl) {
1308             if (controlFlowNestingLevel > 0)
1309                 error(loc, "tessellation control barrier() cannot be placed within flow control", "", "");
1310             if (! inMain)
1311                 error(loc, "tessellation control barrier() must be in main()", "", "");
1312             else if (postEntryPointReturn)
1313                 error(loc, "tessellation control barrier() cannot be placed after a return from main()", "", "");
1314         }
1315         break;
1316     default:
1317         break;
1318     }
1319 }
1320
1321 // Finish processing object.length(). This started earlier in handleDotDereference(), where
1322 // the ".length" part was recognized and semantically checked, and finished here where the
1323 // function syntax "()" is recognized.
1324 //
1325 // Return resulting tree node.
1326 TIntermTyped* TParseContext::handleLengthMethod(const TSourceLoc& loc, TFunction* function, TIntermNode* intermNode)
1327 {
1328     int length = 0;
1329
1330     if (function->getParamCount() > 0)
1331         error(loc, "method does not accept any arguments", function->getName().c_str(), "");
1332     else {
1333         const TType& type = intermNode->getAsTyped()->getType();
1334         if (type.isArray()) {
1335             if (type.isUnsizedArray()) {
1336                 if (intermNode->getAsSymbolNode() && isIoResizeArray(type)) {
1337                     // We could be between a layout declaration that gives a built-in io array implicit size and
1338                     // a user redeclaration of that array, meaning we have to substitute its implicit size here
1339                     // without actually redeclaring the array.  (It is an error to use a member before the
1340                     // redeclaration, but not an error to use the array name itself.)
1341                     const TString& name = intermNode->getAsSymbolNode()->getName();
1342                     if (name == "gl_in" || name == "gl_out"
1343 #ifdef NV_EXTENSIONS
1344                         || name == "gl_MeshVerticesNV"
1345                         || name == "gl_MeshPrimitivesNV"
1346 #endif
1347                         )
1348                     {
1349                         length = getIoArrayImplicitSize(type.getQualifier().isPerPrimitive());
1350                     }
1351                 }
1352                 if (length == 0) {
1353                     if (intermNode->getAsSymbolNode() && isIoResizeArray(type))
1354                         error(loc, "", function->getName().c_str(), "array must first be sized by a redeclaration or layout qualifier");
1355                     else if (isRuntimeLength(*intermNode->getAsTyped())) {
1356                         // Create a unary op and let the back end handle it
1357                         return intermediate.addBuiltInFunctionCall(loc, EOpArrayLength, true, intermNode, TType(EbtInt));
1358                     } else
1359                         error(loc, "", function->getName().c_str(), "array must be declared with a size before using this method");
1360                 }
1361             } else if (type.getOuterArrayNode()) {
1362                 // If the array's outer size is specified by an intermediate node, it means the array's length
1363                 // was specified by a specialization constant. In such a case, we should return the node of the
1364                 // specialization constants to represent the length.
1365                 return type.getOuterArrayNode();
1366             } else
1367                 length = type.getOuterArraySize();
1368         } else if (type.isMatrix())
1369             length = type.getMatrixCols();
1370         else if (type.isVector())
1371             length = type.getVectorSize();
1372         else {
1373             // we should not get here, because earlier semantic checking should have prevented this path
1374             error(loc, ".length()", "unexpected use of .length()", "");
1375         }
1376     }
1377
1378     if (length == 0)
1379         length = 1;
1380
1381     return intermediate.addConstantUnion(length, loc);
1382 }
1383
1384 //
1385 // Add any needed implicit conversions for function-call arguments to input parameters.
1386 //
1387 void TParseContext::addInputArgumentConversions(const TFunction& function, TIntermNode*& arguments) const
1388 {
1389     TIntermAggregate* aggregate = arguments->getAsAggregate();
1390
1391     // Process each argument's conversion
1392     for (int i = 0; i < function.getParamCount(); ++i) {
1393         // At this early point there is a slight ambiguity between whether an aggregate 'arguments'
1394         // is the single argument itself or its children are the arguments.  Only one argument
1395         // means take 'arguments' itself as the one argument.
1396         TIntermTyped* arg = function.getParamCount() == 1 ? arguments->getAsTyped() : (aggregate ? aggregate->getSequence()[i]->getAsTyped() : arguments->getAsTyped());
1397         if (*function[i].type != arg->getType()) {
1398             if (function[i].type->getQualifier().isParamInput()) {
1399                 // In-qualified arguments just need an extra node added above the argument to
1400                 // convert to the correct type.
1401                 arg = intermediate.addConversion(EOpFunctionCall, *function[i].type, arg);
1402                 if (arg) {
1403                     if (function.getParamCount() == 1)
1404                         arguments = arg;
1405                     else {
1406                         if (aggregate)
1407                             aggregate->getSequence()[i] = arg;
1408                         else
1409                             arguments = arg;
1410                     }
1411                 }
1412             }
1413         }
1414     }
1415 }
1416
1417 //
1418 // Add any needed implicit output conversions for function-call arguments.  This
1419 // can require a new tree topology, complicated further by whether the function
1420 // has a return value.
1421 //
1422 // Returns a node of a subtree that evaluates to the return value of the function.
1423 //
1424 TIntermTyped* TParseContext::addOutputArgumentConversions(const TFunction& function, TIntermAggregate& intermNode) const
1425 {
1426     TIntermSequence& arguments = intermNode.getSequence();
1427
1428     // Will there be any output conversions?
1429     bool outputConversions = false;
1430     for (int i = 0; i < function.getParamCount(); ++i) {
1431         if (*function[i].type != arguments[i]->getAsTyped()->getType() && function[i].type->getQualifier().isParamOutput()) {
1432             outputConversions = true;
1433             break;
1434         }
1435     }
1436
1437     if (! outputConversions)
1438         return &intermNode;
1439
1440     // Setup for the new tree, if needed:
1441     //
1442     // Output conversions need a different tree topology.
1443     // Out-qualified arguments need a temporary of the correct type, with the call
1444     // followed by an assignment of the temporary to the original argument:
1445     //     void: function(arg, ...)  ->        (          function(tempArg, ...), arg = tempArg, ...)
1446     //     ret = function(arg, ...)  ->  ret = (tempRet = function(tempArg, ...), arg = tempArg, ..., tempRet)
1447     // Where the "tempArg" type needs no conversion as an argument, but will convert on assignment.
1448     TIntermTyped* conversionTree = nullptr;
1449     TVariable* tempRet = nullptr;
1450     if (intermNode.getBasicType() != EbtVoid) {
1451         // do the "tempRet = function(...), " bit from above
1452         tempRet = makeInternalVariable("tempReturn", intermNode.getType());
1453         TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, intermNode.getLoc());
1454         conversionTree = intermediate.addAssign(EOpAssign, tempRetNode, &intermNode, intermNode.getLoc());
1455     } else
1456         conversionTree = &intermNode;
1457
1458     conversionTree = intermediate.makeAggregate(conversionTree);
1459
1460     // Process each argument's conversion
1461     for (int i = 0; i < function.getParamCount(); ++i) {
1462         if (*function[i].type != arguments[i]->getAsTyped()->getType()) {
1463             if (function[i].type->getQualifier().isParamOutput()) {
1464                 // Out-qualified arguments need to use the topology set up above.
1465                 // do the " ...(tempArg, ...), arg = tempArg" bit from above
1466                 TVariable* tempArg = makeInternalVariable("tempArg", *function[i].type);
1467                 tempArg->getWritableType().getQualifier().makeTemporary();
1468                 TIntermSymbol* tempArgNode = intermediate.addSymbol(*tempArg, intermNode.getLoc());
1469                 TIntermTyped* tempAssign = intermediate.addAssign(EOpAssign, arguments[i]->getAsTyped(), tempArgNode, arguments[i]->getLoc());
1470                 conversionTree = intermediate.growAggregate(conversionTree, tempAssign, arguments[i]->getLoc());
1471                 // replace the argument with another node for the same tempArg variable
1472                 arguments[i] = intermediate.addSymbol(*tempArg, intermNode.getLoc());
1473             }
1474         }
1475     }
1476
1477     // Finalize the tree topology (see bigger comment above).
1478     if (tempRet) {
1479         // do the "..., tempRet" bit from above
1480         TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, intermNode.getLoc());
1481         conversionTree = intermediate.growAggregate(conversionTree, tempRetNode, intermNode.getLoc());
1482     }
1483     conversionTree = intermediate.setAggregateOperator(conversionTree, EOpComma, intermNode.getType(), intermNode.getLoc());
1484
1485     return conversionTree;
1486 }
1487
1488 void TParseContext::memorySemanticsCheck(const TSourceLoc& loc, const TFunction& fnCandidate, const TIntermOperator& callNode)
1489 {
1490     const TIntermSequence* argp = &callNode.getAsAggregate()->getSequence();
1491
1492     const int gl_SemanticsRelaxed         = 0x0;
1493     const int gl_SemanticsAcquire         = 0x2;
1494     const int gl_SemanticsRelease         = 0x4;
1495     const int gl_SemanticsAcquireRelease  = 0x8;
1496     const int gl_SemanticsMakeAvailable   = 0x2000;
1497     const int gl_SemanticsMakeVisible     = 0x4000;
1498
1499     const int gl_StorageSemanticsNone     = 0x0;
1500     const int gl_StorageSemanticsBuffer   = 0x40;
1501     const int gl_StorageSemanticsShared   = 0x100;
1502     const int gl_StorageSemanticsImage    = 0x800;
1503     const int gl_StorageSemanticsOutput   = 0x1000;
1504
1505
1506     unsigned int semantics = 0, storageClassSemantics = 0;
1507     unsigned int semantics2 = 0, storageClassSemantics2 = 0;
1508
1509     // Grab the semantics and storage class semantics from the operands, based on opcode
1510     switch (callNode.getOp()) {
1511     case EOpAtomicAdd:
1512     case EOpAtomicMin:
1513     case EOpAtomicMax:
1514     case EOpAtomicAnd:
1515     case EOpAtomicOr:
1516     case EOpAtomicXor:
1517     case EOpAtomicExchange:
1518     case EOpAtomicStore:
1519         storageClassSemantics = (*argp)[3]->getAsConstantUnion()->getConstArray()[0].getIConst();
1520         semantics = (*argp)[4]->getAsConstantUnion()->getConstArray()[0].getIConst();
1521         break;
1522     case EOpAtomicLoad:
1523         storageClassSemantics = (*argp)[2]->getAsConstantUnion()->getConstArray()[0].getIConst();
1524         semantics = (*argp)[3]->getAsConstantUnion()->getConstArray()[0].getIConst();
1525         break;
1526     case EOpAtomicCompSwap:
1527         storageClassSemantics = (*argp)[4]->getAsConstantUnion()->getConstArray()[0].getIConst();
1528         semantics = (*argp)[5]->getAsConstantUnion()->getConstArray()[0].getIConst();
1529         storageClassSemantics2 = (*argp)[6]->getAsConstantUnion()->getConstArray()[0].getIConst();
1530         semantics2 = (*argp)[7]->getAsConstantUnion()->getConstArray()[0].getIConst();
1531         break;
1532
1533     case EOpImageAtomicAdd:
1534     case EOpImageAtomicMin:
1535     case EOpImageAtomicMax:
1536     case EOpImageAtomicAnd:
1537     case EOpImageAtomicOr:
1538     case EOpImageAtomicXor:
1539     case EOpImageAtomicExchange:
1540     case EOpImageAtomicStore:
1541         storageClassSemantics = (*argp)[4]->getAsConstantUnion()->getConstArray()[0].getIConst();
1542         semantics = (*argp)[5]->getAsConstantUnion()->getConstArray()[0].getIConst();
1543         break;
1544     case EOpImageAtomicLoad:
1545         storageClassSemantics = (*argp)[3]->getAsConstantUnion()->getConstArray()[0].getIConst();
1546         semantics = (*argp)[4]->getAsConstantUnion()->getConstArray()[0].getIConst();
1547         break;
1548     case EOpImageAtomicCompSwap:
1549         storageClassSemantics = (*argp)[5]->getAsConstantUnion()->getConstArray()[0].getIConst();
1550         semantics = (*argp)[6]->getAsConstantUnion()->getConstArray()[0].getIConst();
1551         storageClassSemantics2 = (*argp)[7]->getAsConstantUnion()->getConstArray()[0].getIConst();
1552         semantics2 = (*argp)[8]->getAsConstantUnion()->getConstArray()[0].getIConst();
1553         break;
1554
1555     case EOpBarrier:
1556         storageClassSemantics = (*argp)[2]->getAsConstantUnion()->getConstArray()[0].getIConst();
1557         semantics = (*argp)[3]->getAsConstantUnion()->getConstArray()[0].getIConst();
1558         break;
1559     case EOpMemoryBarrier:
1560         storageClassSemantics = (*argp)[1]->getAsConstantUnion()->getConstArray()[0].getIConst();
1561         semantics = (*argp)[2]->getAsConstantUnion()->getConstArray()[0].getIConst();
1562         break;
1563     default:
1564         break;
1565     }
1566
1567     if ((semantics & gl_SemanticsAcquire) && 
1568         (callNode.getOp() == EOpAtomicStore || callNode.getOp() == EOpImageAtomicStore)) {
1569         error(loc, "gl_SemanticsAcquire must not be used with (image) atomic store",
1570               fnCandidate.getName().c_str(), "");
1571     }
1572     if ((semantics & gl_SemanticsRelease) && 
1573         (callNode.getOp() == EOpAtomicLoad || callNode.getOp() == EOpImageAtomicLoad)) {
1574         error(loc, "gl_SemanticsRelease must not be used with (image) atomic load",
1575               fnCandidate.getName().c_str(), "");
1576     }
1577     if ((semantics & gl_SemanticsAcquireRelease) && 
1578         (callNode.getOp() == EOpAtomicStore || callNode.getOp() == EOpImageAtomicStore || 
1579          callNode.getOp() == EOpAtomicLoad  || callNode.getOp() == EOpImageAtomicLoad)) {
1580         error(loc, "gl_SemanticsAcquireRelease must not be used with (image) atomic load/store",
1581               fnCandidate.getName().c_str(), "");
1582     }
1583     if (((semantics | semantics2) & ~(gl_SemanticsAcquire |
1584                                       gl_SemanticsRelease |
1585                                       gl_SemanticsAcquireRelease |
1586                                       gl_SemanticsMakeAvailable |
1587                                       gl_SemanticsMakeVisible))) {
1588         error(loc, "Invalid semantics value", fnCandidate.getName().c_str(), "");
1589     }
1590     if (((storageClassSemantics | storageClassSemantics2) & ~(gl_StorageSemanticsBuffer |
1591                                                               gl_StorageSemanticsShared |
1592                                                               gl_StorageSemanticsImage |
1593                                                               gl_StorageSemanticsOutput))) {
1594         error(loc, "Invalid storage class semantics value", fnCandidate.getName().c_str(), "");
1595     }
1596
1597     if (callNode.getOp() == EOpMemoryBarrier) {
1598         if (!IsPow2(semantics & (gl_SemanticsAcquire | gl_SemanticsRelease | gl_SemanticsAcquireRelease))) {
1599             error(loc, "Semantics must include exactly one of gl_SemanticsRelease, gl_SemanticsAcquire, or "
1600                        "gl_SemanticsAcquireRelease", fnCandidate.getName().c_str(), "");
1601         }
1602     } else {
1603         if (semantics & (gl_SemanticsAcquire | gl_SemanticsRelease | gl_SemanticsAcquireRelease)) {
1604             if (!IsPow2(semantics & (gl_SemanticsAcquire | gl_SemanticsRelease | gl_SemanticsAcquireRelease))) {
1605                 error(loc, "Semantics must not include multiple of gl_SemanticsRelease, gl_SemanticsAcquire, or "
1606                            "gl_SemanticsAcquireRelease", fnCandidate.getName().c_str(), "");
1607             }
1608         }
1609         if (semantics2 & (gl_SemanticsAcquire | gl_SemanticsRelease | gl_SemanticsAcquireRelease)) {
1610             if (!IsPow2(semantics2 & (gl_SemanticsAcquire | gl_SemanticsRelease | gl_SemanticsAcquireRelease))) {
1611                 error(loc, "semUnequal must not include multiple of gl_SemanticsRelease, gl_SemanticsAcquire, or "
1612                            "gl_SemanticsAcquireRelease", fnCandidate.getName().c_str(), "");
1613             }
1614         }
1615     }
1616     if (callNode.getOp() == EOpMemoryBarrier) {
1617         if (storageClassSemantics == 0) {
1618             error(loc, "Storage class semantics must not be zero", fnCandidate.getName().c_str(), "");
1619         }
1620     }
1621     if (callNode.getOp() == EOpBarrier && semantics != 0 && storageClassSemantics == 0) {
1622         error(loc, "Storage class semantics must not be zero", fnCandidate.getName().c_str(), "");
1623     }
1624     if ((callNode.getOp() == EOpAtomicCompSwap || callNode.getOp() == EOpImageAtomicCompSwap) &&
1625         (semantics2 & (gl_SemanticsRelease | gl_SemanticsAcquireRelease))) {
1626         error(loc, "semUnequal must not be gl_SemanticsRelease or gl_SemanticsAcquireRelease",
1627               fnCandidate.getName().c_str(), "");
1628     }
1629     if ((semantics & gl_SemanticsMakeAvailable) &&
1630         !(semantics & (gl_SemanticsRelease | gl_SemanticsAcquireRelease))) {
1631         error(loc, "gl_SemanticsMakeAvailable requires gl_SemanticsRelease or gl_SemanticsAcquireRelease",
1632               fnCandidate.getName().c_str(), "");
1633     }
1634     if ((semantics & gl_SemanticsMakeVisible) &&
1635         !(semantics & (gl_SemanticsAcquire | gl_SemanticsAcquireRelease))) {
1636         error(loc, "gl_SemanticsMakeVisible requires gl_SemanticsAcquire or gl_SemanticsAcquireRelease",
1637               fnCandidate.getName().c_str(), "");
1638     }
1639
1640 }
1641
1642
1643 //
1644 // Do additional checking of built-in function calls that is not caught
1645 // by normal semantic checks on argument type, extension tagging, etc.
1646 //
1647 // Assumes there has been a semantically correct match to a built-in function prototype.
1648 //
1649 void TParseContext::builtInOpCheck(const TSourceLoc& loc, const TFunction& fnCandidate, TIntermOperator& callNode)
1650 {
1651     // Set up convenience accessors to the argument(s).  There is almost always
1652     // multiple arguments for the cases below, but when there might be one,
1653     // check the unaryArg first.
1654     const TIntermSequence* argp = nullptr;   // confusing to use [] syntax on a pointer, so this is to help get a reference
1655     const TIntermTyped* unaryArg = nullptr;
1656     const TIntermTyped* arg0 = nullptr;
1657     if (callNode.getAsAggregate()) {
1658         argp = &callNode.getAsAggregate()->getSequence();
1659         if (argp->size() > 0)
1660             arg0 = (*argp)[0]->getAsTyped();
1661     } else {
1662         assert(callNode.getAsUnaryNode());
1663         unaryArg = callNode.getAsUnaryNode()->getOperand();
1664         arg0 = unaryArg;
1665     }
1666
1667     TString featureString;
1668     const char* feature = nullptr;
1669     switch (callNode.getOp()) {
1670     case EOpTextureGather:
1671     case EOpTextureGatherOffset:
1672     case EOpTextureGatherOffsets:
1673     {
1674         // Figure out which variants are allowed by what extensions,
1675         // and what arguments must be constant for which situations.
1676
1677         featureString = fnCandidate.getName();
1678         featureString += "(...)";
1679         feature = featureString.c_str();
1680         profileRequires(loc, EEsProfile, 310, nullptr, feature);
1681         int compArg = -1;  // track which argument, if any, is the constant component argument
1682         switch (callNode.getOp()) {
1683         case EOpTextureGather:
1684             // More than two arguments needs gpu_shader5, and rectangular or shadow needs gpu_shader5,
1685             // otherwise, need GL_ARB_texture_gather.
1686             if (fnCandidate.getParamCount() > 2 || fnCandidate[0].type->getSampler().dim == EsdRect || fnCandidate[0].type->getSampler().shadow) {
1687                 profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_gpu_shader5, feature);
1688                 if (! fnCandidate[0].type->getSampler().shadow)
1689                     compArg = 2;
1690             } else
1691                 profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_texture_gather, feature);
1692             break;
1693         case EOpTextureGatherOffset:
1694             // GL_ARB_texture_gather is good enough for 2D non-shadow textures with no component argument
1695             if (fnCandidate[0].type->getSampler().dim == Esd2D && ! fnCandidate[0].type->getSampler().shadow && fnCandidate.getParamCount() == 3)
1696                 profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_texture_gather, feature);
1697             else
1698                 profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_gpu_shader5, feature);
1699             if (! (*argp)[fnCandidate[0].type->getSampler().shadow ? 3 : 2]->getAsConstantUnion())
1700                 profileRequires(loc, EEsProfile, 320, Num_AEP_gpu_shader5, AEP_gpu_shader5,
1701                                 "non-constant offset argument");
1702             if (! fnCandidate[0].type->getSampler().shadow)
1703                 compArg = 3;
1704             break;
1705         case EOpTextureGatherOffsets:
1706             profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_gpu_shader5, feature);
1707             if (! fnCandidate[0].type->getSampler().shadow)
1708                 compArg = 3;
1709             // check for constant offsets
1710             if (! (*argp)[fnCandidate[0].type->getSampler().shadow ? 3 : 2]->getAsConstantUnion())
1711                 error(loc, "must be a compile-time constant:", feature, "offsets argument");
1712             break;
1713         default:
1714             break;
1715         }
1716
1717         if (compArg > 0 && compArg < fnCandidate.getParamCount()) {
1718             if ((*argp)[compArg]->getAsConstantUnion()) {
1719                 int value = (*argp)[compArg]->getAsConstantUnion()->getConstArray()[0].getIConst();
1720                 if (value < 0 || value > 3)
1721                     error(loc, "must be 0, 1, 2, or 3:", feature, "component argument");
1722             } else
1723                 error(loc, "must be a compile-time constant:", feature, "component argument");
1724         }
1725
1726 #ifdef AMD_EXTENSIONS
1727         bool bias = false;
1728         if (callNode.getOp() == EOpTextureGather)
1729             bias = fnCandidate.getParamCount() > 3;
1730         else if (callNode.getOp() == EOpTextureGatherOffset ||
1731                  callNode.getOp() == EOpTextureGatherOffsets)
1732             bias = fnCandidate.getParamCount() > 4;
1733
1734         if (bias) {
1735             featureString = fnCandidate.getName();
1736             featureString += "with bias argument";
1737             feature = featureString.c_str();
1738             profileRequires(loc, ~EEsProfile, 450, nullptr, feature);
1739             requireExtensions(loc, 1, &E_GL_AMD_texture_gather_bias_lod, feature);
1740         }
1741 #endif
1742
1743         break;
1744     }
1745
1746 #ifdef AMD_EXTENSIONS
1747     case EOpSparseTextureGather:
1748     case EOpSparseTextureGatherOffset:
1749     case EOpSparseTextureGatherOffsets:
1750     {
1751         bool bias = false;
1752         if (callNode.getOp() == EOpSparseTextureGather)
1753             bias = fnCandidate.getParamCount() > 4;
1754         else if (callNode.getOp() == EOpSparseTextureGatherOffset ||
1755                  callNode.getOp() == EOpSparseTextureGatherOffsets)
1756             bias = fnCandidate.getParamCount() > 5;
1757
1758         if (bias) {
1759             featureString = fnCandidate.getName();
1760             featureString += "with bias argument";
1761             feature = featureString.c_str();
1762             profileRequires(loc, ~EEsProfile, 450, nullptr, feature);
1763             requireExtensions(loc, 1, &E_GL_AMD_texture_gather_bias_lod, feature);
1764         }
1765
1766         break;
1767     }
1768
1769     case EOpSparseTextureGatherLod:
1770     case EOpSparseTextureGatherLodOffset:
1771     case EOpSparseTextureGatherLodOffsets:
1772     {
1773         requireExtensions(loc, 1, &E_GL_ARB_sparse_texture2, fnCandidate.getName().c_str());
1774         break;
1775     }
1776
1777     case EOpSwizzleInvocations:
1778     {
1779         if (! (*argp)[1]->getAsConstantUnion())
1780             error(loc, "argument must be compile-time constant", "offset", "");
1781         else {
1782             unsigned offset[4] = {};
1783             offset[0] = (*argp)[1]->getAsConstantUnion()->getConstArray()[0].getUConst();
1784             offset[1] = (*argp)[1]->getAsConstantUnion()->getConstArray()[1].getUConst();
1785             offset[2] = (*argp)[1]->getAsConstantUnion()->getConstArray()[2].getUConst();
1786             offset[3] = (*argp)[1]->getAsConstantUnion()->getConstArray()[3].getUConst();
1787             if (offset[0] > 3 || offset[1] > 3 || offset[2] > 3 || offset[3] > 3)
1788                 error(loc, "components must be in the range [0, 3]", "offset", "");
1789         }
1790
1791         break;
1792     }
1793
1794     case EOpSwizzleInvocationsMasked:
1795     {
1796         if (! (*argp)[1]->getAsConstantUnion())
1797             error(loc, "argument must be compile-time constant", "mask", "");
1798         else {
1799             unsigned mask[3] = {};
1800             mask[0] = (*argp)[1]->getAsConstantUnion()->getConstArray()[0].getUConst();
1801             mask[1] = (*argp)[1]->getAsConstantUnion()->getConstArray()[1].getUConst();
1802             mask[2] = (*argp)[1]->getAsConstantUnion()->getConstArray()[2].getUConst();
1803             if (mask[0] > 31 || mask[1] > 31 || mask[2] > 31)
1804                 error(loc, "components must be in the range [0, 31]", "mask", "");
1805         }
1806
1807         break;
1808     }
1809 #endif
1810
1811     case EOpTextureOffset:
1812     case EOpTextureFetchOffset:
1813     case EOpTextureProjOffset:
1814     case EOpTextureLodOffset:
1815     case EOpTextureProjLodOffset:
1816     case EOpTextureGradOffset:
1817     case EOpTextureProjGradOffset:
1818     {
1819         // Handle texture-offset limits checking
1820         // Pick which argument has to hold constant offsets
1821         int arg = -1;
1822         switch (callNode.getOp()) {
1823         case EOpTextureOffset:          arg = 2;  break;
1824         case EOpTextureFetchOffset:     arg = (arg0->getType().getSampler().dim != EsdRect) ? 3 : 2; break;
1825         case EOpTextureProjOffset:      arg = 2;  break;
1826         case EOpTextureLodOffset:       arg = 3;  break;
1827         case EOpTextureProjLodOffset:   arg = 3;  break;
1828         case EOpTextureGradOffset:      arg = 4;  break;
1829         case EOpTextureProjGradOffset:  arg = 4;  break;
1830         default:
1831             assert(0);
1832             break;
1833         }
1834
1835         if (arg > 0) {
1836
1837 #ifdef AMD_EXTENSIONS
1838             bool f16ShadowCompare = (*argp)[1]->getAsTyped()->getBasicType() == EbtFloat16 && arg0->getType().getSampler().shadow;
1839             if (f16ShadowCompare)
1840                 ++arg;
1841 #endif
1842             if (! (*argp)[arg]->getAsConstantUnion())
1843                 error(loc, "argument must be compile-time constant", "texel offset", "");
1844             else {
1845                 const TType& type = (*argp)[arg]->getAsTyped()->getType();
1846                 for (int c = 0; c < type.getVectorSize(); ++c) {
1847                     int offset = (*argp)[arg]->getAsConstantUnion()->getConstArray()[c].getIConst();
1848                     if (offset > resources.maxProgramTexelOffset || offset < resources.minProgramTexelOffset)
1849                         error(loc, "value is out of range:", "texel offset", "[gl_MinProgramTexelOffset, gl_MaxProgramTexelOffset]");
1850                 }
1851             }
1852         }
1853
1854         break;
1855     }
1856
1857     case EOpTextureQuerySamples:
1858     case EOpImageQuerySamples:
1859         // GL_ARB_shader_texture_image_samples
1860         profileRequires(loc, ~EEsProfile, 450, E_GL_ARB_shader_texture_image_samples, "textureSamples and imageSamples");
1861         break;
1862
1863     case EOpImageAtomicAdd:
1864     case EOpImageAtomicMin:
1865     case EOpImageAtomicMax:
1866     case EOpImageAtomicAnd:
1867     case EOpImageAtomicOr:
1868     case EOpImageAtomicXor:
1869     case EOpImageAtomicExchange:
1870     case EOpImageAtomicCompSwap:
1871     case EOpImageAtomicLoad:
1872     case EOpImageAtomicStore:
1873     {
1874         // Make sure the image types have the correct layout() format and correct argument types
1875         const TType& imageType = arg0->getType();
1876         if (imageType.getSampler().type == EbtInt || imageType.getSampler().type == EbtUint) {
1877             if (imageType.getQualifier().layoutFormat != ElfR32i && imageType.getQualifier().layoutFormat != ElfR32ui)
1878                 error(loc, "only supported on image with format r32i or r32ui", fnCandidate.getName().c_str(), "");
1879         } else {
1880             if (fnCandidate.getName().compare(0, 19, "imageAtomicExchange") != 0)
1881                 error(loc, "only supported on integer images", fnCandidate.getName().c_str(), "");
1882             else if (imageType.getQualifier().layoutFormat != ElfR32f && profile == EEsProfile)
1883                 error(loc, "only supported on image with format r32f", fnCandidate.getName().c_str(), "");
1884         }
1885
1886         if (argp->size() > 4) {
1887             requireExtensions(loc, 1, &E_GL_KHR_memory_scope_semantics, fnCandidate.getName().c_str());
1888             memorySemanticsCheck(loc, fnCandidate, callNode);
1889         }
1890
1891         break;
1892     }
1893
1894     case EOpAtomicAdd:
1895     case EOpAtomicMin:
1896     case EOpAtomicMax:
1897     case EOpAtomicAnd:
1898     case EOpAtomicOr:
1899     case EOpAtomicXor:
1900     case EOpAtomicExchange:
1901     case EOpAtomicCompSwap:
1902     case EOpAtomicLoad:
1903     case EOpAtomicStore:
1904     {
1905         if (argp->size() > 3) {
1906             requireExtensions(loc, 1, &E_GL_KHR_memory_scope_semantics, fnCandidate.getName().c_str());
1907             memorySemanticsCheck(loc, fnCandidate, callNode);
1908         } else if (arg0->getType().getBasicType() == EbtInt64 || arg0->getType().getBasicType() == EbtUint64) {
1909 #ifdef NV_EXTENSIONS
1910             const char* const extensions[2] = { E_GL_NV_shader_atomic_int64,
1911                                                 E_GL_EXT_shader_atomic_int64 };
1912             requireExtensions(loc, 2, extensions, fnCandidate.getName().c_str());
1913 #else
1914             requireExtensions(loc, 1, &E_GL_EXT_shader_atomic_int64, fnCandidate.getName().c_str());
1915 #endif
1916         }
1917         break;
1918     }
1919
1920     case EOpInterpolateAtCentroid:
1921     case EOpInterpolateAtSample:
1922     case EOpInterpolateAtOffset:
1923 #ifdef AMD_EXTENSIONS
1924     case EOpInterpolateAtVertex:
1925 #endif
1926         // Make sure the first argument is an interpolant, or an array element of an interpolant
1927         if (arg0->getType().getQualifier().storage != EvqVaryingIn) {
1928             // It might still be an array element.
1929             //
1930             // We could check more, but the semantics of the first argument are already met; the
1931             // only way to turn an array into a float/vec* is array dereference and swizzle.
1932             //
1933             // ES and desktop 4.3 and earlier:  swizzles may not be used
1934             // desktop 4.4 and later: swizzles may be used
1935             bool swizzleOkay = (profile != EEsProfile) && (version >= 440);
1936             const TIntermTyped* base = TIntermediate::findLValueBase(arg0, swizzleOkay);
1937             if (base == nullptr || base->getType().getQualifier().storage != EvqVaryingIn)
1938                 error(loc, "first argument must be an interpolant, or interpolant-array element", fnCandidate.getName().c_str(), "");
1939         }
1940
1941 #ifdef AMD_EXTENSIONS
1942         if (callNode.getOp() == EOpInterpolateAtVertex) {
1943             if (!arg0->getType().getQualifier().isExplicitInterpolation())
1944                 error(loc, "argument must be qualified as __explicitInterpAMD in", "interpolant", "");
1945             else {
1946                 if (! (*argp)[1]->getAsConstantUnion())
1947                     error(loc, "argument must be compile-time constant", "vertex index", "");
1948                 else {
1949                     unsigned vertexIdx = (*argp)[1]->getAsConstantUnion()->getConstArray()[0].getUConst();
1950                     if (vertexIdx > 2)
1951                         error(loc, "must be in the range [0, 2]", "vertex index", "");
1952                 }
1953             }
1954         }
1955 #endif
1956
1957         break;
1958
1959     case EOpEmitStreamVertex:
1960     case EOpEndStreamPrimitive:
1961         intermediate.setMultiStream();
1962         break;
1963
1964     case EOpSubgroupClusteredAdd:
1965     case EOpSubgroupClusteredMul:
1966     case EOpSubgroupClusteredMin:
1967     case EOpSubgroupClusteredMax:
1968     case EOpSubgroupClusteredAnd:
1969     case EOpSubgroupClusteredOr:
1970     case EOpSubgroupClusteredXor:
1971         if ((*argp)[1]->getAsConstantUnion() == nullptr)
1972             error(loc, "argument must be compile-time constant", "cluster size", "");
1973         else {
1974             int size = (*argp)[1]->getAsConstantUnion()->getConstArray()[0].getIConst();
1975             if (size < 1)
1976                 error(loc, "argument must be at least 1", "cluster size", "");
1977             else if (!IsPow2(size))
1978                 error(loc, "argument must be a power of 2", "cluster size", "");
1979         }
1980         break;
1981
1982     case EOpBarrier:
1983     case EOpMemoryBarrier:
1984         if (argp->size() > 0) {
1985             requireExtensions(loc, 1, &E_GL_KHR_memory_scope_semantics, fnCandidate.getName().c_str());
1986             memorySemanticsCheck(loc, fnCandidate, callNode);
1987         }
1988         break;
1989
1990     default:
1991         break;
1992     }
1993
1994     // Texture operations on texture objects (aside from texelFetch on a
1995     // textureBuffer) require EXT_samplerless_texture_functions.
1996     switch (callNode.getOp()) {
1997     case EOpTextureQuerySize:
1998     case EOpTextureQueryLevels:
1999     case EOpTextureQuerySamples:
2000     case EOpTextureFetch:
2001     case EOpTextureFetchOffset:
2002     {
2003         const TSampler& sampler = fnCandidate[0].type->getSampler();
2004
2005         const bool isTexture = sampler.isTexture() && !sampler.isCombined();
2006         const bool isBuffer = sampler.dim == EsdBuffer;
2007         const bool isFetch = callNode.getOp() == EOpTextureFetch || callNode.getOp() == EOpTextureFetchOffset;
2008
2009         if (isTexture && (!isBuffer || !isFetch))
2010             requireExtensions(loc, 1, &E_GL_EXT_samplerless_texture_functions, fnCandidate.getName().c_str());
2011
2012         break;
2013     }
2014
2015     default:
2016         break;
2017     }
2018
2019     if (callNode.getOp() > EOpSubgroupGuardStart && callNode.getOp() < EOpSubgroupGuardStop) {
2020         // these require SPIR-V 1.3
2021         if (spvVersion.spv > 0 && spvVersion.spv < EShTargetSpv_1_3)
2022             error(loc, "requires SPIR-V 1.3", "subgroup op", "");
2023     }
2024 }
2025
2026 extern bool PureOperatorBuiltins;
2027
2028 // Deprecated!  Use PureOperatorBuiltins == true instead, in which case this
2029 // functionality is handled in builtInOpCheck() instead of here.
2030 //
2031 // Do additional checking of built-in function calls that were not mapped
2032 // to built-in operations (e.g., texturing functions).
2033 //
2034 // Assumes there has been a semantically correct match to a built-in function.
2035 //
2036 void TParseContext::nonOpBuiltInCheck(const TSourceLoc& loc, const TFunction& fnCandidate, TIntermAggregate& callNode)
2037 {
2038     // Further maintenance of this function is deprecated, because the "correct"
2039     // future-oriented design is to not have to do string compares on function names.
2040
2041     // If PureOperatorBuiltins == true, then all built-ins should be mapped
2042     // to a TOperator, and this function would then never get called.
2043
2044     assert(PureOperatorBuiltins == false);
2045
2046     // built-in texturing functions get their return value precision from the precision of the sampler
2047     if (fnCandidate.getType().getQualifier().precision == EpqNone &&
2048         fnCandidate.getParamCount() > 0 && fnCandidate[0].type->getBasicType() == EbtSampler)
2049         callNode.getQualifier().precision = callNode.getSequence()[0]->getAsTyped()->getQualifier().precision;
2050
2051     if (fnCandidate.getName().compare(0, 7, "texture") == 0) {
2052         if (fnCandidate.getName().compare(0, 13, "textureGather") == 0) {
2053             TString featureString = fnCandidate.getName() + "(...)";
2054             const char* feature = featureString.c_str();
2055             profileRequires(loc, EEsProfile, 310, nullptr, feature);
2056
2057             int compArg = -1;  // track which argument, if any, is the constant component argument
2058             if (fnCandidate.getName().compare("textureGatherOffset") == 0) {
2059                 // GL_ARB_texture_gather is good enough for 2D non-shadow textures with no component argument
2060                 if (fnCandidate[0].type->getSampler().dim == Esd2D && ! fnCandidate[0].type->getSampler().shadow && fnCandidate.getParamCount() == 3)
2061                     profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_texture_gather, feature);
2062                 else
2063                     profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_gpu_shader5, feature);
2064                 int offsetArg = fnCandidate[0].type->getSampler().shadow ? 3 : 2;
2065                 if (! callNode.getSequence()[offsetArg]->getAsConstantUnion())
2066                     profileRequires(loc, EEsProfile, 320, Num_AEP_gpu_shader5, AEP_gpu_shader5,
2067                                     "non-constant offset argument");
2068                 if (! fnCandidate[0].type->getSampler().shadow)
2069                     compArg = 3;
2070             } else if (fnCandidate.getName().compare("textureGatherOffsets") == 0) {
2071                 profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_gpu_shader5, feature);
2072                 if (! fnCandidate[0].type->getSampler().shadow)
2073                     compArg = 3;
2074                 // check for constant offsets
2075                 int offsetArg = fnCandidate[0].type->getSampler().shadow ? 3 : 2;
2076                 if (! callNode.getSequence()[offsetArg]->getAsConstantUnion())
2077                     error(loc, "must be a compile-time constant:", feature, "offsets argument");
2078             } else if (fnCandidate.getName().compare("textureGather") == 0) {
2079                 // More than two arguments needs gpu_shader5, and rectangular or shadow needs gpu_shader5,
2080                 // otherwise, need GL_ARB_texture_gather.
2081                 if (fnCandidate.getParamCount() > 2 || fnCandidate[0].type->getSampler().dim == EsdRect || fnCandidate[0].type->getSampler().shadow) {
2082                     profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_gpu_shader5, feature);
2083                     if (! fnCandidate[0].type->getSampler().shadow)
2084                         compArg = 2;
2085                 } else
2086                     profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_texture_gather, feature);
2087             }
2088
2089             if (compArg > 0 && compArg < fnCandidate.getParamCount()) {
2090                 if (callNode.getSequence()[compArg]->getAsConstantUnion()) {
2091                     int value = callNode.getSequence()[compArg]->getAsConstantUnion()->getConstArray()[0].getIConst();
2092                     if (value < 0 || value > 3)
2093                         error(loc, "must be 0, 1, 2, or 3:", feature, "component argument");
2094                 } else
2095                     error(loc, "must be a compile-time constant:", feature, "component argument");
2096             }
2097         } else {
2098             // this is only for functions not starting "textureGather"...
2099             if (fnCandidate.getName().find("Offset") != TString::npos) {
2100
2101                 // Handle texture-offset limits checking
2102                 int arg = -1;
2103                 if (fnCandidate.getName().compare("textureOffset") == 0)
2104                     arg = 2;
2105                 else if (fnCandidate.getName().compare("texelFetchOffset") == 0)
2106                     arg = 3;
2107                 else if (fnCandidate.getName().compare("textureProjOffset") == 0)
2108                     arg = 2;
2109                 else if (fnCandidate.getName().compare("textureLodOffset") == 0)
2110                     arg = 3;
2111                 else if (fnCandidate.getName().compare("textureProjLodOffset") == 0)
2112                     arg = 3;
2113                 else if (fnCandidate.getName().compare("textureGradOffset") == 0)
2114                     arg = 4;
2115                 else if (fnCandidate.getName().compare("textureProjGradOffset") == 0)
2116                     arg = 4;
2117
2118                 if (arg > 0) {
2119                     if (! callNode.getSequence()[arg]->getAsConstantUnion())
2120                         error(loc, "argument must be compile-time constant", "texel offset", "");
2121                     else {
2122                         const TType& type = callNode.getSequence()[arg]->getAsTyped()->getType();
2123                         for (int c = 0; c < type.getVectorSize(); ++c) {
2124                             int offset = callNode.getSequence()[arg]->getAsConstantUnion()->getConstArray()[c].getIConst();
2125                             if (offset > resources.maxProgramTexelOffset || offset < resources.minProgramTexelOffset)
2126                                 error(loc, "value is out of range:", "texel offset", "[gl_MinProgramTexelOffset, gl_MaxProgramTexelOffset]");
2127                         }
2128                     }
2129                 }
2130             }
2131         }
2132     }
2133
2134     // GL_ARB_shader_texture_image_samples
2135     if (fnCandidate.getName().compare(0, 14, "textureSamples") == 0 || fnCandidate.getName().compare(0, 12, "imageSamples") == 0)
2136         profileRequires(loc, ~EEsProfile, 450, E_GL_ARB_shader_texture_image_samples, "textureSamples and imageSamples");
2137
2138     if (fnCandidate.getName().compare(0, 11, "imageAtomic") == 0) {
2139         const TType& imageType = callNode.getSequence()[0]->getAsTyped()->getType();
2140         if (imageType.getSampler().type == EbtInt || imageType.getSampler().type == EbtUint) {
2141             if (imageType.getQualifier().layoutFormat != ElfR32i && imageType.getQualifier().layoutFormat != ElfR32ui)
2142                 error(loc, "only supported on image with format r32i or r32ui", fnCandidate.getName().c_str(), "");
2143         } else {
2144             if (fnCandidate.getName().compare(0, 19, "imageAtomicExchange") != 0)
2145                 error(loc, "only supported on integer images", fnCandidate.getName().c_str(), "");
2146             else if (imageType.getQualifier().layoutFormat != ElfR32f && profile == EEsProfile)
2147                 error(loc, "only supported on image with format r32f", fnCandidate.getName().c_str(), "");
2148         }
2149     }
2150 }
2151
2152 //
2153 // Do any extra checking for a user function call.
2154 //
2155 void TParseContext::userFunctionCallCheck(const TSourceLoc& loc, TIntermAggregate& callNode)
2156 {
2157     TIntermSequence& arguments = callNode.getSequence();
2158
2159     for (int i = 0; i < (int)arguments.size(); ++i)
2160         samplerConstructorLocationCheck(loc, "call argument", arguments[i]);
2161 }
2162
2163 //
2164 // Emit an error if this is a sampler constructor
2165 //
2166 void TParseContext::samplerConstructorLocationCheck(const TSourceLoc& loc, const char* token, TIntermNode* node)
2167 {
2168     if (node->getAsOperator() && node->getAsOperator()->getOp() == EOpConstructTextureSampler)
2169         error(loc, "sampler constructor must appear at point of use", token, "");
2170 }
2171
2172 //
2173 // Handle seeing a built-in constructor in a grammar production.
2174 //
2175 TFunction* TParseContext::handleConstructorCall(const TSourceLoc& loc, const TPublicType& publicType)
2176 {
2177     TType type(publicType);
2178     type.getQualifier().precision = EpqNone;
2179
2180     if (type.isArray()) {
2181         profileRequires(loc, ENoProfile, 120, E_GL_3DL_array_objects, "arrayed constructor");
2182         profileRequires(loc, EEsProfile, 300, nullptr, "arrayed constructor");
2183     }
2184
2185     TOperator op = intermediate.mapTypeToConstructorOp(type);
2186
2187     if (op == EOpNull) {
2188         error(loc, "cannot construct this type", type.getBasicString(), "");
2189         op = EOpConstructFloat;
2190         TType errorType(EbtFloat);
2191         type.shallowCopy(errorType);
2192     }
2193
2194     TString empty("");
2195
2196     return new TFunction(&empty, type, op);
2197 }
2198
2199 // Handle seeing a precision qualifier in the grammar.
2200 void TParseContext::handlePrecisionQualifier(const TSourceLoc& /*loc*/, TQualifier& qualifier, TPrecisionQualifier precision)
2201 {
2202     if (obeyPrecisionQualifiers())
2203         qualifier.precision = precision;
2204 }
2205
2206 // Check for messages to give on seeing a precision qualifier used in a
2207 // declaration in the grammar.
2208 void TParseContext::checkPrecisionQualifier(const TSourceLoc& loc, TPrecisionQualifier)
2209 {
2210     if (precisionManager.shouldWarnAboutDefaults()) {
2211         warn(loc, "all default precisions are highp; use precision statements to quiet warning, e.g.:\n"
2212                   "         \"precision mediump int; precision highp float;\"", "", "");
2213         precisionManager.defaultWarningGiven();
2214     }
2215 }
2216
2217 //
2218 // Same error message for all places assignments don't work.
2219 //
2220 void TParseContext::assignError(const TSourceLoc& loc, const char* op, TString left, TString right)
2221 {
2222     error(loc, "", op, "cannot convert from '%s' to '%s'",
2223           right.c_str(), left.c_str());
2224 }
2225
2226 //
2227 // Same error message for all places unary operations don't work.
2228 //
2229 void TParseContext::unaryOpError(const TSourceLoc& loc, const char* op, TString operand)
2230 {
2231    error(loc, " wrong operand type", op,
2232           "no operation '%s' exists that takes an operand of type %s (or there is no acceptable conversion)",
2233           op, operand.c_str());
2234 }
2235
2236 //
2237 // Same error message for all binary operations don't work.
2238 //
2239 void TParseContext::binaryOpError(const TSourceLoc& loc, const char* op, TString left, TString right)
2240 {
2241     error(loc, " wrong operand types:", op,
2242             "no operation '%s' exists that takes a left-hand operand of type '%s' and "
2243             "a right operand of type '%s' (or there is no acceptable conversion)",
2244             op, left.c_str(), right.c_str());
2245 }
2246
2247 //
2248 // A basic type of EbtVoid is a key that the name string was seen in the source, but
2249 // it was not found as a variable in the symbol table.  If so, give the error
2250 // message and insert a dummy variable in the symbol table to prevent future errors.
2251 //
2252 void TParseContext::variableCheck(TIntermTyped*& nodePtr)
2253 {
2254     TIntermSymbol* symbol = nodePtr->getAsSymbolNode();
2255     if (! symbol)
2256         return;
2257
2258     if (symbol->getType().getBasicType() == EbtVoid) {
2259         const char *extraInfoFormat = "";
2260         if (spvVersion.vulkan != 0 && symbol->getName() == "gl_VertexID") {
2261           extraInfoFormat = "(Did you mean gl_VertexIndex?)";
2262         } else if (spvVersion.vulkan != 0 && symbol->getName() == "gl_InstanceID") {
2263           extraInfoFormat = "(Did you mean gl_InstanceIndex?)";
2264         }
2265         error(symbol->getLoc(), "undeclared identifier", symbol->getName().c_str(), extraInfoFormat);
2266
2267         // Add to symbol table to prevent future error messages on the same name
2268         if (symbol->getName().size() > 0) {
2269             TVariable* fakeVariable = new TVariable(&symbol->getName(), TType(EbtFloat));
2270             symbolTable.insert(*fakeVariable);
2271
2272             // substitute a symbol node for this new variable
2273             nodePtr = intermediate.addSymbol(*fakeVariable, symbol->getLoc());
2274         }
2275     } else {
2276         switch (symbol->getQualifier().storage) {
2277         case EvqPointCoord:
2278             profileRequires(symbol->getLoc(), ENoProfile, 120, nullptr, "gl_PointCoord");
2279             break;
2280         default: break; // some compilers want this
2281         }
2282     }
2283 }
2284
2285 //
2286 // Both test and if necessary, spit out an error, to see if the node is really
2287 // an l-value that can be operated on this way.
2288 //
2289 // Returns true if there was an error.
2290 //
2291 bool TParseContext::lValueErrorCheck(const TSourceLoc& loc, const char* op, TIntermTyped* node)
2292 {
2293     TIntermBinary* binaryNode = node->getAsBinaryNode();
2294
2295     if (binaryNode) {
2296         bool errorReturn = false;
2297
2298         switch(binaryNode->getOp()) {
2299         case EOpIndexDirect:
2300         case EOpIndexIndirect:
2301             // ...  tessellation control shader ...
2302             // If a per-vertex output variable is used as an l-value, it is a
2303             // compile-time or link-time error if the expression indicating the
2304             // vertex index is not the identifier gl_InvocationID.
2305             if (language == EShLangTessControl) {
2306                 const TType& leftType = binaryNode->getLeft()->getType();
2307                 if (leftType.getQualifier().storage == EvqVaryingOut && ! leftType.getQualifier().patch && binaryNode->getLeft()->getAsSymbolNode()) {
2308                     // we have a per-vertex output
2309                     const TIntermSymbol* rightSymbol = binaryNode->getRight()->getAsSymbolNode();
2310                     if (! rightSymbol || rightSymbol->getQualifier().builtIn != EbvInvocationId)
2311                         error(loc, "tessellation-control per-vertex output l-value must be indexed with gl_InvocationID", "[]", "");
2312                 }
2313             }
2314
2315             break; // left node is checked by base class
2316         case EOpIndexDirectStruct:
2317             break; // left node is checked by base class
2318         case EOpVectorSwizzle:
2319             errorReturn = lValueErrorCheck(loc, op, binaryNode->getLeft());
2320             if (!errorReturn) {
2321                 int offset[4] = {0,0,0,0};
2322
2323                 TIntermTyped* rightNode = binaryNode->getRight();
2324                 TIntermAggregate *aggrNode = rightNode->getAsAggregate();
2325
2326                 for (TIntermSequence::iterator p = aggrNode->getSequence().begin();
2327                                                p != aggrNode->getSequence().end(); p++) {
2328                     int value = (*p)->getAsTyped()->getAsConstantUnion()->getConstArray()[0].getIConst();
2329                     offset[value]++;
2330                     if (offset[value] > 1) {
2331                         error(loc, " l-value of swizzle cannot have duplicate components", op, "", "");
2332
2333                         return true;
2334                     }
2335                 }
2336             }
2337
2338             return errorReturn;
2339         default:
2340             break;
2341         }
2342
2343         if (errorReturn) {
2344             error(loc, " l-value required", op, "", "");
2345             return true;
2346         }
2347     }
2348
2349     // Let the base class check errors
2350     if (TParseContextBase::lValueErrorCheck(loc, op, node))
2351         return true;
2352
2353     const char* symbol = nullptr;
2354     TIntermSymbol* symNode = node->getAsSymbolNode();
2355     if (symNode != nullptr)
2356         symbol = symNode->getName().c_str();
2357
2358     const char* message = nullptr;
2359     switch (node->getQualifier().storage) {
2360     case EvqVaryingIn:      message = "can't modify shader input";   break;
2361     case EvqInstanceId:     message = "can't modify gl_InstanceID";  break;
2362     case EvqVertexId:       message = "can't modify gl_VertexID";    break;
2363     case EvqFace:           message = "can't modify gl_FrontFace";   break;
2364     case EvqFragCoord:      message = "can't modify gl_FragCoord";   break;
2365     case EvqPointCoord:     message = "can't modify gl_PointCoord";  break;
2366     case EvqFragDepth:
2367         intermediate.setDepthReplacing();
2368         // "In addition, it is an error to statically write to gl_FragDepth in the fragment shader."
2369         if (profile == EEsProfile && intermediate.getEarlyFragmentTests())
2370             message = "can't modify gl_FragDepth if using early_fragment_tests";
2371         break;
2372
2373     default:
2374         break;
2375     }
2376
2377     if (message == nullptr && binaryNode == nullptr && symNode == nullptr) {
2378         error(loc, " l-value required", op, "", "");
2379
2380         return true;
2381     }
2382
2383     //
2384     // Everything else is okay, no error.
2385     //
2386     if (message == nullptr)
2387         return false;
2388
2389     //
2390     // If we get here, we have an error and a message.
2391     //
2392     if (symNode)
2393         error(loc, " l-value required", op, "\"%s\" (%s)", symbol, message);
2394     else
2395         error(loc, " l-value required", op, "(%s)", message);
2396
2397     return true;
2398 }
2399
2400 // Test for and give an error if the node can't be read from.
2401 void TParseContext::rValueErrorCheck(const TSourceLoc& loc, const char* op, TIntermTyped* node)
2402 {
2403     // Let the base class check errors
2404     TParseContextBase::rValueErrorCheck(loc, op, node);
2405
2406 #ifdef AMD_EXTENSIONS
2407     TIntermSymbol* symNode = node->getAsSymbolNode();
2408     if (!(symNode && symNode->getQualifier().writeonly)) // base class checks
2409         if (symNode && symNode->getQualifier().explicitInterp)
2410             error(loc, "can't read from explicitly-interpolated object: ", op, symNode->getName().c_str());
2411 #endif
2412 }
2413
2414 //
2415 // Both test, and if necessary spit out an error, to see if the node is really
2416 // a constant.
2417 //
2418 void TParseContext::constantValueCheck(TIntermTyped* node, const char* token)
2419 {
2420     if (! node->getQualifier().isConstant())
2421         error(node->getLoc(), "constant expression required", token, "");
2422 }
2423
2424 //
2425 // Both test, and if necessary spit out an error, to see if the node is really
2426 // an integer.
2427 //
2428 void TParseContext::integerCheck(const TIntermTyped* node, const char* token)
2429 {
2430     if ((node->getBasicType() == EbtInt || node->getBasicType() == EbtUint) && node->isScalar())
2431         return;
2432
2433     error(node->getLoc(), "scalar integer expression required", token, "");
2434 }
2435
2436 //
2437 // Both test, and if necessary spit out an error, to see if we are currently
2438 // globally scoped.
2439 //
2440 void TParseContext::globalCheck(const TSourceLoc& loc, const char* token)
2441 {
2442     if (! symbolTable.atGlobalLevel())
2443         error(loc, "not allowed in nested scope", token, "");
2444 }
2445
2446 //
2447 // Reserved errors for GLSL.
2448 //
2449 void TParseContext::reservedErrorCheck(const TSourceLoc& loc, const TString& identifier)
2450 {
2451     // "Identifiers starting with "gl_" are reserved for use by OpenGL, and may not be
2452     // declared in a shader; this results in a compile-time error."
2453     if (! symbolTable.atBuiltInLevel()) {
2454         if (builtInName(identifier))
2455             error(loc, "identifiers starting with \"gl_\" are reserved", identifier.c_str(), "");
2456
2457         // "__" are not supposed to be an error.  ES 310 (and desktop) added the clarification:
2458         // "In addition, all identifiers containing two consecutive underscores (__) are
2459         // reserved; using such a name does not itself result in an error, but may result
2460         // in undefined behavior."
2461         // however, before that, ES tests required an error.
2462         if (identifier.find("__") != TString::npos) {
2463             if (profile == EEsProfile && version <= 300)
2464                 error(loc, "identifiers containing consecutive underscores (\"__\") are reserved, and an error if version <= 300", identifier.c_str(), "");
2465             else
2466                 warn(loc, "identifiers containing consecutive underscores (\"__\") are reserved", identifier.c_str(), "");
2467         }
2468     }
2469 }
2470
2471 //
2472 // Reserved errors for the preprocessor.
2473 //
2474 void TParseContext::reservedPpErrorCheck(const TSourceLoc& loc, const char* identifier, const char* op)
2475 {
2476     // "__" are not supposed to be an error.  ES 310 (and desktop) added the clarification:
2477     // "All macro names containing two consecutive underscores ( __ ) are reserved;
2478     // defining such a name does not itself result in an error, but may result in
2479     // undefined behavior.  All macro names prefixed with "GL_" ("GL" followed by a
2480     // single underscore) are also reserved, and defining such a name results in a
2481     // compile-time error."
2482     // however, before that, ES tests required an error.
2483     if (strncmp(identifier, "GL_", 3) == 0)
2484         ppError(loc, "names beginning with \"GL_\" can't be (un)defined:", op,  identifier);
2485     else if (strncmp(identifier, "defined", 8) == 0)
2486         ppError(loc, "\"defined\" can't be (un)defined:", op,  identifier);
2487     else if (strstr(identifier, "__") != 0) {
2488         if (profile == EEsProfile && version >= 300 &&
2489             (strcmp(identifier, "__LINE__") == 0 ||
2490              strcmp(identifier, "__FILE__") == 0 ||
2491              strcmp(identifier, "__VERSION__") == 0))
2492             ppError(loc, "predefined names can't be (un)defined:", op,  identifier);
2493         else {
2494             if (profile == EEsProfile && version <= 300)
2495                 ppError(loc, "names containing consecutive underscores are reserved, and an error if version <= 300:", op, identifier);
2496             else
2497                 ppWarn(loc, "names containing consecutive underscores are reserved:", op, identifier);
2498         }
2499     }
2500 }
2501
2502 //
2503 // See if this version/profile allows use of the line-continuation character '\'.
2504 //
2505 // Returns true if a line continuation should be done.
2506 //
2507 bool TParseContext::lineContinuationCheck(const TSourceLoc& loc, bool endOfComment)
2508 {
2509     const char* message = "line continuation";
2510
2511     bool lineContinuationAllowed = (profile == EEsProfile && version >= 300) ||
2512                                    (profile != EEsProfile && (version >= 420 || extensionTurnedOn(E_GL_ARB_shading_language_420pack)));
2513
2514     if (endOfComment) {
2515         if (lineContinuationAllowed)
2516             warn(loc, "used at end of comment; the following line is still part of the comment", message, "");
2517         else
2518             warn(loc, "used at end of comment, but this version does not provide line continuation", message, "");
2519
2520         return lineContinuationAllowed;
2521     }
2522
2523     if (relaxedErrors()) {
2524         if (! lineContinuationAllowed)
2525             warn(loc, "not allowed in this version", message, "");
2526         return true;
2527     } else {
2528         profileRequires(loc, EEsProfile, 300, nullptr, message);
2529         profileRequires(loc, ~EEsProfile, 420, E_GL_ARB_shading_language_420pack, message);
2530     }
2531
2532     return lineContinuationAllowed;
2533 }
2534
2535 bool TParseContext::builtInName(const TString& identifier)
2536 {
2537     return identifier.compare(0, 3, "gl_") == 0;
2538 }
2539
2540 //
2541 // Make sure there is enough data and not too many arguments provided to the
2542 // constructor to build something of the type of the constructor.  Also returns
2543 // the type of the constructor.
2544 //
2545 // Part of establishing type is establishing specialization-constness.
2546 // We don't yet know "top down" whether type is a specialization constant,
2547 // but a const constructor can becomes a specialization constant if any of
2548 // its children are, subject to KHR_vulkan_glsl rules:
2549 //
2550 //     - int(), uint(), and bool() constructors for type conversions
2551 //       from any of the following types to any of the following types:
2552 //         * int
2553 //         * uint
2554 //         * bool
2555 //     - vector versions of the above conversion constructors
2556 //
2557 // Returns true if there was an error in construction.
2558 //
2559 bool TParseContext::constructorError(const TSourceLoc& loc, TIntermNode* node, TFunction& function, TOperator op, TType& type)
2560 {
2561     type.shallowCopy(function.getType());
2562
2563     bool constructingMatrix = false;
2564     switch(op) {
2565     case EOpConstructTextureSampler:
2566         return constructorTextureSamplerError(loc, function);
2567     case EOpConstructMat2x2:
2568     case EOpConstructMat2x3:
2569     case EOpConstructMat2x4:
2570     case EOpConstructMat3x2:
2571     case EOpConstructMat3x3:
2572     case EOpConstructMat3x4:
2573     case EOpConstructMat4x2:
2574     case EOpConstructMat4x3:
2575     case EOpConstructMat4x4:
2576     case EOpConstructDMat2x2:
2577     case EOpConstructDMat2x3:
2578     case EOpConstructDMat2x4:
2579     case EOpConstructDMat3x2:
2580     case EOpConstructDMat3x3:
2581     case EOpConstructDMat3x4:
2582     case EOpConstructDMat4x2:
2583     case EOpConstructDMat4x3:
2584     case EOpConstructDMat4x4:
2585     case EOpConstructF16Mat2x2:
2586     case EOpConstructF16Mat2x3:
2587     case EOpConstructF16Mat2x4:
2588     case EOpConstructF16Mat3x2:
2589     case EOpConstructF16Mat3x3:
2590     case EOpConstructF16Mat3x4:
2591     case EOpConstructF16Mat4x2:
2592     case EOpConstructF16Mat4x3:
2593     case EOpConstructF16Mat4x4:
2594         constructingMatrix = true;
2595         break;
2596     default:
2597         break;
2598     }
2599
2600     //
2601     // Walk the arguments for first-pass checks and collection of information.
2602     //
2603
2604     int size = 0;
2605     bool constType = true;
2606     bool specConstType = false;   // value is only valid if constType is true
2607     bool full = false;
2608     bool overFull = false;
2609     bool matrixInMatrix = false;
2610     bool arrayArg = false;
2611     bool floatArgument = false;
2612     for (int arg = 0; arg < function.getParamCount(); ++arg) {
2613         if (function[arg].type->isArray()) {
2614             if (function[arg].type->isUnsizedArray()) {
2615                 // Can't construct from an unsized array.
2616                 error(loc, "array argument must be sized", "constructor", "");
2617                 return true;
2618             }
2619             arrayArg = true;
2620         }
2621         if (constructingMatrix && function[arg].type->isMatrix())
2622             matrixInMatrix = true;
2623
2624         // 'full' will go to true when enough args have been seen.  If we loop
2625         // again, there is an extra argument.
2626         if (full) {
2627             // For vectors and matrices, it's okay to have too many components
2628             // available, but not okay to have unused arguments.
2629             overFull = true;
2630         }
2631
2632         size += function[arg].type->computeNumComponents();
2633         if (op != EOpConstructStruct && ! type.isArray() && size >= type.computeNumComponents())
2634             full = true;
2635
2636         if (! function[arg].type->getQualifier().isConstant())
2637             constType = false;
2638         if (function[arg].type->getQualifier().isSpecConstant())
2639             specConstType = true;
2640         if (function[arg].type->isFloatingDomain())
2641             floatArgument = true;
2642         if (type.isStruct()) {
2643             if (function[arg].type->containsBasicType(EbtFloat16)) {
2644                 requireFloat16Arithmetic(loc, "constructor", "can't construct structure containing 16-bit type");
2645             }
2646             if (function[arg].type->containsBasicType(EbtUint16) ||
2647                 function[arg].type->containsBasicType(EbtInt16)) {
2648                 requireInt16Arithmetic(loc, "constructor", "can't construct structure containing 16-bit type");
2649             }
2650             if (function[arg].type->containsBasicType(EbtUint8) ||
2651                 function[arg].type->containsBasicType(EbtInt8)) {
2652                 requireInt8Arithmetic(loc, "constructor", "can't construct structure containing 8-bit type");
2653             }
2654         }
2655     }
2656
2657     switch (op) {
2658     case EOpConstructFloat16:
2659     case EOpConstructF16Vec2:
2660     case EOpConstructF16Vec3:
2661     case EOpConstructF16Vec4:
2662         if (type.isArray())
2663             requireFloat16Arithmetic(loc, "constructor", "16-bit arrays not supported");
2664         if (type.isVector() && function.getParamCount() != 1)
2665             requireFloat16Arithmetic(loc, "constructor", "16-bit vectors only take vector types");
2666         break;
2667     case EOpConstructUint16:
2668     case EOpConstructU16Vec2:
2669     case EOpConstructU16Vec3:
2670     case EOpConstructU16Vec4:
2671     case EOpConstructInt16:
2672     case EOpConstructI16Vec2:
2673     case EOpConstructI16Vec3:
2674     case EOpConstructI16Vec4:
2675         if (type.isArray())
2676             requireInt16Arithmetic(loc, "constructor", "16-bit arrays not supported");
2677         if (type.isVector() && function.getParamCount() != 1)
2678             requireInt16Arithmetic(loc, "constructor", "16-bit vectors only take vector types");
2679         break;
2680     case EOpConstructUint8:
2681     case EOpConstructU8Vec2:
2682     case EOpConstructU8Vec3:
2683     case EOpConstructU8Vec4:
2684     case EOpConstructInt8:
2685     case EOpConstructI8Vec2:
2686     case EOpConstructI8Vec3:
2687     case EOpConstructI8Vec4:
2688         if (type.isArray())
2689             requireInt8Arithmetic(loc, "constructor", "8-bit arrays not supported");
2690         if (type.isVector() && function.getParamCount() != 1)
2691             requireInt8Arithmetic(loc, "constructor", "8-bit vectors only take vector types");
2692         break;
2693     default:
2694         break;
2695     }
2696
2697     // inherit constness from children
2698     if (constType) {
2699         bool makeSpecConst;
2700         // Finish pinning down spec-const semantics
2701         if (specConstType) {
2702             switch (op) {
2703             case EOpConstructInt8:
2704             case EOpConstructUint8:
2705             case EOpConstructInt16:
2706             case EOpConstructUint16:
2707             case EOpConstructInt:
2708             case EOpConstructUint:
2709             case EOpConstructInt64:
2710             case EOpConstructUint64:
2711             case EOpConstructBool:
2712             case EOpConstructBVec2:
2713             case EOpConstructBVec3:
2714             case EOpConstructBVec4:
2715             case EOpConstructI8Vec2:
2716             case EOpConstructI8Vec3:
2717             case EOpConstructI8Vec4:
2718             case EOpConstructU8Vec2:
2719             case EOpConstructU8Vec3:
2720             case EOpConstructU8Vec4:
2721             case EOpConstructI16Vec2:
2722             case EOpConstructI16Vec3:
2723             case EOpConstructI16Vec4:
2724             case EOpConstructU16Vec2:
2725             case EOpConstructU16Vec3:
2726             case EOpConstructU16Vec4:
2727             case EOpConstructIVec2:
2728             case EOpConstructIVec3:
2729             case EOpConstructIVec4:
2730             case EOpConstructUVec2:
2731             case EOpConstructUVec3:
2732             case EOpConstructUVec4:
2733             case EOpConstructI64Vec2:
2734             case EOpConstructI64Vec3:
2735             case EOpConstructI64Vec4:
2736             case EOpConstructU64Vec2:
2737             case EOpConstructU64Vec3:
2738             case EOpConstructU64Vec4:
2739                 // This was the list of valid ones, if they aren't converting from float
2740                 // and aren't making an array.
2741                 makeSpecConst = ! floatArgument && ! type.isArray();
2742                 break;
2743             default:
2744                 // anything else wasn't white-listed in the spec as a conversion
2745                 makeSpecConst = false;
2746                 break;
2747             }
2748         } else
2749             makeSpecConst = false;
2750
2751         if (makeSpecConst)
2752             type.getQualifier().makeSpecConstant();
2753         else if (specConstType)
2754             type.getQualifier().makeTemporary();
2755         else
2756             type.getQualifier().storage = EvqConst;
2757     }
2758
2759     if (type.isArray()) {
2760         if (function.getParamCount() == 0) {
2761             error(loc, "array constructor must have at least one argument", "constructor", "");
2762             return true;
2763         }
2764
2765         if (type.isUnsizedArray()) {
2766             // auto adapt the constructor type to the number of arguments
2767             type.changeOuterArraySize(function.getParamCount());
2768         } else if (type.getOuterArraySize() != function.getParamCount()) {
2769             error(loc, "array constructor needs one argument per array element", "constructor", "");
2770             return true;
2771         }
2772
2773         if (type.isArrayOfArrays()) {
2774             // Types have to match, but we're still making the type.
2775             // Finish making the type, and the comparison is done later
2776             // when checking for conversion.
2777             TArraySizes& arraySizes = *type.getArraySizes();
2778
2779             // At least the dimensionalities have to match.
2780             if (! function[0].type->isArray() ||
2781                     arraySizes.getNumDims() != function[0].type->getArraySizes()->getNumDims() + 1) {
2782                 error(loc, "array constructor argument not correct type to construct array element", "constructor", "");
2783                 return true;
2784             }
2785
2786             if (arraySizes.isInnerUnsized()) {
2787                 // "Arrays of arrays ..., and the size for any dimension is optional"
2788                 // That means we need to adopt (from the first argument) the other array sizes into the type.
2789                 for (int d = 1; d < arraySizes.getNumDims(); ++d) {
2790                     if (arraySizes.getDimSize(d) == UnsizedArraySize) {
2791                         arraySizes.setDimSize(d, function[0].type->getArraySizes()->getDimSize(d - 1));
2792                     }
2793                 }
2794             }
2795         }
2796     }
2797
2798     if (arrayArg && op != EOpConstructStruct && ! type.isArrayOfArrays()) {
2799         error(loc, "constructing non-array constituent from array argument", "constructor", "");
2800         return true;
2801     }
2802
2803     if (matrixInMatrix && ! type.isArray()) {
2804         profileRequires(loc, ENoProfile, 120, nullptr, "constructing matrix from matrix");
2805
2806         // "If a matrix argument is given to a matrix constructor,
2807         // it is a compile-time error to have any other arguments."
2808         if (function.getParamCount() != 1)
2809             error(loc, "matrix constructed from matrix can only have one argument", "constructor", "");
2810         return false;
2811     }
2812
2813     if (overFull) {
2814         error(loc, "too many arguments", "constructor", "");
2815         return true;
2816     }
2817
2818     if (op == EOpConstructStruct && ! type.isArray() && (int)type.getStruct()->size() != function.getParamCount()) {
2819         error(loc, "Number of constructor parameters does not match the number of structure fields", "constructor", "");
2820         return true;
2821     }
2822
2823     if ((op != EOpConstructStruct && size != 1 && size < type.computeNumComponents()) ||
2824         (op == EOpConstructStruct && size < type.computeNumComponents())) {
2825         error(loc, "not enough data provided for construction", "constructor", "");
2826         return true;
2827     }
2828
2829     TIntermTyped* typed = node->getAsTyped();
2830     if (typed == nullptr) {
2831         error(loc, "constructor argument does not have a type", "constructor", "");
2832         return true;
2833     }
2834     if (op != EOpConstructStruct && typed->getBasicType() == EbtSampler) {
2835         error(loc, "cannot convert a sampler", "constructor", "");
2836         return true;
2837     }
2838     if (op != EOpConstructStruct && typed->getBasicType() == EbtAtomicUint) {
2839         error(loc, "cannot convert an atomic_uint", "constructor", "");
2840         return true;
2841     }
2842     if (typed->getBasicType() == EbtVoid) {
2843         error(loc, "cannot convert a void", "constructor", "");
2844         return true;
2845     }
2846
2847     return false;
2848 }
2849
2850 // Verify all the correct semantics for constructing a combined texture/sampler.
2851 // Return true if the semantics are incorrect.
2852 bool TParseContext::constructorTextureSamplerError(const TSourceLoc& loc, const TFunction& function)
2853 {
2854     TString constructorName = function.getType().getBasicTypeString();  // TODO: performance: should not be making copy; interface needs to change
2855     const char* token = constructorName.c_str();
2856
2857     // exactly two arguments needed
2858     if (function.getParamCount() != 2) {
2859         error(loc, "sampler-constructor requires two arguments", token, "");
2860         return true;
2861     }
2862
2863     // For now, not allowing arrayed constructors, the rest of this function
2864     // is set up to allow them, if this test is removed:
2865     if (function.getType().isArray()) {
2866         error(loc, "sampler-constructor cannot make an array of samplers", token, "");
2867         return true;
2868     }
2869
2870     // first argument
2871     //  * the constructor's first argument must be a texture type
2872     //  * the dimensionality (1D, 2D, 3D, Cube, Rect, Buffer, MS, and Array)
2873     //    of the texture type must match that of the constructed sampler type
2874     //    (that is, the suffixes of the type of the first argument and the
2875     //    type of the constructor will be spelled the same way)
2876     if (function[0].type->getBasicType() != EbtSampler ||
2877         ! function[0].type->getSampler().isTexture() ||
2878         function[0].type->isArray()) {
2879         error(loc, "sampler-constructor first argument must be a scalar textureXXX type", token, "");
2880         return true;
2881     }
2882     // simulate the first argument's impact on the result type, so it can be compared with the encapsulated operator!=()
2883     TSampler texture = function.getType().getSampler();
2884     texture.combined = false;
2885     texture.shadow = false;
2886     if (texture != function[0].type->getSampler()) {
2887         error(loc, "sampler-constructor first argument must match type and dimensionality of constructor type", token, "");
2888         return true;
2889     }
2890
2891     // second argument
2892     //   * the constructor's second argument must be a scalar of type
2893     //     *sampler* or *samplerShadow*
2894     if (  function[1].type->getBasicType() != EbtSampler ||
2895         ! function[1].type->getSampler().isPureSampler() ||
2896           function[1].type->isArray()) {
2897         error(loc, "sampler-constructor second argument must be a scalar type 'sampler'", token, "");
2898         return true;
2899     }
2900
2901     return false;
2902 }
2903
2904 // Checks to see if a void variable has been declared and raise an error message for such a case
2905 //
2906 // returns true in case of an error
2907 //
2908 bool TParseContext::voidErrorCheck(const TSourceLoc& loc, const TString& identifier, const TBasicType basicType)
2909 {
2910     if (basicType == EbtVoid) {
2911         error(loc, "illegal use of type 'void'", identifier.c_str(), "");
2912         return true;
2913     }
2914
2915     return false;
2916 }
2917
2918 // Checks to see if the node (for the expression) contains a scalar boolean expression or not
2919 void TParseContext::boolCheck(const TSourceLoc& loc, const TIntermTyped* type)
2920 {
2921     if (type->getBasicType() != EbtBool || type->isArray() || type->isMatrix() || type->isVector())
2922         error(loc, "boolean expression expected", "", "");
2923 }
2924
2925 // This function checks to see if the node (for the expression) contains a scalar boolean expression or not
2926 void TParseContext::boolCheck(const TSourceLoc& loc, const TPublicType& pType)
2927 {
2928     if (pType.basicType != EbtBool || pType.arraySizes || pType.matrixCols > 1 || (pType.vectorSize > 1))
2929         error(loc, "boolean expression expected", "", "");
2930 }
2931
2932 void TParseContext::samplerCheck(const TSourceLoc& loc, const TType& type, const TString& identifier, TIntermTyped* /*initializer*/)
2933 {
2934     // Check that the appropriate extension is enabled if external sampler is used.
2935     // There are two extensions. The correct one must be used based on GLSL version.
2936     if (type.getBasicType() == EbtSampler && type.getSampler().external) {
2937         if (version < 300) {
2938             requireExtensions(loc, 1, &E_GL_OES_EGL_image_external, "samplerExternalOES");
2939         } else {
2940             requireExtensions(loc, 1, &E_GL_OES_EGL_image_external_essl3, "samplerExternalOES");
2941         }
2942     }
2943
2944     if (type.getQualifier().storage == EvqUniform)
2945         return;
2946
2947     if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtSampler))
2948         error(loc, "non-uniform struct contains a sampler or image:", type.getBasicTypeString().c_str(), identifier.c_str());
2949     else if (type.getBasicType() == EbtSampler && type.getQualifier().storage != EvqUniform) {
2950         // non-uniform sampler
2951         // not yet:  okay if it has an initializer
2952         // if (! initializer)
2953         error(loc, "sampler/image types can only be used in uniform variables or function parameters:", type.getBasicTypeString().c_str(), identifier.c_str());
2954     }
2955 }
2956
2957 void TParseContext::atomicUintCheck(const TSourceLoc& loc, const TType& type, const TString& identifier)
2958 {
2959     if (type.getQualifier().storage == EvqUniform)
2960         return;
2961
2962     if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtAtomicUint))
2963         error(loc, "non-uniform struct contains an atomic_uint:", type.getBasicTypeString().c_str(), identifier.c_str());
2964     else if (type.getBasicType() == EbtAtomicUint && type.getQualifier().storage != EvqUniform)
2965         error(loc, "atomic_uints can only be used in uniform variables or function parameters:", type.getBasicTypeString().c_str(), identifier.c_str());
2966 }
2967 #ifdef NV_EXTENSIONS
2968 void TParseContext::accStructNVCheck(const TSourceLoc& loc, const TType& type, const TString& identifier)
2969 {
2970     if (type.getQualifier().storage == EvqUniform)
2971         return;
2972
2973     if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtAccStructNV))
2974         error(loc, "non-uniform struct contains an accelerationStructureNVX:", type.getBasicTypeString().c_str(), identifier.c_str());
2975     else if (type.getBasicType() == EbtAccStructNV && type.getQualifier().storage != EvqUniform)
2976         error(loc, "accelerationStructureNVX can only be used in uniform variables or function parameters:",
2977             type.getBasicTypeString().c_str(), identifier.c_str());
2978
2979 }
2980 #endif
2981
2982 void TParseContext::transparentOpaqueCheck(const TSourceLoc& loc, const TType& type, const TString& identifier)
2983 {
2984     if (parsingBuiltins)
2985         return;
2986
2987     if (type.getQualifier().storage != EvqUniform)
2988         return;
2989
2990     if (type.containsNonOpaque()) {
2991         // Vulkan doesn't allow transparent uniforms outside of blocks
2992         if (spvVersion.vulkan > 0)
2993             vulkanRemoved(loc, "non-opaque uniforms outside a block");
2994         // OpenGL wants locations on these (unless they are getting automapped)
2995         if (spvVersion.openGl > 0 && !type.getQualifier().hasLocation() && !intermediate.getAutoMapLocations())
2996             error(loc, "non-opaque uniform variables need a layout(location=L)", identifier.c_str(), "");
2997     }
2998 }
2999
3000 //
3001 // Qualifier checks knowing the qualifier and that it is a member of a struct/block.
3002 //
3003 void TParseContext::memberQualifierCheck(glslang::TPublicType& publicType)
3004 {
3005     globalQualifierFixCheck(publicType.loc, publicType.qualifier);
3006     checkNoShaderLayouts(publicType.loc, publicType.shaderQualifiers);
3007     if (publicType.qualifier.isNonUniform()) {
3008         error(publicType.loc, "not allowed on block or structure members", "nonuniformEXT", "");
3009         publicType.qualifier.nonUniform = false;
3010     }
3011 }
3012
3013 //
3014 // Check/fix just a full qualifier (no variables or types yet, but qualifier is complete) at global level.
3015 //
3016 void TParseContext::globalQualifierFixCheck(const TSourceLoc& loc, TQualifier& qualifier)
3017 {
3018     bool nonuniformOkay = false;
3019
3020     // move from parameter/unknown qualifiers to pipeline in/out qualifiers
3021     switch (qualifier.storage) {
3022     case EvqIn:
3023         profileRequires(loc, ENoProfile, 130, nullptr, "in for stage inputs");
3024         profileRequires(loc, EEsProfile, 300, nullptr, "in for stage inputs");
3025         qualifier.storage = EvqVaryingIn;
3026         nonuniformOkay = true;
3027         break;
3028     case EvqOut:
3029         profileRequires(loc, ENoProfile, 130, nullptr, "out for stage outputs");
3030         profileRequires(loc, EEsProfile, 300, nullptr, "out for stage outputs");
3031         qualifier.storage = EvqVaryingOut;
3032         break;
3033     case EvqInOut:
3034         qualifier.storage = EvqVaryingIn;
3035         error(loc, "cannot use 'inout' at global scope", "", "");
3036         break;
3037     case EvqGlobal:
3038     case EvqTemporary:
3039         nonuniformOkay = true;
3040         break;
3041     default:
3042         break;
3043     }
3044
3045     if (!nonuniformOkay && qualifier.nonUniform)
3046         error(loc, "for non-parameter, can only apply to 'in' or no storage qualifier", "nonuniformEXT", "");
3047
3048     invariantCheck(loc, qualifier);
3049 }
3050
3051 //
3052 // Check a full qualifier and type (no variable yet) at global level.
3053 //
3054 void TParseContext::globalQualifierTypeCheck(const TSourceLoc& loc, const TQualifier& qualifier, const TPublicType& publicType)
3055 {
3056     if (! symbolTable.atGlobalLevel())
3057         return;
3058
3059     if (qualifier.isMemoryQualifierImageAndSSBOOnly() && ! publicType.isImage() && publicType.qualifier.storage != EvqBuffer) {
3060         error(loc, "memory qualifiers cannot be used on this type", "", "");
3061     } else if (qualifier.isMemory() && (publicType.basicType != EbtSampler) && !publicType.qualifier.isUniformOrBuffer()) {
3062         error(loc, "memory qualifiers cannot be used on this type", "", "");
3063     }
3064
3065     if (qualifier.storage == EvqBuffer && publicType.basicType != EbtBlock)
3066         error(loc, "buffers can be declared only as blocks", "buffer", "");
3067
3068     if (qualifier.storage != EvqVaryingIn && qualifier.storage != EvqVaryingOut)
3069         return;
3070
3071     if (publicType.shaderQualifiers.blendEquation)
3072         error(loc, "can only be applied to a standalone 'out'", "blend equation", "");
3073
3074     // now, knowing it is a shader in/out, do all the in/out semantic checks
3075
3076     if (publicType.basicType == EbtBool && !parsingBuiltins) {
3077         error(loc, "cannot be bool", GetStorageQualifierString(qualifier.storage), "");
3078         return;
3079     }
3080
3081     if (isTypeInt(publicType.basicType) || publicType.basicType == EbtDouble)
3082         profileRequires(loc, EEsProfile, 300, nullptr, "shader input/output");
3083
3084     if (!qualifier.flat
3085 #ifdef AMD_EXTENSIONS
3086         && !qualifier.explicitInterp
3087 #endif
3088 #ifdef NV_EXTENSIONS
3089         && !qualifier.pervertexNV
3090 #endif
3091         ) {
3092         if (isTypeInt(publicType.basicType) ||
3093             publicType.basicType == EbtDouble ||
3094             (publicType.userDef && (publicType.userDef->containsBasicType(EbtInt8)   ||
3095                                     publicType.userDef->containsBasicType(EbtUint8)  ||
3096                                     publicType.userDef->containsBasicType(EbtInt16)  ||
3097                                     publicType.userDef->containsBasicType(EbtUint16) ||
3098                                     publicType.userDef->containsBasicType(EbtInt)    ||
3099                                     publicType.userDef->containsBasicType(EbtUint)   ||
3100                                     publicType.userDef->containsBasicType(EbtInt64)  ||
3101                                     publicType.userDef->containsBasicType(EbtUint64) ||
3102                                     publicType.userDef->containsBasicType(EbtDouble)))) {
3103             if (qualifier.storage == EvqVaryingIn && language == EShLangFragment)
3104                 error(loc, "must be qualified as flat", TType::getBasicString(publicType.basicType), GetStorageQualifierString(qualifier.storage));
3105             else if (qualifier.storage == EvqVaryingOut && language == EShLangVertex && version == 300)
3106                 error(loc, "must be qualified as flat", TType::getBasicString(publicType.basicType), GetStorageQualifierString(qualifier.storage));
3107         }
3108     }
3109
3110     if (qualifier.patch && qualifier.isInterpolation())
3111         error(loc, "cannot use interpolation qualifiers with patch", "patch", "");
3112
3113 #ifdef NV_EXTENSIONS
3114     if (qualifier.perTaskNV && publicType.basicType != EbtBlock)
3115         error(loc, "taskNV variables can be declared only as blocks", "taskNV", "");
3116 #endif
3117
3118     if (qualifier.storage == EvqVaryingIn) {
3119         switch (language) {
3120         case EShLangVertex:
3121             if (publicType.basicType == EbtStruct) {
3122                 error(loc, "cannot be a structure or array", GetStorageQualifierString(qualifier.storage), "");
3123                 return;
3124             }
3125             if (publicType.arraySizes) {
3126                 requireProfile(loc, ~EEsProfile, "vertex input arrays");
3127                 profileRequires(loc, ENoProfile, 150, nullptr, "vertex input arrays");
3128             }
3129             if (publicType.basicType == EbtDouble)
3130                 profileRequires(loc, ~EEsProfile, 410, nullptr, "vertex-shader `double` type input");
3131             if (qualifier.isAuxiliary() || qualifier.isInterpolation() || qualifier.isMemory() || qualifier.invariant)
3132                 error(loc, "vertex input cannot be further qualified", "", "");
3133             break;
3134
3135         case EShLangTessControl:
3136             if (qualifier.patch)
3137                 error(loc, "can only use on output in tessellation-control shader", "patch", "");
3138             break;
3139
3140         case EShLangTessEvaluation:
3141             break;
3142
3143         case EShLangGeometry:
3144             break;
3145
3146         case EShLangFragment:
3147             if (publicType.userDef) {
3148                 profileRequires(loc, EEsProfile, 300, nullptr, "fragment-shader struct input");
3149                 profileRequires(loc, ~EEsProfile, 150, nullptr, "fragment-shader struct input");
3150                 if (publicType.userDef->containsStructure())
3151                     requireProfile(loc, ~EEsProfile, "fragment-shader struct input containing structure");
3152                 if (publicType.userDef->containsArray())
3153                     requireProfile(loc, ~EEsProfile, "fragment-shader struct input containing an array");
3154             }
3155             break;
3156
3157         case EShLangCompute:
3158             if (! symbolTable.atBuiltInLevel())
3159                 error(loc, "global storage input qualifier cannot be used in a compute shader", "in", "");
3160             break;
3161
3162         default:
3163             break;
3164         }
3165     } else {
3166         // qualifier.storage == EvqVaryingOut
3167         switch (language) {
3168         case EShLangVertex:
3169             if (publicType.userDef) {
3170                 profileRequires(loc, EEsProfile, 300, nullptr, "vertex-shader struct output");
3171                 profileRequires(loc, ~EEsProfile, 150, nullptr, "vertex-shader struct output");
3172                 if (publicType.userDef->containsStructure())
3173                     requireProfile(loc, ~EEsProfile, "vertex-shader struct output containing structure");
3174                 if (publicType.userDef->containsArray())
3175                     requireProfile(loc, ~EEsProfile, "vertex-shader struct output containing an array");
3176             }
3177
3178             break;
3179
3180         case EShLangTessControl:
3181             break;
3182
3183         case EShLangTessEvaluation:
3184             if (qualifier.patch)
3185                 error(loc, "can only use on input in tessellation-evaluation shader", "patch", "");
3186             break;
3187
3188         case EShLangGeometry:
3189             break;
3190
3191         case EShLangFragment:
3192             profileRequires(loc, EEsProfile, 300, nullptr, "fragment shader output");
3193             if (publicType.basicType == EbtStruct) {
3194                 error(loc, "cannot be a structure", GetStorageQualifierString(qualifier.storage), "");
3195                 return;
3196             }
3197             if (publicType.matrixRows > 0) {
3198                 error(loc, "cannot be a matrix", GetStorageQualifierString(qualifier.storage), "");
3199                 return;
3200             }
3201             if (qualifier.isAuxiliary())
3202                 error(loc, "can't use auxiliary qualifier on a fragment output", "centroid/sample/patch", "");
3203             if (qualifier.isInterpolation())
3204                 error(loc, "can't use interpolation qualifier on a fragment output", "flat/smooth/noperspective", "");
3205             if (publicType.basicType == EbtDouble || publicType.basicType == EbtInt64 || publicType.basicType == EbtUint64)
3206                 error(loc, "cannot contain a double, int64, or uint64", GetStorageQualifierString(qualifier.storage), "");
3207         break;
3208
3209         case EShLangCompute:
3210             error(loc, "global storage output qualifier cannot be used in a compute shader", "out", "");
3211             break;
3212
3213         default:
3214             break;
3215         }
3216     }
3217 }
3218
3219 //
3220 // Merge characteristics of the 'src' qualifier into the 'dst'.
3221 // If there is duplication, issue error messages, unless 'force'
3222 // is specified, which means to just override default settings.
3223 //
3224 // Also, when force is false, it will be assumed that 'src' follows
3225 // 'dst', for the purpose of error checking order for versions
3226 // that require specific orderings of qualifiers.
3227 //
3228 void TParseContext::mergeQualifiers(const TSourceLoc& loc, TQualifier& dst, const TQualifier& src, bool force)
3229 {
3230     // Multiple auxiliary qualifiers (mostly done later by 'individual qualifiers')
3231     if (src.isAuxiliary() && dst.isAuxiliary())
3232         error(loc, "can only have one auxiliary qualifier (centroid, patch, and sample)", "", "");
3233
3234     // Multiple interpolation qualifiers (mostly done later by 'individual qualifiers')
3235     if (src.isInterpolation() && dst.isInterpolation())
3236 #ifdef AMD_EXTENSIONS
3237         error(loc, "can only have one interpolation qualifier (flat, smooth, noperspective, __explicitInterpAMD)", "", "");
3238 #else
3239         error(loc, "can only have one interpolation qualifier (flat, smooth, noperspective)", "", "");
3240 #endif
3241
3242     // Ordering
3243     if (! force && ((profile != EEsProfile && version < 420) ||
3244                     (profile == EEsProfile && version < 310))
3245                 && ! extensionTurnedOn(E_GL_ARB_shading_language_420pack)) {
3246         // non-function parameters
3247         if (src.noContraction && (dst.invariant || dst.isInterpolation() || dst.isAuxiliary() || dst.storage != EvqTemporary || dst.precision != EpqNone))
3248             error(loc, "precise qualifier must appear first", "", "");
3249         if (src.invariant && (dst.isInterpolation() || dst.isAuxiliary() || dst.storage != EvqTemporary || dst.precision != EpqNone))
3250             error(loc, "invariant qualifier must appear before interpolation, storage, and precision qualifiers ", "", "");
3251         else if (src.isInterpolation() && (dst.isAuxiliary() || dst.storage != EvqTemporary || dst.precision != EpqNone))
3252             error(loc, "interpolation qualifiers must appear before storage and precision qualifiers", "", "");
3253         else if (src.isAuxiliary() && (dst.storage != EvqTemporary || dst.precision != EpqNone))
3254             error(loc, "Auxiliary qualifiers (centroid, patch, and sample) must appear before storage and precision qualifiers", "", "");
3255         else if (src.storage != EvqTemporary && (dst.precision != EpqNone))
3256             error(loc, "precision qualifier must appear as last qualifier", "", "");
3257
3258         // function parameters
3259         if (src.noContraction && (dst.storage == EvqConst || dst.storage == EvqIn || dst.storage == EvqOut))
3260             error(loc, "precise qualifier must appear first", "", "");
3261         if (src.storage == EvqConst && (dst.storage == EvqIn || dst.storage == EvqOut))
3262             error(loc, "in/out must appear before const", "", "");
3263     }
3264
3265     // Storage qualification
3266     if (dst.storage == EvqTemporary || dst.storage == EvqGlobal)
3267         dst.storage = src.storage;
3268     else if ((dst.storage == EvqIn  && src.storage == EvqOut) ||
3269              (dst.storage == EvqOut && src.storage == EvqIn))
3270         dst.storage = EvqInOut;
3271     else if ((dst.storage == EvqIn    && src.storage == EvqConst) ||
3272              (dst.storage == EvqConst && src.storage == EvqIn))
3273         dst.storage = EvqConstReadOnly;
3274     else if (src.storage != EvqTemporary &&
3275              src.storage != EvqGlobal)
3276         error(loc, "too many storage qualifiers", GetStorageQualifierString(src.storage), "");
3277
3278     // Precision qualifiers
3279     if (! force && src.precision != EpqNone && dst.precision != EpqNone)
3280         error(loc, "only one precision qualifier allowed", GetPrecisionQualifierString(src.precision), "");
3281     if (dst.precision == EpqNone || (force && src.precision != EpqNone))
3282         dst.precision = src.precision;
3283
3284     if (!force && ((src.coherent && (dst.devicecoherent || dst.queuefamilycoherent || dst.workgroupcoherent || dst.subgroupcoherent)) ||
3285                    (src.devicecoherent && (dst.coherent || dst.queuefamilycoherent || dst.workgroupcoherent || dst.subgroupcoherent)) ||
3286                    (src.queuefamilycoherent && (dst.coherent || dst.devicecoherent || dst.workgroupcoherent || dst.subgroupcoherent)) ||
3287                    (src.workgroupcoherent && (dst.coherent || dst.devicecoherent || dst.queuefamilycoherent || dst.subgroupcoherent)) ||
3288                    (src.subgroupcoherent  && (dst.coherent || dst.devicecoherent || dst.queuefamilycoherent || dst.workgroupcoherent)))) {
3289         error(loc, "only one coherent/devicecoherent/queuefamilycoherent/workgroupcoherent/subgroupcoherent qualifier allowed", GetPrecisionQualifierString(src.precision), "");
3290     }
3291     // Layout qualifiers
3292     mergeObjectLayoutQualifiers(dst, src, false);
3293
3294     // individual qualifiers
3295     bool repeated = false;
3296     #define MERGE_SINGLETON(field) repeated |= dst.field && src.field; dst.field |= src.field;
3297     MERGE_SINGLETON(invariant);
3298     MERGE_SINGLETON(noContraction);
3299     MERGE_SINGLETON(centroid);
3300     MERGE_SINGLETON(smooth);
3301     MERGE_SINGLETON(flat);
3302     MERGE_SINGLETON(nopersp);
3303 #ifdef AMD_EXTENSIONS
3304     MERGE_SINGLETON(explicitInterp);
3305 #endif
3306 #ifdef NV_EXTENSIONS
3307     MERGE_SINGLETON(perPrimitiveNV);
3308     MERGE_SINGLETON(perViewNV);
3309     MERGE_SINGLETON(perTaskNV);
3310 #endif
3311     MERGE_SINGLETON(patch);
3312     MERGE_SINGLETON(sample);
3313     MERGE_SINGLETON(coherent);
3314     MERGE_SINGLETON(devicecoherent);
3315     MERGE_SINGLETON(queuefamilycoherent);
3316     MERGE_SINGLETON(workgroupcoherent);
3317     MERGE_SINGLETON(subgroupcoherent);
3318     MERGE_SINGLETON(nonprivate);
3319     MERGE_SINGLETON(volatil);
3320     MERGE_SINGLETON(restrict);
3321     MERGE_SINGLETON(readonly);
3322     MERGE_SINGLETON(writeonly);
3323     MERGE_SINGLETON(specConstant);
3324     MERGE_SINGLETON(nonUniform);
3325
3326     if (repeated)
3327         error(loc, "replicated qualifiers", "", "");
3328 }
3329
3330 void TParseContext::setDefaultPrecision(const TSourceLoc& loc, TPublicType& publicType, TPrecisionQualifier qualifier)
3331 {
3332     TBasicType basicType = publicType.basicType;
3333
3334     if (basicType == EbtSampler) {
3335         defaultSamplerPrecision[computeSamplerTypeIndex(publicType.sampler)] = qualifier;
3336
3337         return;  // all is well
3338     }
3339
3340     if (basicType == EbtInt || basicType == EbtFloat) {
3341         if (publicType.isScalar()) {
3342             defaultPrecision[basicType] = qualifier;
3343             if (basicType == EbtInt) {
3344                 defaultPrecision[EbtUint] = qualifier;
3345                 precisionManager.explicitIntDefaultSeen();
3346             } else
3347                 precisionManager.explicitFloatDefaultSeen();
3348
3349             return;  // all is well
3350         }
3351     }
3352
3353     if (basicType == EbtAtomicUint) {
3354         if (qualifier != EpqHigh)
3355             error(loc, "can only apply highp to atomic_uint", "precision", "");
3356
3357         return;
3358     }
3359
3360     error(loc, "cannot apply precision statement to this type; use 'float', 'int' or a sampler type", TType::getBasicString(basicType), "");
3361 }
3362
3363 // used to flatten the sampler type space into a single dimension
3364 // correlates with the declaration of defaultSamplerPrecision[]
3365 int TParseContext::computeSamplerTypeIndex(TSampler& sampler)
3366 {
3367     int arrayIndex    = sampler.arrayed ? 1 : 0;
3368     int shadowIndex   = sampler.shadow  ? 1 : 0;
3369     int externalIndex = sampler.external? 1 : 0;
3370     int imageIndex    = sampler.image   ? 1 : 0;
3371     int msIndex       = sampler.ms      ? 1 : 0;
3372
3373     int flattened = EsdNumDims * (EbtNumTypes * (2 * (2 * (2 * (2 * arrayIndex + msIndex) + imageIndex) + shadowIndex) +
3374                                                  externalIndex) + sampler.type) + sampler.dim;
3375     assert(flattened < maxSamplerIndex);
3376
3377     return flattened;
3378 }
3379
3380 TPrecisionQualifier TParseContext::getDefaultPrecision(TPublicType& publicType)
3381 {
3382     if (publicType.basicType == EbtSampler)
3383         return defaultSamplerPrecision[computeSamplerTypeIndex(publicType.sampler)];
3384     else
3385         return defaultPrecision[publicType.basicType];
3386 }
3387
3388 void TParseContext::precisionQualifierCheck(const TSourceLoc& loc, TBasicType baseType, TQualifier& qualifier)
3389 {
3390     // Built-in symbols are allowed some ambiguous precisions, to be pinned down
3391     // later by context.
3392     if (! obeyPrecisionQualifiers() || parsingBuiltins)
3393         return;
3394
3395     if (baseType == EbtAtomicUint && qualifier.precision != EpqNone && qualifier.precision != EpqHigh)
3396         error(loc, "atomic counters can only be highp", "atomic_uint", "");
3397
3398     if (baseType == EbtFloat || baseType == EbtUint || baseType == EbtInt || baseType == EbtSampler || baseType == EbtAtomicUint) {
3399         if (qualifier.precision == EpqNone) {
3400             if (relaxedErrors())
3401                 warn(loc, "type requires declaration of default precision qualifier", TType::getBasicString(baseType), "substituting 'mediump'");
3402             else
3403                 error(loc, "type requires declaration of default precision qualifier", TType::getBasicString(baseType), "");
3404             qualifier.precision = EpqMedium;
3405             defaultPrecision[baseType] = EpqMedium;
3406         }
3407     } else if (qualifier.precision != EpqNone)
3408         error(loc, "type cannot have precision qualifier", TType::getBasicString(baseType), "");
3409 }
3410
3411 void TParseContext::parameterTypeCheck(const TSourceLoc& loc, TStorageQualifier qualifier, const TType& type)
3412 {
3413     if ((qualifier == EvqOut || qualifier == EvqInOut) && type.isOpaque())
3414         error(loc, "samplers and atomic_uints cannot be output parameters", type.getBasicTypeString().c_str(), "");
3415
3416     if (!parsingBuiltins && type.containsBasicType(EbtFloat16))
3417         requireFloat16Arithmetic(loc, type.getBasicTypeString().c_str(), "float16 types can only be in uniform block or buffer storage");
3418     if (!parsingBuiltins && type.contains16BitInt())
3419         requireInt16Arithmetic(loc, type.getBasicTypeString().c_str(), "(u)int16 types can only be in uniform block or buffer storage");
3420     if (!parsingBuiltins && type.contains8BitInt())
3421         requireInt8Arithmetic(loc, type.getBasicTypeString().c_str(), "(u)int8 types can only be in uniform block or buffer storage");
3422 }
3423
3424 bool TParseContext::containsFieldWithBasicType(const TType& type, TBasicType basicType)
3425 {
3426     if (type.getBasicType() == basicType)
3427         return true;
3428
3429     if (type.getBasicType() == EbtStruct) {
3430         const TTypeList& structure = *type.getStruct();
3431         for (unsigned int i = 0; i < structure.size(); ++i) {
3432             if (containsFieldWithBasicType(*structure[i].type, basicType))
3433                 return true;
3434         }
3435     }
3436
3437     return false;
3438 }
3439
3440 //
3441 // Do size checking for an array type's size.
3442 //
3443 void TParseContext::arraySizeCheck(const TSourceLoc& loc, TIntermTyped* expr, TArraySize& sizePair)
3444 {
3445     bool isConst = false;
3446     sizePair.node = nullptr;
3447
3448     int size = 1;
3449
3450     TIntermConstantUnion* constant = expr->getAsConstantUnion();
3451     if (constant) {
3452         // handle true (non-specialization) constant
3453         size = constant->getConstArray()[0].getIConst();
3454         isConst = true;
3455     } else {
3456         // see if it's a specialization constant instead
3457         if (expr->getQualifier().isSpecConstant()) {
3458             isConst = true;
3459             sizePair.node = expr;
3460             TIntermSymbol* symbol = expr->getAsSymbolNode();
3461             if (symbol && symbol->getConstArray().size() > 0)
3462                 size = symbol->getConstArray()[0].getIConst();
3463         }
3464     }
3465
3466     sizePair.size = size;
3467
3468     if (! isConst || (expr->getBasicType() != EbtInt && expr->getBasicType() != EbtUint)) {
3469         error(loc, "array size must be a constant integer expression", "", "");
3470         return;
3471     }
3472
3473     if (size <= 0) {
3474         error(loc, "array size must be a positive integer", "", "");
3475         return;
3476     }
3477 }
3478
3479 //
3480 // See if this qualifier can be an array.
3481 //
3482 // Returns true if there is an error.
3483 //
3484 bool TParseContext::arrayQualifierError(const TSourceLoc& loc, const TQualifier& qualifier)
3485 {
3486     if (qualifier.storage == EvqConst) {
3487         profileRequires(loc, ENoProfile, 120, E_GL_3DL_array_objects, "const array");
3488         profileRequires(loc, EEsProfile, 300, nullptr, "const array");
3489     }
3490
3491     if (qualifier.storage == EvqVaryingIn && language == EShLangVertex) {
3492         requireProfile(loc, ~EEsProfile, "vertex input arrays");
3493         profileRequires(loc, ENoProfile, 150, nullptr, "vertex input arrays");
3494     }
3495
3496     return false;
3497 }
3498
3499 //
3500 // See if this qualifier and type combination can be an array.
3501 // Assumes arrayQualifierError() was also called to catch the type-invariant tests.
3502 //
3503 // Returns true if there is an error.
3504 //
3505 bool TParseContext::arrayError(const TSourceLoc& loc, const TType& type)
3506 {
3507     if (type.getQualifier().storage == EvqVaryingOut && language == EShLangVertex) {
3508         if (type.isArrayOfArrays())
3509             requireProfile(loc, ~EEsProfile, "vertex-shader array-of-array output");
3510         else if (type.isStruct())
3511             requireProfile(loc, ~EEsProfile, "vertex-shader array-of-struct output");
3512     }
3513     if (type.getQualifier().storage == EvqVaryingIn && language == EShLangFragment) {
3514         if (type.isArrayOfArrays())
3515             requireProfile(loc, ~EEsProfile, "fragment-shader array-of-array input");
3516         else if (type.isStruct())
3517             requireProfile(loc, ~EEsProfile, "fragment-shader array-of-struct input");
3518     }
3519     if (type.getQualifier().storage == EvqVaryingOut && language == EShLangFragment) {
3520         if (type.isArrayOfArrays())
3521             requireProfile(loc, ~EEsProfile, "fragment-shader array-of-array output");
3522     }
3523
3524     return false;
3525 }
3526
3527 //
3528 // Require array to be completely sized
3529 //
3530 void TParseContext::arraySizeRequiredCheck(const TSourceLoc& loc, const TArraySizes& arraySizes)
3531 {
3532     if (arraySizes.hasUnsized())
3533         error(loc, "array size required", "", "");
3534 }
3535
3536 void TParseContext::structArrayCheck(const TSourceLoc& /*loc*/, const TType& type)
3537 {
3538     const TTypeList& structure = *type.getStruct();
3539     for (int m = 0; m < (int)structure.size(); ++m) {
3540         const TType& member = *structure[m].type;
3541         if (member.isArray())
3542             arraySizeRequiredCheck(structure[m].loc, *member.getArraySizes());
3543     }
3544 }
3545
3546 void TParseContext::arraySizesCheck(const TSourceLoc& loc, const TQualifier& qualifier, TArraySizes* arraySizes,
3547     const TIntermTyped* initializer, bool lastMember)
3548 {
3549     assert(arraySizes);
3550
3551     // always allow special built-in ins/outs sized to topologies
3552     if (parsingBuiltins)
3553         return;
3554
3555     // initializer must be a sized array, in which case
3556     // allow the initializer to set any unknown array sizes
3557     if (initializer != nullptr) {
3558         if (initializer->getType().isUnsizedArray())
3559             error(loc, "array initializer must be sized", "[]", "");
3560         return;
3561     }
3562
3563     // No environment allows any non-outer-dimension to be implicitly sized
3564     if (arraySizes->isInnerUnsized()) {
3565         error(loc, "only outermost dimension of an array of arrays can be implicitly sized", "[]", "");
3566         arraySizes->clearInnerUnsized();
3567     }
3568
3569     if (arraySizes->isInnerSpecialization())
3570         error(loc, "only outermost dimension of an array of arrays can be a specialization constant", "[]", "");
3571
3572     // desktop always allows outer-dimension-unsized variable arrays,
3573     if (profile != EEsProfile)
3574         return;
3575
3576     // for ES, if size isn't coming from an initializer, it has to be explicitly declared now,
3577     // with very few exceptions
3578
3579     // last member of ssbo block exception:
3580     if (qualifier.storage == EvqBuffer && lastMember)
3581         return;
3582
3583     // implicitly-sized io exceptions:
3584     switch (language) {
3585     case EShLangGeometry:
3586         if (qualifier.storage == EvqVaryingIn)
3587             if ((profile == EEsProfile && version >= 320) ||
3588                 extensionsTurnedOn(Num_AEP_geometry_shader, AEP_geometry_shader))
3589                 return;
3590         break;
3591     case EShLangTessControl:
3592         if ( qualifier.storage == EvqVaryingIn ||
3593             (qualifier.storage == EvqVaryingOut && ! qualifier.patch))
3594             if ((profile == EEsProfile && version >= 320) ||
3595                 extensionsTurnedOn(Num_AEP_tessellation_shader, AEP_tessellation_shader))
3596                 return;
3597         break;
3598     case EShLangTessEvaluation:
3599         if ((qualifier.storage == EvqVaryingIn && ! qualifier.patch) ||
3600              qualifier.storage == EvqVaryingOut)
3601             if ((profile == EEsProfile && version >= 320) ||
3602                 extensionsTurnedOn(Num_AEP_tessellation_shader, AEP_tessellation_shader))
3603                 return;
3604         break;
3605 #ifdef NV_EXTENSIONS
3606     case EShLangMeshNV:
3607         if (qualifier.storage == EvqVaryingOut)
3608             if ((profile == EEsProfile && version >= 320) ||
3609                 extensionTurnedOn(E_GL_NV_mesh_shader))
3610                 return;
3611         break;
3612 #endif
3613     default:
3614         break;
3615     }
3616
3617     arraySizeRequiredCheck(loc, *arraySizes);
3618 }
3619
3620 void TParseContext::arrayOfArrayVersionCheck(const TSourceLoc& loc, const TArraySizes* sizes)
3621 {
3622     if (sizes == nullptr || sizes->getNumDims() == 1)
3623         return;
3624
3625     const char* feature = "arrays of arrays";
3626
3627     requireProfile(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, feature);
3628     profileRequires(loc, EEsProfile, 310, nullptr, feature);
3629     profileRequires(loc, ECoreProfile | ECompatibilityProfile, 430, nullptr, feature);
3630 }
3631
3632 //
3633 // Do all the semantic checking for declaring or redeclaring an array, with and
3634 // without a size, and make the right changes to the symbol table.
3635 //
3636 void TParseContext::declareArray(const TSourceLoc& loc, const TString& identifier, const TType& type, TSymbol*& symbol)
3637 {
3638     if (symbol == nullptr) {
3639         bool currentScope;
3640         symbol = symbolTable.find(identifier, nullptr, &currentScope);
3641
3642         if (symbol && builtInName(identifier) && ! symbolTable.atBuiltInLevel()) {
3643             // bad shader (errors already reported) trying to redeclare a built-in name as an array
3644             symbol = nullptr;
3645             return;
3646         }
3647         if (symbol == nullptr || ! currentScope) {
3648             //
3649             // Successfully process a new definition.
3650             // (Redeclarations have to take place at the same scope; otherwise they are hiding declarations)
3651             //
3652             symbol = new TVariable(&identifier, type);
3653             symbolTable.insert(*symbol);
3654             if (symbolTable.atGlobalLevel())
3655                 trackLinkage(*symbol);
3656
3657             if (! symbolTable.atBuiltInLevel()) {
3658                 if (isIoResizeArray(type)) {
3659                     ioArraySymbolResizeList.push_back(symbol);
3660                     checkIoArraysConsistency(loc, true, type.getQualifier().isPerPrimitive());
3661                 } else
3662                     fixIoArraySize(loc, symbol->getWritableType());
3663             }
3664
3665             return;
3666         }
3667         if (symbol->getAsAnonMember()) {
3668             error(loc, "cannot redeclare a user-block member array", identifier.c_str(), "");
3669             symbol = nullptr;
3670             return;
3671         }
3672     }
3673
3674     //
3675     // Process a redeclaration.
3676     //
3677
3678     if (symbol == nullptr) {
3679         error(loc, "array variable name expected", identifier.c_str(), "");
3680         return;
3681     }
3682
3683     // redeclareBuiltinVariable() should have already done the copyUp()
3684     TType& existingType = symbol->getWritableType();
3685
3686     if (! existingType.isArray()) {
3687         error(loc, "redeclaring non-array as array", identifier.c_str(), "");
3688         return;
3689     }
3690
3691     if (! existingType.sameElementType(type)) {
3692         error(loc, "redeclaration of array with a different element type", identifier.c_str(), "");
3693         return;
3694     }
3695
3696     if (! existingType.sameInnerArrayness(type)) {
3697         error(loc, "redeclaration of array with a different array dimensions or sizes", identifier.c_str(), "");
3698         return;
3699     }
3700
3701     if (existingType.isSizedArray()) {
3702         // be more leniant for input arrays to geometry shaders and tessellation control outputs, where the redeclaration is the same size
3703         if (! (isIoResizeArray(type) && existingType.getOuterArraySize() == type.getOuterArraySize()))
3704             error(loc, "redeclaration of array with size", identifier.c_str(), "");
3705         return;
3706     }
3707
3708     arrayLimitCheck(loc, identifier, type.getOuterArraySize());
3709
3710     existingType.updateArraySizes(type);
3711
3712     if (isIoResizeArray(type))
3713         checkIoArraysConsistency(loc, false, type.getQualifier().isPerPrimitive());
3714 }
3715
3716 // Policy and error check for needing a runtime sized array.
3717 void TParseContext::checkRuntimeSizable(const TSourceLoc& loc, const TIntermTyped& base)
3718 {
3719     // runtime length implies runtime sizeable, so no problem
3720     if (isRuntimeLength(base))
3721         return;
3722
3723     // check for additional things allowed by GL_EXT_nonuniform_qualifier
3724     if (base.getBasicType() == EbtSampler ||
3725             (base.getBasicType() == EbtBlock && base.getType().getQualifier().isUniformOrBuffer()))
3726         requireExtensions(loc, 1, &E_GL_EXT_nonuniform_qualifier, "variable index");
3727     else
3728         error(loc, "", "[", "array must be redeclared with a size before being indexed with a variable");
3729 }
3730
3731 // Policy decision for whether a run-time .length() is allowed.
3732 bool TParseContext::isRuntimeLength(const TIntermTyped& base) const
3733 {
3734     if (base.getType().getQualifier().storage == EvqBuffer) {
3735         // in a buffer block
3736         const TIntermBinary* binary = base.getAsBinaryNode();
3737         if (binary != nullptr && binary->getOp() == EOpIndexDirectStruct) {
3738             // is it the last member?
3739             const int index = binary->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
3740             const int memberCount = (int)binary->getLeft()->getType().getStruct()->size();
3741             if (index == memberCount - 1)
3742                 return true;
3743         }
3744     }
3745
3746     return false;
3747 }
3748
3749 #ifdef NV_EXTENSIONS
3750 // Fix mesh view output array dimension
3751 void TParseContext::resizeMeshViewDimension(const TSourceLoc& loc, TType& type)
3752 {
3753     // see if member is a per-view attribute
3754     if (type.getQualifier().isPerView()) {
3755         // since we don't have the maxMeshViewCountNV set during parsing builtins, we hardcode the value
3756         int maxViewCount = parsingBuiltins ? 4 : resources.maxMeshViewCountNV;
3757
3758         if (! type.isArray()) {
3759             error(loc, "requires an view array dimension", "perviewNV", "");
3760         }
3761         else if (!type.isUnsizedArray() && type.getOuterArraySize() != maxViewCount) {
3762             error(loc, "mesh view output array size must be gl_MaxMeshViewCountNV or implicitly sized", "[]", "");
3763         }
3764         else if (type.isUnsizedArray()) {
3765             type.changeOuterArraySize(maxViewCount);
3766         }
3767     }
3768 }
3769 #endif
3770
3771 // Returns true if the first argument to the #line directive is the line number for the next line.
3772 //
3773 // Desktop, pre-version 3.30:  "After processing this directive
3774 // (including its new-line), the implementation will behave as if it is compiling at line number line+1 and
3775 // source string number source-string-number."
3776 //
3777 // Desktop, version 3.30 and later, and ES:  "After processing this directive
3778 // (including its new-line), the implementation will behave as if it is compiling at line number line and
3779 // source string number source-string-number.
3780 bool TParseContext::lineDirectiveShouldSetNextLine() const
3781 {
3782     return profile == EEsProfile || version >= 330;
3783 }
3784
3785 //
3786 // Enforce non-initializer type/qualifier rules.
3787 //
3788 void TParseContext::nonInitConstCheck(const TSourceLoc& loc, TString& identifier, TType& type)
3789 {
3790     //
3791     // Make the qualifier make sense, given that there is not an initializer.
3792     //
3793     if (type.getQualifier().storage == EvqConst ||
3794         type.getQualifier().storage == EvqConstReadOnly) {
3795         type.getQualifier().makeTemporary();
3796         error(loc, "variables with qualifier 'const' must be initialized", identifier.c_str(), "");
3797     }
3798 }
3799
3800 //
3801 // See if the identifier is a built-in symbol that can be redeclared, and if so,
3802 // copy the symbol table's read-only built-in variable to the current
3803 // global level, where it can be modified based on the passed in type.
3804 //
3805 // Returns nullptr if no redeclaration took place; meaning a normal declaration still
3806 // needs to occur for it, not necessarily an error.
3807 //
3808 // Returns a redeclared and type-modified variable if a redeclarated occurred.
3809 //
3810 TSymbol* TParseContext::redeclareBuiltinVariable(const TSourceLoc& loc, const TString& identifier,
3811                                                  const TQualifier& qualifier, const TShaderQualifiers& publicType)
3812 {
3813     if (! builtInName(identifier) || symbolTable.atBuiltInLevel() || ! symbolTable.atGlobalLevel())
3814         return nullptr;
3815
3816     bool nonEsRedecls = (profile != EEsProfile && (version >= 130 || identifier == "gl_TexCoord"));
3817     bool    esRedecls = (profile == EEsProfile &&
3818                          (version >= 320 || extensionsTurnedOn(Num_AEP_shader_io_blocks, AEP_shader_io_blocks)));
3819     if (! esRedecls && ! nonEsRedecls)
3820         return nullptr;
3821
3822     // Special case when using GL_ARB_separate_shader_objects
3823     bool ssoPre150 = false;  // means the only reason this variable is redeclared is due to this combination
3824     if (profile != EEsProfile && version <= 140 && extensionTurnedOn(E_GL_ARB_separate_shader_objects)) {
3825         if (identifier == "gl_Position"     ||
3826             identifier == "gl_PointSize"    ||
3827             identifier == "gl_ClipVertex"   ||
3828             identifier == "gl_FogFragCoord")
3829             ssoPre150 = true;
3830     }
3831
3832     // Potentially redeclaring a built-in variable...
3833
3834     if (ssoPre150 ||
3835         (identifier == "gl_FragDepth"           && ((nonEsRedecls && version >= 420) || esRedecls)) ||
3836         (identifier == "gl_FragCoord"           && ((nonEsRedecls && version >= 150) || esRedecls)) ||
3837          identifier == "gl_ClipDistance"                                                            ||
3838          identifier == "gl_CullDistance"                                                            ||
3839          identifier == "gl_FrontColor"                                                              ||
3840          identifier == "gl_BackColor"                                                               ||
3841          identifier == "gl_FrontSecondaryColor"                                                     ||
3842          identifier == "gl_BackSecondaryColor"                                                      ||
3843          identifier == "gl_SecondaryColor"                                                          ||
3844         (identifier == "gl_Color"               && language == EShLangFragment)                     ||
3845 #ifdef NV_EXTENSIONS
3846          identifier == "gl_SampleMask"                                                              ||
3847          identifier == "gl_Layer"                                                                   ||
3848 #endif
3849          identifier == "gl_TexCoord") {
3850
3851         // Find the existing symbol, if any.
3852         bool builtIn;
3853         TSymbol* symbol = symbolTable.find(identifier, &builtIn);
3854
3855         // If the symbol was not found, this must be a version/profile/stage
3856         // that doesn't have it.
3857         if (! symbol)
3858             return nullptr;
3859
3860         // If it wasn't at a built-in level, then it's already been redeclared;
3861         // that is, this is a redeclaration of a redeclaration; reuse that initial
3862         // redeclaration.  Otherwise, make the new one.
3863         if (builtIn)
3864             makeEditable(symbol);
3865
3866         // Now, modify the type of the copy, as per the type of the current redeclaration.
3867
3868         TQualifier& symbolQualifier = symbol->getWritableType().getQualifier();
3869         if (ssoPre150) {
3870             if (intermediate.inIoAccessed(identifier))
3871                 error(loc, "cannot redeclare after use", identifier.c_str(), "");
3872             if (qualifier.hasLayout())
3873                 error(loc, "cannot apply layout qualifier to", "redeclaration", symbol->getName().c_str());
3874             if (qualifier.isMemory() || qualifier.isAuxiliary() || (language == EShLangVertex   && qualifier.storage != EvqVaryingOut) ||
3875                                                                    (language == EShLangFragment && qualifier.storage != EvqVaryingIn))
3876                 error(loc, "cannot change storage, memory, or auxiliary qualification of", "redeclaration", symbol->getName().c_str());
3877             if (! qualifier.smooth)
3878                 error(loc, "cannot change interpolation qualification of", "redeclaration", symbol->getName().c_str());
3879         } else if (identifier == "gl_FrontColor"          ||
3880                    identifier == "gl_BackColor"           ||
3881                    identifier == "gl_FrontSecondaryColor" ||
3882                    identifier == "gl_BackSecondaryColor"  ||
3883                    identifier == "gl_SecondaryColor"      ||
3884                    identifier == "gl_Color") {
3885             symbolQualifier.flat = qualifier.flat;
3886             symbolQualifier.smooth = qualifier.smooth;
3887             symbolQualifier.nopersp = qualifier.nopersp;
3888             if (qualifier.hasLayout())
3889                 error(loc, "cannot apply layout qualifier to", "redeclaration", symbol->getName().c_str());
3890             if (qualifier.isMemory() || qualifier.isAuxiliary() || symbol->getType().getQualifier().storage != qualifier.storage)
3891                 error(loc, "cannot change storage, memory, or auxiliary qualification of", "redeclaration", symbol->getName().c_str());
3892         } else if (identifier == "gl_TexCoord"     ||
3893                    identifier == "gl_ClipDistance" ||
3894                    identifier == "gl_CullDistance") {
3895             if (qualifier.hasLayout() || qualifier.isMemory() || qualifier.isAuxiliary() ||
3896                 qualifier.nopersp != symbolQualifier.nopersp || qualifier.flat != symbolQualifier.flat ||
3897                 symbolQualifier.storage != qualifier.storage)
3898                 error(loc, "cannot change qualification of", "redeclaration", symbol->getName().c_str());
3899         } else if (identifier == "gl_FragCoord") {
3900             if (intermediate.inIoAccessed("gl_FragCoord"))
3901                 error(loc, "cannot redeclare after use", "gl_FragCoord", "");
3902             if (qualifier.nopersp != symbolQualifier.nopersp || qualifier.flat != symbolQualifier.flat ||
3903                 qualifier.isMemory() || qualifier.isAuxiliary())
3904                 error(loc, "can only change layout qualification of", "redeclaration", symbol->getName().c_str());
3905             if (qualifier.storage != EvqVaryingIn)
3906                 error(loc, "cannot change input storage qualification of", "redeclaration", symbol->getName().c_str());
3907             if (! builtIn && (publicType.pixelCenterInteger != intermediate.getPixelCenterInteger() ||
3908                               publicType.originUpperLeft != intermediate.getOriginUpperLeft()))
3909                 error(loc, "cannot redeclare with different qualification:", "redeclaration", symbol->getName().c_str());
3910             if (publicType.pixelCenterInteger)
3911                 intermediate.setPixelCenterInteger();
3912             if (publicType.originUpperLeft)
3913                 intermediate.setOriginUpperLeft();
3914         } else if (identifier == "gl_FragDepth") {
3915             if (qualifier.nopersp != symbolQualifier.nopersp || qualifier.flat != symbolQualifier.flat ||
3916                 qualifier.isMemory() || qualifier.isAuxiliary())
3917                 error(loc, "can only change layout qualification of", "redeclaration", symbol->getName().c_str());
3918             if (qualifier.storage != EvqVaryingOut)
3919                 error(loc, "cannot change output storage qualification of", "redeclaration", symbol->getName().c_str());
3920             if (publicType.layoutDepth != EldNone) {
3921                 if (intermediate.inIoAccessed("gl_FragDepth"))
3922                     error(loc, "cannot redeclare after use", "gl_FragDepth", "");
3923                 if (! intermediate.setDepth(publicType.layoutDepth))
3924                     error(loc, "all redeclarations must use the same depth layout on", "redeclaration", symbol->getName().c_str());
3925             }
3926         }
3927 #ifdef NV_EXTENSIONS
3928         else if (identifier == "gl_SampleMask") {
3929             if (!publicType.layoutOverrideCoverage) {
3930                 error(loc, "redeclaration only allowed for override_coverage layout", "redeclaration", symbol->getName().c_str());
3931             }
3932             intermediate.setLayoutOverrideCoverage();
3933         }
3934         else if (identifier == "gl_Layer") {
3935             if (!qualifier.layoutViewportRelative && qualifier.layoutSecondaryViewportRelativeOffset == -2048)
3936                 error(loc, "redeclaration only allowed for viewport_relative or secondary_view_offset layout", "redeclaration", symbol->getName().c_str());
3937             symbolQualifier.layoutViewportRelative = qualifier.layoutViewportRelative;
3938             symbolQualifier.layoutSecondaryViewportRelativeOffset = qualifier.layoutSecondaryViewportRelativeOffset;
3939         }
3940 #endif
3941
3942         // TODO: semantics quality: separate smooth from nothing declared, then use IsInterpolation for several tests above
3943
3944         return symbol;
3945     }
3946
3947     return nullptr;
3948 }
3949
3950 //
3951 // Either redeclare the requested block, or give an error message why it can't be done.
3952 //
3953 // TODO: functionality: explicitly sizing members of redeclared blocks is not giving them an explicit size
3954 void TParseContext::redeclareBuiltinBlock(const TSourceLoc& loc, TTypeList& newTypeList, const TString& blockName,
3955     const TString* instanceName, TArraySizes* arraySizes)
3956 {
3957     const char* feature = "built-in block redeclaration";
3958     profileRequires(loc, EEsProfile, 320, Num_AEP_shader_io_blocks, AEP_shader_io_blocks, feature);
3959     profileRequires(loc, ~EEsProfile, 410, E_GL_ARB_separate_shader_objects, feature);
3960
3961     if (blockName != "gl_PerVertex" && blockName != "gl_PerFragment"
3962 #ifdef NV_EXTENSIONS
3963         && blockName != "gl_MeshPerVertexNV" && blockName != "gl_MeshPerPrimitiveNV"
3964 #endif
3965        )
3966     {
3967         error(loc, "cannot redeclare block: ", "block declaration", blockName.c_str());
3968         return;
3969     }
3970
3971     // Redeclaring a built-in block...
3972
3973     if (instanceName && ! builtInName(*instanceName)) {
3974         error(loc, "cannot redeclare a built-in block with a user name", instanceName->c_str(), "");
3975         return;
3976     }
3977
3978     // Blocks with instance names are easy to find, lookup the instance name,
3979     // Anonymous blocks need to be found via a member.
3980     bool builtIn;
3981     TSymbol* block;
3982     if (instanceName)
3983         block = symbolTable.find(*instanceName, &builtIn);
3984     else
3985         block = symbolTable.find(newTypeList.front().type->getFieldName(), &builtIn);
3986
3987     // If the block was not found, this must be a version/profile/stage
3988     // that doesn't have it, or the instance name is wrong.
3989     const char* errorName = instanceName ? instanceName->c_str() : newTypeList.front().type->getFieldName().c_str();
3990     if (! block) {
3991         error(loc, "no declaration found for redeclaration", errorName, "");
3992         return;
3993     }
3994     // Built-in blocks cannot be redeclared more than once, which if happened,
3995     // we'd be finding the already redeclared one here, rather than the built in.
3996     if (! builtIn) {
3997         error(loc, "can only redeclare a built-in block once, and before any use", blockName.c_str(), "");
3998         return;
3999     }
4000
4001     // Copy the block to make a writable version, to insert into the block table after editing.
4002     block = symbolTable.copyUpDeferredInsert(block);
4003
4004     if (block->getType().getBasicType() != EbtBlock) {
4005         error(loc, "cannot redeclare a non block as a block", errorName, "");
4006         return;
4007     }
4008
4009     // Fix XFB stuff up, it applies to the order of the redeclaration, not
4010     // the order of the original members.
4011     if (currentBlockQualifier.storage == EvqVaryingOut && globalOutputDefaults.hasXfbBuffer()) {
4012         if (!currentBlockQualifier.hasXfbBuffer())
4013             currentBlockQualifier.layoutXfbBuffer = globalOutputDefaults.layoutXfbBuffer;
4014         fixBlockXfbOffsets(currentBlockQualifier, newTypeList);
4015     }
4016
4017     // Edit and error check the container against the redeclaration
4018     //  - remove unused members
4019     //  - ensure remaining qualifiers/types match
4020
4021     TType& type = block->getWritableType();
4022
4023 #ifdef NV_EXTENSIONS
4024     // if gl_PerVertex is redeclared for the purpose of passing through "gl_Position"
4025     // for passthrough purpose, the redeclared block should have the same qualifers as
4026     // the current one
4027     if (currentBlockQualifier.layoutPassthrough) {
4028         type.getQualifier().layoutPassthrough = currentBlockQualifier.layoutPassthrough;
4029         type.getQualifier().storage = currentBlockQualifier.storage;
4030         type.getQualifier().layoutStream = currentBlockQualifier.layoutStream;
4031         type.getQualifier().layoutXfbBuffer = currentBlockQualifier.layoutXfbBuffer;
4032     }
4033 #endif
4034
4035     TTypeList::iterator member = type.getWritableStruct()->begin();
4036     size_t numOriginalMembersFound = 0;
4037     while (member != type.getStruct()->end()) {
4038         // look for match
4039         bool found = false;
4040         TTypeList::const_iterator newMember;
4041         TSourceLoc memberLoc;
4042         memberLoc.init();
4043         for (newMember = newTypeList.begin(); newMember != newTypeList.end(); ++newMember) {
4044             if (member->type->getFieldName() == newMember->type->getFieldName()) {
4045                 found = true;
4046                 memberLoc = newMember->loc;
4047                 break;
4048             }
4049         }
4050
4051         if (found) {
4052             ++numOriginalMembersFound;
4053             // - ensure match between redeclared members' types
4054             // - check for things that can't be changed
4055             // - update things that can be changed
4056             TType& oldType = *member->type;
4057             const TType& newType = *newMember->type;
4058             if (! newType.sameElementType(oldType))
4059                 error(memberLoc, "cannot redeclare block member with a different type", member->type->getFieldName().c_str(), "");
4060             if (oldType.isArray() != newType.isArray())
4061                 error(memberLoc, "cannot change arrayness of redeclared block member", member->type->getFieldName().c_str(), "");
4062             else if (! oldType.sameArrayness(newType) && oldType.isSizedArray())
4063                 error(memberLoc, "cannot change array size of redeclared block member", member->type->getFieldName().c_str(), "");
4064             else if (newType.isArray())
4065                 arrayLimitCheck(loc, member->type->getFieldName(), newType.getOuterArraySize());
4066             if (newType.getQualifier().isMemory())
4067                 error(memberLoc, "cannot add memory qualifier to redeclared block member", member->type->getFieldName().c_str(), "");
4068             if (newType.getQualifier().hasNonXfbLayout())
4069                 error(memberLoc, "cannot add non-XFB layout to redeclared block member", member->type->getFieldName().c_str(), "");
4070             if (newType.getQualifier().patch)
4071                 error(memberLoc, "cannot add patch to redeclared block member", member->type->getFieldName().c_str(), "");
4072             if (newType.getQualifier().hasXfbBuffer() &&
4073                 newType.getQualifier().layoutXfbBuffer != currentBlockQualifier.layoutXfbBuffer)
4074                 error(memberLoc, "member cannot contradict block (or what block inherited from global)", "xfb_buffer", "");
4075             oldType.getQualifier().centroid = newType.getQualifier().centroid;
4076             oldType.getQualifier().sample = newType.getQualifier().sample;
4077             oldType.getQualifier().invariant = newType.getQualifier().invariant;
4078             oldType.getQualifier().noContraction = newType.getQualifier().noContraction;
4079             oldType.getQualifier().smooth = newType.getQualifier().smooth;
4080             oldType.getQualifier().flat = newType.getQualifier().flat;
4081             oldType.getQualifier().nopersp = newType.getQualifier().nopersp;
4082             oldType.getQualifier().layoutXfbOffset = newType.getQualifier().layoutXfbOffset;
4083             oldType.getQualifier().layoutXfbBuffer = newType.getQualifier().layoutXfbBuffer;
4084             oldType.getQualifier().layoutXfbStride = newType.getQualifier().layoutXfbStride;
4085             if (oldType.getQualifier().layoutXfbOffset != TQualifier::layoutXfbBufferEnd) {
4086                 // if any member as an xfb_offset, then the block's xfb_buffer inherents current xfb_buffer,
4087                 // and for xfb processing, the member needs it as well, along with xfb_stride
4088                 type.getQualifier().layoutXfbBuffer = currentBlockQualifier.layoutXfbBuffer;
4089                 oldType.getQualifier().layoutXfbBuffer = currentBlockQualifier.layoutXfbBuffer;
4090             }
4091             if (oldType.isUnsizedArray() && newType.isSizedArray())
4092                 oldType.changeOuterArraySize(newType.getOuterArraySize());
4093
4094             //  check and process the member's type, which will include managing xfb information
4095             layoutTypeCheck(loc, oldType);
4096
4097             // go to next member
4098             ++member;
4099         } else {
4100             // For missing members of anonymous blocks that have been redeclared,
4101             // hide the original (shared) declaration.
4102             // Instance-named blocks can just have the member removed.
4103             if (instanceName)
4104                 member = type.getWritableStruct()->erase(member);
4105             else {
4106                 member->type->hideMember();
4107                 ++member;
4108             }
4109         }
4110     }
4111
4112     if (numOriginalMembersFound < newTypeList.size())
4113         error(loc, "block redeclaration has extra members", blockName.c_str(), "");
4114     if (type.isArray() != (arraySizes != nullptr) ||
4115         (type.isArray() && arraySizes != nullptr && type.getArraySizes()->getNumDims() != arraySizes->getNumDims()))
4116         error(loc, "cannot change arrayness of redeclared block", blockName.c_str(), "");
4117     else if (type.isArray()) {
4118         // At this point, we know both are arrays and both have the same number of dimensions.
4119
4120         // It is okay for a built-in block redeclaration to be unsized, and keep the size of the
4121         // original block declaration.
4122         if (!arraySizes->isSized() && type.isSizedArray())
4123             arraySizes->changeOuterSize(type.getOuterArraySize());
4124
4125         // And, okay to be giving a size to the array, by the redeclaration
4126         if (!type.isSizedArray() && arraySizes->isSized())
4127             type.changeOuterArraySize(arraySizes->getOuterSize());
4128
4129         // Now, they must match in all dimensions.
4130         if (type.isSizedArray() && *type.getArraySizes() != *arraySizes)
4131             error(loc, "cannot change array size of redeclared block", blockName.c_str(), "");
4132     }
4133
4134     symbolTable.insert(*block);
4135
4136     // Check for general layout qualifier errors
4137     layoutObjectCheck(loc, *block);
4138
4139     // Tracking for implicit sizing of array
4140     if (isIoResizeArray(block->getType())) {
4141         ioArraySymbolResizeList.push_back(block);
4142         checkIoArraysConsistency(loc, true, block->getType().getQualifier().isPerPrimitive());
4143     } else if (block->getType().isArray())
4144         fixIoArraySize(loc, block->getWritableType());
4145
4146     // Save it in the AST for linker use.
4147     trackLinkage(*block);
4148 }
4149
4150 void TParseContext::paramCheckFixStorage(const TSourceLoc& loc, const TStorageQualifier& qualifier, TType& type)
4151 {
4152     switch (qualifier) {
4153     case EvqConst:
4154     case EvqConstReadOnly:
4155         type.getQualifier().storage = EvqConstReadOnly;
4156         break;
4157     case EvqIn:
4158     case EvqOut:
4159     case EvqInOut:
4160         type.getQualifier().storage = qualifier;
4161         break;
4162     case EvqGlobal:
4163     case EvqTemporary:
4164         type.getQualifier().storage = EvqIn;
4165         break;
4166     default:
4167         type.getQualifier().storage = EvqIn;
4168         error(loc, "storage qualifier not allowed on function parameter", GetStorageQualifierString(qualifier), "");
4169         break;
4170     }
4171 }
4172
4173 void TParseContext::paramCheckFix(const TSourceLoc& loc, const TQualifier& qualifier, TType& type)
4174 {
4175     if (qualifier.isMemory()) {
4176         type.getQualifier().volatil   = qualifier.volatil;
4177         type.getQualifier().coherent  = qualifier.coherent;
4178         type.getQualifier().devicecoherent  = qualifier.devicecoherent ;
4179         type.getQualifier().queuefamilycoherent  = qualifier.queuefamilycoherent;
4180         type.getQualifier().workgroupcoherent  = qualifier.workgroupcoherent;
4181         type.getQualifier().subgroupcoherent  = qualifier.subgroupcoherent;
4182         type.getQualifier().nonprivate = qualifier.nonprivate;
4183         type.getQualifier().readonly  = qualifier.readonly;
4184         type.getQualifier().writeonly = qualifier.writeonly;
4185         type.getQualifier().restrict  = qualifier.restrict;
4186     }
4187
4188     if (qualifier.isAuxiliary() ||
4189         qualifier.isInterpolation())
4190         error(loc, "cannot use auxiliary or interpolation qualifiers on a function parameter", "", "");
4191     if (qualifier.hasLayout())
4192         error(loc, "cannot use layout qualifiers on a function parameter", "", "");
4193     if (qualifier.invariant)
4194         error(loc, "cannot use invariant qualifier on a function parameter", "", "");
4195     if (qualifier.noContraction) {
4196         if (qualifier.isParamOutput())
4197             type.getQualifier().noContraction = true;
4198         else
4199             warn(loc, "qualifier has no effect on non-output parameters", "precise", "");
4200     }
4201     if (qualifier.isNonUniform())
4202         type.getQualifier().nonUniform = qualifier.nonUniform;
4203
4204     paramCheckFixStorage(loc, qualifier.storage, type);
4205 }
4206
4207 void TParseContext::nestedBlockCheck(const TSourceLoc& loc)
4208 {
4209     if (structNestingLevel > 0)
4210         error(loc, "cannot nest a block definition inside a structure or block", "", "");
4211     ++structNestingLevel;
4212 }
4213
4214 void TParseContext::nestedStructCheck(const TSourceLoc& loc)
4215 {
4216     if (structNestingLevel > 0)
4217         error(loc, "cannot nest a structure definition inside a structure or block", "", "");
4218     ++structNestingLevel;
4219 }
4220
4221 void TParseContext::arrayObjectCheck(const TSourceLoc& loc, const TType& type, const char* op)
4222 {
4223     // Some versions don't allow comparing arrays or structures containing arrays
4224     if (type.containsArray()) {
4225         profileRequires(loc, ENoProfile, 120, E_GL_3DL_array_objects, op);
4226         profileRequires(loc, EEsProfile, 300, nullptr, op);
4227     }
4228 }
4229
4230 void TParseContext::opaqueCheck(const TSourceLoc& loc, const TType& type, const char* op)
4231 {
4232     if (containsFieldWithBasicType(type, EbtSampler))
4233         error(loc, "can't use with samplers or structs containing samplers", op, "");
4234 }
4235
4236 void TParseContext::storage16BitAssignmentCheck(const TSourceLoc& loc, const TType& type, const char* op)
4237 {
4238     if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtFloat16))
4239         requireFloat16Arithmetic(loc, op, "can't use with structs containing float16");
4240
4241     if (type.isArray() && type.getBasicType() == EbtFloat16)
4242         requireFloat16Arithmetic(loc, op, "can't use with arrays containing float16");
4243
4244     if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtInt16))
4245         requireInt16Arithmetic(loc, op, "can't use with structs containing int16");
4246
4247     if (type.isArray() && type.getBasicType() == EbtInt16)
4248         requireInt16Arithmetic(loc, op, "can't use with arrays containing int16");
4249
4250     if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtUint16))
4251         requireInt16Arithmetic(loc, op, "can't use with structs containing uint16");
4252
4253     if (type.isArray() && type.getBasicType() == EbtUint16)
4254         requireInt16Arithmetic(loc, op, "can't use with arrays containing uint16");
4255
4256     if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtInt8))
4257         requireInt8Arithmetic(loc, op, "can't use with structs containing int8");
4258
4259     if (type.isArray() && type.getBasicType() == EbtInt8)
4260         requireInt8Arithmetic(loc, op, "can't use with arrays containing int8");
4261
4262     if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtUint8))
4263         requireInt8Arithmetic(loc, op, "can't use with structs containing uint8");
4264
4265     if (type.isArray() && type.getBasicType() == EbtUint8)
4266         requireInt8Arithmetic(loc, op, "can't use with arrays containing uint8");
4267 }
4268
4269 void TParseContext::specializationCheck(const TSourceLoc& loc, const TType& type, const char* op)
4270 {
4271     if (type.containsSpecializationSize())
4272         error(loc, "can't use with types containing arrays sized with a specialization constant", op, "");
4273 }
4274
4275 void TParseContext::structTypeCheck(const TSourceLoc& /*loc*/, TPublicType& publicType)
4276 {
4277     const TTypeList& typeList = *publicType.userDef->getStruct();
4278
4279     // fix and check for member storage qualifiers and types that don't belong within a structure
4280     for (unsigned int member = 0; member < typeList.size(); ++member) {
4281         TQualifier& memberQualifier = typeList[member].type->getQualifier();
4282         const TSourceLoc& memberLoc = typeList[member].loc;
4283         if (memberQualifier.isAuxiliary() ||
4284             memberQualifier.isInterpolation() ||
4285             (memberQualifier.storage != EvqTemporary && memberQualifier.storage != EvqGlobal))
4286             error(memberLoc, "cannot use storage or interpolation qualifiers on structure members", typeList[member].type->getFieldName().c_str(), "");
4287         if (memberQualifier.isMemory())
4288             error(memberLoc, "cannot use memory qualifiers on structure members", typeList[member].type->getFieldName().c_str(), "");
4289         if (memberQualifier.hasLayout()) {
4290             error(memberLoc, "cannot use layout qualifiers on structure members", typeList[member].type->getFieldName().c_str(), "");
4291             memberQualifier.clearLayout();
4292         }
4293         if (memberQualifier.invariant)
4294             error(memberLoc, "cannot use invariant qualifier on structure members", typeList[member].type->getFieldName().c_str(), "");
4295     }
4296 }
4297
4298 //
4299 // See if this loop satisfies the limitations for ES 2.0 (version 100) for loops in Appendex A:
4300 //
4301 // "The loop index has type int or float.
4302 //
4303 // "The for statement has the form:
4304 //     for ( init-declaration ; condition ; expression )
4305 //     init-declaration has the form: type-specifier identifier = constant-expression
4306 //     condition has the form:  loop-index relational_operator constant-expression
4307 //         where relational_operator is one of: > >= < <= == or !=
4308 //     expression [sic] has one of the following forms:
4309 //         loop-index++
4310 //         loop-index--
4311 //         loop-index += constant-expression
4312 //         loop-index -= constant-expression
4313 //
4314 // The body is handled in an AST traversal.
4315 //
4316 void TParseContext::inductiveLoopCheck(const TSourceLoc& loc, TIntermNode* init, TIntermLoop* loop)
4317 {
4318     // loop index init must exist and be a declaration, which shows up in the AST as an aggregate of size 1 of the declaration
4319     bool badInit = false;
4320     if (! init || ! init->getAsAggregate() || init->getAsAggregate()->getSequence().size() != 1)
4321         badInit = true;
4322     TIntermBinary* binaryInit = 0;
4323     if (! badInit) {
4324         // get the declaration assignment
4325         binaryInit = init->getAsAggregate()->getSequence()[0]->getAsBinaryNode();
4326         if (! binaryInit)
4327             badInit = true;
4328     }
4329     if (badInit) {
4330         error(loc, "inductive-loop init-declaration requires the form \"type-specifier loop-index = constant-expression\"", "limitations", "");
4331         return;
4332     }
4333
4334     // loop index must be type int or float
4335     if (! binaryInit->getType().isScalar() || (binaryInit->getBasicType() != EbtInt && binaryInit->getBasicType() != EbtFloat)) {
4336         error(loc, "inductive loop requires a scalar 'int' or 'float' loop index", "limitations", "");
4337         return;
4338     }
4339
4340     // init is the form "loop-index = constant"
4341     if (binaryInit->getOp() != EOpAssign || ! binaryInit->getLeft()->getAsSymbolNode() || ! binaryInit->getRight()->getAsConstantUnion()) {
4342         error(loc, "inductive-loop init-declaration requires the form \"type-specifier loop-index = constant-expression\"", "limitations", "");
4343         return;
4344     }
4345
4346     // get the unique id of the loop index
4347     int loopIndex = binaryInit->getLeft()->getAsSymbolNode()->getId();
4348     inductiveLoopIds.insert(loopIndex);
4349
4350     // condition's form must be "loop-index relational-operator constant-expression"
4351     bool badCond = ! loop->getTest();
4352     if (! badCond) {
4353         TIntermBinary* binaryCond = loop->getTest()->getAsBinaryNode();
4354         badCond = ! binaryCond;
4355         if (! badCond) {
4356             switch (binaryCond->getOp()) {
4357             case EOpGreaterThan:
4358             case EOpGreaterThanEqual:
4359             case EOpLessThan:
4360             case EOpLessThanEqual:
4361             case EOpEqual:
4362             case EOpNotEqual:
4363                 break;
4364             default:
4365                 badCond = true;
4366             }
4367         }
4368         if (binaryCond && (! binaryCond->getLeft()->getAsSymbolNode() ||
4369                            binaryCond->getLeft()->getAsSymbolNode()->getId() != loopIndex ||
4370                            ! binaryCond->getRight()->getAsConstantUnion()))
4371             badCond = true;
4372     }
4373     if (badCond) {
4374         error(loc, "inductive-loop condition requires the form \"loop-index <comparison-op> constant-expression\"", "limitations", "");
4375         return;
4376     }
4377
4378     // loop-index++
4379     // loop-index--
4380     // loop-index += constant-expression
4381     // loop-index -= constant-expression
4382     bool badTerminal = ! loop->getTerminal();
4383     if (! badTerminal) {
4384         TIntermUnary* unaryTerminal = loop->getTerminal()->getAsUnaryNode();
4385         TIntermBinary* binaryTerminal = loop->getTerminal()->getAsBinaryNode();
4386         if (unaryTerminal || binaryTerminal) {
4387             switch(loop->getTerminal()->getAsOperator()->getOp()) {
4388             case EOpPostDecrement:
4389             case EOpPostIncrement:
4390             case EOpAddAssign:
4391             case EOpSubAssign:
4392                 break;
4393             default:
4394                 badTerminal = true;
4395             }
4396         } else
4397             badTerminal = true;
4398         if (binaryTerminal && (! binaryTerminal->getLeft()->getAsSymbolNode() ||
4399                                binaryTerminal->getLeft()->getAsSymbolNode()->getId() != loopIndex ||
4400                                ! binaryTerminal->getRight()->getAsConstantUnion()))
4401             badTerminal = true;
4402         if (unaryTerminal && (! unaryTerminal->getOperand()->getAsSymbolNode() ||
4403                               unaryTerminal->getOperand()->getAsSymbolNode()->getId() != loopIndex))
4404             badTerminal = true;
4405     }
4406     if (badTerminal) {
4407         error(loc, "inductive-loop termination requires the form \"loop-index++, loop-index--, loop-index += constant-expression, or loop-index -= constant-expression\"", "limitations", "");
4408         return;
4409     }
4410
4411     // the body
4412     inductiveLoopBodyCheck(loop->getBody(), loopIndex, symbolTable);
4413 }
4414
4415 // Do limit checks for built-in arrays.
4416 void TParseContext::arrayLimitCheck(const TSourceLoc& loc, const TString& identifier, int size)
4417 {
4418     if (identifier.compare("gl_TexCoord") == 0)
4419         limitCheck(loc, size, "gl_MaxTextureCoords", "gl_TexCoord array size");
4420     else if (identifier.compare("gl_ClipDistance") == 0)
4421         limitCheck(loc, size, "gl_MaxClipDistances", "gl_ClipDistance array size");
4422     else if (identifier.compare("gl_CullDistance") == 0)
4423         limitCheck(loc, size, "gl_MaxCullDistances", "gl_CullDistance array size");
4424 }
4425
4426 // See if the provided value is less than or equal to the symbol indicated by limit,
4427 // which should be a constant in the symbol table.
4428 void TParseContext::limitCheck(const TSourceLoc& loc, int value, const char* limit, const char* feature)
4429 {
4430     TSymbol* symbol = symbolTable.find(limit);
4431     assert(symbol->getAsVariable());
4432     const TConstUnionArray& constArray = symbol->getAsVariable()->getConstArray();
4433     assert(! constArray.empty());
4434     if (value > constArray[0].getIConst())
4435         error(loc, "must be less than or equal to", feature, "%s (%d)", limit, constArray[0].getIConst());
4436 }
4437
4438 //
4439 // Do any additional error checking, etc., once we know the parsing is done.
4440 //
4441 void TParseContext::finish()
4442 {
4443     TParseContextBase::finish();
4444
4445     if (parsingBuiltins)
4446         return;
4447
4448     // Check on array indexes for ES 2.0 (version 100) limitations.
4449     for (size_t i = 0; i < needsIndexLimitationChecking.size(); ++i)
4450         constantIndexExpressionCheck(needsIndexLimitationChecking[i]);
4451
4452     // Check for stages that are enabled by extension.
4453     // Can't do this at the beginning, it is chicken and egg to add a stage by
4454     // extension.
4455     // Stage-specific features were correctly tested for already, this is just
4456     // about the stage itself.
4457     switch (language) {
4458     case EShLangGeometry:
4459         if (profile == EEsProfile && version == 310)
4460             requireExtensions(getCurrentLoc(), Num_AEP_geometry_shader, AEP_geometry_shader, "geometry shaders");
4461         break;
4462     case EShLangTessControl:
4463     case EShLangTessEvaluation:
4464         if (profile == EEsProfile && version == 310)
4465             requireExtensions(getCurrentLoc(), Num_AEP_tessellation_shader, AEP_tessellation_shader, "tessellation shaders");
4466         else if (profile != EEsProfile && version < 400)
4467             requireExtensions(getCurrentLoc(), 1, &E_GL_ARB_tessellation_shader, "tessellation shaders");
4468         break;
4469     case EShLangCompute:
4470         if (profile != EEsProfile && version < 430)
4471             requireExtensions(getCurrentLoc(), 1, &E_GL_ARB_compute_shader, "compute shaders");
4472         break;
4473 #ifdef NV_EXTENSIONS
4474     case EShLangTaskNV:
4475     case EShLangMeshNV:
4476         requireExtensions(getCurrentLoc(), 1, &E_GL_NV_mesh_shader, "mesh shaders");
4477         break;
4478 #endif
4479     default:
4480         break;
4481     }
4482
4483 #ifdef NV_EXTENSIONS
4484     // Set default outputs for GL_NV_geometry_shader_passthrough
4485     if (language == EShLangGeometry && extensionTurnedOn(E_SPV_NV_geometry_shader_passthrough)) {
4486         if (intermediate.getOutputPrimitive() == ElgNone) {
4487             switch (intermediate.getInputPrimitive()) {
4488             case ElgPoints:      intermediate.setOutputPrimitive(ElgPoints);    break;
4489             case ElgLines:       intermediate.setOutputPrimitive(ElgLineStrip); break;
4490             case ElgTriangles:   intermediate.setOutputPrimitive(ElgTriangleStrip); break;
4491             default: break;
4492             }
4493         }
4494         if (intermediate.getVertices() == TQualifier::layoutNotSet) {
4495             switch (intermediate.getInputPrimitive()) {
4496             case ElgPoints:      intermediate.setVertices(1); break;
4497             case ElgLines:       intermediate.setVertices(2); break;
4498             case ElgTriangles:   intermediate.setVertices(3); break;
4499             default: break;
4500             }
4501         }
4502     }
4503 #endif
4504 }
4505
4506 //
4507 // Layout qualifier stuff.
4508 //
4509
4510 // Put the id's layout qualification into the public type, for qualifiers not having a number set.
4511 // This is before we know any type information for error checking.
4512 void TParseContext::setLayoutQualifier(const TSourceLoc& loc, TPublicType& publicType, TString& id)
4513 {
4514     std::transform(id.begin(), id.end(), id.begin(), ::tolower);
4515
4516     if (id == TQualifier::getLayoutMatrixString(ElmColumnMajor)) {
4517         publicType.qualifier.layoutMatrix = ElmColumnMajor;
4518         return;
4519     }
4520     if (id == TQualifier::getLayoutMatrixString(ElmRowMajor)) {
4521         publicType.qualifier.layoutMatrix = ElmRowMajor;
4522         return;
4523     }
4524     if (id == TQualifier::getLayoutPackingString(ElpPacked)) {
4525         if (spvVersion.spv != 0)
4526             spvRemoved(loc, "packed");
4527         publicType.qualifier.layoutPacking = ElpPacked;
4528         return;
4529     }
4530     if (id == TQualifier::getLayoutPackingString(ElpShared)) {
4531         if (spvVersion.spv != 0)
4532             spvRemoved(loc, "shared");
4533         publicType.qualifier.layoutPacking = ElpShared;
4534         return;
4535     }
4536     if (id == TQualifier::getLayoutPackingString(ElpStd140)) {
4537         publicType.qualifier.layoutPacking = ElpStd140;
4538         return;
4539     }
4540     if (id == TQualifier::getLayoutPackingString(ElpStd430)) {
4541         requireProfile(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, "std430");
4542         profileRequires(loc, ECoreProfile | ECompatibilityProfile, 430, nullptr, "std430");
4543         profileRequires(loc, EEsProfile, 310, nullptr, "std430");
4544         publicType.qualifier.layoutPacking = ElpStd430;
4545         return;
4546     }
4547     // TODO: compile-time performance: may need to stop doing linear searches
4548     for (TLayoutFormat format = (TLayoutFormat)(ElfNone + 1); format < ElfCount; format = (TLayoutFormat)(format + 1)) {
4549         if (id == TQualifier::getLayoutFormatString(format)) {
4550             if ((format > ElfEsFloatGuard && format < ElfFloatGuard) ||
4551                 (format > ElfEsIntGuard && format < ElfIntGuard) ||
4552                 (format > ElfEsUintGuard && format < ElfCount))
4553                 requireProfile(loc, ENoProfile | ECoreProfile | ECompatibilityProfile, "image load-store format");
4554             profileRequires(loc, ENoProfile | ECoreProfile | ECompatibilityProfile, 420, E_GL_ARB_shader_image_load_store, "image load store");
4555             profileRequires(loc, EEsProfile, 310, E_GL_ARB_shader_image_load_store, "image load store");
4556             publicType.qualifier.layoutFormat = format;
4557             return;
4558         }
4559     }
4560     if (id == "push_constant") {
4561         requireVulkan(loc, "push_constant");
4562         publicType.qualifier.layoutPushConstant = true;
4563         return;
4564     }
4565     if (language == EShLangGeometry || language == EShLangTessEvaluation
4566 #ifdef NV_EXTENSIONS
4567         || language == EShLangMeshNV
4568 #endif
4569        ) {
4570         if (id == TQualifier::getGeometryString(ElgTriangles)) {
4571             publicType.shaderQualifiers.geometry = ElgTriangles;
4572             return;
4573         }
4574         if (language == EShLangGeometry
4575 #ifdef NV_EXTENSIONS
4576             || language == EShLangMeshNV
4577 #endif
4578            ) {
4579             if (id == TQualifier::getGeometryString(ElgPoints)) {
4580                 publicType.shaderQualifiers.geometry = ElgPoints;
4581                 return;
4582             }
4583             if (id == TQualifier::getGeometryString(ElgLines)) {
4584                 publicType.shaderQualifiers.geometry = ElgLines;
4585                 return;
4586             }
4587 #ifdef NV_EXTENSIONS
4588             if (language == EShLangGeometry)
4589 #endif
4590             {
4591                 if (id == TQualifier::getGeometryString(ElgLineStrip)) {
4592                     publicType.shaderQualifiers.geometry = ElgLineStrip;
4593                     return;
4594                 }
4595                 if (id == TQualifier::getGeometryString(ElgLinesAdjacency)) {
4596                     publicType.shaderQualifiers.geometry = ElgLinesAdjacency;
4597                     return;
4598                 }
4599                 if (id == TQualifier::getGeometryString(ElgTrianglesAdjacency)) {
4600                     publicType.shaderQualifiers.geometry = ElgTrianglesAdjacency;
4601                     return;
4602                 }
4603                 if (id == TQualifier::getGeometryString(ElgTriangleStrip)) {
4604                     publicType.shaderQualifiers.geometry = ElgTriangleStrip;
4605                     return;
4606                 }
4607 #ifdef NV_EXTENSIONS
4608                 if (id == "passthrough") {
4609                     requireExtensions(loc, 1, &E_SPV_NV_geometry_shader_passthrough, "geometry shader passthrough");
4610                     publicType.qualifier.layoutPassthrough = true;
4611                     intermediate.setGeoPassthroughEXT();
4612                     return;
4613                 }
4614 #endif
4615             }
4616         } else {
4617             assert(language == EShLangTessEvaluation);
4618
4619             // input primitive
4620             if (id == TQualifier::getGeometryString(ElgTriangles)) {
4621                 publicType.shaderQualifiers.geometry = ElgTriangles;
4622                 return;
4623             }
4624             if (id == TQualifier::getGeometryString(ElgQuads)) {
4625                 publicType.shaderQualifiers.geometry = ElgQuads;
4626                 return;
4627             }
4628             if (id == TQualifier::getGeometryString(ElgIsolines)) {
4629                 publicType.shaderQualifiers.geometry = ElgIsolines;
4630                 return;
4631             }
4632
4633             // vertex spacing
4634             if (id == TQualifier::getVertexSpacingString(EvsEqual)) {
4635                 publicType.shaderQualifiers.spacing = EvsEqual;
4636                 return;
4637             }
4638             if (id == TQualifier::getVertexSpacingString(EvsFractionalEven)) {
4639                 publicType.shaderQualifiers.spacing = EvsFractionalEven;
4640                 return;
4641             }
4642             if (id == TQualifier::getVertexSpacingString(EvsFractionalOdd)) {
4643                 publicType.shaderQualifiers.spacing = EvsFractionalOdd;
4644                 return;
4645             }
4646
4647             // triangle order
4648             if (id == TQualifier::getVertexOrderString(EvoCw)) {
4649                 publicType.shaderQualifiers.order = EvoCw;
4650                 return;
4651             }
4652             if (id == TQualifier::getVertexOrderString(EvoCcw)) {
4653                 publicType.shaderQualifiers.order = EvoCcw;
4654                 return;
4655             }
4656
4657             // point mode
4658             if (id == "point_mode") {
4659                 publicType.shaderQualifiers.pointMode = true;
4660                 return;
4661             }
4662         }
4663     }
4664     if (language == EShLangFragment) {
4665         if (id == "origin_upper_left") {
4666             requireProfile(loc, ECoreProfile | ECompatibilityProfile, "origin_upper_left");
4667             publicType.shaderQualifiers.originUpperLeft = true;
4668             return;
4669         }
4670         if (id == "pixel_center_integer") {
4671             requireProfile(loc, ECoreProfile | ECompatibilityProfile, "pixel_center_integer");
4672             publicType.shaderQualifiers.pixelCenterInteger = true;
4673             return;
4674         }
4675         if (id == "early_fragment_tests") {
4676             profileRequires(loc, ENoProfile | ECoreProfile | ECompatibilityProfile, 420, E_GL_ARB_shader_image_load_store, "early_fragment_tests");
4677             profileRequires(loc, EEsProfile, 310, nullptr, "early_fragment_tests");
4678             publicType.shaderQualifiers.earlyFragmentTests = true;
4679             return;
4680         }
4681         if (id == "post_depth_coverage") {
4682             requireExtensions(loc, Num_post_depth_coverageEXTs, post_depth_coverageEXTs, "post depth coverage");
4683             if (extensionTurnedOn(E_GL_ARB_post_depth_coverage)) {
4684                 publicType.shaderQualifiers.earlyFragmentTests = true;
4685             }
4686             publicType.shaderQualifiers.postDepthCoverage = true;
4687             return;
4688         }
4689         for (TLayoutDepth depth = (TLayoutDepth)(EldNone + 1); depth < EldCount; depth = (TLayoutDepth)(depth+1)) {
4690             if (id == TQualifier::getLayoutDepthString(depth)) {
4691                 requireProfile(loc, ECoreProfile | ECompatibilityProfile, "depth layout qualifier");
4692                 profileRequires(loc, ECoreProfile | ECompatibilityProfile, 420, nullptr, "depth layout qualifier");
4693                 publicType.shaderQualifiers.layoutDepth = depth;
4694                 return;
4695             }
4696         }
4697         if (id.compare(0, 13, "blend_support") == 0) {
4698             bool found = false;
4699             for (TBlendEquationShift be = (TBlendEquationShift)0; be < EBlendCount; be = (TBlendEquationShift)(be + 1)) {
4700                 if (id == TQualifier::getBlendEquationString(be)) {
4701                     profileRequires(loc, EEsProfile, 320, E_GL_KHR_blend_equation_advanced, "blend equation");
4702                     profileRequires(loc, ~EEsProfile, 0, E_GL_KHR_blend_equation_advanced, "blend equation");
4703                     intermediate.addBlendEquation(be);
4704                     publicType.shaderQualifiers.blendEquation = true;
4705                     found = true;
4706                     break;
4707                 }
4708             }
4709             if (! found)
4710                 error(loc, "unknown blend equation", "blend_support", "");
4711             return;
4712         }
4713 #ifdef NV_EXTENSIONS
4714         if (id == "override_coverage") {
4715             requireExtensions(loc, 1, &E_GL_NV_sample_mask_override_coverage, "sample mask override coverage");
4716             publicType.shaderQualifiers.layoutOverrideCoverage = true;
4717             return;
4718         }
4719     }
4720     if (language == EShLangVertex ||
4721         language == EShLangTessControl ||
4722         language == EShLangTessEvaluation ||
4723         language == EShLangGeometry ) {
4724         if (id == "viewport_relative") {
4725             requireExtensions(loc, 1, &E_GL_NV_viewport_array2, "view port array2");
4726             publicType.qualifier.layoutViewportRelative = true;
4727             return;
4728         }
4729     } else {
4730         if (language == EShLangRayGenNV || language == EShLangIntersectNV ||
4731         language == EShLangAnyHitNV || language == EShLangClosestHitNV ||
4732         language == EShLangMissNV || language == EShLangCallableNV) {
4733             if (id == "shaderrecordnvx") {
4734                 publicType.qualifier.layoutShaderRecordNV = true;
4735                 return;
4736             }
4737         }
4738     }
4739     if (language == EShLangCompute) {
4740         if (id.compare(0, 17, "derivative_group_") == 0) {
4741             requireExtensions(loc, 1, &E_GL_NV_compute_shader_derivatives, "compute shader derivatives");
4742             if (id == "derivative_group_quadsnv") {
4743                 publicType.shaderQualifiers.layoutDerivativeGroupQuads = true;
4744                 return;
4745             } else if (id == "derivative_group_linearnv") {
4746                 publicType.shaderQualifiers.layoutDerivativeGroupLinear = true;
4747                 return;
4748             }
4749         }
4750     }
4751 #else
4752     }
4753 #endif
4754     error(loc, "unrecognized layout identifier, or qualifier requires assignment (e.g., binding = 4)", id.c_str(), "");
4755 }
4756
4757 // Put the id's layout qualifier value into the public type, for qualifiers having a number set.
4758 // This is before we know any type information for error checking.
4759 void TParseContext::setLayoutQualifier(const TSourceLoc& loc, TPublicType& publicType, TString& id, const TIntermTyped* node)
4760 {
4761     const char* feature = "layout-id value";
4762     const char* nonLiteralFeature = "non-literal layout-id value";
4763
4764     integerCheck(node, feature);
4765     const TIntermConstantUnion* constUnion = node->getAsConstantUnion();
4766     int value;
4767     if (constUnion) {
4768         value = constUnion->getConstArray()[0].getIConst();
4769         if (! constUnion->isLiteral()) {
4770             requireProfile(loc, ECoreProfile | ECompatibilityProfile, nonLiteralFeature);
4771             profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, E_GL_ARB_enhanced_layouts, nonLiteralFeature);
4772         }
4773     } else {
4774         // grammar should have give out the error message
4775         value = 0;
4776     }
4777
4778     if (value < 0) {
4779         error(loc, "cannot be negative", feature, "");
4780         return;
4781     }
4782
4783     std::transform(id.begin(), id.end(), id.begin(), ::tolower);
4784
4785     if (id == "offset") {
4786         // "offset" can be for either
4787         //  - uniform offsets
4788         //  - atomic_uint offsets
4789         const char* feature = "offset";
4790         if (spvVersion.spv == 0) {
4791             requireProfile(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, feature);
4792             const char* exts[2] = { E_GL_ARB_enhanced_layouts, E_GL_ARB_shader_atomic_counters };
4793             profileRequires(loc, ECoreProfile | ECompatibilityProfile, 420, 2, exts, feature);
4794             profileRequires(loc, EEsProfile, 310, nullptr, feature);
4795         }
4796         publicType.qualifier.layoutOffset = value;
4797         return;
4798     } else if (id == "align") {
4799         const char* feature = "uniform buffer-member align";
4800         if (spvVersion.spv == 0) {
4801             requireProfile(loc, ECoreProfile | ECompatibilityProfile, feature);
4802             profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, E_GL_ARB_enhanced_layouts, feature);
4803         }
4804         // "The specified alignment must be a power of 2, or a compile-time error results."
4805         if (! IsPow2(value))
4806             error(loc, "must be a power of 2", "align", "");
4807         else
4808             publicType.qualifier.layoutAlign = value;
4809         return;
4810     } else if (id == "location") {
4811         profileRequires(loc, EEsProfile, 300, nullptr, "location");
4812         const char* exts[2] = { E_GL_ARB_separate_shader_objects, E_GL_ARB_explicit_attrib_location };
4813         profileRequires(loc, ~EEsProfile, 330, 2, exts, "location");
4814         if ((unsigned int)value >= TQualifier::layoutLocationEnd)
4815             error(loc, "location is too large", id.c_str(), "");
4816         else
4817             publicType.qualifier.layoutLocation = value;
4818         return;
4819     } else if (id == "set") {
4820         if ((unsigned int)value >= TQualifier::layoutSetEnd)
4821             error(loc, "set is too large", id.c_str(), "");
4822         else
4823             publicType.qualifier.layoutSet = value;
4824         if (value != 0)
4825             requireVulkan(loc, "descriptor set");
4826         return;
4827     } else if (id == "binding") {
4828         profileRequires(loc, ~EEsProfile, 420, E_GL_ARB_shading_language_420pack, "binding");
4829         profileRequires(loc, EEsProfile, 310, nullptr, "binding");
4830         if ((unsigned int)value >= TQualifier::layoutBindingEnd)
4831             error(loc, "binding is too large", id.c_str(), "");
4832         else
4833             publicType.qualifier.layoutBinding = value;
4834         return;
4835     } else if (id == "component") {
4836         requireProfile(loc, ECoreProfile | ECompatibilityProfile, "component");
4837         profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, E_GL_ARB_enhanced_layouts, "component");
4838         if ((unsigned)value >= TQualifier::layoutComponentEnd)
4839             error(loc, "component is too large", id.c_str(), "");
4840         else
4841             publicType.qualifier.layoutComponent = value;
4842         return;
4843     } else if (id.compare(0, 4, "xfb_") == 0) {
4844         // "Any shader making any static use (after preprocessing) of any of these
4845         // *xfb_* qualifiers will cause the shader to be in a transform feedback
4846         // capturing mode and hence responsible for describing the transform feedback
4847         // setup."
4848         intermediate.setXfbMode();
4849         const char* feature = "transform feedback qualifier";
4850         requireStage(loc, (EShLanguageMask)(EShLangVertexMask | EShLangGeometryMask | EShLangTessControlMask | EShLangTessEvaluationMask), feature);
4851         requireProfile(loc, ECoreProfile | ECompatibilityProfile, feature);
4852         profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, E_GL_ARB_enhanced_layouts, feature);
4853         if (id == "xfb_buffer") {
4854             // "It is a compile-time error to specify an *xfb_buffer* that is greater than
4855             // the implementation-dependent constant gl_MaxTransformFeedbackBuffers."
4856             if (value >= resources.maxTransformFeedbackBuffers)
4857                 error(loc, "buffer is too large:", id.c_str(), "gl_MaxTransformFeedbackBuffers is %d", resources.maxTransformFeedbackBuffers);
4858             if (value >= (int)TQualifier::layoutXfbBufferEnd)
4859                 error(loc, "buffer is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbBufferEnd-1);
4860             else
4861                 publicType.qualifier.layoutXfbBuffer = value;
4862             return;
4863         } else if (id == "xfb_offset") {
4864             if (value >= (int)TQualifier::layoutXfbOffsetEnd)
4865                 error(loc, "offset is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbOffsetEnd-1);
4866             else
4867                 publicType.qualifier.layoutXfbOffset = value;
4868             return;
4869         } else if (id == "xfb_stride") {
4870             // "The resulting stride (implicit or explicit), when divided by 4, must be less than or equal to the
4871             // implementation-dependent constant gl_MaxTransformFeedbackInterleavedComponents."
4872             if (value > 4 * resources.maxTransformFeedbackInterleavedComponents)
4873                 error(loc, "1/4 stride is too large:", id.c_str(), "gl_MaxTransformFeedbackInterleavedComponents is %d", resources.maxTransformFeedbackInterleavedComponents);
4874             else if (value >= (int)TQualifier::layoutXfbStrideEnd)
4875                 error(loc, "stride is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbStrideEnd-1);
4876             if (value < (int)TQualifier::layoutXfbStrideEnd)
4877                 publicType.qualifier.layoutXfbStride = value;
4878             return;
4879         }
4880     }
4881
4882     if (id == "input_attachment_index") {
4883         requireVulkan(loc, "input_attachment_index");
4884         if (value >= (int)TQualifier::layoutAttachmentEnd)
4885             error(loc, "attachment index is too large", id.c_str(), "");
4886         else
4887             publicType.qualifier.layoutAttachment = value;
4888         return;
4889     }
4890     if (id == "constant_id") {
4891         requireSpv(loc, "constant_id");
4892         if (value >= (int)TQualifier::layoutSpecConstantIdEnd) {
4893             error(loc, "specialization-constant id is too large", id.c_str(), "");
4894         } else {
4895             publicType.qualifier.layoutSpecConstantId = value;
4896             publicType.qualifier.specConstant = true;
4897             if (! intermediate.addUsedConstantId(value))
4898                 error(loc, "specialization-constant id already used", id.c_str(), "");
4899         }
4900         return;
4901     }
4902     if (id == "num_views") {
4903         requireExtensions(loc, Num_OVR_multiview_EXTs, OVR_multiview_EXTs, "num_views");
4904         publicType.shaderQualifiers.numViews = value;
4905         return;
4906     }
4907
4908 #if NV_EXTENSIONS
4909     if (language == EShLangVertex ||
4910         language == EShLangTessControl ||
4911         language == EShLangTessEvaluation ||
4912         language == EShLangGeometry) {
4913         if (id == "secondary_view_offset") {
4914             requireExtensions(loc, 1, &E_GL_NV_stereo_view_rendering, "stereo view rendering");
4915             publicType.qualifier.layoutSecondaryViewportRelativeOffset = value;
4916             return;
4917         }
4918     }
4919 #endif
4920
4921     switch (language) {
4922     case EShLangVertex:
4923         break;
4924
4925     case EShLangTessControl:
4926         if (id == "vertices") {
4927             if (value == 0)
4928                 error(loc, "must be greater than 0", "vertices", "");
4929             else
4930                 publicType.shaderQualifiers.vertices = value;
4931             return;
4932         }
4933         break;
4934
4935     case EShLangTessEvaluation:
4936         break;
4937
4938     case EShLangGeometry:
4939         if (id == "invocations") {
4940             profileRequires(loc, ECompatibilityProfile | ECoreProfile, 400, nullptr, "invocations");
4941             if (value == 0)
4942                 error(loc, "must be at least 1", "invocations", "");
4943             else
4944                 publicType.shaderQualifiers.invocations = value;
4945             return;
4946         }
4947         if (id == "max_vertices") {
4948             publicType.shaderQualifiers.vertices = value;
4949             if (value > resources.maxGeometryOutputVertices)
4950                 error(loc, "too large, must be less than gl_MaxGeometryOutputVertices", "max_vertices", "");
4951             return;
4952         }
4953         if (id == "stream") {
4954             requireProfile(loc, ~EEsProfile, "selecting output stream");
4955             publicType.qualifier.layoutStream = value;
4956             if (value > 0)
4957                 intermediate.setMultiStream();
4958             return;
4959         }
4960         break;
4961
4962     case EShLangFragment:
4963         if (id == "index") {
4964             requireProfile(loc, ECompatibilityProfile | ECoreProfile, "index layout qualifier on fragment output");
4965             const char* exts[2] = { E_GL_ARB_separate_shader_objects, E_GL_ARB_explicit_attrib_location };
4966             profileRequires(loc, ECompatibilityProfile | ECoreProfile, 330, 2, exts, "index layout qualifier on fragment output");
4967
4968             // "It is also a compile-time error if a fragment shader sets a layout index to less than 0 or greater than 1."
4969             if (value < 0 || value > 1) {
4970                 value = 0;
4971                 error(loc, "value must be 0 or 1", "index", "");
4972             }
4973
4974             publicType.qualifier.layoutIndex = value;
4975             return;
4976         }
4977         break;
4978
4979 #ifdef NV_EXTENSIONS
4980     case EShLangMeshNV:
4981         if (id == "max_vertices") {
4982             requireExtensions(loc, 1, &E_GL_NV_mesh_shader, "max_vertices");
4983             publicType.shaderQualifiers.vertices = value;
4984             if (value > resources.maxMeshOutputVerticesNV)
4985                 error(loc, "too large, must be less than gl_MaxMeshOutputVerticesNV", "max_vertices", "");
4986             return;
4987         }
4988         if (id == "max_primitives") {
4989             requireExtensions(loc, 1, &E_GL_NV_mesh_shader, "max_primitives");
4990             publicType.shaderQualifiers.primitives = value;
4991             if (value > resources.maxMeshOutputPrimitivesNV)
4992                 error(loc, "too large, must be less than gl_MaxMeshOutputPrimitivesNV", "max_primitives", "");
4993             return;
4994         }
4995         // Fall through
4996
4997     case EShLangTaskNV:
4998         // Fall through
4999 #endif
5000     case EShLangCompute:
5001         if (id.compare(0, 11, "local_size_") == 0) {
5002 #ifdef NV_EXTENSIONS
5003             if (language == EShLangMeshNV || language == EShLangTaskNV) {
5004                 requireExtensions(loc, 1, &E_GL_NV_mesh_shader, "gl_WorkGroupSize");
5005             }
5006             else
5007 #endif
5008             {
5009                 profileRequires(loc, EEsProfile, 310, 0, "gl_WorkGroupSize");
5010                 profileRequires(loc, ~EEsProfile, 430, E_GL_ARB_compute_shader, "gl_WorkGroupSize");
5011             }
5012             if (id.size() == 12 && value == 0) {
5013                 error(loc, "must be at least 1", id.c_str(), "");
5014                 return;
5015             }
5016             if (id == "local_size_x") {
5017                 publicType.shaderQualifiers.localSize[0] = value;
5018                 return;
5019             }
5020             if (id == "local_size_y") {
5021                 publicType.shaderQualifiers.localSize[1] = value;
5022                 return;
5023             }
5024             if (id == "local_size_z") {
5025                 publicType.shaderQualifiers.localSize[2] = value;
5026                 return;
5027             }
5028             if (spvVersion.spv != 0) {
5029                 if (id == "local_size_x_id") {
5030                     publicType.shaderQualifiers.localSizeSpecId[0] = value;
5031                     return;
5032                 }
5033                 if (id == "local_size_y_id") {
5034                     publicType.shaderQualifiers.localSizeSpecId[1] = value;
5035                     return;
5036                 }
5037                 if (id == "local_size_z_id") {
5038                     publicType.shaderQualifiers.localSizeSpecId[2] = value;
5039                     return;
5040                 }
5041             }
5042         }
5043         break;
5044
5045     default:
5046         break;
5047     }
5048
5049     error(loc, "there is no such layout identifier for this stage taking an assigned value", id.c_str(), "");
5050 }
5051
5052 // Merge any layout qualifier information from src into dst, leaving everything else in dst alone
5053 //
5054 // "More than one layout qualifier may appear in a single declaration.
5055 // Additionally, the same layout-qualifier-name can occur multiple times
5056 // within a layout qualifier or across multiple layout qualifiers in the
5057 // same declaration. When the same layout-qualifier-name occurs
5058 // multiple times, in a single declaration, the last occurrence overrides
5059 // the former occurrence(s).  Further, if such a layout-qualifier-name
5060 // will effect subsequent declarations or other observable behavior, it
5061 // is only the last occurrence that will have any effect, behaving as if
5062 // the earlier occurrence(s) within the declaration are not present.
5063 // This is also true for overriding layout-qualifier-names, where one
5064 // overrides the other (e.g., row_major vs. column_major); only the last
5065 // occurrence has any effect."
5066 void TParseContext::mergeObjectLayoutQualifiers(TQualifier& dst, const TQualifier& src, bool inheritOnly)
5067 {
5068     if (src.hasMatrix())
5069         dst.layoutMatrix = src.layoutMatrix;
5070     if (src.hasPacking())
5071         dst.layoutPacking = src.layoutPacking;
5072
5073     if (src.hasStream())
5074         dst.layoutStream = src.layoutStream;
5075
5076     if (src.hasFormat())
5077         dst.layoutFormat = src.layoutFormat;
5078
5079     if (src.hasXfbBuffer())
5080         dst.layoutXfbBuffer = src.layoutXfbBuffer;
5081
5082     if (src.hasAlign())
5083         dst.layoutAlign = src.layoutAlign;
5084
5085     if (! inheritOnly) {
5086         if (src.hasLocation())
5087             dst.layoutLocation = src.layoutLocation;
5088         if (src.hasComponent())
5089             dst.layoutComponent = src.layoutComponent;
5090         if (src.hasIndex())
5091             dst.layoutIndex = src.layoutIndex;
5092
5093         if (src.hasOffset())
5094             dst.layoutOffset = src.layoutOffset;
5095
5096         if (src.hasSet())
5097             dst.layoutSet = src.layoutSet;
5098         if (src.layoutBinding != TQualifier::layoutBindingEnd)
5099             dst.layoutBinding = src.layoutBinding;
5100
5101         if (src.hasXfbStride())
5102             dst.layoutXfbStride = src.layoutXfbStride;
5103         if (src.hasXfbOffset())
5104             dst.layoutXfbOffset = src.layoutXfbOffset;
5105         if (src.hasAttachment())
5106             dst.layoutAttachment = src.layoutAttachment;
5107         if (src.hasSpecConstantId())
5108             dst.layoutSpecConstantId = src.layoutSpecConstantId;
5109
5110         if (src.layoutPushConstant)
5111             dst.layoutPushConstant = true;
5112
5113 #ifdef NV_EXTENSIONS
5114         if (src.layoutPassthrough)
5115             dst.layoutPassthrough = true;
5116         if (src.layoutViewportRelative)
5117             dst.layoutViewportRelative = true;
5118         if (src.layoutSecondaryViewportRelativeOffset != -2048)
5119             dst.layoutSecondaryViewportRelativeOffset = src.layoutSecondaryViewportRelativeOffset;
5120         if (src.layoutShaderRecordNV)
5121             dst.layoutShaderRecordNV = true;
5122         if (src.pervertexNV)
5123             dst.pervertexNV = true;
5124 #endif
5125     }
5126 }
5127
5128 // Do error layout error checking given a full variable/block declaration.
5129 void TParseContext::layoutObjectCheck(const TSourceLoc& loc, const TSymbol& symbol)
5130 {
5131     const TType& type = symbol.getType();
5132     const TQualifier& qualifier = type.getQualifier();
5133
5134     // first, cross check WRT to just the type
5135     layoutTypeCheck(loc, type);
5136
5137     // now, any remaining error checking based on the object itself
5138
5139     if (qualifier.hasAnyLocation()) {
5140         switch (qualifier.storage) {
5141         case EvqUniform:
5142         case EvqBuffer:
5143             if (symbol.getAsVariable() == nullptr)
5144                 error(loc, "can only be used on variable declaration", "location", "");
5145             break;
5146         default:
5147             break;
5148         }
5149     }
5150
5151     // user-variable location check, which are required for SPIR-V in/out:
5152     //  - variables have it directly,
5153     //  - blocks have it on each member (already enforced), so check first one
5154     if (spvVersion.spv > 0 && !parsingBuiltins && qualifier.builtIn == EbvNone &&
5155         !qualifier.hasLocation() && !intermediate.getAutoMapLocations()) {
5156
5157         switch (qualifier.storage) {
5158         case EvqVaryingIn:
5159         case EvqVaryingOut:
5160             if (!type.getQualifier().isTaskMemory() &&
5161                 (type.getBasicType() != EbtBlock ||
5162                  (!(*type.getStruct())[0].type->getQualifier().hasLocation() &&
5163                    (*type.getStruct())[0].type->getQualifier().builtIn == EbvNone)))
5164                 error(loc, "SPIR-V requires location for user input/output", "location", "");
5165             break;
5166         default:
5167             break;
5168         }
5169     }
5170
5171     // Check packing and matrix
5172     if (qualifier.hasUniformLayout()) {
5173         switch (qualifier.storage) {
5174         case EvqUniform:
5175         case EvqBuffer:
5176             if (type.getBasicType() != EbtBlock) {
5177                 if (qualifier.hasMatrix())
5178                     error(loc, "cannot specify matrix layout on a variable declaration", "layout", "");
5179                 if (qualifier.hasPacking())
5180                     error(loc, "cannot specify packing on a variable declaration", "layout", "");
5181                 // "The offset qualifier can only be used on block members of blocks..."
5182                 if (qualifier.hasOffset() && type.getBasicType() != EbtAtomicUint)
5183                     error(loc, "cannot specify on a variable declaration", "offset", "");
5184                 // "The align qualifier can only be used on blocks or block members..."
5185                 if (qualifier.hasAlign())
5186                     error(loc, "cannot specify on a variable declaration", "align", "");
5187                 if (qualifier.layoutPushConstant)
5188                     error(loc, "can only specify on a uniform block", "push_constant", "");
5189 #ifdef NV_EXTENSIONS
5190                 if (qualifier.layoutShaderRecordNV)
5191                     error(loc, "can only specify on a buffer block", "shaderRecordNVX", "");
5192 #endif
5193             }
5194             break;
5195         default:
5196             // these were already filtered by layoutTypeCheck() (or its callees)
5197             break;
5198         }
5199     }
5200 }
5201
5202 // "For some blocks declared as arrays, the location can only be applied at the block level:
5203 // When a block is declared as an array where additional locations are needed for each member
5204 // for each block array element, it is a compile-time error to specify locations on the block
5205 // members.  That is, when locations would be under specified by applying them on block members,
5206 // they are not allowed on block members.  For arrayed interfaces (those generally having an
5207 // extra level of arrayness due to interface expansion), the outer array is stripped before
5208 // applying this rule."
5209 void TParseContext::layoutMemberLocationArrayCheck(const TSourceLoc& loc, bool memberWithLocation,
5210     TArraySizes* arraySizes)
5211 {
5212     if (memberWithLocation && arraySizes != nullptr) {
5213         if (arraySizes->getNumDims() > (currentBlockQualifier.isArrayedIo(language) ? 1 : 0))
5214             error(loc, "cannot use in a block array where new locations are needed for each block element",
5215                        "location", "");
5216     }
5217 }
5218
5219 // Do layout error checking with respect to a type.
5220 void TParseContext::layoutTypeCheck(const TSourceLoc& loc, const TType& type)
5221 {
5222     const TQualifier& qualifier = type.getQualifier();
5223
5224     // first, intra-layout qualifier-only error checking
5225     layoutQualifierCheck(loc, qualifier);
5226
5227     // now, error checking combining type and qualifier
5228
5229     if (qualifier.hasAnyLocation()) {
5230         if (qualifier.hasLocation()) {
5231             if (qualifier.storage == EvqVaryingOut && language == EShLangFragment) {
5232                 if (qualifier.layoutLocation >= (unsigned int)resources.maxDrawBuffers)
5233                     error(loc, "too large for fragment output", "location", "");
5234             }
5235         }
5236         if (qualifier.hasComponent()) {
5237             // "It is a compile-time error if this sequence of components gets larger than 3."
5238             if (qualifier.layoutComponent + type.getVectorSize() * (type.getBasicType() == EbtDouble ? 2 : 1) > 4)
5239                 error(loc, "type overflows the available 4 components", "component", "");
5240
5241             // "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."
5242             if (type.isMatrix() || type.getBasicType() == EbtBlock || type.getBasicType() == EbtStruct)
5243                 error(loc, "cannot apply to a matrix, structure, or block", "component", "");
5244
5245             // " It is a compile-time error to use component 1 or 3 as the beginning of a double or dvec2."
5246             if (type.getBasicType() == EbtDouble)
5247                 if (qualifier.layoutComponent & 1)
5248                     error(loc, "doubles cannot start on an odd-numbered component", "component", "");
5249         }
5250
5251         switch (qualifier.storage) {
5252         case EvqVaryingIn:
5253         case EvqVaryingOut:
5254             if (type.getBasicType() == EbtBlock)
5255                 profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, E_GL_ARB_enhanced_layouts, "location qualifier on in/out block");
5256 #ifdef NV_EXTENSIONS
5257             if (type.getQualifier().isTaskMemory())
5258                 error(loc, "cannot apply to taskNV in/out blocks", "location", "");
5259 #endif
5260             break;
5261         case EvqUniform:
5262         case EvqBuffer:
5263             if (type.getBasicType() == EbtBlock)
5264                 error(loc, "cannot apply to uniform or buffer block", "location", "");
5265             break;
5266 #ifdef NV_EXTENSIONS
5267         case EvqPayloadNV:
5268         case EvqPayloadInNV:
5269         case EvqHitAttrNV:
5270             break;
5271 #endif
5272         default:
5273             error(loc, "can only apply to uniform, buffer, in, or out storage qualifiers", "location", "");
5274             break;
5275         }
5276
5277         bool typeCollision;
5278         int repeated = intermediate.addUsedLocation(qualifier, type, typeCollision);
5279         if (repeated >= 0 && ! typeCollision)
5280             error(loc, "overlapping use of location", "location", "%d", repeated);
5281         // "fragment-shader outputs ... if two variables are placed within the same
5282         // location, they must have the same underlying type (floating-point or integer)"
5283         if (typeCollision && language == EShLangFragment && qualifier.isPipeOutput())
5284             error(loc, "fragment outputs sharing the same location must be the same basic type", "location", "%d", repeated);
5285     }
5286
5287     if (qualifier.hasXfbOffset() && qualifier.hasXfbBuffer()) {
5288         int repeated = intermediate.addXfbBufferOffset(type);
5289         if (repeated >= 0)
5290             error(loc, "overlapping offsets at", "xfb_offset", "offset %d in buffer %d", repeated, qualifier.layoutXfbBuffer);
5291
5292         // "The offset must be a multiple of the size of the first component of the first
5293         // qualified variable or block member, or a compile-time error results. Further, if applied to an aggregate
5294         // containing a double, the offset must also be a multiple of 8..."
5295         if (type.containsBasicType(EbtDouble) && ! IsMultipleOfPow2(qualifier.layoutXfbOffset, 8))
5296             error(loc, "type contains double; xfb_offset must be a multiple of 8", "xfb_offset", "");
5297         // ..., if applied to an aggregate containing a float16_t, the offset must also be a multiple of 2..."
5298         else if (type.containsBasicType(EbtFloat16) && !IsMultipleOfPow2(qualifier.layoutXfbOffset, 2))
5299             error(loc, "type contains half float; xfb_offset must be a multiple of 2", "xfb_offset", "");
5300         else if (! IsMultipleOfPow2(qualifier.layoutXfbOffset, 4))
5301             error(loc, "must be a multiple of size of first component", "xfb_offset", "");
5302     }
5303
5304     if (qualifier.hasXfbStride() && qualifier.hasXfbBuffer()) {
5305         if (! intermediate.setXfbBufferStride(qualifier.layoutXfbBuffer, qualifier.layoutXfbStride))
5306             error(loc, "all stride settings must match for xfb buffer", "xfb_stride", "%d", qualifier.layoutXfbBuffer);
5307     }
5308
5309     if (qualifier.hasBinding()) {
5310         // Binding checking, from the spec:
5311         //
5312         // "If the binding point for any uniform or shader storage block instance is less than zero, or greater than or
5313         // equal to the implementation-dependent maximum number of uniform buffer bindings, a compile-time
5314         // error will occur. When the binding identifier is used with a uniform or shader storage block instanced as
5315         // an array of size N, all elements of the array from binding through binding + N - 1 must be within this
5316         // range."
5317         //
5318         if (! type.isOpaque() && type.getBasicType() != EbtBlock)
5319             error(loc, "requires block, or sampler/image, or atomic-counter type", "binding", "");
5320         if (type.getBasicType() == EbtSampler) {
5321             int lastBinding = qualifier.layoutBinding;
5322             if (type.isArray()) {
5323                 if (spvVersion.vulkan > 0)
5324                     lastBinding += 1;
5325                 else {
5326                     if (type.isSizedArray())
5327                         lastBinding += type.getCumulativeArraySize();
5328                     else {
5329                         lastBinding += 1;
5330                         if (spvVersion.vulkan == 0)
5331                             warn(loc, "assuming binding count of one for compile-time checking of binding numbers for unsized array", "[]", "");
5332                     }
5333                 }
5334             }
5335             if (spvVersion.vulkan == 0 && lastBinding >= resources.maxCombinedTextureImageUnits)
5336                 error(loc, "sampler binding not less than gl_MaxCombinedTextureImageUnits", "binding", type.isArray() ? "(using array)" : "");
5337         }
5338         if (type.getBasicType() == EbtAtomicUint) {
5339             if (qualifier.layoutBinding >= (unsigned int)resources.maxAtomicCounterBindings) {
5340                 error(loc, "atomic_uint binding is too large; see gl_MaxAtomicCounterBindings", "binding", "");
5341                 return;
5342             }
5343         }
5344     } else if (!intermediate.getAutoMapBindings()) {
5345         // some types require bindings
5346
5347         // atomic_uint
5348         if (type.getBasicType() == EbtAtomicUint)
5349             error(loc, "layout(binding=X) is required", "atomic_uint", "");
5350
5351         // SPIR-V
5352         if (spvVersion.spv > 0) {
5353             if (qualifier.isUniformOrBuffer()) {
5354                 if (type.getBasicType() == EbtBlock && !qualifier.layoutPushConstant &&
5355 #ifdef NV_EXTENSIONS
5356                        !qualifier.layoutShaderRecordNV &&
5357 #endif
5358                        !qualifier.layoutAttachment)
5359                     error(loc, "uniform/buffer blocks require layout(binding=X)", "binding", "");
5360                 else if (spvVersion.vulkan > 0 && type.getBasicType() == EbtSampler)
5361                     error(loc, "sampler/texture/image requires layout(binding=X)", "binding", "");
5362             }
5363         }
5364     }
5365
5366     // some things can't have arrays of arrays
5367     if (type.isArrayOfArrays()) {
5368         if (spvVersion.vulkan > 0) {
5369             if (type.isOpaque() || (type.getQualifier().isUniformOrBuffer() && type.getBasicType() == EbtBlock))
5370                 warn(loc, "Generating SPIR-V array-of-arrays, but Vulkan only supports single array level for this resource", "[][]", "");
5371         }
5372     }
5373
5374     // "The offset qualifier can only be used on block members of blocks..."
5375     if (qualifier.hasOffset()) {
5376         if (type.getBasicType() == EbtBlock)
5377             error(loc, "only applies to block members, not blocks", "offset", "");
5378     }
5379
5380     // Image format
5381     if (qualifier.hasFormat()) {
5382         if (! type.isImage())
5383             error(loc, "only apply to images", TQualifier::getLayoutFormatString(qualifier.layoutFormat), "");
5384         else {
5385             if (type.getSampler().type == EbtFloat && qualifier.layoutFormat > ElfFloatGuard)
5386                 error(loc, "does not apply to floating point images", TQualifier::getLayoutFormatString(qualifier.layoutFormat), "");
5387             if (type.getSampler().type == EbtInt && (qualifier.layoutFormat < ElfFloatGuard || qualifier.layoutFormat > ElfIntGuard))
5388                 error(loc, "does not apply to signed integer images", TQualifier::getLayoutFormatString(qualifier.layoutFormat), "");
5389             if (type.getSampler().type == EbtUint && qualifier.layoutFormat < ElfIntGuard)
5390                 error(loc, "does not apply to unsigned integer images", TQualifier::getLayoutFormatString(qualifier.layoutFormat), "");
5391
5392             if (profile == EEsProfile) {
5393                 // "Except for image variables qualified with the format qualifiers r32f, r32i, and r32ui, image variables must
5394                 // specify either memory qualifier readonly or the memory qualifier writeonly."
5395                 if (! (qualifier.layoutFormat == ElfR32f || qualifier.layoutFormat == ElfR32i || qualifier.layoutFormat == ElfR32ui)) {
5396                     if (! qualifier.readonly && ! qualifier.writeonly)
5397                         error(loc, "format requires readonly or writeonly memory qualifier", TQualifier::getLayoutFormatString(qualifier.layoutFormat), "");
5398                 }
5399             }
5400         }
5401     } else if (type.isImage() && ! qualifier.writeonly) {
5402         const char *explanation = "image variables not declared 'writeonly' and without a format layout qualifier";
5403         requireProfile(loc, ECoreProfile | ECompatibilityProfile, explanation);
5404         profileRequires(loc, ECoreProfile | ECompatibilityProfile, 0, E_GL_EXT_shader_image_load_formatted, explanation);
5405     }
5406
5407     if (qualifier.layoutPushConstant && type.getBasicType() != EbtBlock)
5408         error(loc, "can only be used with a block", "push_constant", "");
5409
5410 #ifdef NV_EXTENSIONS
5411     if (qualifier.layoutShaderRecordNV && type.getBasicType() != EbtBlock)
5412         error(loc, "can only be used with a block", "shaderRecordNVX", "");
5413 #endif
5414
5415     // input attachment
5416     if (type.isSubpass()) {
5417         if (! qualifier.hasAttachment())
5418             error(loc, "requires an input_attachment_index layout qualifier", "subpass", "");
5419     } else {
5420         if (qualifier.hasAttachment())
5421             error(loc, "can only be used with a subpass", "input_attachment_index", "");
5422     }
5423
5424     // specialization-constant id
5425     if (qualifier.hasSpecConstantId()) {
5426         if (type.getQualifier().storage != EvqConst)
5427             error(loc, "can only be applied to 'const'-qualified scalar", "constant_id", "");
5428         if (! type.isScalar())
5429             error(loc, "can only be applied to a scalar", "constant_id", "");
5430         switch (type.getBasicType())
5431         {
5432         case EbtInt8:
5433         case EbtUint8:
5434         case EbtInt16:
5435         case EbtUint16:
5436         case EbtInt:
5437         case EbtUint:
5438         case EbtInt64:
5439         case EbtUint64:
5440         case EbtBool:
5441         case EbtFloat:
5442         case EbtDouble:
5443         case EbtFloat16:
5444             break;
5445         default:
5446             error(loc, "cannot be applied to this type", "constant_id", "");
5447             break;
5448         }
5449     }
5450 }
5451
5452 // Do layout error checking that can be done within a layout qualifier proper, not needing to know
5453 // if there are blocks, atomic counters, variables, etc.
5454 void TParseContext::layoutQualifierCheck(const TSourceLoc& loc, const TQualifier& qualifier)
5455 {
5456     if (qualifier.storage == EvqShared && qualifier.hasLayout())
5457         error(loc, "cannot apply layout qualifiers to a shared variable", "shared", "");
5458
5459     // "It is a compile-time error to use *component* without also specifying the location qualifier (order does not matter)."
5460     if (qualifier.hasComponent() && ! qualifier.hasLocation())
5461         error(loc, "must specify 'location' to use 'component'", "component", "");
5462
5463     if (qualifier.hasAnyLocation()) {
5464
5465         // "As with input layout qualifiers, all shaders except compute shaders
5466         // allow *location* layout qualifiers on output variable declarations,
5467         // output block declarations, and output block member declarations."
5468
5469         switch (qualifier.storage) {
5470         case EvqVaryingIn:
5471         {
5472             const char* feature = "location qualifier on input";
5473             if (profile == EEsProfile && version < 310)
5474                 requireStage(loc, EShLangVertex, feature);
5475             else
5476                 requireStage(loc, (EShLanguageMask)~EShLangComputeMask, feature);
5477             if (language == EShLangVertex) {
5478                 const char* exts[2] = { E_GL_ARB_separate_shader_objects, E_GL_ARB_explicit_attrib_location };
5479                 profileRequires(loc, ~EEsProfile, 330, 2, exts, feature);
5480                 profileRequires(loc, EEsProfile, 300, nullptr, feature);
5481             } else {
5482                 profileRequires(loc, ~EEsProfile, 410, E_GL_ARB_separate_shader_objects, feature);
5483                 profileRequires(loc, EEsProfile, 310, nullptr, feature);
5484             }
5485             break;
5486         }
5487         case EvqVaryingOut:
5488         {
5489             const char* feature = "location qualifier on output";
5490             if (profile == EEsProfile && version < 310)
5491                 requireStage(loc, EShLangFragment, feature);
5492             else
5493                 requireStage(loc, (EShLanguageMask)~EShLangComputeMask, feature);
5494             if (language == EShLangFragment) {
5495                 const char* exts[2] = { E_GL_ARB_separate_shader_objects, E_GL_ARB_explicit_attrib_location };
5496                 profileRequires(loc, ~EEsProfile, 330, 2, exts, feature);
5497                 profileRequires(loc, EEsProfile, 300, nullptr, feature);
5498             } else {
5499                 profileRequires(loc, ~EEsProfile, 410, E_GL_ARB_separate_shader_objects, feature);
5500                 profileRequires(loc, EEsProfile, 310, nullptr, feature);
5501             }
5502             break;
5503         }
5504         case EvqUniform:
5505         case EvqBuffer:
5506         {
5507             const char* feature = "location qualifier on uniform or buffer";
5508             requireProfile(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, feature);
5509             profileRequires(loc, ECoreProfile | ECompatibilityProfile, 430, nullptr, feature);
5510             profileRequires(loc, EEsProfile, 310, nullptr, feature);
5511             break;
5512         }
5513         default:
5514             break;
5515         }
5516         if (qualifier.hasIndex()) {
5517             if (qualifier.storage != EvqVaryingOut)
5518                 error(loc, "can only be used on an output", "index", "");
5519             if (! qualifier.hasLocation())
5520                 error(loc, "can only be used with an explicit location", "index", "");
5521         }
5522     }
5523
5524     if (qualifier.hasBinding()) {
5525         if (! qualifier.isUniformOrBuffer() && !qualifier.isTaskMemory())
5526             error(loc, "requires uniform or buffer storage qualifier", "binding", "");
5527     }
5528     if (qualifier.hasStream()) {
5529         if (!qualifier.isPipeOutput())
5530             error(loc, "can only be used on an output", "stream", "");
5531     }
5532     if (qualifier.hasXfb()) {
5533         if (!qualifier.isPipeOutput())
5534             error(loc, "can only be used on an output", "xfb layout qualifier", "");
5535     }
5536     if (qualifier.hasUniformLayout()) {
5537         if (! qualifier.isUniformOrBuffer() && !qualifier.isTaskMemory()) {
5538             if (qualifier.hasMatrix() || qualifier.hasPacking())
5539                 error(loc, "matrix or packing qualifiers can only be used on a uniform or buffer", "layout", "");
5540             if (qualifier.hasOffset() || qualifier.hasAlign())
5541                 error(loc, "offset/align can only be used on a uniform or buffer", "layout", "");
5542         }
5543     }
5544     if (qualifier.layoutPushConstant) {
5545         if (qualifier.storage != EvqUniform)
5546             error(loc, "can only be used with a uniform", "push_constant", "");
5547         if (qualifier.hasSet())
5548             error(loc, "cannot be used with push_constant", "set", "");
5549     }
5550 #ifdef NV_EXTENSIONS
5551     if (qualifier.layoutShaderRecordNV) {
5552         if (qualifier.storage != EvqBuffer)
5553             error(loc, "can only be used with a buffer", "shaderRecordNVX", "");
5554         if (qualifier.hasBinding())
5555             error(loc, "cannot be used with shaderRecordNVX", "binding", "");
5556         if (qualifier.hasSet())
5557             error(loc, "cannot be used with shaderRecordNVX", "set", "");
5558     }
5559 #endif
5560 }
5561
5562 // For places that can't have shader-level layout qualifiers
5563 void TParseContext::checkNoShaderLayouts(const TSourceLoc& loc, const TShaderQualifiers& shaderQualifiers)
5564 {
5565     const char* message = "can only apply to a standalone qualifier";
5566
5567     if (shaderQualifiers.geometry != ElgNone)
5568         error(loc, message, TQualifier::getGeometryString(shaderQualifiers.geometry), "");
5569     if (shaderQualifiers.spacing != EvsNone)
5570         error(loc, message, TQualifier::getVertexSpacingString(shaderQualifiers.spacing), "");
5571     if (shaderQualifiers.order != EvoNone)
5572         error(loc, message, TQualifier::getVertexOrderString(shaderQualifiers.order), "");
5573     if (shaderQualifiers.pointMode)
5574         error(loc, message, "point_mode", "");
5575     if (shaderQualifiers.invocations != TQualifier::layoutNotSet)
5576         error(loc, message, "invocations", "");
5577     if (shaderQualifiers.earlyFragmentTests)
5578         error(loc, message, "early_fragment_tests", "");
5579     if (shaderQualifiers.postDepthCoverage)
5580         error(loc, message, "post_depth_coverage", "");
5581     for (int i = 0; i < 3; ++i) {
5582         if (shaderQualifiers.localSize[i] > 1)
5583             error(loc, message, "local_size", "");
5584         if (shaderQualifiers.localSizeSpecId[i] != TQualifier::layoutNotSet)
5585             error(loc, message, "local_size id", "");
5586     }
5587     if (shaderQualifiers.vertices != TQualifier::layoutNotSet) {
5588         if (language == EShLangGeometry
5589 #ifdef NV_EXTENSIONS
5590             || language == EShLangMeshNV
5591 #endif
5592            )
5593             error(loc, message, "max_vertices", "");
5594         else if (language == EShLangTessControl)
5595             error(loc, message, "vertices", "");
5596         else
5597             assert(0);
5598     }
5599 #ifdef NV_EXTENSIONS
5600     if (shaderQualifiers.primitives != TQualifier::layoutNotSet) {
5601         if (language == EShLangMeshNV)
5602             error(loc, message, "max_primitives", "");
5603         else
5604             assert(0);
5605     }
5606 #endif
5607     if (shaderQualifiers.blendEquation)
5608         error(loc, message, "blend equation", "");
5609     if (shaderQualifiers.numViews != TQualifier::layoutNotSet)
5610         error(loc, message, "num_views", "");
5611 }
5612
5613 // Correct and/or advance an object's offset layout qualifier.
5614 void TParseContext::fixOffset(const TSourceLoc& loc, TSymbol& symbol)
5615 {
5616     const TQualifier& qualifier = symbol.getType().getQualifier();
5617     if (symbol.getType().getBasicType() == EbtAtomicUint) {
5618         if (qualifier.hasBinding() && (int)qualifier.layoutBinding < resources.maxAtomicCounterBindings) {
5619
5620             // Set the offset
5621             int offset;
5622             if (qualifier.hasOffset())
5623                 offset = qualifier.layoutOffset;
5624             else
5625                 offset = atomicUintOffsets[qualifier.layoutBinding];
5626             symbol.getWritableType().getQualifier().layoutOffset = offset;
5627
5628             // Check for overlap
5629             int numOffsets = 4;
5630             if (symbol.getType().isArray()) {
5631                 if (symbol.getType().isSizedArray() && !symbol.getType().getArraySizes()->isInnerUnsized())
5632                     numOffsets *= symbol.getType().getCumulativeArraySize();
5633                 else {
5634                     // "It is a compile-time error to declare an unsized array of atomic_uint."
5635                     error(loc, "array must be explicitly sized", "atomic_uint", "");
5636                 }
5637             }
5638             int repeated = intermediate.addUsedOffsets(qualifier.layoutBinding, offset, numOffsets);
5639             if (repeated >= 0)
5640                 error(loc, "atomic counters sharing the same offset:", "offset", "%d", repeated);
5641
5642             // Bump the default offset
5643             atomicUintOffsets[qualifier.layoutBinding] = offset + numOffsets;
5644         }
5645     }
5646 }
5647
5648 //
5649 // Look up a function name in the symbol table, and make sure it is a function.
5650 //
5651 // Return the function symbol if found, otherwise nullptr.
5652 //
5653 const TFunction* TParseContext::findFunction(const TSourceLoc& loc, const TFunction& call, bool& builtIn)
5654 {
5655     const TFunction* function = nullptr;
5656
5657     if (symbolTable.isFunctionNameVariable(call.getName())) {
5658         error(loc, "can't use function syntax on variable", call.getName().c_str(), "");
5659         return nullptr;
5660     }
5661
5662     bool explicitTypesEnabled = extensionTurnedOn(E_GL_KHX_shader_explicit_arithmetic_types) ||
5663                                 extensionTurnedOn(E_GL_KHX_shader_explicit_arithmetic_types_int8) ||
5664                                 extensionTurnedOn(E_GL_KHX_shader_explicit_arithmetic_types_int16) ||
5665                                 extensionTurnedOn(E_GL_KHX_shader_explicit_arithmetic_types_int32) ||
5666                                 extensionTurnedOn(E_GL_KHX_shader_explicit_arithmetic_types_int64) ||
5667                                 extensionTurnedOn(E_GL_KHX_shader_explicit_arithmetic_types_float16) ||
5668                                 extensionTurnedOn(E_GL_KHX_shader_explicit_arithmetic_types_float32) ||
5669                                 extensionTurnedOn(E_GL_KHX_shader_explicit_arithmetic_types_float64);
5670
5671     if (profile == EEsProfile || version < 120)
5672         function = findFunctionExact(loc, call, builtIn);
5673     else if (version < 400)
5674         function = findFunction120(loc, call, builtIn);
5675     else if (explicitTypesEnabled)
5676         function = findFunctionExplicitTypes(loc, call, builtIn);
5677     else
5678         function = findFunction400(loc, call, builtIn);
5679
5680     return function;
5681 }
5682
5683 // Function finding algorithm for ES and desktop 110.
5684 const TFunction* TParseContext::findFunctionExact(const TSourceLoc& loc, const TFunction& call, bool& builtIn)
5685 {
5686     TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn);
5687     if (symbol == nullptr) {
5688         error(loc, "no matching overloaded function found", call.getName().c_str(), "");
5689
5690         return nullptr;
5691     }
5692
5693     return symbol->getAsFunction();
5694 }
5695
5696 // Function finding algorithm for desktop versions 120 through 330.
5697 const TFunction* TParseContext::findFunction120(const TSourceLoc& loc, const TFunction& call, bool& builtIn)
5698 {
5699     // first, look for an exact match
5700     TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn);
5701     if (symbol)
5702         return symbol->getAsFunction();
5703
5704     // exact match not found, look through a list of overloaded functions of the same name
5705
5706     // "If no exact match is found, then [implicit conversions] will be applied to find a match. Mismatched types
5707     // on input parameters (in or inout or default) must have a conversion from the calling argument type to the
5708     // formal parameter type. Mismatched types on output parameters (out or inout) must have a conversion
5709     // from the formal parameter type to the calling argument type.  When argument conversions are used to find
5710     // a match, it is a semantic error if there are multiple ways to apply these conversions to make the call match
5711     // more than one function."
5712
5713     const TFunction* candidate = nullptr;
5714     TVector<const TFunction*> candidateList;
5715     symbolTable.findFunctionNameList(call.getMangledName(), candidateList, builtIn);
5716
5717     for (auto it = candidateList.begin(); it != candidateList.end(); ++it) {
5718         const TFunction& function = *(*it);
5719
5720         // to even be a potential match, number of arguments has to match
5721         if (call.getParamCount() != function.getParamCount())
5722             continue;
5723
5724         bool possibleMatch = true;
5725         for (int i = 0; i < function.getParamCount(); ++i) {
5726             // same types is easy
5727             if (*function[i].type == *call[i].type)
5728                 continue;
5729
5730             // We have a mismatch in type, see if it is implicitly convertible
5731
5732             if (function[i].type->isArray() || call[i].type->isArray() ||
5733                 ! function[i].type->sameElementShape(*call[i].type))
5734                 possibleMatch = false;
5735             else {
5736                 // do direction-specific checks for conversion of basic type
5737                 if (function[i].type->getQualifier().isParamInput()) {
5738                     if (! intermediate.canImplicitlyPromote(call[i].type->getBasicType(), function[i].type->getBasicType()))
5739                         possibleMatch = false;
5740                 }
5741                 if (function[i].type->getQualifier().isParamOutput()) {
5742                     if (! intermediate.canImplicitlyPromote(function[i].type->getBasicType(), call[i].type->getBasicType()))
5743                         possibleMatch = false;
5744                 }
5745             }
5746             if (! possibleMatch)
5747                 break;
5748         }
5749         if (possibleMatch) {
5750             if (candidate) {
5751                 // our second match, meaning ambiguity
5752                 error(loc, "ambiguous function signature match: multiple signatures match under implicit type conversion", call.getName().c_str(), "");
5753             } else
5754                 candidate = &function;
5755         }
5756     }
5757
5758     if (candidate == nullptr)
5759         error(loc, "no matching overloaded function found", call.getName().c_str(), "");
5760
5761     return candidate;
5762 }
5763
5764 // Function finding algorithm for desktop version 400 and above.
5765 //
5766 // "When function calls are resolved, an exact type match for all the arguments
5767 // is sought. If an exact match is found, all other functions are ignored, and
5768 // the exact match is used. If no exact match is found, then the implicit
5769 // conversions in section 4.1.10 Implicit Conversions will be applied to find
5770 // a match. Mismatched types on input parameters (in or inout or default) must
5771 // have a conversion from the calling argument type to the formal parameter type.
5772 // Mismatched types on output parameters (out or inout) must have a conversion
5773 // from the formal parameter type to the calling argument type.
5774 //
5775 // "If implicit conversions can be used to find more than one matching function,
5776 // a single best-matching function is sought. To determine a best match, the
5777 // conversions between calling argument and formal parameter types are compared
5778 // for each function argument and pair of matching functions. After these
5779 // comparisons are performed, each pair of matching functions are compared.
5780 // A function declaration A is considered a better match than function
5781 // declaration B if
5782 //
5783 //  * for at least one function argument, the conversion for that argument in A
5784 //    is better than the corresponding conversion in B; and
5785 //  * there is no function argument for which the conversion in B is better than
5786 //    the corresponding conversion in A.
5787 //
5788 // "If a single function declaration is considered a better match than every
5789 // other matching function declaration, it will be used. Otherwise, a
5790 // compile-time semantic error for an ambiguous overloaded function call occurs.
5791 //
5792 // "To determine whether the conversion for a single argument in one match is
5793 // better than that for another match, the following rules are applied, in order:
5794 //
5795 //  1. An exact match is better than a match involving any implicit conversion.
5796 //  2. A match involving an implicit conversion from float to double is better
5797 //     than a match involving any other implicit conversion.
5798 //  3. A match involving an implicit conversion from either int or uint to float
5799 //     is better than a match involving an implicit conversion from either int
5800 //     or uint to double.
5801 //
5802 // "If none of the rules above apply to a particular pair of conversions, neither
5803 // conversion is considered better than the other."
5804 //
5805 const TFunction* TParseContext::findFunction400(const TSourceLoc& loc, const TFunction& call, bool& builtIn)
5806 {
5807     // first, look for an exact match
5808     TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn);
5809     if (symbol)
5810         return symbol->getAsFunction();
5811
5812     // no exact match, use the generic selector, parameterized by the GLSL rules
5813
5814     // create list of candidates to send
5815     TVector<const TFunction*> candidateList;
5816     symbolTable.findFunctionNameList(call.getMangledName(), candidateList, builtIn);
5817
5818     // can 'from' convert to 'to'?
5819     const auto convertible = [this](const TType& from, const TType& to, TOperator, int) -> bool {
5820         if (from == to)
5821             return true;
5822         if (from.isArray() || to.isArray() || ! from.sameElementShape(to))
5823             return false;
5824         return intermediate.canImplicitlyPromote(from.getBasicType(), to.getBasicType());
5825     };
5826
5827     // Is 'to2' a better conversion than 'to1'?
5828     // Ties should not be considered as better.
5829     // Assumes 'convertible' already said true.
5830     const auto better = [](const TType& from, const TType& to1, const TType& to2) -> bool {
5831         // 1. exact match
5832         if (from == to2)
5833             return from != to1;
5834         if (from == to1)
5835             return false;
5836
5837         // 2. float -> double is better
5838         if (from.getBasicType() == EbtFloat) {
5839             if (to2.getBasicType() == EbtDouble && to1.getBasicType() != EbtDouble)
5840                 return true;
5841         }
5842
5843         // 3. -> float is better than -> double
5844         return to2.getBasicType() == EbtFloat && to1.getBasicType() == EbtDouble;
5845     };
5846
5847     // for ambiguity reporting
5848     bool tie = false;
5849
5850     // send to the generic selector
5851     const TFunction* bestMatch = selectFunction(candidateList, call, convertible, better, tie);
5852
5853     if (bestMatch == nullptr)
5854         error(loc, "no matching overloaded function found", call.getName().c_str(), "");
5855     else if (tie)
5856         error(loc, "ambiguous best function under implicit type conversion", call.getName().c_str(), "");
5857
5858     return bestMatch;
5859 }
5860
5861 // "To determine whether the conversion for a single argument in one match
5862 //  is better than that for another match, the conversion is assigned of the
5863 //  three ranks ordered from best to worst:
5864 //   1. Exact match: no conversion.
5865 //    2. Promotion: integral or floating-point promotion.
5866 //    3. Conversion: integral conversion, floating-point conversion,
5867 //       floating-integral conversion.
5868 //  A conversion C1 is better than a conversion C2 if the rank of C1 is
5869 //  better than the rank of C2."
5870 const TFunction* TParseContext::findFunctionExplicitTypes(const TSourceLoc& loc, const TFunction& call, bool& builtIn)
5871 {
5872     // first, look for an exact match
5873     TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn);
5874     if (symbol)
5875         return symbol->getAsFunction();
5876
5877     // no exact match, use the generic selector, parameterized by the GLSL rules
5878
5879     // create list of candidates to send
5880     TVector<const TFunction*> candidateList;
5881     symbolTable.findFunctionNameList(call.getMangledName(), candidateList, builtIn);
5882
5883     // can 'from' convert to 'to'?
5884     const auto convertible = [this](const TType& from, const TType& to, TOperator, int) -> bool {
5885         if (from == to)
5886             return true;
5887         if (from.isArray() || to.isArray() || ! from.sameElementShape(to))
5888             return false;
5889         return intermediate.canImplicitlyPromote(from.getBasicType(), to.getBasicType());
5890     };
5891
5892     // Is 'to2' a better conversion than 'to1'?
5893     // Ties should not be considered as better.
5894     // Assumes 'convertible' already said true.
5895     const auto better = [this](const TType& from, const TType& to1, const TType& to2) -> bool {
5896         // 1. exact match
5897         if (from == to2)
5898             return from != to1;
5899         if (from == to1)
5900             return false;
5901
5902         // 2. Promotion (integral, floating-point) is better
5903         TBasicType from_type = from.getBasicType();
5904         TBasicType to1_type = to1.getBasicType();
5905         TBasicType to2_type = to2.getBasicType();
5906         bool isPromotion1 = (intermediate.isIntegralPromotion(from_type, to1_type) ||
5907                              intermediate.isFPPromotion(from_type, to1_type));
5908         bool isPromotion2 = (intermediate.isIntegralPromotion(from_type, to2_type) ||
5909                              intermediate.isFPPromotion(from_type, to2_type));
5910         if (isPromotion2)
5911             return !isPromotion1;
5912         if(isPromotion1)
5913             return false;
5914
5915         // 3. Conversion (integral, floating-point , floating-integral)
5916         bool isConversion1 = (intermediate.isIntegralConversion(from_type, to1_type) ||
5917                               intermediate.isFPConversion(from_type, to1_type) ||
5918                               intermediate.isFPIntegralConversion(from_type, to1_type));
5919         bool isConversion2 = (intermediate.isIntegralConversion(from_type, to2_type) ||
5920                               intermediate.isFPConversion(from_type, to2_type) ||
5921                               intermediate.isFPIntegralConversion(from_type, to2_type));
5922
5923         return isConversion2 && !isConversion1;
5924     };
5925
5926     // for ambiguity reporting
5927     bool tie = false;
5928
5929     // send to the generic selector
5930     const TFunction* bestMatch = selectFunction(candidateList, call, convertible, better, tie);
5931
5932     if (bestMatch == nullptr)
5933         error(loc, "no matching overloaded function found", call.getName().c_str(), "");
5934     else if (tie)
5935         error(loc, "ambiguous best function under implicit type conversion", call.getName().c_str(), "");
5936
5937     return bestMatch;
5938 }
5939
5940 // When a declaration includes a type, but not a variable name, it can be
5941 // to establish defaults.
5942 void TParseContext::declareTypeDefaults(const TSourceLoc& loc, const TPublicType& publicType)
5943 {
5944     if (publicType.basicType == EbtAtomicUint && publicType.qualifier.hasBinding() && publicType.qualifier.hasOffset()) {
5945         if (publicType.qualifier.layoutBinding >= (unsigned int)resources.maxAtomicCounterBindings) {
5946             error(loc, "atomic_uint binding is too large", "binding", "");
5947             return;
5948         }
5949         atomicUintOffsets[publicType.qualifier.layoutBinding] = publicType.qualifier.layoutOffset;
5950         return;
5951     }
5952
5953     if (publicType.qualifier.hasLayout())
5954         warn(loc, "useless application of layout qualifier", "layout", "");
5955 }
5956
5957 //
5958 // Do everything necessary to handle a variable (non-block) declaration.
5959 // Either redeclaring a variable, or making a new one, updating the symbol
5960 // table, and all error checking.
5961 //
5962 // Returns a subtree node that computes an initializer, if needed.
5963 // Returns nullptr if there is no code to execute for initialization.
5964 //
5965 // 'publicType' is the type part of the declaration (to the left)
5966 // 'arraySizes' is the arrayness tagged on the identifier (to the right)
5967 //
5968 TIntermNode* TParseContext::declareVariable(const TSourceLoc& loc, TString& identifier, const TPublicType& publicType,
5969     TArraySizes* arraySizes, TIntermTyped* initializer)
5970 {
5971     // Make a fresh type that combines the characteristics from the individual
5972     // identifier syntax and the declaration-type syntax.
5973     TType type(publicType);
5974     type.transferArraySizes(arraySizes);
5975     type.copyArrayInnerSizes(publicType.arraySizes);
5976     arrayOfArrayVersionCheck(loc, type.getArraySizes());
5977
5978     if (voidErrorCheck(loc, identifier, type.getBasicType()))
5979         return nullptr;
5980
5981     if (initializer)
5982         rValueErrorCheck(loc, "initializer", initializer);
5983     else
5984         nonInitConstCheck(loc, identifier, type);
5985
5986     samplerCheck(loc, type, identifier, initializer);
5987     atomicUintCheck(loc, type, identifier);
5988     transparentOpaqueCheck(loc, type, identifier);
5989 #ifdef NV_EXTENSIONS
5990     accStructNVCheck(loc, type, identifier);
5991 #endif
5992
5993     if (type.getQualifier().storage != EvqUniform && type.getQualifier().storage != EvqBuffer) {
5994         if (type.containsBasicType(EbtFloat16))
5995             requireFloat16Arithmetic(loc, "qualifier", "float16 types can only be in uniform block or buffer storage");
5996         if (type.contains16BitInt())
5997             requireInt16Arithmetic(loc, "qualifier", "(u)int16 types can only be in uniform block or buffer storage");
5998         if (type.contains8BitInt())
5999             requireInt8Arithmetic(loc, "qualifier", "(u)int8 types can only be in uniform block or buffer storage");
6000     }
6001
6002     if (identifier != "gl_FragCoord" && (publicType.shaderQualifiers.originUpperLeft || publicType.shaderQualifiers.pixelCenterInteger))
6003         error(loc, "can only apply origin_upper_left and pixel_center_origin to gl_FragCoord", "layout qualifier", "");
6004     if (identifier != "gl_FragDepth" && publicType.shaderQualifiers.layoutDepth != EldNone)
6005         error(loc, "can only apply depth layout to gl_FragDepth", "layout qualifier", "");
6006
6007     // Check for redeclaration of built-ins and/or attempting to declare a reserved name
6008     TSymbol* symbol = redeclareBuiltinVariable(loc, identifier, type.getQualifier(), publicType.shaderQualifiers);
6009     if (symbol == nullptr)
6010         reservedErrorCheck(loc, identifier);
6011
6012     inheritGlobalDefaults(type.getQualifier());
6013
6014     // Declare the variable
6015     if (type.isArray()) {
6016         // Check that implicit sizing is only where allowed.
6017         arraySizesCheck(loc, type.getQualifier(), type.getArraySizes(), initializer, false);
6018
6019         if (! arrayQualifierError(loc, type.getQualifier()) && ! arrayError(loc, type))
6020             declareArray(loc, identifier, type, symbol);
6021
6022         if (initializer) {
6023             profileRequires(loc, ENoProfile, 120, E_GL_3DL_array_objects, "initializer");
6024             profileRequires(loc, EEsProfile, 300, nullptr, "initializer");
6025         }
6026     } else {
6027         // non-array case
6028         if (symbol == nullptr)
6029             symbol = declareNonArray(loc, identifier, type);
6030         else if (type != symbol->getType())
6031             error(loc, "cannot change the type of", "redeclaration", symbol->getName().c_str());
6032     }
6033
6034     if (symbol == nullptr)
6035         return nullptr;
6036
6037     // Deal with initializer
6038     TIntermNode* initNode = nullptr;
6039     if (symbol != nullptr && initializer) {
6040         TVariable* variable = symbol->getAsVariable();
6041         if (! variable) {
6042             error(loc, "initializer requires a variable, not a member", identifier.c_str(), "");
6043             return nullptr;
6044         }
6045         initNode = executeInitializer(loc, initializer, variable);
6046     }
6047
6048     // look for errors in layout qualifier use
6049     layoutObjectCheck(loc, *symbol);
6050
6051     // fix up
6052     fixOffset(loc, *symbol);
6053
6054     return initNode;
6055 }
6056
6057 // Pick up global defaults from the provide global defaults into dst.
6058 void TParseContext::inheritGlobalDefaults(TQualifier& dst) const
6059 {
6060     if (dst.storage == EvqVaryingOut) {
6061         if (! dst.hasStream() && language == EShLangGeometry)
6062             dst.layoutStream = globalOutputDefaults.layoutStream;
6063         if (! dst.hasXfbBuffer())
6064             dst.layoutXfbBuffer = globalOutputDefaults.layoutXfbBuffer;
6065     }
6066 }
6067
6068 //
6069 // Make an internal-only variable whose name is for debug purposes only
6070 // and won't be searched for.  Callers will only use the return value to use
6071 // the variable, not the name to look it up.  It is okay if the name
6072 // is the same as other names; there won't be any conflict.
6073 //
6074 TVariable* TParseContext::makeInternalVariable(const char* name, const TType& type) const
6075 {
6076     TString* nameString = NewPoolTString(name);
6077     TVariable* variable = new TVariable(nameString, type);
6078     symbolTable.makeInternalVariable(*variable);
6079
6080     return variable;
6081 }
6082
6083 //
6084 // Declare a non-array variable, the main point being there is no redeclaration
6085 // for resizing allowed.
6086 //
6087 // Return the successfully declared variable.
6088 //
6089 TVariable* TParseContext::declareNonArray(const TSourceLoc& loc, const TString& identifier, const TType& type)
6090 {
6091     // make a new variable
6092     TVariable* variable = new TVariable(&identifier, type);
6093
6094     ioArrayCheck(loc, type, identifier);
6095
6096     // add variable to symbol table
6097     if (symbolTable.insert(*variable)) {
6098         if (symbolTable.atGlobalLevel())
6099             trackLinkage(*variable);
6100         return variable;
6101     }
6102
6103     error(loc, "redefinition", variable->getName().c_str(), "");
6104     return nullptr;
6105 }
6106
6107 //
6108 // Handle all types of initializers from the grammar.
6109 //
6110 // Returning nullptr just means there is no code to execute to handle the
6111 // initializer, which will, for example, be the case for constant initializers.
6112 //
6113 TIntermNode* TParseContext::executeInitializer(const TSourceLoc& loc, TIntermTyped* initializer, TVariable* variable)
6114 {
6115     //
6116     // Identifier must be of type constant, a global, or a temporary, and
6117     // starting at version 120, desktop allows uniforms to have initializers.
6118     //
6119     TStorageQualifier qualifier = variable->getType().getQualifier().storage;
6120     if (! (qualifier == EvqTemporary || qualifier == EvqGlobal || qualifier == EvqConst ||
6121            (qualifier == EvqUniform && profile != EEsProfile && version >= 120))) {
6122         error(loc, " cannot initialize this type of qualifier ", variable->getType().getStorageQualifierString(), "");
6123         return nullptr;
6124     }
6125     arrayObjectCheck(loc, variable->getType(), "array initializer");
6126
6127     //
6128     // If the initializer was from braces { ... }, we convert the whole subtree to a
6129     // constructor-style subtree, allowing the rest of the code to operate
6130     // identically for both kinds of initializers.
6131     //
6132     // Type can't be deduced from the initializer list, so a skeletal type to
6133     // follow has to be passed in.  Constness and specialization-constness
6134     // should be deduced bottom up, not dictated by the skeletal type.
6135     //
6136     TType skeletalType;
6137     skeletalType.shallowCopy(variable->getType());
6138     skeletalType.getQualifier().makeTemporary();
6139     initializer = convertInitializerList(loc, skeletalType, initializer);
6140     if (! initializer) {
6141         // error recovery; don't leave const without constant values
6142         if (qualifier == EvqConst)
6143             variable->getWritableType().getQualifier().makeTemporary();
6144         return nullptr;
6145     }
6146
6147     // Fix outer arrayness if variable is unsized, getting size from the initializer
6148     if (initializer->getType().isSizedArray() && variable->getType().isUnsizedArray())
6149         variable->getWritableType().changeOuterArraySize(initializer->getType().getOuterArraySize());
6150
6151     // Inner arrayness can also get set by an initializer
6152     if (initializer->getType().isArrayOfArrays() && variable->getType().isArrayOfArrays() &&
6153         initializer->getType().getArraySizes()->getNumDims() ==
6154            variable->getType().getArraySizes()->getNumDims()) {
6155         // adopt unsized sizes from the initializer's sizes
6156         for (int d = 1; d < variable->getType().getArraySizes()->getNumDims(); ++d) {
6157             if (variable->getType().getArraySizes()->getDimSize(d) == UnsizedArraySize) {
6158                 variable->getWritableType().getArraySizes()->setDimSize(d,
6159                     initializer->getType().getArraySizes()->getDimSize(d));
6160             }
6161         }
6162     }
6163
6164     // Uniforms require a compile-time constant initializer
6165     if (qualifier == EvqUniform && ! initializer->getType().getQualifier().isFrontEndConstant()) {
6166         error(loc, "uniform initializers must be constant", "=", "'%s'", variable->getType().getCompleteString().c_str());
6167         variable->getWritableType().getQualifier().makeTemporary();
6168         return nullptr;
6169     }
6170     // Global consts require a constant initializer (specialization constant is okay)
6171     if (qualifier == EvqConst && symbolTable.atGlobalLevel() && ! initializer->getType().getQualifier().isConstant()) {
6172         error(loc, "global const initializers must be constant", "=", "'%s'", variable->getType().getCompleteString().c_str());
6173         variable->getWritableType().getQualifier().makeTemporary();
6174         return nullptr;
6175     }
6176
6177     // Const variables require a constant initializer, depending on version
6178     if (qualifier == EvqConst) {
6179         if (! initializer->getType().getQualifier().isConstant()) {
6180             const char* initFeature = "non-constant initializer";
6181             requireProfile(loc, ~EEsProfile, initFeature);
6182             profileRequires(loc, ~EEsProfile, 420, E_GL_ARB_shading_language_420pack, initFeature);
6183             variable->getWritableType().getQualifier().storage = EvqConstReadOnly;
6184             qualifier = EvqConstReadOnly;
6185         }
6186     } else {
6187         // Non-const global variables in ES need a const initializer.
6188         //
6189         // "In declarations of global variables with no storage qualifier or with a const
6190         // qualifier any initializer must be a constant expression."
6191         if (symbolTable.atGlobalLevel() && ! initializer->getType().getQualifier().isConstant()) {
6192             const char* initFeature = "non-constant global initializer (needs GL_EXT_shader_non_constant_global_initializers)";
6193             if (profile == EEsProfile) {
6194                 if (relaxedErrors() && ! extensionTurnedOn(E_GL_EXT_shader_non_constant_global_initializers))
6195                     warn(loc, "not allowed in this version", initFeature, "");
6196                 else
6197                     profileRequires(loc, EEsProfile, 0, E_GL_EXT_shader_non_constant_global_initializers, initFeature);
6198             }
6199         }
6200     }
6201
6202     if (qualifier == EvqConst || qualifier == EvqUniform) {
6203         // Compile-time tagging of the variable with its constant value...
6204
6205         initializer = intermediate.addConversion(EOpAssign, variable->getType(), initializer);
6206         if (! initializer || ! initializer->getType().getQualifier().isConstant() || variable->getType() != initializer->getType()) {
6207             error(loc, "non-matching or non-convertible constant type for const initializer",
6208                   variable->getType().getStorageQualifierString(), "");
6209             variable->getWritableType().getQualifier().makeTemporary();
6210             return nullptr;
6211         }
6212
6213         // We either have a folded constant in getAsConstantUnion, or we have to use
6214         // the initializer's subtree in the AST to represent the computation of a
6215         // specialization constant.
6216         assert(initializer->getAsConstantUnion() || initializer->getType().getQualifier().isSpecConstant());
6217         if (initializer->getAsConstantUnion())
6218             variable->setConstArray(initializer->getAsConstantUnion()->getConstArray());
6219         else {
6220             // It's a specialization constant.
6221             variable->getWritableType().getQualifier().makeSpecConstant();
6222
6223             // Keep the subtree that computes the specialization constant with the variable.
6224             // Later, a symbol node will adopt the subtree from the variable.
6225             variable->setConstSubtree(initializer);
6226         }
6227     } else {
6228         // normal assigning of a value to a variable...
6229         specializationCheck(loc, initializer->getType(), "initializer");
6230         TIntermSymbol* intermSymbol = intermediate.addSymbol(*variable, loc);
6231         TIntermTyped* initNode = intermediate.addAssign(EOpAssign, intermSymbol, initializer, loc);
6232         if (! initNode)
6233             assignError(loc, "=", intermSymbol->getCompleteString(), initializer->getCompleteString());
6234
6235         return initNode;
6236     }
6237
6238     return nullptr;
6239 }
6240
6241 //
6242 // Reprocess any initializer-list (the  "{ ... }" syntax) parts of the
6243 // initializer.
6244 //
6245 // Need to hierarchically assign correct types and implicit
6246 // conversions. Will do this mimicking the same process used for
6247 // creating a constructor-style initializer, ensuring we get the
6248 // same form.  However, it has to in parallel walk the 'type'
6249 // passed in, as type cannot be deduced from an initializer list.
6250 //
6251 TIntermTyped* TParseContext::convertInitializerList(const TSourceLoc& loc, const TType& type, TIntermTyped* initializer)
6252 {
6253     // Will operate recursively.  Once a subtree is found that is constructor style,
6254     // everything below it is already good: Only the "top part" of the initializer
6255     // can be an initializer list, where "top part" can extend for several (or all) levels.
6256
6257     // see if we have bottomed out in the tree within the initializer-list part
6258     TIntermAggregate* initList = initializer->getAsAggregate();
6259     if (! initList || initList->getOp() != EOpNull)
6260         return initializer;
6261
6262     // Of the initializer-list set of nodes, need to process bottom up,
6263     // so recurse deep, then process on the way up.
6264
6265     // Go down the tree here...
6266     if (type.isArray()) {
6267         // The type's array might be unsized, which could be okay, so base sizes on the size of the aggregate.
6268         // Later on, initializer execution code will deal with array size logic.
6269         TType arrayType;
6270         arrayType.shallowCopy(type);                     // sharing struct stuff is fine
6271         arrayType.copyArraySizes(*type.getArraySizes());  // but get a fresh copy of the array information, to edit below
6272
6273         // edit array sizes to fill in unsized dimensions
6274         arrayType.changeOuterArraySize((int)initList->getSequence().size());
6275         TIntermTyped* firstInit = initList->getSequence()[0]->getAsTyped();
6276         if (arrayType.isArrayOfArrays() && firstInit->getType().isArray() &&
6277             arrayType.getArraySizes()->getNumDims() == firstInit->getType().getArraySizes()->getNumDims() + 1) {
6278             for (int d = 1; d < arrayType.getArraySizes()->getNumDims(); ++d) {
6279                 if (arrayType.getArraySizes()->getDimSize(d) == UnsizedArraySize)
6280                     arrayType.getArraySizes()->setDimSize(d, firstInit->getType().getArraySizes()->getDimSize(d - 1));
6281             }
6282         }
6283
6284         TType elementType(arrayType, 0); // dereferenced type
6285         for (size_t i = 0; i < initList->getSequence().size(); ++i) {
6286             initList->getSequence()[i] = convertInitializerList(loc, elementType, initList->getSequence()[i]->getAsTyped());
6287             if (initList->getSequence()[i] == nullptr)
6288                 return nullptr;
6289         }
6290
6291         return addConstructor(loc, initList, arrayType);
6292     } else if (type.isStruct()) {
6293         if (type.getStruct()->size() != initList->getSequence().size()) {
6294             error(loc, "wrong number of structure members", "initializer list", "");
6295             return nullptr;
6296         }
6297         for (size_t i = 0; i < type.getStruct()->size(); ++i) {
6298             initList->getSequence()[i] = convertInitializerList(loc, *(*type.getStruct())[i].type, initList->getSequence()[i]->getAsTyped());
6299             if (initList->getSequence()[i] == nullptr)
6300                 return nullptr;
6301         }
6302     } else if (type.isMatrix()) {
6303         if (type.getMatrixCols() != (int)initList->getSequence().size()) {
6304             error(loc, "wrong number of matrix columns:", "initializer list", type.getCompleteString().c_str());
6305             return nullptr;
6306         }
6307         TType vectorType(type, 0); // dereferenced type
6308         for (int i = 0; i < type.getMatrixCols(); ++i) {
6309             initList->getSequence()[i] = convertInitializerList(loc, vectorType, initList->getSequence()[i]->getAsTyped());
6310             if (initList->getSequence()[i] == nullptr)
6311                 return nullptr;
6312         }
6313     } else if (type.isVector()) {
6314         if (type.getVectorSize() != (int)initList->getSequence().size()) {
6315             error(loc, "wrong vector size (or rows in a matrix column):", "initializer list", type.getCompleteString().c_str());
6316             return nullptr;
6317         }
6318     } else {
6319         error(loc, "unexpected initializer-list type:", "initializer list", type.getCompleteString().c_str());
6320         return nullptr;
6321     }
6322
6323     // Now that the subtree is processed, process this node as if the
6324     // initializer list is a set of arguments to a constructor.
6325     TIntermNode* emulatedConstructorArguments;
6326     if (initList->getSequence().size() == 1)
6327         emulatedConstructorArguments = initList->getSequence()[0];
6328     else
6329         emulatedConstructorArguments = initList;
6330     return addConstructor(loc, emulatedConstructorArguments, type);
6331 }
6332
6333 //
6334 // Test for the correctness of the parameters passed to various constructor functions
6335 // and also convert them to the right data type, if allowed and required.
6336 //
6337 // 'node' is what to construct from.
6338 // 'type' is what type to construct.
6339 //
6340 // Returns nullptr for an error or the constructed node (aggregate or typed) for no error.
6341 //
6342 TIntermTyped* TParseContext::addConstructor(const TSourceLoc& loc, TIntermNode* node, const TType& type)
6343 {
6344     if (node == nullptr || node->getAsTyped() == nullptr)
6345         return nullptr;
6346     rValueErrorCheck(loc, "constructor", node->getAsTyped());
6347
6348     TIntermAggregate* aggrNode = node->getAsAggregate();
6349     TOperator op = intermediate.mapTypeToConstructorOp(type);
6350
6351     // Combined texture-sampler constructors are completely semantic checked
6352     // in constructorTextureSamplerError()
6353     if (op == EOpConstructTextureSampler) {
6354         if (aggrNode->getSequence()[1]->getAsTyped()->getType().getSampler().shadow) {
6355             // Transfer depth into the texture (SPIR-V image) type, as a hint
6356             // for tools to know this texture/image is a depth image.
6357             aggrNode->getSequence()[0]->getAsTyped()->getWritableType().getSampler().shadow = true;
6358         }
6359         return intermediate.setAggregateOperator(aggrNode, op, type, loc);
6360     }
6361
6362     TTypeList::const_iterator memberTypes;
6363     if (op == EOpConstructStruct)
6364         memberTypes = type.getStruct()->begin();
6365
6366     TType elementType;
6367     if (type.isArray()) {
6368         TType dereferenced(type, 0);
6369         elementType.shallowCopy(dereferenced);
6370     } else
6371         elementType.shallowCopy(type);
6372
6373     bool singleArg;
6374     if (aggrNode) {
6375         if (aggrNode->getOp() != EOpNull)
6376             singleArg = true;
6377         else
6378             singleArg = false;
6379     } else
6380         singleArg = true;
6381
6382     TIntermTyped *newNode;
6383     if (singleArg) {
6384         // If structure constructor or array constructor is being called
6385         // for only one parameter inside the structure, we need to call constructAggregate function once.
6386         if (type.isArray())
6387             newNode = constructAggregate(node, elementType, 1, node->getLoc());
6388         else if (op == EOpConstructStruct)
6389             newNode = constructAggregate(node, *(*memberTypes).type, 1, node->getLoc());
6390         else
6391             newNode = constructBuiltIn(type, op, node->getAsTyped(), node->getLoc(), false);
6392
6393         if (newNode && (type.isArray() || op == EOpConstructStruct))
6394             newNode = intermediate.setAggregateOperator(newNode, EOpConstructStruct, type, loc);
6395
6396         return newNode;
6397     }
6398
6399     //
6400     // Handle list of arguments.
6401     //
6402     TIntermSequence &sequenceVector = aggrNode->getSequence();    // Stores the information about the parameter to the constructor
6403     // if the structure constructor contains more than one parameter, then construct
6404     // each parameter
6405
6406     int paramCount = 0;  // keeps track of the constructor parameter number being checked
6407
6408     // for each parameter to the constructor call, check to see if the right type is passed or convert them
6409     // to the right type if possible (and allowed).
6410     // for structure constructors, just check if the right type is passed, no conversion is allowed.
6411     for (TIntermSequence::iterator p = sequenceVector.begin();
6412                                    p != sequenceVector.end(); p++, paramCount++) {
6413         if (type.isArray())
6414             newNode = constructAggregate(*p, elementType, paramCount+1, node->getLoc());
6415         else if (op == EOpConstructStruct)
6416             newNode = constructAggregate(*p, *(memberTypes[paramCount]).type, paramCount+1, node->getLoc());
6417         else
6418             newNode = constructBuiltIn(type, op, (*p)->getAsTyped(), node->getLoc(), true);
6419
6420         if (newNode)
6421             *p = newNode;
6422         else
6423             return nullptr;
6424     }
6425
6426     return intermediate.setAggregateOperator(aggrNode, op, type, loc);
6427 }
6428
6429 // Function for constructor implementation. Calls addUnaryMath with appropriate EOp value
6430 // for the parameter to the constructor (passed to this function). Essentially, it converts
6431 // the parameter types correctly. If a constructor expects an int (like ivec2) and is passed a
6432 // float, then float is converted to int.
6433 //
6434 // Returns nullptr for an error or the constructed node.
6435 //
6436 TIntermTyped* TParseContext::constructBuiltIn(const TType& type, TOperator op, TIntermTyped* node, const TSourceLoc& loc,
6437     bool subset)
6438 {
6439     // If we are changing a matrix in both domain of basic type and to a non matrix,
6440     // do the shape change first (by default, below, basic type is changed before shape).
6441     // This avoids requesting a matrix of a new type that is going to be discarded anyway.
6442     // TODO: This could be generalized to more type combinations, but that would require
6443     // more extensive testing and full algorithm rework. For now, the need to do two changes makes
6444     // the recursive call work, and avoids the most aggregious case of creating integer matrices.
6445     if (node->getType().isMatrix() && (type.isScalar() || type.isVector()) &&
6446             type.isFloatingDomain() != node->getType().isFloatingDomain()) {
6447         TType transitionType(node->getBasicType(), glslang::EvqTemporary, type.getVectorSize(), 0, 0, node->isVector());
6448         TOperator transitionOp = intermediate.mapTypeToConstructorOp(transitionType);
6449         node = constructBuiltIn(transitionType, transitionOp, node, loc, false);
6450     }
6451
6452     TIntermTyped* newNode;
6453     TOperator basicOp;
6454
6455     //
6456     // First, convert types as needed.
6457     //
6458     switch (op) {
6459     case EOpConstructVec2:
6460     case EOpConstructVec3:
6461     case EOpConstructVec4:
6462     case EOpConstructMat2x2:
6463     case EOpConstructMat2x3:
6464     case EOpConstructMat2x4:
6465     case EOpConstructMat3x2:
6466     case EOpConstructMat3x3:
6467     case EOpConstructMat3x4:
6468     case EOpConstructMat4x2:
6469     case EOpConstructMat4x3:
6470     case EOpConstructMat4x4:
6471     case EOpConstructFloat:
6472         basicOp = EOpConstructFloat;
6473         break;
6474
6475     case EOpConstructDVec2:
6476     case EOpConstructDVec3:
6477     case EOpConstructDVec4:
6478     case EOpConstructDMat2x2:
6479     case EOpConstructDMat2x3:
6480     case EOpConstructDMat2x4:
6481     case EOpConstructDMat3x2:
6482     case EOpConstructDMat3x3:
6483     case EOpConstructDMat3x4:
6484     case EOpConstructDMat4x2:
6485     case EOpConstructDMat4x3:
6486     case EOpConstructDMat4x4:
6487     case EOpConstructDouble:
6488         basicOp = EOpConstructDouble;
6489         break;
6490
6491     case EOpConstructF16Vec2:
6492     case EOpConstructF16Vec3:
6493     case EOpConstructF16Vec4:
6494     case EOpConstructF16Mat2x2:
6495     case EOpConstructF16Mat2x3:
6496     case EOpConstructF16Mat2x4:
6497     case EOpConstructF16Mat3x2:
6498     case EOpConstructF16Mat3x3:
6499     case EOpConstructF16Mat3x4:
6500     case EOpConstructF16Mat4x2:
6501     case EOpConstructF16Mat4x3:
6502     case EOpConstructF16Mat4x4:
6503     case EOpConstructFloat16:
6504         basicOp = EOpConstructFloat16;
6505         break;
6506
6507     case EOpConstructI8Vec2:
6508     case EOpConstructI8Vec3:
6509     case EOpConstructI8Vec4:
6510     case EOpConstructInt8:
6511         basicOp = EOpConstructInt8;
6512         break;
6513
6514     case EOpConstructU8Vec2:
6515     case EOpConstructU8Vec3:
6516     case EOpConstructU8Vec4:
6517     case EOpConstructUint8:
6518         basicOp = EOpConstructUint8;
6519         break;
6520
6521     case EOpConstructI16Vec2:
6522     case EOpConstructI16Vec3:
6523     case EOpConstructI16Vec4:
6524     case EOpConstructInt16:
6525         basicOp = EOpConstructInt16;
6526         break;
6527
6528     case EOpConstructU16Vec2:
6529     case EOpConstructU16Vec3:
6530     case EOpConstructU16Vec4:
6531     case EOpConstructUint16:
6532         basicOp = EOpConstructUint16;
6533         break;
6534
6535     case EOpConstructIVec2:
6536     case EOpConstructIVec3:
6537     case EOpConstructIVec4:
6538     case EOpConstructInt:
6539         basicOp = EOpConstructInt;
6540         break;
6541
6542     case EOpConstructUVec2:
6543     case EOpConstructUVec3:
6544     case EOpConstructUVec4:
6545     case EOpConstructUint:
6546         basicOp = EOpConstructUint;
6547         break;
6548
6549     case EOpConstructI64Vec2:
6550     case EOpConstructI64Vec3:
6551     case EOpConstructI64Vec4:
6552     case EOpConstructInt64:
6553         basicOp = EOpConstructInt64;
6554         break;
6555
6556     case EOpConstructU64Vec2:
6557     case EOpConstructU64Vec3:
6558     case EOpConstructU64Vec4:
6559     case EOpConstructUint64:
6560         basicOp = EOpConstructUint64;
6561         break;
6562
6563     case EOpConstructBVec2:
6564     case EOpConstructBVec3:
6565     case EOpConstructBVec4:
6566     case EOpConstructBool:
6567         basicOp = EOpConstructBool;
6568         break;
6569
6570     case EOpConstructNonuniform:
6571         node->getWritableType().getQualifier().nonUniform = true;
6572         return node;
6573         break;
6574
6575     default:
6576         error(loc, "unsupported construction", "", "");
6577
6578         return nullptr;
6579     }
6580     newNode = intermediate.addUnaryMath(basicOp, node, node->getLoc());
6581     if (newNode == nullptr) {
6582         error(loc, "can't convert", "constructor", "");
6583         return nullptr;
6584     }
6585
6586     //
6587     // Now, if there still isn't an operation to do the construction, and we need one, add one.
6588     //
6589
6590     // Otherwise, skip out early.
6591     if (subset || (newNode != node && newNode->getType() == type))
6592         return newNode;
6593
6594     // setAggregateOperator will insert a new node for the constructor, as needed.
6595     return intermediate.setAggregateOperator(newNode, op, type, loc);
6596 }
6597
6598 // This function tests for the type of the parameters to the structure or array constructor. Raises
6599 // an error message if the expected type does not match the parameter passed to the constructor.
6600 //
6601 // Returns nullptr for an error or the input node itself if the expected and the given parameter types match.
6602 //
6603 TIntermTyped* TParseContext::constructAggregate(TIntermNode* node, const TType& type, int paramCount, const TSourceLoc& loc)
6604 {
6605     TIntermTyped* converted = intermediate.addConversion(EOpConstructStruct, type, node->getAsTyped());
6606     if (! converted || converted->getType() != type) {
6607         error(loc, "", "constructor", "cannot convert parameter %d from '%s' to '%s'", paramCount,
6608               node->getAsTyped()->getType().getCompleteString().c_str(), type.getCompleteString().c_str());
6609
6610         return nullptr;
6611     }
6612
6613     return converted;
6614 }
6615
6616 //
6617 // Do everything needed to add an interface block.
6618 //
6619 void TParseContext::declareBlock(const TSourceLoc& loc, TTypeList& typeList, const TString* instanceName,
6620     TArraySizes* arraySizes)
6621 {
6622     blockStageIoCheck(loc, currentBlockQualifier);
6623     blockQualifierCheck(loc, currentBlockQualifier, instanceName != nullptr);
6624     if (arraySizes != nullptr) {
6625         arraySizesCheck(loc, currentBlockQualifier, arraySizes, nullptr, false);
6626         arrayOfArrayVersionCheck(loc, arraySizes);
6627         if (arraySizes->getNumDims() > 1)
6628             requireProfile(loc, ~EEsProfile, "array-of-array of block");
6629     }
6630
6631     // fix and check for member storage qualifiers and types that don't belong within a block
6632     for (unsigned int member = 0; member < typeList.size(); ++member) {
6633         TType& memberType = *typeList[member].type;
6634         TQualifier& memberQualifier = memberType.getQualifier();
6635         const TSourceLoc& memberLoc = typeList[member].loc;
6636         globalQualifierFixCheck(memberLoc, memberQualifier);
6637         if (memberQualifier.storage != EvqTemporary && memberQualifier.storage != EvqGlobal && memberQualifier.storage != currentBlockQualifier.storage)
6638             error(memberLoc, "member storage qualifier cannot contradict block storage qualifier", memberType.getFieldName().c_str(), "");
6639         memberQualifier.storage = currentBlockQualifier.storage;
6640 #ifdef NV_EXTENSIONS
6641         if (currentBlockQualifier.perPrimitiveNV)
6642             memberQualifier.perPrimitiveNV = currentBlockQualifier.perPrimitiveNV;
6643         if (currentBlockQualifier.perViewNV)
6644             memberQualifier.perViewNV = currentBlockQualifier.perViewNV;
6645         if (currentBlockQualifier.perTaskNV)
6646             memberQualifier.perTaskNV = currentBlockQualifier.perTaskNV;
6647 #endif
6648         if ((currentBlockQualifier.storage == EvqUniform || currentBlockQualifier.storage == EvqBuffer) && (memberQualifier.isInterpolation() || memberQualifier.isAuxiliary()))
6649             error(memberLoc, "member of uniform or buffer block cannot have an auxiliary or interpolation qualifier", memberType.getFieldName().c_str(), "");
6650         if (memberType.isArray())
6651             arraySizesCheck(memberLoc, currentBlockQualifier, memberType.getArraySizes(), nullptr, member == typeList.size() - 1);
6652         if (memberQualifier.hasOffset()) {
6653             if (spvVersion.spv == 0) {
6654                 requireProfile(memberLoc, ~EEsProfile, "offset on block member");
6655                 profileRequires(memberLoc, ~EEsProfile, 440, E_GL_ARB_enhanced_layouts, "offset on block member");
6656             }
6657         }
6658
6659         if (memberType.containsOpaque())
6660             error(memberLoc, "member of block cannot be or contain a sampler, image, or atomic_uint type", typeList[member].type->getFieldName().c_str(), "");
6661     }
6662
6663     // This might be a redeclaration of a built-in block.  If so, redeclareBuiltinBlock() will
6664     // do all the rest.
6665     if (! symbolTable.atBuiltInLevel() && builtInName(*blockName)) {
6666         redeclareBuiltinBlock(loc, typeList, *blockName, instanceName, arraySizes);
6667         return;
6668     }
6669
6670     // Not a redeclaration of a built-in; check that all names are user names.
6671     reservedErrorCheck(loc, *blockName);
6672     if (instanceName)
6673         reservedErrorCheck(loc, *instanceName);
6674     for (unsigned int member = 0; member < typeList.size(); ++member)
6675         reservedErrorCheck(typeList[member].loc, typeList[member].type->getFieldName());
6676
6677     // Make default block qualification, and adjust the member qualifications
6678
6679     TQualifier defaultQualification;
6680     switch (currentBlockQualifier.storage) {
6681     case EvqUniform:    defaultQualification = globalUniformDefaults;    break;
6682     case EvqBuffer:     defaultQualification = globalBufferDefaults;     break;
6683     case EvqVaryingIn:  defaultQualification = globalInputDefaults;      break;
6684     case EvqVaryingOut: defaultQualification = globalOutputDefaults;     break;
6685     default:            defaultQualification.clear();                    break;
6686     }
6687
6688     // Special case for "push_constant uniform", which has a default of std430,
6689     // contrary to normal uniform defaults, and can't have a default tracked for it.
6690     if ((currentBlockQualifier.layoutPushConstant && !currentBlockQualifier.hasPacking())
6691 #ifdef NV_EXTENSIONS
6692         || (currentBlockQualifier.layoutShaderRecordNV && !currentBlockQualifier.hasPacking())
6693 #endif
6694        )
6695         currentBlockQualifier.layoutPacking = ElpStd430;
6696
6697 #ifdef NV_EXTENSIONS
6698     // Special case for "taskNV in/out", which has a default of std430,
6699     if (currentBlockQualifier.perTaskNV && !currentBlockQualifier.hasPacking())
6700         currentBlockQualifier.layoutPacking = ElpStd430;
6701 #endif
6702
6703     // fix and check for member layout qualifiers
6704
6705     mergeObjectLayoutQualifiers(defaultQualification, currentBlockQualifier, true);
6706
6707     // "The align qualifier can only be used on blocks or block members, and only for blocks declared with std140 or std430 layouts."
6708     if (currentBlockQualifier.hasAlign()) {
6709         if (defaultQualification.layoutPacking != ElpStd140 && defaultQualification.layoutPacking != ElpStd430) {
6710             error(loc, "can only be used with std140 or std430 layout packing", "align", "");
6711             defaultQualification.layoutAlign = -1;
6712         }
6713     }
6714
6715     bool memberWithLocation = false;
6716     bool memberWithoutLocation = false;
6717 #ifdef NV_EXTENSIONS
6718     bool memberWithPerViewQualifier = false;
6719 #endif
6720     for (unsigned int member = 0; member < typeList.size(); ++member) {
6721         TQualifier& memberQualifier = typeList[member].type->getQualifier();
6722         const TSourceLoc& memberLoc = typeList[member].loc;
6723         if (memberQualifier.hasStream()) {
6724             if (defaultQualification.layoutStream != memberQualifier.layoutStream)
6725                 error(memberLoc, "member cannot contradict block", "stream", "");
6726         }
6727
6728         // "This includes a block's inheritance of the
6729         // current global default buffer, a block member's inheritance of the block's
6730         // buffer, and the requirement that any *xfb_buffer* declared on a block
6731         // member must match the buffer inherited from the block."
6732         if (memberQualifier.hasXfbBuffer()) {
6733             if (defaultQualification.layoutXfbBuffer != memberQualifier.layoutXfbBuffer)
6734                 error(memberLoc, "member cannot contradict block (or what block inherited from global)", "xfb_buffer", "");
6735         }
6736
6737         if (memberQualifier.hasPacking())
6738             error(memberLoc, "member of block cannot have a packing layout qualifier", typeList[member].type->getFieldName().c_str(), "");
6739         if (memberQualifier.hasLocation()) {
6740             const char* feature = "location on block member";
6741             switch (currentBlockQualifier.storage) {
6742             case EvqVaryingIn:
6743             case EvqVaryingOut:
6744                 requireProfile(memberLoc, ECoreProfile | ECompatibilityProfile | EEsProfile, feature);
6745                 profileRequires(memberLoc, ECoreProfile | ECompatibilityProfile, 440, E_GL_ARB_enhanced_layouts, feature);
6746                 profileRequires(memberLoc, EEsProfile, 320, Num_AEP_shader_io_blocks, AEP_shader_io_blocks, feature);
6747                 memberWithLocation = true;
6748                 break;
6749             default:
6750                 error(memberLoc, "can only use in an in/out block", feature, "");
6751                 break;
6752             }
6753         } else
6754             memberWithoutLocation = true;
6755
6756         // "The offset qualifier can only be used on block members of blocks declared with std140 or std430 layouts."
6757         // "The align qualifier can only be used on blocks or block members, and only for blocks declared with std140 or std430 layouts."
6758         if (memberQualifier.hasAlign() || memberQualifier.hasOffset()) {
6759             if (defaultQualification.layoutPacking != ElpStd140 && defaultQualification.layoutPacking != ElpStd430)
6760                 error(memberLoc, "can only be used with std140 or std430 layout packing", "offset/align", "");
6761         }
6762
6763 #ifdef NV_EXTENSIONS
6764         if (memberQualifier.isPerView()) {
6765             memberWithPerViewQualifier = true;
6766         }
6767 #endif
6768
6769         TQualifier newMemberQualification = defaultQualification;
6770         mergeQualifiers(memberLoc, newMemberQualification, memberQualifier, false);
6771         memberQualifier = newMemberQualification;
6772     }
6773
6774     layoutMemberLocationArrayCheck(loc, memberWithLocation, arraySizes);
6775
6776     // Process the members
6777     fixBlockLocations(loc, currentBlockQualifier, typeList, memberWithLocation, memberWithoutLocation);
6778     fixBlockXfbOffsets(currentBlockQualifier, typeList);
6779     fixBlockUniformOffsets(currentBlockQualifier, typeList);
6780     for (unsigned int member = 0; member < typeList.size(); ++member)
6781         layoutTypeCheck(typeList[member].loc, *typeList[member].type);
6782
6783 #ifdef NV_EXTENSIONS
6784     if (memberWithPerViewQualifier) {
6785         for (unsigned int member = 0; member < typeList.size(); ++member) {
6786             resizeMeshViewDimension(typeList[member].loc, *typeList[member].type);
6787         }
6788     }
6789 #endif
6790
6791     // reverse merge, so that currentBlockQualifier now has all layout information
6792     // (can't use defaultQualification directly, it's missing other non-layout-default-class qualifiers)
6793     mergeObjectLayoutQualifiers(currentBlockQualifier, defaultQualification, true);
6794
6795     //
6796     // Build and add the interface block as a new type named 'blockName'
6797     //
6798
6799     TType blockType(&typeList, *blockName, currentBlockQualifier);
6800     if (arraySizes != nullptr)
6801         blockType.transferArraySizes(arraySizes);
6802     else
6803         ioArrayCheck(loc, blockType, instanceName ? *instanceName : *blockName);
6804
6805     //
6806     // Don't make a user-defined type out of block name; that will cause an error
6807     // if the same block name gets reused in a different interface.
6808     //
6809     // "Block names have no other use within a shader
6810     // beyond interface matching; it is a compile-time error to use a block name at global scope for anything
6811     // other than as a block name (e.g., use of a block name for a global variable name or function name is
6812     // currently reserved)."
6813     //
6814     // Use the symbol table to prevent normal reuse of the block's name, as a variable entry,
6815     // whose type is EbtBlock, but without all the structure; that will come from the type
6816     // the instances point to.
6817     //
6818     TType blockNameType(EbtBlock, blockType.getQualifier().storage);
6819     TVariable* blockNameVar = new TVariable(blockName, blockNameType);
6820     if (! symbolTable.insert(*blockNameVar)) {
6821         TSymbol* existingName = symbolTable.find(*blockName);
6822         if (existingName->getType().getBasicType() == EbtBlock) {
6823             if (existingName->getType().getQualifier().storage == blockType.getQualifier().storage) {
6824                 error(loc, "Cannot reuse block name within the same interface:", blockName->c_str(), blockType.getStorageQualifierString());
6825                 return;
6826             }
6827         } else {
6828             error(loc, "block name cannot redefine a non-block name", blockName->c_str(), "");
6829             return;
6830         }
6831     }
6832
6833     // Add the variable, as anonymous or named instanceName.
6834     // Make an anonymous variable if no name was provided.
6835     if (! instanceName)
6836         instanceName = NewPoolTString("");
6837
6838     TVariable& variable = *new TVariable(instanceName, blockType);
6839     if (! symbolTable.insert(variable)) {
6840         if (*instanceName == "")
6841             error(loc, "nameless block contains a member that already has a name at global scope", blockName->c_str(), "");
6842         else
6843             error(loc, "block instance name redefinition", variable.getName().c_str(), "");
6844
6845         return;
6846     }
6847
6848     // Check for general layout qualifier errors
6849     layoutObjectCheck(loc, variable);
6850
6851     // fix up
6852     if (isIoResizeArray(blockType)) {
6853         ioArraySymbolResizeList.push_back(&variable);
6854         checkIoArraysConsistency(loc, true, blockType.getQualifier().isPerPrimitive());
6855     } else
6856         fixIoArraySize(loc, variable.getWritableType());
6857
6858     // Save it in the AST for linker use.
6859     trackLinkage(variable);
6860 }
6861
6862 // Do all block-declaration checking regarding the combination of in/out/uniform/buffer
6863 // with a particular stage.
6864 void TParseContext::blockStageIoCheck(const TSourceLoc& loc, const TQualifier& qualifier)
6865 {
6866     switch (qualifier.storage) {
6867     case EvqUniform:
6868         profileRequires(loc, EEsProfile, 300, nullptr, "uniform block");
6869         profileRequires(loc, ENoProfile, 140, nullptr, "uniform block");
6870         if (currentBlockQualifier.layoutPacking == ElpStd430 && ! currentBlockQualifier.layoutPushConstant)
6871             error(loc, "requires the 'buffer' storage qualifier", "std430", "");
6872         break;
6873     case EvqBuffer:
6874         requireProfile(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, "buffer block");
6875         profileRequires(loc, ECoreProfile | ECompatibilityProfile, 430, nullptr, "buffer block");
6876         profileRequires(loc, EEsProfile, 310, nullptr, "buffer block");
6877         break;
6878     case EvqVaryingIn:
6879         profileRequires(loc, ~EEsProfile, 150, E_GL_ARB_separate_shader_objects, "input block");
6880         // It is a compile-time error to have an input block in a vertex shader or an output block in a fragment shader
6881         // "Compute shaders do not permit user-defined input variables..."
6882         requireStage(loc, (EShLanguageMask)(EShLangTessControlMask|EShLangTessEvaluationMask|EShLangGeometryMask|EShLangFragmentMask
6883 #ifdef NV_EXTENSIONS
6884                                             |EShLangMeshNVMask
6885 #endif
6886                                            ), "input block");
6887         if (language == EShLangFragment) {
6888             profileRequires(loc, EEsProfile, 320, Num_AEP_shader_io_blocks, AEP_shader_io_blocks, "fragment input block");
6889         }
6890 #ifdef NV_EXTENSIONS
6891         else if (language == EShLangMeshNV && ! qualifier.isTaskMemory()) {
6892             error(loc, "input blocks cannot be used in a mesh shader", "out", "");
6893         }
6894 #endif
6895         break;
6896     case EvqVaryingOut:
6897         profileRequires(loc, ~EEsProfile, 150, E_GL_ARB_separate_shader_objects, "output block");
6898         requireStage(loc, (EShLanguageMask)(EShLangVertexMask|EShLangTessControlMask|EShLangTessEvaluationMask|EShLangGeometryMask
6899 #ifdef NV_EXTENSIONS
6900                                             |EShLangMeshNVMask|EShLangTaskNVMask
6901 #endif
6902                                            ), "output block");
6903         // ES 310 can have a block before shader_io is turned on, so skip this test for built-ins
6904         if (language == EShLangVertex && ! parsingBuiltins) {
6905             profileRequires(loc, EEsProfile, 320, Num_AEP_shader_io_blocks, AEP_shader_io_blocks, "vertex output block");
6906         }
6907 #ifdef NV_EXTENSIONS
6908         else if (language == EShLangMeshNV && qualifier.isTaskMemory()) {
6909             error(loc, "can only use on input blocks in mesh shader", "taskNV", "");
6910         }
6911         else if (language == EShLangTaskNV && ! qualifier.isTaskMemory()) {
6912             error(loc, "output blocks cannot be used in a task shader", "out", "");
6913         }
6914 #endif
6915         break;
6916 #ifdef NV_EXTENSIONS
6917     case EvqPayloadNV:
6918         profileRequires(loc, ~EEsProfile, 450, E_GL_NVX_raytracing, "rayPayloadNVX block");
6919         requireStage(loc, (EShLanguageMask)(EShLangRayGenNVMask | EShLangAnyHitNVMask | EShLangClosestHitNVMask | EShLangMissNVMask),
6920             "rayPayloadNVX block");
6921         break;
6922     case EvqPayloadInNV:
6923         profileRequires(loc, ~EEsProfile, 450, E_GL_NVX_raytracing, "rayPayloadInNVX block");
6924         requireStage(loc, (EShLanguageMask)(EShLangAnyHitNVMask | EShLangClosestHitNVMask | EShLangMissNVMask),
6925             "rayPayloadInNVX block");
6926         break;
6927     case EvqHitAttrNV:
6928         profileRequires(loc, ~EEsProfile, 450, E_GL_NVX_raytracing, "hitAttributeNVX block");
6929         requireStage(loc, (EShLanguageMask)(EShLangIntersectNVMask | EShLangAnyHitNVMask | EShLangClosestHitNVMask), "hitAttributeNVX block");
6930         break;
6931 #endif
6932     default:
6933         error(loc, "only uniform, buffer, in, or out blocks are supported", blockName->c_str(), "");
6934         break;
6935     }
6936 }
6937
6938 // Do all block-declaration checking regarding its qualifiers.
6939 void TParseContext::blockQualifierCheck(const TSourceLoc& loc, const TQualifier& qualifier, bool /*instanceName*/)
6940 {
6941     // The 4.5 specification says:
6942     //
6943     // interface-block :
6944     //    layout-qualifieropt interface-qualifier  block-name { member-list } instance-nameopt ;
6945     //
6946     // interface-qualifier :
6947     //    in
6948     //    out
6949     //    patch in
6950     //    patch out
6951     //    uniform
6952     //    buffer
6953     //
6954     // Note however memory qualifiers aren't included, yet the specification also says
6955     //
6956     // "...memory qualifiers may also be used in the declaration of shader storage blocks..."
6957
6958     if (qualifier.isInterpolation())
6959         error(loc, "cannot use interpolation qualifiers on an interface block", "flat/smooth/noperspective", "");
6960     if (qualifier.centroid)
6961         error(loc, "cannot use centroid qualifier on an interface block", "centroid", "");
6962     if (qualifier.sample)
6963         error(loc, "cannot use sample qualifier on an interface block", "sample", "");
6964     if (qualifier.invariant)
6965         error(loc, "cannot use invariant qualifier on an interface block", "invariant", "");
6966     if (qualifier.layoutPushConstant)
6967         intermediate.addPushConstantCount();
6968 #ifdef NV_EXTENSIONS
6969     if (qualifier.layoutShaderRecordNV)
6970         intermediate.addShaderRecordNVCount();
6971     if (qualifier.perTaskNV)
6972         intermediate.addTaskNVCount();
6973 #endif
6974 }
6975
6976 //
6977 // "For a block, this process applies to the entire block, or until the first member
6978 // is reached that has a location layout qualifier. When a block member is declared with a location
6979 // qualifier, its location comes from that qualifier: The member's location qualifier overrides the block-level
6980 // declaration. Subsequent members are again assigned consecutive locations, based on the newest location,
6981 // until the next member declared with a location qualifier. The values used for locations do not have to be
6982 // declared in increasing order."
6983 void TParseContext::fixBlockLocations(const TSourceLoc& loc, TQualifier& qualifier, TTypeList& typeList, bool memberWithLocation, bool memberWithoutLocation)
6984 {
6985     // "If a block has no block-level location layout qualifier, it is required that either all or none of its members
6986     // have a location layout qualifier, or a compile-time error results."
6987     if (! qualifier.hasLocation() && memberWithLocation && memberWithoutLocation)
6988         error(loc, "either the block needs a location, or all members need a location, or no members have a location", "location", "");
6989     else {
6990         if (memberWithLocation) {
6991             // remove any block-level location and make it per *every* member
6992             int nextLocation = 0;  // by the rule above, initial value is not relevant
6993             if (qualifier.hasAnyLocation()) {
6994                 nextLocation = qualifier.layoutLocation;
6995                 qualifier.layoutLocation = TQualifier::layoutLocationEnd;
6996                 if (qualifier.hasComponent()) {
6997                     // "It is a compile-time error to apply the *component* qualifier to a ... block"
6998                     error(loc, "cannot apply to a block", "component", "");
6999                 }
7000                 if (qualifier.hasIndex()) {
7001                     error(loc, "cannot apply to a block", "index", "");
7002                 }
7003             }
7004             for (unsigned int member = 0; member < typeList.size(); ++member) {
7005                 TQualifier& memberQualifier = typeList[member].type->getQualifier();
7006                 const TSourceLoc& memberLoc = typeList[member].loc;
7007                 if (! memberQualifier.hasLocation()) {
7008                     if (nextLocation >= (int)TQualifier::layoutLocationEnd)
7009                         error(memberLoc, "location is too large", "location", "");
7010                     memberQualifier.layoutLocation = nextLocation;
7011                     memberQualifier.layoutComponent = TQualifier::layoutComponentEnd;
7012                 }
7013                 nextLocation = memberQualifier.layoutLocation + intermediate.computeTypeLocationSize(
7014                                     *typeList[member].type, language);
7015             }
7016         }
7017     }
7018 }
7019
7020 void TParseContext::fixBlockXfbOffsets(TQualifier& qualifier, TTypeList& typeList)
7021 {
7022     // "If a block is qualified with xfb_offset, all its
7023     // members are assigned transform feedback buffer offsets. If a block is not qualified with xfb_offset, any
7024     // members of that block not qualified with an xfb_offset will not be assigned transform feedback buffer
7025     // offsets."
7026
7027     if (! qualifier.hasXfbBuffer() || ! qualifier.hasXfbOffset())
7028         return;
7029
7030     int nextOffset = qualifier.layoutXfbOffset;
7031     for (unsigned int member = 0; member < typeList.size(); ++member) {
7032         TQualifier& memberQualifier = typeList[member].type->getQualifier();
7033         bool containsDouble = false;
7034         int memberSize = intermediate.computeTypeXfbSize(*typeList[member].type, containsDouble);
7035         // see if we need to auto-assign an offset to this member
7036         if (! memberQualifier.hasXfbOffset()) {
7037             // "if applied to an aggregate containing a double, the offset must also be a multiple of 8"
7038             if (containsDouble)
7039                 RoundToPow2(nextOffset, 8);
7040             memberQualifier.layoutXfbOffset = nextOffset;
7041         } else
7042             nextOffset = memberQualifier.layoutXfbOffset;
7043         nextOffset += memberSize;
7044     }
7045
7046     // The above gave all block members an offset, so we can take it off the block now,
7047     // which will avoid double counting the offset usage.
7048     qualifier.layoutXfbOffset = TQualifier::layoutXfbOffsetEnd;
7049 }
7050
7051 // Calculate and save the offset of each block member, using the recursively
7052 // defined block offset rules and the user-provided offset and align.
7053 //
7054 // Also, compute and save the total size of the block. For the block's size, arrayness
7055 // is not taken into account, as each element is backed by a separate buffer.
7056 //
7057 void TParseContext::fixBlockUniformOffsets(TQualifier& qualifier, TTypeList& typeList)
7058 {
7059     if (!qualifier.isUniformOrBuffer() && !qualifier.isTaskMemory())
7060         return;
7061     if (qualifier.layoutPacking != ElpStd140 && qualifier.layoutPacking != ElpStd430)
7062         return;
7063
7064     int offset = 0;
7065     int memberSize;
7066     for (unsigned int member = 0; member < typeList.size(); ++member) {
7067         TQualifier& memberQualifier = typeList[member].type->getQualifier();
7068         const TSourceLoc& memberLoc = typeList[member].loc;
7069
7070         // "When align is applied to an array, it effects only the start of the array, not the array's internal stride."
7071
7072         // modify just the children's view of matrix layout, if there is one for this member
7073         TLayoutMatrix subMatrixLayout = typeList[member].type->getQualifier().layoutMatrix;
7074         int dummyStride;
7075         int memberAlignment = intermediate.getBaseAlignment(*typeList[member].type, memberSize, dummyStride, qualifier.layoutPacking == ElpStd140,
7076                                                             subMatrixLayout != ElmNone ? subMatrixLayout == ElmRowMajor : qualifier.layoutMatrix == ElmRowMajor);
7077         if (memberQualifier.hasOffset()) {
7078             // "The specified offset must be a multiple
7079             // of the base alignment of the type of the block member it qualifies, or a compile-time error results."
7080             if (! IsMultipleOfPow2(memberQualifier.layoutOffset, memberAlignment))
7081                 error(memberLoc, "must be a multiple of the member's alignment", "offset", "");
7082
7083             // GLSL: "It is a compile-time error to specify an offset that is smaller than the offset of the previous
7084             // member in the block or that lies within the previous member of the block"
7085             if (spvVersion.spv == 0) {
7086                 if (memberQualifier.layoutOffset < offset)
7087                     error(memberLoc, "cannot lie in previous members", "offset", "");
7088
7089                 // "The offset qualifier forces the qualified member to start at or after the specified
7090                 // integral-constant expression, which will be its byte offset from the beginning of the buffer.
7091                 // "The actual offset of a member is computed as
7092                 // follows: If offset was declared, start with that offset, otherwise start with the next available offset."
7093                 offset = std::max(offset, memberQualifier.layoutOffset);
7094             } else {
7095                 // TODO: Vulkan: "It is a compile-time error to have any offset, explicit or assigned,
7096                 // that lies within another member of the block."
7097
7098                 offset = memberQualifier.layoutOffset;
7099             }
7100         }
7101
7102         // "The actual alignment of a member will be the greater of the specified align alignment and the standard
7103         // (e.g., std140) base alignment for the member's type."
7104         if (memberQualifier.hasAlign())
7105             memberAlignment = std::max(memberAlignment, memberQualifier.layoutAlign);
7106
7107         // "If the resulting offset is not a multiple of the actual alignment,
7108         // increase it to the first offset that is a multiple of
7109         // the actual alignment."
7110         RoundToPow2(offset, memberAlignment);
7111         typeList[member].type->getQualifier().layoutOffset = offset;
7112         offset += memberSize;
7113     }
7114 }
7115
7116 // For an identifier that is already declared, add more qualification to it.
7117 void TParseContext::addQualifierToExisting(const TSourceLoc& loc, TQualifier qualifier, const TString& identifier)
7118 {
7119     TSymbol* symbol = symbolTable.find(identifier);
7120     if (! symbol) {
7121         error(loc, "identifier not previously declared", identifier.c_str(), "");
7122         return;
7123     }
7124     if (symbol->getAsFunction()) {
7125         error(loc, "cannot re-qualify a function name", identifier.c_str(), "");
7126         return;
7127     }
7128
7129     if (qualifier.isAuxiliary() ||
7130         qualifier.isMemory() ||
7131         qualifier.isInterpolation() ||
7132         qualifier.hasLayout() ||
7133         qualifier.storage != EvqTemporary ||
7134         qualifier.precision != EpqNone) {
7135         error(loc, "cannot add storage, auxiliary, memory, interpolation, layout, or precision qualifier to an existing variable", identifier.c_str(), "");
7136         return;
7137     }
7138
7139     // For read-only built-ins, add a new symbol for holding the modified qualifier.
7140     // This will bring up an entire block, if a block type has to be modified (e.g., gl_Position inside a block)
7141     if (symbol->isReadOnly())
7142         symbol = symbolTable.copyUp(symbol);
7143
7144     if (qualifier.invariant) {
7145         if (intermediate.inIoAccessed(identifier))
7146             error(loc, "cannot change qualification after use", "invariant", "");
7147         symbol->getWritableType().getQualifier().invariant = true;
7148         invariantCheck(loc, symbol->getType().getQualifier());
7149     } else if (qualifier.noContraction) {
7150         if (intermediate.inIoAccessed(identifier))
7151             error(loc, "cannot change qualification after use", "precise", "");
7152         symbol->getWritableType().getQualifier().noContraction = true;
7153     } else if (qualifier.specConstant) {
7154         symbol->getWritableType().getQualifier().makeSpecConstant();
7155         if (qualifier.hasSpecConstantId())
7156             symbol->getWritableType().getQualifier().layoutSpecConstantId = qualifier.layoutSpecConstantId;
7157     } else
7158         warn(loc, "unknown requalification", "", "");
7159 }
7160
7161 void TParseContext::addQualifierToExisting(const TSourceLoc& loc, TQualifier qualifier, TIdentifierList& identifiers)
7162 {
7163     for (unsigned int i = 0; i < identifiers.size(); ++i)
7164         addQualifierToExisting(loc, qualifier, *identifiers[i]);
7165 }
7166
7167 // Make sure 'invariant' isn't being applied to a non-allowed object.
7168 void TParseContext::invariantCheck(const TSourceLoc& loc, const TQualifier& qualifier)
7169 {
7170     if (! qualifier.invariant)
7171         return;
7172
7173     bool pipeOut = qualifier.isPipeOutput();
7174     bool pipeIn = qualifier.isPipeInput();
7175     if (version >= 300 || (profile != EEsProfile && version >= 420)) {
7176         if (! pipeOut)
7177             error(loc, "can only apply to an output", "invariant", "");
7178     } else {
7179         if ((language == EShLangVertex && pipeIn) || (! pipeOut && ! pipeIn))
7180             error(loc, "can only apply to an output, or to an input in a non-vertex stage\n", "invariant", "");
7181     }
7182 }
7183
7184 //
7185 // Updating default qualifier for the case of a declaration with just a qualifier,
7186 // no type, block, or identifier.
7187 //
7188 void TParseContext::updateStandaloneQualifierDefaults(const TSourceLoc& loc, const TPublicType& publicType)
7189 {
7190     if (publicType.shaderQualifiers.vertices != TQualifier::layoutNotSet) {
7191 #ifdef NV_EXTENSIONS
7192         assert(language == EShLangTessControl || language == EShLangGeometry || language == EShLangMeshNV);
7193 #else
7194         assert(language == EShLangTessControl || language == EShLangGeometry);
7195 #endif
7196         const char* id = (language == EShLangTessControl) ? "vertices" : "max_vertices";
7197
7198         if (publicType.qualifier.storage != EvqVaryingOut)
7199             error(loc, "can only apply to 'out'", id, "");
7200         if (! intermediate.setVertices(publicType.shaderQualifiers.vertices))
7201             error(loc, "cannot change previously set layout value", id, "");
7202
7203         if (language == EShLangTessControl)
7204             checkIoArraysConsistency(loc);
7205     }
7206 #ifdef NV_EXTENSIONS
7207     if (publicType.shaderQualifiers.primitives != TQualifier::layoutNotSet) {
7208         assert(language == EShLangMeshNV);
7209         const char* id = "max_primitives";
7210
7211         if (publicType.qualifier.storage != EvqVaryingOut)
7212             error(loc, "can only apply to 'out'", id, "");
7213         if (! intermediate.setPrimitives(publicType.shaderQualifiers.primitives))
7214             error(loc, "cannot change previously set layout value", id, "");
7215     }
7216 #endif
7217     if (publicType.shaderQualifiers.invocations != TQualifier::layoutNotSet) {
7218         if (publicType.qualifier.storage != EvqVaryingIn)
7219             error(loc, "can only apply to 'in'", "invocations", "");
7220         if (! intermediate.setInvocations(publicType.shaderQualifiers.invocations))
7221             error(loc, "cannot change previously set layout value", "invocations", "");
7222     }
7223     if (publicType.shaderQualifiers.geometry != ElgNone) {
7224         if (publicType.qualifier.storage == EvqVaryingIn) {
7225             switch (publicType.shaderQualifiers.geometry) {
7226             case ElgPoints:
7227             case ElgLines:
7228             case ElgLinesAdjacency:
7229             case ElgTriangles:
7230             case ElgTrianglesAdjacency:
7231             case ElgQuads:
7232             case ElgIsolines:
7233 #ifdef NV_EXTENSIONS
7234                 if (language == EShLangMeshNV) {
7235                     error(loc, "cannot apply to input", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
7236                     break;
7237                 }
7238 #endif
7239                 if (intermediate.setInputPrimitive(publicType.shaderQualifiers.geometry)) {
7240                     if (language == EShLangGeometry)
7241                         checkIoArraysConsistency(loc);
7242                 } else
7243                     error(loc, "cannot change previously set input primitive", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
7244                 break;
7245             default:
7246                 error(loc, "cannot apply to input", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
7247             }
7248         } else if (publicType.qualifier.storage == EvqVaryingOut) {
7249             switch (publicType.shaderQualifiers.geometry) {
7250 #ifdef NV_EXTENSIONS
7251             case ElgLines:
7252             case ElgTriangles:
7253                 if (language != EShLangMeshNV) {
7254                     error(loc, "cannot apply to 'out'", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
7255                     break;
7256                 }
7257 #endif
7258                 // Fall through
7259             case ElgPoints:
7260             case ElgLineStrip:
7261             case ElgTriangleStrip:
7262                 if (! intermediate.setOutputPrimitive(publicType.shaderQualifiers.geometry))
7263                     error(loc, "cannot change previously set output primitive", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
7264                 break;
7265             default:
7266                 error(loc, "cannot apply to 'out'", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
7267             }
7268         } else
7269             error(loc, "cannot apply to:", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), GetStorageQualifierString(publicType.qualifier.storage));
7270     }
7271     if (publicType.shaderQualifiers.spacing != EvsNone) {
7272         if (publicType.qualifier.storage == EvqVaryingIn) {
7273             if (! intermediate.setVertexSpacing(publicType.shaderQualifiers.spacing))
7274                 error(loc, "cannot change previously set vertex spacing", TQualifier::getVertexSpacingString(publicType.shaderQualifiers.spacing), "");
7275         } else
7276             error(loc, "can only apply to 'in'", TQualifier::getVertexSpacingString(publicType.shaderQualifiers.spacing), "");
7277     }
7278     if (publicType.shaderQualifiers.order != EvoNone) {
7279         if (publicType.qualifier.storage == EvqVaryingIn) {
7280             if (! intermediate.setVertexOrder(publicType.shaderQualifiers.order))
7281                 error(loc, "cannot change previously set vertex order", TQualifier::getVertexOrderString(publicType.shaderQualifiers.order), "");
7282         } else
7283             error(loc, "can only apply to 'in'", TQualifier::getVertexOrderString(publicType.shaderQualifiers.order), "");
7284     }
7285     if (publicType.shaderQualifiers.pointMode) {
7286         if (publicType.qualifier.storage == EvqVaryingIn)
7287             intermediate.setPointMode();
7288         else
7289             error(loc, "can only apply to 'in'", "point_mode", "");
7290     }
7291     for (int i = 0; i < 3; ++i) {
7292         if (publicType.shaderQualifiers.localSize[i] > 1) {
7293             if (publicType.qualifier.storage == EvqVaryingIn) {
7294                 if (! intermediate.setLocalSize(i, publicType.shaderQualifiers.localSize[i]))
7295                     error(loc, "cannot change previously set size", "local_size", "");
7296                 else {
7297                     int max = 0;
7298                     if (language == EShLangCompute) {
7299                         switch (i) {
7300                         case 0: max = resources.maxComputeWorkGroupSizeX; break;
7301                         case 1: max = resources.maxComputeWorkGroupSizeY; break;
7302                         case 2: max = resources.maxComputeWorkGroupSizeZ; break;
7303                         default: break;
7304                         }
7305                         if (intermediate.getLocalSize(i) > (unsigned int)max)
7306                             error(loc, "too large; see gl_MaxComputeWorkGroupSize", "local_size", "");
7307                     }
7308 #ifdef NV_EXTENSIONS
7309                     else if (language == EShLangMeshNV) {
7310                         switch (i) {
7311                         case 0: max = resources.maxMeshWorkGroupSizeX_NV; break;
7312                         case 1: max = resources.maxMeshWorkGroupSizeY_NV; break;
7313                         case 2: max = resources.maxMeshWorkGroupSizeZ_NV; break;
7314                         default: break;
7315                         }
7316                         if (intermediate.getLocalSize(i) > (unsigned int)max)
7317                             error(loc, "too large; see gl_MaxMeshWorkGroupSizeNV", "local_size", "");
7318                     }
7319                     else if (language == EShLangTaskNV) {
7320                         switch (i) {
7321                         case 0: max = resources.maxTaskWorkGroupSizeX_NV; break;
7322                         case 1: max = resources.maxTaskWorkGroupSizeY_NV; break;
7323                         case 2: max = resources.maxTaskWorkGroupSizeZ_NV; break;
7324                         default: break;
7325                         }
7326                         if (intermediate.getLocalSize(i) > (unsigned int)max)
7327                             error(loc, "too large; see gl_MaxTaskWorkGroupSizeNV", "local_size", "");
7328                     }
7329 #endif
7330                     else {
7331                         assert(0);
7332                     }
7333
7334                     // Fix the existing constant gl_WorkGroupSize with this new information.
7335                     TVariable* workGroupSize = getEditableVariable("gl_WorkGroupSize");
7336                     if (workGroupSize != nullptr)
7337                         workGroupSize->getWritableConstArray()[i].setUConst(intermediate.getLocalSize(i));
7338                 }
7339             } else
7340                 error(loc, "can only apply to 'in'", "local_size", "");
7341         }
7342         if (publicType.shaderQualifiers.localSizeSpecId[i] != TQualifier::layoutNotSet) {
7343             if (publicType.qualifier.storage == EvqVaryingIn) {
7344                 if (! intermediate.setLocalSizeSpecId(i, publicType.shaderQualifiers.localSizeSpecId[i]))
7345                     error(loc, "cannot change previously set size", "local_size", "");
7346             } else
7347                 error(loc, "can only apply to 'in'", "local_size id", "");
7348             // Set the workgroup built-in variable as a specialization constant
7349             TVariable* workGroupSize = getEditableVariable("gl_WorkGroupSize");
7350             if (workGroupSize != nullptr)
7351                 workGroupSize->getWritableType().getQualifier().specConstant = true;
7352         }
7353     }
7354     if (publicType.shaderQualifiers.earlyFragmentTests) {
7355         if (publicType.qualifier.storage == EvqVaryingIn)
7356             intermediate.setEarlyFragmentTests();
7357         else
7358             error(loc, "can only apply to 'in'", "early_fragment_tests", "");
7359     }
7360     if (publicType.shaderQualifiers.postDepthCoverage) {
7361         if (publicType.qualifier.storage == EvqVaryingIn)
7362             intermediate.setPostDepthCoverage();
7363         else
7364             error(loc, "can only apply to 'in'", "post_coverage_coverage", "");
7365     }
7366     if (publicType.shaderQualifiers.blendEquation) {
7367         if (publicType.qualifier.storage != EvqVaryingOut)
7368             error(loc, "can only apply to 'out'", "blend equation", "");
7369     }
7370
7371 #ifdef NV_EXTENSIONS
7372     if (publicType.shaderQualifiers.layoutDerivativeGroupQuads &&
7373         publicType.shaderQualifiers.layoutDerivativeGroupLinear) {
7374         error(loc, "cannot be both specified", "derivative_group_quadsNV and derivative_group_linearNV", "");
7375     }
7376
7377     if (publicType.shaderQualifiers.layoutDerivativeGroupQuads) {
7378         if (publicType.qualifier.storage == EvqVaryingIn) {
7379             if ((intermediate.getLocalSize(0) & 1) ||
7380                 (intermediate.getLocalSize(1) & 1))
7381                 error(loc, "requires local_size_x and local_size_y to be multiple of two", "derivative_group_quadsNV", "");
7382             else
7383                 intermediate.setLayoutDerivativeMode(LayoutDerivativeGroupQuads);
7384         }
7385         else
7386             error(loc, "can only apply to 'in'", "derivative_group_quadsNV", "");
7387     }
7388     if (publicType.shaderQualifiers.layoutDerivativeGroupLinear) {
7389         if (publicType.qualifier.storage == EvqVaryingIn) {
7390             if((intermediate.getLocalSize(0) *
7391                 intermediate.getLocalSize(1) *
7392                 intermediate.getLocalSize(2)) % 4 != 0)
7393                 error(loc, "requires total group size to be multiple of four", "derivative_group_linearNV", "");
7394             else
7395                 intermediate.setLayoutDerivativeMode(LayoutDerivativeGroupLinear);
7396         }
7397         else
7398             error(loc, "can only apply to 'in'", "derivative_group_linearNV", "");
7399     }
7400 #endif 
7401     const TQualifier& qualifier = publicType.qualifier;
7402
7403     if (qualifier.isAuxiliary() ||
7404         qualifier.isMemory() ||
7405         qualifier.isInterpolation() ||
7406         qualifier.precision != EpqNone)
7407         error(loc, "cannot use auxiliary, memory, interpolation, or precision qualifier in a default qualifier declaration (declaration with no type)", "qualifier", "");
7408     // "The offset qualifier can only be used on block members of blocks..."
7409     // "The align qualifier can only be used on blocks or block members..."
7410     if (qualifier.hasOffset() ||
7411         qualifier.hasAlign())
7412         error(loc, "cannot use offset or align qualifiers in a default qualifier declaration (declaration with no type)", "layout qualifier", "");
7413
7414     layoutQualifierCheck(loc, qualifier);
7415
7416     switch (qualifier.storage) {
7417     case EvqUniform:
7418         if (qualifier.hasMatrix())
7419             globalUniformDefaults.layoutMatrix = qualifier.layoutMatrix;
7420         if (qualifier.hasPacking())
7421             globalUniformDefaults.layoutPacking = qualifier.layoutPacking;
7422         break;
7423     case EvqBuffer:
7424         if (qualifier.hasMatrix())
7425             globalBufferDefaults.layoutMatrix = qualifier.layoutMatrix;
7426         if (qualifier.hasPacking())
7427             globalBufferDefaults.layoutPacking = qualifier.layoutPacking;
7428         break;
7429     case EvqVaryingIn:
7430         break;
7431     case EvqVaryingOut:
7432         if (qualifier.hasStream())
7433             globalOutputDefaults.layoutStream = qualifier.layoutStream;
7434         if (qualifier.hasXfbBuffer())
7435             globalOutputDefaults.layoutXfbBuffer = qualifier.layoutXfbBuffer;
7436         if (globalOutputDefaults.hasXfbBuffer() && qualifier.hasXfbStride()) {
7437             if (! intermediate.setXfbBufferStride(globalOutputDefaults.layoutXfbBuffer, qualifier.layoutXfbStride))
7438                 error(loc, "all stride settings must match for xfb buffer", "xfb_stride", "%d", qualifier.layoutXfbBuffer);
7439         }
7440         break;
7441     default:
7442         error(loc, "default qualifier requires 'uniform', 'buffer', 'in', or 'out' storage qualification", "", "");
7443         return;
7444     }
7445
7446     if (qualifier.hasBinding())
7447         error(loc, "cannot declare a default, include a type or full declaration", "binding", "");
7448     if (qualifier.hasAnyLocation())
7449         error(loc, "cannot declare a default, use a full declaration", "location/component/index", "");
7450     if (qualifier.hasXfbOffset())
7451         error(loc, "cannot declare a default, use a full declaration", "xfb_offset", "");
7452     if (qualifier.layoutPushConstant)
7453         error(loc, "cannot declare a default, can only be used on a block", "push_constant", "");
7454     if (qualifier.hasSpecConstantId())
7455         error(loc, "cannot declare a default, can only be used on a scalar", "constant_id", "");
7456 #ifdef NV_EXTENSIONS
7457     if (qualifier.layoutShaderRecordNV)
7458         error(loc, "cannot declare a default, can only be used on a block", "shaderRecordNVX", "");
7459 #endif
7460 }
7461
7462 //
7463 // Take the sequence of statements that has been built up since the last case/default,
7464 // put it on the list of top-level nodes for the current (inner-most) switch statement,
7465 // and follow that by the case/default we are on now.  (See switch topology comment on
7466 // TIntermSwitch.)
7467 //
7468 void TParseContext::wrapupSwitchSubsequence(TIntermAggregate* statements, TIntermNode* branchNode)
7469 {
7470     TIntermSequence* switchSequence = switchSequenceStack.back();
7471
7472     if (statements) {
7473         if (switchSequence->size() == 0)
7474             error(statements->getLoc(), "cannot have statements before first case/default label", "switch", "");
7475         statements->setOperator(EOpSequence);
7476         switchSequence->push_back(statements);
7477     }
7478     if (branchNode) {
7479         // check all previous cases for the same label (or both are 'default')
7480         for (unsigned int s = 0; s < switchSequence->size(); ++s) {
7481             TIntermBranch* prevBranch = (*switchSequence)[s]->getAsBranchNode();
7482             if (prevBranch) {
7483                 TIntermTyped* prevExpression = prevBranch->getExpression();
7484                 TIntermTyped* newExpression = branchNode->getAsBranchNode()->getExpression();
7485                 if (prevExpression == nullptr && newExpression == nullptr)
7486                     error(branchNode->getLoc(), "duplicate label", "default", "");
7487                 else if (prevExpression != nullptr &&
7488                           newExpression != nullptr &&
7489                          prevExpression->getAsConstantUnion() &&
7490                           newExpression->getAsConstantUnion() &&
7491                          prevExpression->getAsConstantUnion()->getConstArray()[0].getIConst() ==
7492                           newExpression->getAsConstantUnion()->getConstArray()[0].getIConst())
7493                     error(branchNode->getLoc(), "duplicated value", "case", "");
7494             }
7495         }
7496         switchSequence->push_back(branchNode);
7497     }
7498 }
7499
7500 //
7501 // Turn the top-level node sequence built up of wrapupSwitchSubsequence9)
7502 // into a switch node.
7503 //
7504 TIntermNode* TParseContext::addSwitch(const TSourceLoc& loc, TIntermTyped* expression, TIntermAggregate* lastStatements)
7505 {
7506     profileRequires(loc, EEsProfile, 300, nullptr, "switch statements");
7507     profileRequires(loc, ENoProfile, 130, nullptr, "switch statements");
7508
7509     wrapupSwitchSubsequence(lastStatements, nullptr);
7510
7511     if (expression == nullptr ||
7512         (expression->getBasicType() != EbtInt && expression->getBasicType() != EbtUint) ||
7513         expression->getType().isArray() || expression->getType().isMatrix() || expression->getType().isVector())
7514             error(loc, "condition must be a scalar integer expression", "switch", "");
7515
7516     // If there is nothing to do, drop the switch but still execute the expression
7517     TIntermSequence* switchSequence = switchSequenceStack.back();
7518     if (switchSequence->size() == 0)
7519         return expression;
7520
7521     if (lastStatements == nullptr) {
7522         // This was originally an ERRROR, because early versions of the specification said
7523         // "it is an error to have no statement between a label and the end of the switch statement."
7524         // The specifications were updated to remove this (being ill-defined what a "statement" was),
7525         // so, this became a warning.  However, 3.0 tests still check for the error.
7526         if (profile == EEsProfile && version <= 300 && ! relaxedErrors())
7527             error(loc, "last case/default label not followed by statements", "switch", "");
7528         else
7529             warn(loc, "last case/default label not followed by statements", "switch", "");
7530
7531         // emulate a break for error recovery
7532         lastStatements = intermediate.makeAggregate(intermediate.addBranch(EOpBreak, loc));
7533         lastStatements->setOperator(EOpSequence);
7534         switchSequence->push_back(lastStatements);
7535     }
7536
7537     TIntermAggregate* body = new TIntermAggregate(EOpSequence);
7538     body->getSequence() = *switchSequenceStack.back();
7539     body->setLoc(loc);
7540
7541     TIntermSwitch* switchNode = new TIntermSwitch(expression, body);
7542     switchNode->setLoc(loc);
7543
7544     return switchNode;
7545 }
7546
7547 } // end namespace glslang