HLSL: Protect against some crashes
[platform/upstream/glslang.git] / hlsl / hlslParseHelper.cpp
1 //
2 // Copyright (C) 2017-2018 Google, Inc.
3 // Copyright (C) 2017 LunarG, Inc.
4 //
5 // All rights reserved.
6 //
7 // Redistribution and use in source and binary forms, with or without
8 // modification, are permitted provided that the following conditions
9 // are met:
10 //
11 //    Redistributions of source code must retain the above copyright
12 //    notice, this list of conditions and the following disclaimer.
13 //
14 //    Redistributions in binary form must reproduce the above
15 //    copyright notice, this list of conditions and the following
16 //    disclaimer in the documentation and/or other materials provided
17 //    with the distribution.
18 //
19 //    Neither the name of 3Dlabs Inc. Ltd. nor the names of its
20 //    contributors may be used to endorse or promote products derived
21 //    from this software without specific prior written permission.
22 //
23 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26 // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27 // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28 // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29 // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30 // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31 // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33 // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34 // POSSIBILITY OF SUCH DAMAGE.
35 //
36
37 #include "hlslParseHelper.h"
38 #include "hlslScanContext.h"
39 #include "hlslGrammar.h"
40 #include "hlslAttributes.h"
41
42 #include "../glslang/Include/Common.h"
43 #include "../glslang/MachineIndependent/Scan.h"
44 #include "../glslang/MachineIndependent/preprocessor/PpContext.h"
45
46 #include "../glslang/OSDependent/osinclude.h"
47
48 #include <algorithm>
49 #include <functional>
50 #include <cctype>
51 #include <array>
52 #include <set>
53
54 namespace glslang {
55
56 HlslParseContext::HlslParseContext(TSymbolTable& symbolTable, TIntermediate& interm, bool parsingBuiltins,
57                                    int version, EProfile profile, const SpvVersion& spvVersion, EShLanguage language,
58                                    TInfoSink& infoSink,
59                                    const TString sourceEntryPointName,
60                                    bool forwardCompatible, EShMessages messages) :
61     TParseContextBase(symbolTable, interm, parsingBuiltins, version, profile, spvVersion, language, infoSink,
62                       forwardCompatible, messages, &sourceEntryPointName),
63     annotationNestingLevel(0),
64     inputPatch(nullptr),
65     nextInLocation(0), nextOutLocation(0),
66     entryPointFunction(nullptr),
67     entryPointFunctionBody(nullptr),
68     gsStreamOutput(nullptr),
69     clipDistanceOutput(nullptr),
70     cullDistanceOutput(nullptr),
71     clipDistanceInput(nullptr),
72     cullDistanceInput(nullptr)
73 {
74     globalUniformDefaults.clear();
75     globalUniformDefaults.layoutMatrix = ElmRowMajor;
76     globalUniformDefaults.layoutPacking = ElpStd140;
77
78     globalBufferDefaults.clear();
79     globalBufferDefaults.layoutMatrix = ElmRowMajor;
80     globalBufferDefaults.layoutPacking = ElpStd430;
81
82     globalInputDefaults.clear();
83     globalOutputDefaults.clear();
84
85     clipSemanticNSizeIn.fill(0);
86     cullSemanticNSizeIn.fill(0);
87     clipSemanticNSizeOut.fill(0);
88     cullSemanticNSizeOut.fill(0);
89
90     // "Shaders in the transform
91     // feedback capturing mode have an initial global default of
92     //     layout(xfb_buffer = 0) out;"
93     if (language == EShLangVertex ||
94         language == EShLangTessControl ||
95         language == EShLangTessEvaluation ||
96         language == EShLangGeometry)
97         globalOutputDefaults.layoutXfbBuffer = 0;
98
99     if (language == EShLangGeometry)
100         globalOutputDefaults.layoutStream = 0;
101 }
102
103 HlslParseContext::~HlslParseContext()
104 {
105 }
106
107 void HlslParseContext::initializeExtensionBehavior()
108 {
109     TParseContextBase::initializeExtensionBehavior();
110
111     // HLSL allows #line by default.
112     extensionBehavior[E_GL_GOOGLE_cpp_style_line_directive] = EBhEnable;
113 }
114
115 void HlslParseContext::setLimits(const TBuiltInResource& r)
116 {
117     resources = r;
118     intermediate.setLimits(resources);
119 }
120
121 //
122 // Parse an array of strings using the parser in HlslRules.
123 //
124 // Returns true for successful acceptance of the shader, false if any errors.
125 //
126 bool HlslParseContext::parseShaderStrings(TPpContext& ppContext, TInputScanner& input, bool versionWillBeError)
127 {
128     currentScanner = &input;
129     ppContext.setInput(input, versionWillBeError);
130
131     HlslScanContext scanContext(*this, ppContext);
132     HlslGrammar grammar(scanContext, *this);
133     if (!grammar.parse()) {
134         // Print a message formated such that if you click on the message it will take you right to
135         // the line through most UIs.
136         const glslang::TSourceLoc& sourceLoc = input.getSourceLoc();
137         infoSink.info << sourceLoc.getFilenameStr() << "(" << sourceLoc.line << "): error at column " << sourceLoc.column
138                       << ", HLSL parsing failed.\n";
139         ++numErrors;
140         return false;
141     }
142
143     finish();
144
145     return numErrors == 0;
146 }
147
148 //
149 // Return true if this l-value node should be converted in some manner.
150 // For instance: turning a load aggregate into a store in an l-value.
151 //
152 bool HlslParseContext::shouldConvertLValue(const TIntermNode* node) const
153 {
154     if (node == nullptr || node->getAsTyped() == nullptr)
155         return false;
156
157     const TIntermAggregate* lhsAsAggregate = node->getAsAggregate();
158     const TIntermBinary* lhsAsBinary = node->getAsBinaryNode();
159
160     // If it's a swizzled/indexed aggregate, look at the left node instead.
161     if (lhsAsBinary != nullptr &&
162         (lhsAsBinary->getOp() == EOpVectorSwizzle || lhsAsBinary->getOp() == EOpIndexDirect))
163         lhsAsAggregate = lhsAsBinary->getLeft()->getAsAggregate();
164     if (lhsAsAggregate != nullptr && lhsAsAggregate->getOp() == EOpImageLoad)
165         return true;
166
167     return false;
168 }
169
170 void HlslParseContext::growGlobalUniformBlock(const TSourceLoc& loc, TType& memberType, const TString& memberName,
171                                               TTypeList* newTypeList)
172 {
173     newTypeList = nullptr;
174     correctUniform(memberType.getQualifier());
175     if (memberType.isStruct()) {
176         auto it = ioTypeMap.find(memberType.getStruct());
177         if (it != ioTypeMap.end() && it->second.uniform)
178             newTypeList = it->second.uniform;
179     }
180     TParseContextBase::growGlobalUniformBlock(loc, memberType, memberName, newTypeList);
181 }
182
183 //
184 // Return a TLayoutFormat corresponding to the given texture type.
185 //
186 TLayoutFormat HlslParseContext::getLayoutFromTxType(const TSourceLoc& loc, const TType& txType)
187 {
188     if (txType.isStruct()) {
189         // TODO: implement.
190         error(loc, "unimplemented: structure type in image or buffer", "", "");
191         return ElfNone;
192     }
193
194     const int components = txType.getVectorSize();
195     const TBasicType txBasicType = txType.getBasicType();
196
197     const auto selectFormat = [this,&components](TLayoutFormat v1, TLayoutFormat v2, TLayoutFormat v4) -> TLayoutFormat {
198         if (intermediate.getNoStorageFormat())
199             return ElfNone;
200
201         return components == 1 ? v1 :
202                components == 2 ? v2 : v4;
203     };
204
205     switch (txBasicType) {
206     case EbtFloat: return selectFormat(ElfR32f,  ElfRg32f,  ElfRgba32f);
207     case EbtInt:   return selectFormat(ElfR32i,  ElfRg32i,  ElfRgba32i);
208     case EbtUint:  return selectFormat(ElfR32ui, ElfRg32ui, ElfRgba32ui);
209     default:
210         error(loc, "unknown basic type in image format", "", "");
211         return ElfNone;
212     }
213 }
214
215 //
216 // Both test and if necessary, spit out an error, to see if the node is really
217 // an l-value that can be operated on this way.
218 //
219 // Returns true if there was an error.
220 //
221 bool HlslParseContext::lValueErrorCheck(const TSourceLoc& loc, const char* op, TIntermTyped* node)
222 {
223     if (shouldConvertLValue(node)) {
224         // if we're writing to a texture, it must be an RW form.
225
226         TIntermAggregate* lhsAsAggregate = node->getAsAggregate();
227         TIntermTyped* object = lhsAsAggregate->getSequence()[0]->getAsTyped();
228
229         if (!object->getType().getSampler().isImage()) {
230             error(loc, "operator[] on a non-RW texture must be an r-value", "", "");
231             return true;
232         }
233     }
234
235     // We tolerate samplers as l-values, even though they are nominally
236     // illegal, because we expect a later optimization to eliminate them.
237     if (node->getType().getBasicType() == EbtSampler) {
238         intermediate.setNeedsLegalization();
239         return false;
240     }
241
242     // Let the base class check errors
243     return TParseContextBase::lValueErrorCheck(loc, op, node);
244 }
245
246 //
247 // This function handles l-value conversions and verifications.  It uses, but is not synonymous
248 // with lValueErrorCheck.  That function accepts an l-value directly, while this one must be
249 // given the surrounding tree - e.g, with an assignment, so we can convert the assign into a
250 // series of other image operations.
251 //
252 // Most things are passed through unmodified, except for error checking.
253 //
254 TIntermTyped* HlslParseContext::handleLvalue(const TSourceLoc& loc, const char* op, TIntermTyped*& node)
255 {
256     if (node == nullptr)
257         return nullptr;
258
259     TIntermBinary* nodeAsBinary = node->getAsBinaryNode();
260     TIntermUnary* nodeAsUnary = node->getAsUnaryNode();
261     TIntermAggregate* sequence = nullptr;
262
263     TIntermTyped* lhs = nodeAsUnary  ? nodeAsUnary->getOperand() :
264                         nodeAsBinary ? nodeAsBinary->getLeft() :
265                         nullptr;
266
267     // Early bail out if there is no conversion to apply
268     if (!shouldConvertLValue(lhs)) {
269         if (lhs != nullptr)
270             if (lValueErrorCheck(loc, op, lhs))
271                 return nullptr;
272         return node;
273     }
274
275     // *** If we get here, we're going to apply some conversion to an l-value.
276
277     // Helper to create a load.
278     const auto makeLoad = [&](TIntermSymbol* rhsTmp, TIntermTyped* object, TIntermTyped* coord, const TType& derefType) {
279         TIntermAggregate* loadOp = new TIntermAggregate(EOpImageLoad);
280         loadOp->setLoc(loc);
281         loadOp->getSequence().push_back(object);
282         loadOp->getSequence().push_back(intermediate.addSymbol(*coord->getAsSymbolNode()));
283         loadOp->setType(derefType);
284
285         sequence = intermediate.growAggregate(sequence,
286                                               intermediate.addAssign(EOpAssign, rhsTmp, loadOp, loc),
287                                               loc);
288     };
289
290     // Helper to create a store.
291     const auto makeStore = [&](TIntermTyped* object, TIntermTyped* coord, TIntermSymbol* rhsTmp) {
292         TIntermAggregate* storeOp = new TIntermAggregate(EOpImageStore);
293         storeOp->getSequence().push_back(object);
294         storeOp->getSequence().push_back(coord);
295         storeOp->getSequence().push_back(intermediate.addSymbol(*rhsTmp));
296         storeOp->setLoc(loc);
297         storeOp->setType(TType(EbtVoid));
298
299         sequence = intermediate.growAggregate(sequence, storeOp);
300     };
301
302     // Helper to create an assign.
303     const auto makeBinary = [&](TOperator op, TIntermTyped* lhs, TIntermTyped* rhs) {
304         sequence = intermediate.growAggregate(sequence,
305                                               intermediate.addBinaryNode(op, lhs, rhs, loc, lhs->getType()),
306                                               loc);
307     };
308
309     // Helper to complete sequence by adding trailing variable, so we evaluate to the right value.
310     const auto finishSequence = [&](TIntermSymbol* rhsTmp, const TType& derefType) -> TIntermAggregate* {
311         // Add a trailing use of the temp, so the sequence returns the proper value.
312         sequence = intermediate.growAggregate(sequence, intermediate.addSymbol(*rhsTmp));
313         sequence->setOperator(EOpSequence);
314         sequence->setLoc(loc);
315         sequence->setType(derefType);
316
317         return sequence;
318     };
319
320     // Helper to add unary op
321     const auto makeUnary = [&](TOperator op, TIntermSymbol* rhsTmp) {
322         sequence = intermediate.growAggregate(sequence,
323                                               intermediate.addUnaryNode(op, intermediate.addSymbol(*rhsTmp), loc,
324                                                                         rhsTmp->getType()),
325                                               loc);
326     };
327
328     // Return true if swizzle or index writes all components of the given variable.
329     const auto writesAllComponents = [&](TIntermSymbol* var, TIntermBinary* swizzle) -> bool {
330         if (swizzle == nullptr)  // not a swizzle or index
331             return true;
332
333         // Track which components are being set.
334         std::array<bool, 4> compIsSet;
335         compIsSet.fill(false);
336
337         const TIntermConstantUnion* asConst     = swizzle->getRight()->getAsConstantUnion();
338         const TIntermAggregate*     asAggregate = swizzle->getRight()->getAsAggregate();
339
340         // This could be either a direct index, or a swizzle.
341         if (asConst) {
342             compIsSet[asConst->getConstArray()[0].getIConst()] = true;
343         } else if (asAggregate) {
344             const TIntermSequence& seq = asAggregate->getSequence();
345             for (int comp=0; comp<int(seq.size()); ++comp)
346                 compIsSet[seq[comp]->getAsConstantUnion()->getConstArray()[0].getIConst()] = true;
347         } else {
348             assert(0);
349         }
350
351         // Return true if all components are being set by the index or swizzle
352         return std::all_of(compIsSet.begin(), compIsSet.begin() + var->getType().getVectorSize(),
353                            [](bool isSet) { return isSet; } );
354     };
355
356     // Create swizzle matching input swizzle
357     const auto addSwizzle = [&](TIntermSymbol* var, TIntermBinary* swizzle) -> TIntermTyped* {
358         if (swizzle)
359             return intermediate.addBinaryNode(swizzle->getOp(), var, swizzle->getRight(), loc, swizzle->getType());
360         else
361             return var;
362     };
363
364     TIntermBinary*    lhsAsBinary    = lhs->getAsBinaryNode();
365     TIntermAggregate* lhsAsAggregate = lhs->getAsAggregate();
366     bool lhsIsSwizzle = false;
367
368     // If it's a swizzled L-value, remember the swizzle, and use the LHS.
369     if (lhsAsBinary != nullptr && (lhsAsBinary->getOp() == EOpVectorSwizzle || lhsAsBinary->getOp() == EOpIndexDirect)) {
370         lhsAsAggregate = lhsAsBinary->getLeft()->getAsAggregate();
371         lhsIsSwizzle = true;
372     }
373
374     TIntermTyped* object = lhsAsAggregate->getSequence()[0]->getAsTyped();
375     TIntermTyped* coord  = lhsAsAggregate->getSequence()[1]->getAsTyped();
376
377     const TSampler& texSampler = object->getType().getSampler();
378
379     TType objDerefType;
380     getTextureReturnType(texSampler, objDerefType);
381
382     if (nodeAsBinary) {
383         TIntermTyped* rhs = nodeAsBinary->getRight();
384         const TOperator assignOp = nodeAsBinary->getOp();
385
386         bool isModifyOp = false;
387
388         switch (assignOp) {
389         case EOpAddAssign:
390         case EOpSubAssign:
391         case EOpMulAssign:
392         case EOpVectorTimesMatrixAssign:
393         case EOpVectorTimesScalarAssign:
394         case EOpMatrixTimesScalarAssign:
395         case EOpMatrixTimesMatrixAssign:
396         case EOpDivAssign:
397         case EOpModAssign:
398         case EOpAndAssign:
399         case EOpInclusiveOrAssign:
400         case EOpExclusiveOrAssign:
401         case EOpLeftShiftAssign:
402         case EOpRightShiftAssign:
403             isModifyOp = true;
404             // fall through...
405         case EOpAssign:
406             {
407                 // Since this is an lvalue, we'll convert an image load to a sequence like this
408                 // (to still provide the value):
409                 //   OpSequence
410                 //      OpImageStore(object, lhs, rhs)
411                 //      rhs
412                 // But if it's not a simple symbol RHS (say, a fn call), we don't want to duplicate the RHS,
413                 // so we'll convert instead to this:
414                 //   OpSequence
415                 //      rhsTmp = rhs
416                 //      OpImageStore(object, coord, rhsTmp)
417                 //      rhsTmp
418                 // If this is a read-modify-write op, like +=, we issue:
419                 //   OpSequence
420                 //      coordtmp = load's param1
421                 //      rhsTmp = OpImageLoad(object, coordTmp)
422                 //      rhsTmp op= rhs
423                 //      OpImageStore(object, coordTmp, rhsTmp)
424                 //      rhsTmp
425                 //
426                 // If the lvalue is swizzled, we apply that when writing the temp variable, like so:
427                 //    ...
428                 //    rhsTmp.some_swizzle = ...
429                 // For partial writes, an error is generated.
430
431                 TIntermSymbol* rhsTmp = rhs->getAsSymbolNode();
432                 TIntermTyped* coordTmp = coord;
433
434                 if (rhsTmp == nullptr || isModifyOp || lhsIsSwizzle) {
435                     rhsTmp = makeInternalVariableNode(loc, "storeTemp", objDerefType);
436
437                     // Partial updates not yet supported
438                     if (!writesAllComponents(rhsTmp, lhsAsBinary)) {
439                         error(loc, "unimplemented: partial image updates", "", "");
440                     }
441
442                     // Assign storeTemp = rhs
443                     if (isModifyOp) {
444                         // We have to make a temp var for the coordinate, to avoid evaluating it twice.
445                         coordTmp = makeInternalVariableNode(loc, "coordTemp", coord->getType());
446                         makeBinary(EOpAssign, coordTmp, coord); // coordtmp = load[param1]
447                         makeLoad(rhsTmp, object, coordTmp, objDerefType); // rhsTmp = OpImageLoad(object, coordTmp)
448                     }
449
450                     // rhsTmp op= rhs.
451                     makeBinary(assignOp, addSwizzle(intermediate.addSymbol(*rhsTmp), lhsAsBinary), rhs);
452                 }
453
454                 makeStore(object, coordTmp, rhsTmp);         // add a store
455                 return finishSequence(rhsTmp, objDerefType); // return rhsTmp from sequence
456             }
457
458         default:
459             break;
460         }
461     }
462
463     if (nodeAsUnary) {
464         const TOperator assignOp = nodeAsUnary->getOp();
465
466         switch (assignOp) {
467         case EOpPreIncrement:
468         case EOpPreDecrement:
469             {
470                 // We turn this into:
471                 //   OpSequence
472                 //      coordtmp = load's param1
473                 //      rhsTmp = OpImageLoad(object, coordTmp)
474                 //      rhsTmp op
475                 //      OpImageStore(object, coordTmp, rhsTmp)
476                 //      rhsTmp
477
478                 TIntermSymbol* rhsTmp = makeInternalVariableNode(loc, "storeTemp", objDerefType);
479                 TIntermTyped* coordTmp = makeInternalVariableNode(loc, "coordTemp", coord->getType());
480
481                 makeBinary(EOpAssign, coordTmp, coord);           // coordtmp = load[param1]
482                 makeLoad(rhsTmp, object, coordTmp, objDerefType); // rhsTmp = OpImageLoad(object, coordTmp)
483                 makeUnary(assignOp, rhsTmp);                      // op rhsTmp
484                 makeStore(object, coordTmp, rhsTmp);              // OpImageStore(object, coordTmp, rhsTmp)
485                 return finishSequence(rhsTmp, objDerefType);      // return rhsTmp from sequence
486             }
487
488         case EOpPostIncrement:
489         case EOpPostDecrement:
490             {
491                 // We turn this into:
492                 //   OpSequence
493                 //      coordtmp = load's param1
494                 //      rhsTmp1 = OpImageLoad(object, coordTmp)
495                 //      rhsTmp2 = rhsTmp1
496                 //      rhsTmp2 op
497                 //      OpImageStore(object, coordTmp, rhsTmp2)
498                 //      rhsTmp1 (pre-op value)
499                 TIntermSymbol* rhsTmp1 = makeInternalVariableNode(loc, "storeTempPre",  objDerefType);
500                 TIntermSymbol* rhsTmp2 = makeInternalVariableNode(loc, "storeTempPost", objDerefType);
501                 TIntermTyped* coordTmp = makeInternalVariableNode(loc, "coordTemp", coord->getType());
502
503                 makeBinary(EOpAssign, coordTmp, coord);            // coordtmp = load[param1]
504                 makeLoad(rhsTmp1, object, coordTmp, objDerefType); // rhsTmp1 = OpImageLoad(object, coordTmp)
505                 makeBinary(EOpAssign, rhsTmp2, rhsTmp1);           // rhsTmp2 = rhsTmp1
506                 makeUnary(assignOp, rhsTmp2);                      // rhsTmp op
507                 makeStore(object, coordTmp, rhsTmp2);              // OpImageStore(object, coordTmp, rhsTmp2)
508                 return finishSequence(rhsTmp1, objDerefType);      // return rhsTmp from sequence
509             }
510
511         default:
512             break;
513         }
514     }
515
516     if (lhs)
517         if (lValueErrorCheck(loc, op, lhs))
518             return nullptr;
519
520     return node;
521 }
522
523 void HlslParseContext::handlePragma(const TSourceLoc& loc, const TVector<TString>& tokens)
524 {
525     if (pragmaCallback)
526         pragmaCallback(loc.line, tokens);
527
528     if (tokens.size() == 0)
529         return;
530
531     // These pragmas are case insensitive in HLSL, so we'll compare in lower case.
532     TVector<TString> lowerTokens = tokens;
533
534     for (auto it = lowerTokens.begin(); it != lowerTokens.end(); ++it)
535         std::transform(it->begin(), it->end(), it->begin(), ::tolower);
536
537     // Handle pack_matrix
538     if (tokens.size() == 4 && lowerTokens[0] == "pack_matrix" && tokens[1] == "(" && tokens[3] == ")") {
539         // Note that HLSL semantic order is Mrc, not Mcr like SPIR-V, so we reverse the sense.
540         // Row major becomes column major and vice versa.
541
542         if (lowerTokens[2] == "row_major") {
543             globalUniformDefaults.layoutMatrix = globalBufferDefaults.layoutMatrix = ElmColumnMajor;
544         } else if (lowerTokens[2] == "column_major") {
545             globalUniformDefaults.layoutMatrix = globalBufferDefaults.layoutMatrix = ElmRowMajor;
546         } else {
547             // unknown majorness strings are treated as (HLSL column major)==(SPIR-V row major)
548             warn(loc, "unknown pack_matrix pragma value", tokens[2].c_str(), "");
549             globalUniformDefaults.layoutMatrix = globalBufferDefaults.layoutMatrix = ElmRowMajor;
550         }
551         return;
552     }
553
554     // Handle once
555     if (lowerTokens[0] == "once") {
556         warn(loc, "not implemented", "#pragma once", "");
557         return;
558     }
559 }
560
561 //
562 // Look at a '.' matrix selector string and change it into components
563 // for a matrix. There are two types:
564 //
565 //   _21    second row, first column (one based)
566 //   _m21   third row, second column (zero based)
567 //
568 // Returns true if there is no error.
569 //
570 bool HlslParseContext::parseMatrixSwizzleSelector(const TSourceLoc& loc, const TString& fields, int cols, int rows,
571                                                   TSwizzleSelectors<TMatrixSelector>& components)
572 {
573     int startPos[MaxSwizzleSelectors];
574     int numComps = 0;
575     TString compString = fields;
576
577     // Find where each component starts,
578     // recording the first character position after the '_'.
579     for (size_t c = 0; c < compString.size(); ++c) {
580         if (compString[c] == '_') {
581             if (numComps >= MaxSwizzleSelectors) {
582                 error(loc, "matrix component swizzle has too many components", compString.c_str(), "");
583                 return false;
584             }
585             if (c > compString.size() - 3 ||
586                     ((compString[c+1] == 'm' || compString[c+1] == 'M') && c > compString.size() - 4)) {
587                 error(loc, "matrix component swizzle missing", compString.c_str(), "");
588                 return false;
589             }
590             startPos[numComps++] = (int)c + 1;
591         }
592     }
593
594     // Process each component
595     for (int i = 0; i < numComps; ++i) {
596         int pos = startPos[i];
597         int bias = -1;
598         if (compString[pos] == 'm' || compString[pos] == 'M') {
599             bias = 0;
600             ++pos;
601         }
602         TMatrixSelector comp;
603         comp.coord1 = compString[pos+0] - '0' + bias;
604         comp.coord2 = compString[pos+1] - '0' + bias;
605         if (comp.coord1 < 0 || comp.coord1 >= cols) {
606             error(loc, "matrix row component out of range", compString.c_str(), "");
607             return false;
608         }
609         if (comp.coord2 < 0 || comp.coord2 >= rows) {
610             error(loc, "matrix column component out of range", compString.c_str(), "");
611             return false;
612         }
613         components.push_back(comp);
614     }
615
616     return true;
617 }
618
619 // If the 'comps' express a column of a matrix,
620 // return the column.  Column means the first coords all match.
621 //
622 // Otherwise, return -1.
623 //
624 int HlslParseContext::getMatrixComponentsColumn(int rows, const TSwizzleSelectors<TMatrixSelector>& selector)
625 {
626     int col = -1;
627
628     // right number of comps?
629     if (selector.size() != rows)
630         return -1;
631
632     // all comps in the same column?
633     // rows in order?
634     col = selector[0].coord1;
635     for (int i = 0; i < rows; ++i) {
636         if (col != selector[i].coord1)
637             return -1;
638         if (i != selector[i].coord2)
639             return -1;
640     }
641
642     return col;
643 }
644
645 //
646 // Handle seeing a variable identifier in the grammar.
647 //
648 TIntermTyped* HlslParseContext::handleVariable(const TSourceLoc& loc, const TString* string)
649 {
650     int thisDepth;
651     TSymbol* symbol = symbolTable.find(*string, thisDepth);
652     if (symbol && symbol->getAsVariable() && symbol->getAsVariable()->isUserType()) {
653         error(loc, "expected symbol, not user-defined type", string->c_str(), "");
654         return nullptr;
655     }
656
657     // Error check for requiring specific extensions present.
658     if (symbol && symbol->getNumExtensions())
659         requireExtensions(loc, symbol->getNumExtensions(), symbol->getExtensions(), symbol->getName().c_str());
660
661     const TVariable* variable = nullptr;
662     const TAnonMember* anon = symbol ? symbol->getAsAnonMember() : nullptr;
663     TIntermTyped* node = nullptr;
664     if (anon) {
665         // It was a member of an anonymous container, which could be a 'this' structure.
666
667         // Create a subtree for its dereference.
668         if (thisDepth > 0) {
669             variable = getImplicitThis(thisDepth);
670             if (variable == nullptr)
671                 error(loc, "cannot access member variables (static member function?)", "this", "");
672         }
673         if (variable == nullptr)
674             variable = anon->getAnonContainer().getAsVariable();
675
676         TIntermTyped* container = intermediate.addSymbol(*variable, loc);
677         TIntermTyped* constNode = intermediate.addConstantUnion(anon->getMemberNumber(), loc);
678         node = intermediate.addIndex(EOpIndexDirectStruct, container, constNode, loc);
679
680         node->setType(*(*variable->getType().getStruct())[anon->getMemberNumber()].type);
681         if (node->getType().hiddenMember())
682             error(loc, "member of nameless block was not redeclared", string->c_str(), "");
683     } else {
684         // Not a member of an anonymous container.
685
686         // The symbol table search was done in the lexical phase.
687         // See if it was a variable.
688         variable = symbol ? symbol->getAsVariable() : nullptr;
689         if (variable) {
690             if ((variable->getType().getBasicType() == EbtBlock ||
691                 variable->getType().getBasicType() == EbtStruct) && variable->getType().getStruct() == nullptr) {
692                 error(loc, "cannot be used (maybe an instance name is needed)", string->c_str(), "");
693                 variable = nullptr;
694             }
695         } else {
696             if (symbol)
697                 error(loc, "variable name expected", string->c_str(), "");
698         }
699
700         // Recovery, if it wasn't found or was not a variable.
701         if (variable == nullptr) {
702             error(loc, "unknown variable", string->c_str(), "");
703             variable = new TVariable(string, TType(EbtVoid));
704         }
705
706         if (variable->getType().getQualifier().isFrontEndConstant())
707             node = intermediate.addConstantUnion(variable->getConstArray(), variable->getType(), loc);
708         else
709             node = intermediate.addSymbol(*variable, loc);
710     }
711
712     if (variable->getType().getQualifier().isIo())
713         intermediate.addIoAccessed(*string);
714
715     return node;
716 }
717
718 //
719 // Handle operator[] on any objects it applies to.  Currently:
720 //    Textures
721 //    Buffers
722 //
723 TIntermTyped* HlslParseContext::handleBracketOperator(const TSourceLoc& loc, TIntermTyped* base, TIntermTyped* index)
724 {
725     // handle r-value operator[] on textures and images.  l-values will be processed later.
726     if (base->getType().getBasicType() == EbtSampler && !base->isArray()) {
727         const TSampler& sampler = base->getType().getSampler();
728         if (sampler.isImage() || sampler.isTexture()) {
729             if (! mipsOperatorMipArg.empty() && mipsOperatorMipArg.back().mipLevel == nullptr) {
730                 // The first operator[] to a .mips[] sequence is the mip level.  We'll remember it.
731                 mipsOperatorMipArg.back().mipLevel = index;
732                 return base;  // next [] index is to the same base.
733             } else {
734                 TIntermAggregate* load = new TIntermAggregate(sampler.isImage() ? EOpImageLoad : EOpTextureFetch);
735
736                 TType sampReturnType;
737                 getTextureReturnType(sampler, sampReturnType);
738
739                 load->setType(sampReturnType);
740                 load->setLoc(loc);
741                 load->getSequence().push_back(base);
742                 load->getSequence().push_back(index);
743
744                 // Textures need a MIP.  If we saw one go by, use it.  Otherwise, use zero.
745                 if (sampler.isTexture()) {
746                     if (! mipsOperatorMipArg.empty()) {
747                         load->getSequence().push_back(mipsOperatorMipArg.back().mipLevel);
748                         mipsOperatorMipArg.pop_back();
749                     } else {
750                         load->getSequence().push_back(intermediate.addConstantUnion(0, loc, true));
751                     }
752                 }
753
754                 return load;
755             }
756         }
757     }
758
759     // Handle operator[] on structured buffers: this indexes into the array element of the buffer.
760     // indexStructBufferContent returns nullptr if it isn't a structuredbuffer (SSBO).
761     TIntermTyped* sbArray = indexStructBufferContent(loc, base);
762     if (sbArray != nullptr) {
763         if (sbArray == nullptr)
764             return nullptr;
765
766         // Now we'll apply the [] index to that array
767         const TOperator idxOp = (index->getQualifier().storage == EvqConst) ? EOpIndexDirect : EOpIndexIndirect;
768
769         TIntermTyped* element = intermediate.addIndex(idxOp, sbArray, index, loc);
770         const TType derefType(sbArray->getType(), 0);
771         element->setType(derefType);
772         return element;
773     }
774
775     return nullptr;
776 }
777
778 //
779 // Cast index value to a uint if it isn't already (for operator[], load indexes, etc)
780 TIntermTyped* HlslParseContext::makeIntegerIndex(TIntermTyped* index)
781 {
782     const TBasicType indexBasicType = index->getType().getBasicType();
783     const int vecSize = index->getType().getVectorSize();
784
785     // We can use int types directly as the index
786     if (indexBasicType == EbtInt || indexBasicType == EbtUint ||
787         indexBasicType == EbtInt64 || indexBasicType == EbtUint64)
788         return index;
789
790     // Cast index to unsigned integer if it isn't one.
791     return intermediate.addConversion(EOpConstructUint, TType(EbtUint, EvqTemporary, vecSize), index);
792 }
793
794 //
795 // Handle seeing a base[index] dereference in the grammar.
796 //
797 TIntermTyped* HlslParseContext::handleBracketDereference(const TSourceLoc& loc, TIntermTyped* base, TIntermTyped* index)
798 {
799     index = makeIntegerIndex(index);
800
801     if (index == nullptr) {
802         error(loc, " unknown index type ", "", "");
803         return nullptr;
804     }
805
806     TIntermTyped* result = handleBracketOperator(loc, base, index);
807
808     if (result != nullptr)
809         return result;  // it was handled as an operator[]
810
811     bool flattened = false;
812     int indexValue = 0;
813     if (index->getQualifier().isFrontEndConstant())
814         indexValue = index->getAsConstantUnion()->getConstArray()[0].getIConst();
815
816     variableCheck(base);
817     if (! base->isArray() && ! base->isMatrix() && ! base->isVector()) {
818         if (base->getAsSymbolNode())
819             error(loc, " left of '[' is not of type array, matrix, or vector ",
820                   base->getAsSymbolNode()->getName().c_str(), "");
821         else
822             error(loc, " left of '[' is not of type array, matrix, or vector ", "expression", "");
823     } else if (base->getType().getQualifier().storage == EvqConst && index->getQualifier().storage == EvqConst) {
824         // both base and index are front-end constants
825         checkIndex(loc, base->getType(), indexValue);
826         return intermediate.foldDereference(base, indexValue, loc);
827     } else {
828         // at least one of base and index is variable...
829
830         if (index->getQualifier().isFrontEndConstant())
831             checkIndex(loc, base->getType(), indexValue);
832
833         if (base->getType().isScalarOrVec1())
834             result = base;
835         else if (base->getAsSymbolNode() && wasFlattened(base)) {
836             if (index->getQualifier().storage != EvqConst)
837                 error(loc, "Invalid variable index to flattened array", base->getAsSymbolNode()->getName().c_str(), "");
838
839             result = flattenAccess(base, indexValue);
840             flattened = (result != base);
841         } else {
842             if (index->getQualifier().isFrontEndConstant()) {
843                 if (base->getType().isUnsizedArray())
844                     base->getWritableType().updateImplicitArraySize(indexValue + 1);
845                 else
846                     checkIndex(loc, base->getType(), indexValue);
847                 result = intermediate.addIndex(EOpIndexDirect, base, index, loc);
848             } else
849                 result = intermediate.addIndex(EOpIndexIndirect, base, index, loc);
850         }
851     }
852
853     if (result == nullptr) {
854         // Insert dummy error-recovery result
855         result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
856     } else {
857         // If the array reference was flattened, it has the correct type.  E.g, if it was
858         // a uniform array, it was flattened INTO a set of scalar uniforms, not scalar temps.
859         // In that case, we preserve the qualifiers.
860         if (!flattened) {
861             // Insert valid dereferenced result
862             TType newType(base->getType(), 0);  // dereferenced type
863             if (base->getType().getQualifier().storage == EvqConst && index->getQualifier().storage == EvqConst)
864                 newType.getQualifier().storage = EvqConst;
865             else
866                 newType.getQualifier().storage = EvqTemporary;
867             result->setType(newType);
868         }
869     }
870
871     return result;
872 }
873
874 // Handle seeing a binary node with a math operation.
875 TIntermTyped* HlslParseContext::handleBinaryMath(const TSourceLoc& loc, const char* str, TOperator op,
876                                                  TIntermTyped* left, TIntermTyped* right)
877 {
878     TIntermTyped* result = intermediate.addBinaryMath(op, left, right, loc);
879     if (result == nullptr)
880         binaryOpError(loc, str, left->getCompleteString(), right->getCompleteString());
881
882     return result;
883 }
884
885 // Handle seeing a unary node with a math operation.
886 TIntermTyped* HlslParseContext::handleUnaryMath(const TSourceLoc& loc, const char* str, TOperator op,
887                                                 TIntermTyped* childNode)
888 {
889     TIntermTyped* result = intermediate.addUnaryMath(op, childNode, loc);
890
891     if (result)
892         return result;
893     else
894         unaryOpError(loc, str, childNode->getCompleteString());
895
896     return childNode;
897 }
898 //
899 // Return true if the name is a struct buffer method
900 //
901 bool HlslParseContext::isStructBufferMethod(const TString& name) const
902 {
903     return
904         name == "GetDimensions"              ||
905         name == "Load"                       ||
906         name == "Load2"                      ||
907         name == "Load3"                      ||
908         name == "Load4"                      ||
909         name == "Store"                      ||
910         name == "Store2"                     ||
911         name == "Store3"                     ||
912         name == "Store4"                     ||
913         name == "InterlockedAdd"             ||
914         name == "InterlockedAnd"             ||
915         name == "InterlockedCompareExchange" ||
916         name == "InterlockedCompareStore"    ||
917         name == "InterlockedExchange"        ||
918         name == "InterlockedMax"             ||
919         name == "InterlockedMin"             ||
920         name == "InterlockedOr"              ||
921         name == "InterlockedXor"             ||
922         name == "IncrementCounter"           ||
923         name == "DecrementCounter"           ||
924         name == "Append"                     ||
925         name == "Consume";
926 }
927
928 //
929 // Handle seeing a base.field dereference in the grammar, where 'field' is a
930 // swizzle or member variable.
931 //
932 TIntermTyped* HlslParseContext::handleDotDereference(const TSourceLoc& loc, TIntermTyped* base, const TString& field)
933 {
934     variableCheck(base);
935
936     if (base->isArray()) {
937         error(loc, "cannot apply to an array:", ".", field.c_str());
938         return base;
939     }
940
941     TIntermTyped* result = base;
942
943     if (base->getType().getBasicType() == EbtSampler) {
944         // Handle .mips[mipid][pos] operation on textures
945         const TSampler& sampler = base->getType().getSampler();
946         if (sampler.isTexture() && field == "mips") {
947             // Push a null to signify that we expect a mip level under operator[] next.
948             mipsOperatorMipArg.push_back(tMipsOperatorData(loc, nullptr));
949             // Keep 'result' pointing to 'base', since we expect an operator[] to go by next.
950         } else {
951             if (field == "mips")
952                 error(loc, "unexpected texture type for .mips[][] operator:",
953                       base->getType().getCompleteString().c_str(), "");
954             else
955                 error(loc, "unexpected operator on texture type:", field.c_str(),
956                       base->getType().getCompleteString().c_str());
957         }
958     } else if (base->isVector() || base->isScalar()) {
959         TSwizzleSelectors<TVectorSelector> selectors;
960         parseSwizzleSelector(loc, field, base->getVectorSize(), selectors);
961
962         if (base->isScalar()) {
963             if (selectors.size() == 1)
964                 return result;
965             else {
966                 TType type(base->getBasicType(), EvqTemporary, selectors.size());
967                 return addConstructor(loc, base, type);
968             }
969         }
970         if (base->getVectorSize() == 1) {
971             TType scalarType(base->getBasicType(), EvqTemporary, 1);
972             if (selectors.size() == 1)
973                 return addConstructor(loc, base, scalarType);
974             else {
975                 TType vectorType(base->getBasicType(), EvqTemporary, selectors.size());
976                 return addConstructor(loc, addConstructor(loc, base, scalarType), vectorType);
977             }
978         }
979
980         if (base->getType().getQualifier().isFrontEndConstant())
981             result = intermediate.foldSwizzle(base, selectors, loc);
982         else {
983             if (selectors.size() == 1) {
984                 TIntermTyped* index = intermediate.addConstantUnion(selectors[0], loc);
985                 result = intermediate.addIndex(EOpIndexDirect, base, index, loc);
986                 result->setType(TType(base->getBasicType(), EvqTemporary));
987             } else {
988                 TIntermTyped* index = intermediate.addSwizzle(selectors, loc);
989                 result = intermediate.addIndex(EOpVectorSwizzle, base, index, loc);
990                 result->setType(TType(base->getBasicType(), EvqTemporary, base->getType().getQualifier().precision,
991                                 selectors.size()));
992             }
993         }
994     } else if (base->isMatrix()) {
995         TSwizzleSelectors<TMatrixSelector> selectors;
996         if (! parseMatrixSwizzleSelector(loc, field, base->getMatrixCols(), base->getMatrixRows(), selectors))
997             return result;
998
999         if (selectors.size() == 1) {
1000             // Representable by m[c][r]
1001             if (base->getType().getQualifier().isFrontEndConstant()) {
1002                 result = intermediate.foldDereference(base, selectors[0].coord1, loc);
1003                 result = intermediate.foldDereference(result, selectors[0].coord2, loc);
1004             } else {
1005                 result = intermediate.addIndex(EOpIndexDirect, base,
1006                                                intermediate.addConstantUnion(selectors[0].coord1, loc),
1007                                                loc);
1008                 TType dereferencedCol(base->getType(), 0);
1009                 result->setType(dereferencedCol);
1010                 result = intermediate.addIndex(EOpIndexDirect, result,
1011                                                intermediate.addConstantUnion(selectors[0].coord2, loc),
1012                                                loc);
1013                 TType dereferenced(dereferencedCol, 0);
1014                 result->setType(dereferenced);
1015             }
1016         } else {
1017             int column = getMatrixComponentsColumn(base->getMatrixRows(), selectors);
1018             if (column >= 0) {
1019                 // Representable by m[c]
1020                 if (base->getType().getQualifier().isFrontEndConstant())
1021                     result = intermediate.foldDereference(base, column, loc);
1022                 else {
1023                     result = intermediate.addIndex(EOpIndexDirect, base, intermediate.addConstantUnion(column, loc),
1024                                                    loc);
1025                     TType dereferenced(base->getType(), 0);
1026                     result->setType(dereferenced);
1027                 }
1028             } else {
1029                 // general case, not a column, not a single component
1030                 TIntermTyped* index = intermediate.addSwizzle(selectors, loc);
1031                 result = intermediate.addIndex(EOpMatrixSwizzle, base, index, loc);
1032                 result->setType(TType(base->getBasicType(), EvqTemporary, base->getType().getQualifier().precision,
1033                                       selectors.size()));
1034            }
1035         }
1036     } else if (base->getBasicType() == EbtStruct || base->getBasicType() == EbtBlock) {
1037         const TTypeList* fields = base->getType().getStruct();
1038         bool fieldFound = false;
1039         int member;
1040         for (member = 0; member < (int)fields->size(); ++member) {
1041             if ((*fields)[member].type->getFieldName() == field) {
1042                 fieldFound = true;
1043                 break;
1044             }
1045         }
1046         if (fieldFound) {
1047             if (base->getAsSymbolNode() && wasFlattened(base)) {
1048                 result = flattenAccess(base, member);
1049             } else {
1050                 if (base->getType().getQualifier().storage == EvqConst)
1051                     result = intermediate.foldDereference(base, member, loc);
1052                 else {
1053                     TIntermTyped* index = intermediate.addConstantUnion(member, loc);
1054                     result = intermediate.addIndex(EOpIndexDirectStruct, base, index, loc);
1055                     result->setType(*(*fields)[member].type);
1056                 }
1057             }
1058         } else
1059             error(loc, "no such field in structure", field.c_str(), "");
1060     } else
1061         error(loc, "does not apply to this type:", field.c_str(), base->getType().getCompleteString().c_str());
1062
1063     return result;
1064 }
1065
1066 //
1067 // Return true if the field should be treated as a built-in method.
1068 // Return false otherwise.
1069 //
1070 bool HlslParseContext::isBuiltInMethod(const TSourceLoc&, TIntermTyped* base, const TString& field)
1071 {
1072     if (base == nullptr)
1073         return false;
1074
1075     variableCheck(base);
1076
1077     if (base->getType().getBasicType() == EbtSampler) {
1078         return true;
1079     } else if (isStructBufferType(base->getType()) && isStructBufferMethod(field)) {
1080         return true;
1081     } else if (field == "Append" ||
1082                field == "RestartStrip") {
1083         // We cannot check the type here: it may be sanitized if we're not compiling a geometry shader, but
1084         // the code is around in the shader source.
1085         return true;
1086     } else
1087         return false;
1088 }
1089
1090 // Independently establish a built-in that is a member of a structure.
1091 // 'arraySizes' are what's desired for the independent built-in, whatever
1092 // the higher-level source/expression of them was.
1093 void HlslParseContext::splitBuiltIn(const TString& baseName, const TType& memberType, const TArraySizes* arraySizes,
1094                                     const TQualifier& outerQualifier)
1095 {
1096     // Because of arrays of structs, we might be asked more than once,
1097     // but the arraySizes passed in should have captured the whole thing
1098     // the first time.
1099     // However, clip/cull rely on multiple updates.
1100     if (!isClipOrCullDistance(memberType))
1101         if (splitBuiltIns.find(tInterstageIoData(memberType.getQualifier().builtIn, outerQualifier.storage)) !=
1102             splitBuiltIns.end())
1103             return;
1104
1105     TVariable* ioVar = makeInternalVariable(baseName + "." + memberType.getFieldName(), memberType);
1106
1107     if (arraySizes != nullptr && !memberType.isArray())
1108         ioVar->getWritableType().copyArraySizes(*arraySizes);
1109
1110     splitBuiltIns[tInterstageIoData(memberType.getQualifier().builtIn, outerQualifier.storage)] = ioVar;
1111     if (!isClipOrCullDistance(ioVar->getType()))
1112         trackLinkage(*ioVar);
1113
1114     // Merge qualifier from the user structure
1115     mergeQualifiers(ioVar->getWritableType().getQualifier(), outerQualifier);
1116
1117     // Fix the builtin type if needed (e.g, some types require fixed array sizes, no matter how the
1118     // shader declared them).  This is done after mergeQualifiers(), in case fixBuiltInIoType looks
1119     // at the qualifier to determine e.g, in or out qualifications.
1120     fixBuiltInIoType(ioVar->getWritableType());
1121
1122     // But, not location, we're losing that
1123     ioVar->getWritableType().getQualifier().layoutLocation = TQualifier::layoutLocationEnd;
1124 }
1125
1126 // Split a type into
1127 //   1. a struct of non-I/O members
1128 //   2. a collection of independent I/O variables
1129 void HlslParseContext::split(const TVariable& variable)
1130 {
1131     // Create a new variable:
1132     const TType& clonedType = *variable.getType().clone();
1133     const TType& splitType = split(clonedType, variable.getName(), clonedType.getQualifier());
1134     splitNonIoVars[variable.getUniqueId()] = makeInternalVariable(variable.getName(), splitType);
1135 }
1136
1137 // Recursive implementation of split().
1138 // Returns reference to the modified type.
1139 const TType& HlslParseContext::split(const TType& type, const TString& name, const TQualifier& outerQualifier)
1140 {
1141     if (type.isStruct()) {
1142         TTypeList* userStructure = type.getWritableStruct();
1143         for (auto ioType = userStructure->begin(); ioType != userStructure->end(); ) {
1144             if (ioType->type->isBuiltIn()) {
1145                 // move out the built-in
1146                 splitBuiltIn(name, *ioType->type, type.getArraySizes(), outerQualifier);
1147                 ioType = userStructure->erase(ioType);
1148             } else {
1149                 split(*ioType->type, name + "." + ioType->type->getFieldName(), outerQualifier);
1150                 ++ioType;
1151             }
1152         }
1153     }
1154
1155     return type;
1156 }
1157
1158 // Is this an aggregate that should be flattened?
1159 // Can be applied to intermediate levels of type in a hierarchy.
1160 // Some things like flattening uniform arrays are only about the top level
1161 // of the aggregate, triggered on 'topLevel'.
1162 bool HlslParseContext::shouldFlatten(const TType& type, TStorageQualifier qualifier, bool topLevel) const
1163 {
1164     switch (qualifier) {
1165     case EvqVaryingIn:
1166     case EvqVaryingOut:
1167         return type.isStruct() || type.isArray();
1168     case EvqUniform:
1169         return (type.isArray() && intermediate.getFlattenUniformArrays() && topLevel) ||
1170                (type.isStruct() && type.containsOpaque());
1171     default:
1172         return false;
1173     };
1174 }
1175
1176 // Top level variable flattening: construct data
1177 void HlslParseContext::flatten(const TVariable& variable, bool linkage)
1178 {
1179     const TType& type = variable.getType();
1180
1181     // If it's a standalone built-in, there is nothing to flatten
1182     if (type.isBuiltIn() && !type.isStruct())
1183         return;
1184
1185     auto entry = flattenMap.insert(std::make_pair(variable.getUniqueId(),
1186                                                   TFlattenData(type.getQualifier().layoutBinding,
1187                                                                type.getQualifier().layoutLocation)));
1188
1189     // the item is a map pair, so first->second is the TFlattenData itself.
1190     flatten(variable, type, entry.first->second, variable.getName(), linkage, type.getQualifier(), nullptr);
1191 }
1192
1193 // Recursively flatten the given variable at the provided type, building the flattenData as we go.
1194 //
1195 // This is mutually recursive with flattenStruct and flattenArray.
1196 // We are going to flatten an arbitrarily nested composite structure into a linear sequence of
1197 // members, and later on, we want to turn a path through the tree structure into a final
1198 // location in this linear sequence.
1199 //
1200 // If the tree was N-ary, that can be directly calculated.  However, we are dealing with
1201 // arbitrary numbers - perhaps a struct of 7 members containing an array of 3.  Thus, we must
1202 // build a data structure to allow the sequence of bracket and dot operators on arrays and
1203 // structs to arrive at the proper member.
1204 //
1205 // To avoid storing a tree with pointers, we are going to flatten the tree into a vector of integers.
1206 // The leaves are the indexes into the flattened member array.
1207 // Each level will have the next location for the Nth item stored sequentially, so for instance:
1208 //
1209 // struct { float2 a[2]; int b; float4 c[3] };
1210 //
1211 // This will produce the following flattened tree:
1212 // Pos: 0  1   2    3  4    5  6   7     8   9  10   11  12 13
1213 //     (3, 7,  8,   5, 6,   0, 1,  2,   11, 12, 13,   3,  4, 5}
1214 //
1215 // Given a reference to mystruct.c[1], the access chain is (2,1), so we traverse:
1216 //   (0+2) = 8  -->  (8+1) = 12 -->   12 = 4
1217 //
1218 // so the 4th flattened member in traversal order is ours.
1219 //
1220 int HlslParseContext::flatten(const TVariable& variable, const TType& type,
1221                               TFlattenData& flattenData, TString name, bool linkage,
1222                               const TQualifier& outerQualifier,
1223                               const TArraySizes* builtInArraySizes)
1224 {
1225     // If something is an arrayed struct, the array flattener will recursively call flatten()
1226     // to then flatten the struct, so this is an "if else": we don't do both.
1227     if (type.isArray())
1228         return flattenArray(variable, type, flattenData, name, linkage, outerQualifier);
1229     else if (type.isStruct())
1230         return flattenStruct(variable, type, flattenData, name, linkage, outerQualifier, builtInArraySizes);
1231     else {
1232         assert(0); // should never happen
1233         return -1;
1234     }
1235 }
1236
1237 // Add a single flattened member to the flattened data being tracked for the composite
1238 // Returns true for the final flattening level.
1239 int HlslParseContext::addFlattenedMember(const TVariable& variable, const TType& type, TFlattenData& flattenData,
1240                                          const TString& memberName, bool linkage,
1241                                          const TQualifier& outerQualifier,
1242                                          const TArraySizes* builtInArraySizes)
1243 {
1244     if (!shouldFlatten(type, outerQualifier.storage, false)) {
1245         // This is as far as we flatten.  Insert the variable.
1246         TVariable* memberVariable = makeInternalVariable(memberName, type);
1247         mergeQualifiers(memberVariable->getWritableType().getQualifier(), variable.getType().getQualifier());
1248
1249         if (flattenData.nextBinding != TQualifier::layoutBindingEnd)
1250             memberVariable->getWritableType().getQualifier().layoutBinding = flattenData.nextBinding++;
1251
1252         if (memberVariable->getType().isBuiltIn()) {
1253             // inherited locations are nonsensical for built-ins (TODO: what if semantic had a number)
1254             memberVariable->getWritableType().getQualifier().layoutLocation = TQualifier::layoutLocationEnd;
1255         } else {
1256             // inherited locations must be auto bumped, not replicated
1257             if (flattenData.nextLocation != TQualifier::layoutLocationEnd) {
1258                 memberVariable->getWritableType().getQualifier().layoutLocation = flattenData.nextLocation;
1259                 flattenData.nextLocation += intermediate.computeTypeLocationSize(memberVariable->getType(), language);
1260                 nextOutLocation = std::max(nextOutLocation, flattenData.nextLocation);
1261             }
1262         }
1263
1264         flattenData.offsets.push_back(static_cast<int>(flattenData.members.size()));
1265         flattenData.members.push_back(memberVariable);
1266
1267         if (linkage)
1268             trackLinkage(*memberVariable);
1269
1270         return static_cast<int>(flattenData.offsets.size()) - 1; // location of the member reference
1271     } else {
1272         // Further recursion required
1273         return flatten(variable, type, flattenData, memberName, linkage, outerQualifier, builtInArraySizes);
1274     }
1275 }
1276
1277 // Figure out the mapping between an aggregate's top members and an
1278 // equivalent set of individual variables.
1279 //
1280 // Assumes shouldFlatten() or equivalent was called first.
1281 int HlslParseContext::flattenStruct(const TVariable& variable, const TType& type,
1282                                     TFlattenData& flattenData, TString name, bool linkage,
1283                                     const TQualifier& outerQualifier,
1284                                     const TArraySizes* builtInArraySizes)
1285 {
1286     assert(type.isStruct());
1287
1288     auto members = *type.getStruct();
1289
1290     // Reserve space for this tree level.
1291     int start = static_cast<int>(flattenData.offsets.size());
1292     int pos = start;
1293     flattenData.offsets.resize(int(pos + members.size()), -1);
1294
1295     for (int member = 0; member < (int)members.size(); ++member) {
1296         TType& dereferencedType = *members[member].type;
1297         if (dereferencedType.isBuiltIn())
1298             splitBuiltIn(variable.getName(), dereferencedType, builtInArraySizes, outerQualifier);
1299         else {
1300             const int mpos = addFlattenedMember(variable, dereferencedType, flattenData,
1301                                                 name + "." + dereferencedType.getFieldName(),
1302                                                 linkage, outerQualifier,
1303                                                 builtInArraySizes == nullptr && dereferencedType.isArray()
1304                                                                        ? dereferencedType.getArraySizes()
1305                                                                        : builtInArraySizes);
1306             flattenData.offsets[pos++] = mpos;
1307         }
1308     }
1309
1310     return start;
1311 }
1312
1313 // Figure out mapping between an array's members and an
1314 // equivalent set of individual variables.
1315 //
1316 // Assumes shouldFlatten() or equivalent was called first.
1317 int HlslParseContext::flattenArray(const TVariable& variable, const TType& type,
1318                                    TFlattenData& flattenData, TString name, bool linkage,
1319                                    const TQualifier& outerQualifier)
1320 {
1321     assert(type.isSizedArray());
1322
1323     const int size = type.getOuterArraySize();
1324     const TType dereferencedType(type, 0);
1325
1326     if (name.empty())
1327         name = variable.getName();
1328
1329     // Reserve space for this tree level.
1330     int start = static_cast<int>(flattenData.offsets.size());
1331     int pos   = start;
1332     flattenData.offsets.resize(int(pos + size), -1);
1333
1334     for (int element=0; element < size; ++element) {
1335         char elementNumBuf[20];  // sufficient for MAXINT
1336         snprintf(elementNumBuf, sizeof(elementNumBuf)-1, "[%d]", element);
1337         const int mpos = addFlattenedMember(variable, dereferencedType, flattenData,
1338                                             name + elementNumBuf, linkage, outerQualifier,
1339                                             type.getArraySizes());
1340
1341         flattenData.offsets[pos++] = mpos;
1342     }
1343
1344     return start;
1345 }
1346
1347 // Return true if we have flattened this node.
1348 bool HlslParseContext::wasFlattened(const TIntermTyped* node) const
1349 {
1350     return node != nullptr && node->getAsSymbolNode() != nullptr &&
1351            wasFlattened(node->getAsSymbolNode()->getId());
1352 }
1353
1354 // Return true if we have split this structure
1355 bool HlslParseContext::wasSplit(const TIntermTyped* node) const
1356 {
1357     return node != nullptr && node->getAsSymbolNode() != nullptr &&
1358            wasSplit(node->getAsSymbolNode()->getId());
1359 }
1360
1361 // Turn an access into an aggregate that was flattened to instead be
1362 // an access to the individual variable the member was flattened to.
1363 // Assumes wasFlattened() or equivalent was called first.
1364 TIntermTyped* HlslParseContext::flattenAccess(TIntermTyped* base, int member)
1365 {
1366     const TType dereferencedType(base->getType(), member);  // dereferenced type
1367     const TIntermSymbol& symbolNode = *base->getAsSymbolNode();
1368     TIntermTyped* flattened = flattenAccess(symbolNode.getId(), member, base->getQualifier().storage,
1369                                             dereferencedType, symbolNode.getFlattenSubset());
1370
1371     return flattened ? flattened : base;
1372 }
1373 TIntermTyped* HlslParseContext::flattenAccess(int uniqueId, int member, TStorageQualifier outerStorage,
1374     const TType& dereferencedType, int subset)
1375 {
1376     const auto flattenData = flattenMap.find(uniqueId);
1377
1378     if (flattenData == flattenMap.end())
1379         return nullptr;
1380
1381     // Calculate new cumulative offset from the packed tree
1382     int newSubset = flattenData->second.offsets[subset >= 0 ? subset + member : member];
1383
1384     TIntermSymbol* subsetSymbol;
1385     if (!shouldFlatten(dereferencedType, outerStorage, false)) {
1386         // Finished flattening: create symbol for variable
1387         member = flattenData->second.offsets[newSubset];
1388         const TVariable* memberVariable = flattenData->second.members[member];
1389         subsetSymbol = intermediate.addSymbol(*memberVariable);
1390         subsetSymbol->setFlattenSubset(-1);
1391     } else {
1392
1393         // If this is not the final flattening, accumulate the position and return
1394         // an object of the partially dereferenced type.
1395         subsetSymbol = new TIntermSymbol(uniqueId, "flattenShadow", dereferencedType);
1396         subsetSymbol->setFlattenSubset(newSubset);
1397     }
1398
1399     return subsetSymbol;
1400 }
1401
1402 // For finding where the first leaf is in a subtree of a multi-level aggregate
1403 // that is just getting a subset assigned. Follows the same logic as flattenAccess,
1404 // but logically going down the "left-most" tree branch each step of the way.
1405 //
1406 // Returns the offset into the first leaf of the subset.
1407 int HlslParseContext::findSubtreeOffset(const TIntermNode& node) const
1408 {
1409     const TIntermSymbol* sym = node.getAsSymbolNode();
1410     if (sym == nullptr)
1411         return 0;
1412     if (!sym->isArray() && !sym->isStruct())
1413         return 0;
1414     int subset = sym->getFlattenSubset();
1415     if (subset == -1)
1416         return 0;
1417
1418     // Getting this far means a partial aggregate is identified by the flatten subset.
1419     // Find the first leaf of the subset.
1420
1421     const auto flattenData = flattenMap.find(sym->getId());
1422     if (flattenData == flattenMap.end())
1423         return 0;
1424
1425     return findSubtreeOffset(sym->getType(), subset, flattenData->second.offsets);
1426
1427     do {
1428         subset = flattenData->second.offsets[subset];
1429     } while (true);
1430 }
1431 // Recursively do the desent
1432 int HlslParseContext::findSubtreeOffset(const TType& type, int subset, const TVector<int>& offsets) const
1433 {
1434     if (!type.isArray() && !type.isStruct())
1435         return offsets[subset];
1436     TType derefType(type, 0);
1437     return findSubtreeOffset(derefType, offsets[subset], offsets);
1438 };
1439
1440 // Find and return the split IO TVariable for id, or nullptr if none.
1441 TVariable* HlslParseContext::getSplitNonIoVar(int id) const
1442 {
1443     const auto splitNonIoVar = splitNonIoVars.find(id);
1444     if (splitNonIoVar == splitNonIoVars.end())
1445         return nullptr;
1446
1447     return splitNonIoVar->second;
1448 }
1449
1450 // Pass through to base class after remembering built-in mappings.
1451 void HlslParseContext::trackLinkage(TSymbol& symbol)
1452 {
1453     TBuiltInVariable biType = symbol.getType().getQualifier().builtIn;
1454
1455     if (biType != EbvNone)
1456         builtInTessLinkageSymbols[biType] = symbol.clone();
1457
1458     TParseContextBase::trackLinkage(symbol);
1459 }
1460
1461
1462 // Returns true if the built-in is a clip or cull distance variable.
1463 bool HlslParseContext::isClipOrCullDistance(TBuiltInVariable builtIn)
1464 {
1465     return builtIn == EbvClipDistance || builtIn == EbvCullDistance;
1466 }
1467
1468 // Some types require fixed array sizes in SPIR-V, but can be scalars or
1469 // arrays of sizes SPIR-V doesn't allow.  For example, tessellation factors.
1470 // This creates the right size.  A conversion is performed when the internal
1471 // type is copied to or from the external type.  This corrects the externally
1472 // facing input or output type to abide downstream semantics.
1473 void HlslParseContext::fixBuiltInIoType(TType& type)
1474 {
1475     int requiredArraySize = 0;
1476     int requiredVectorSize = 0;
1477
1478     switch (type.getQualifier().builtIn) {
1479     case EbvTessLevelOuter: requiredArraySize = 4; break;
1480     case EbvTessLevelInner: requiredArraySize = 2; break;
1481
1482     case EbvSampleMask:
1483         {
1484             // Promote scalar to array of size 1.  Leave existing arrays alone.
1485             if (!type.isArray())
1486                 requiredArraySize = 1;
1487             break;
1488         }
1489
1490     case EbvWorkGroupId:        requiredVectorSize = 3; break;
1491     case EbvGlobalInvocationId: requiredVectorSize = 3; break;
1492     case EbvLocalInvocationId:  requiredVectorSize = 3; break;
1493     case EbvTessCoord:          requiredVectorSize = 3; break;
1494
1495     default:
1496         if (isClipOrCullDistance(type)) {
1497             const int loc = type.getQualifier().layoutLocation;
1498
1499             if (type.getQualifier().builtIn == EbvClipDistance) {
1500                 if (type.getQualifier().storage == EvqVaryingIn)
1501                     clipSemanticNSizeIn[loc] = type.getVectorSize();
1502                 else
1503                     clipSemanticNSizeOut[loc] = type.getVectorSize();
1504             } else {
1505                 if (type.getQualifier().storage == EvqVaryingIn)
1506                     cullSemanticNSizeIn[loc] = type.getVectorSize();
1507                 else
1508                     cullSemanticNSizeOut[loc] = type.getVectorSize();
1509             }
1510         }
1511
1512         return;
1513     }
1514
1515     // Alter or set vector size as needed.
1516     if (requiredVectorSize > 0) {
1517         TType newType(type.getBasicType(), type.getQualifier().storage, requiredVectorSize);
1518         newType.getQualifier() = type.getQualifier();
1519
1520         type.shallowCopy(newType);
1521     }
1522
1523     // Alter or set array size as needed.
1524     if (requiredArraySize > 0) {
1525         if (!type.isArray() || type.getOuterArraySize() != requiredArraySize) {
1526             TArraySizes* arraySizes = new TArraySizes;
1527             arraySizes->addInnerSize(requiredArraySize);
1528             type.transferArraySizes(arraySizes);
1529         }
1530     }
1531 }
1532
1533 // Variables that correspond to the user-interface in and out of a stage
1534 // (not the built-in interface) are
1535 //  - assigned locations
1536 //  - registered as a linkage node (part of the stage's external interface).
1537 // Assumes it is called in the order in which locations should be assigned.
1538 void HlslParseContext::assignToInterface(TVariable& variable)
1539 {
1540     const auto assignLocation = [&](TVariable& variable) {
1541         TType& type = variable.getWritableType();
1542         if (!type.isStruct() || type.getStruct()->size() > 0) {
1543             TQualifier& qualifier = type.getQualifier();
1544             if (qualifier.storage == EvqVaryingIn || qualifier.storage == EvqVaryingOut) {
1545                 if (qualifier.builtIn == EbvNone && !qualifier.hasLocation()) {
1546                     // Strip off the outer array dimension for those having an extra one.
1547                     int size;
1548                     if (type.isArray() && qualifier.isArrayedIo(language)) {
1549                         TType elementType(type, 0);
1550                         size = intermediate.computeTypeLocationSize(elementType, language);
1551                     } else
1552                         size = intermediate.computeTypeLocationSize(type, language);
1553
1554                     if (qualifier.storage == EvqVaryingIn) {
1555                         variable.getWritableType().getQualifier().layoutLocation = nextInLocation;
1556                         nextInLocation += size;
1557                     } else {
1558                         variable.getWritableType().getQualifier().layoutLocation = nextOutLocation;
1559                         nextOutLocation += size;
1560                     }
1561                 }
1562                 trackLinkage(variable);
1563             }
1564         }
1565     };
1566
1567     if (wasFlattened(variable.getUniqueId())) {
1568         auto& memberList = flattenMap[variable.getUniqueId()].members;
1569         for (auto member = memberList.begin(); member != memberList.end(); ++member)
1570             assignLocation(**member);
1571     } else if (wasSplit(variable.getUniqueId())) {
1572         TVariable* splitIoVar = getSplitNonIoVar(variable.getUniqueId());
1573         assignLocation(*splitIoVar);
1574     } else {
1575         assignLocation(variable);
1576     }
1577 }
1578
1579 //
1580 // Handle seeing a function declarator in the grammar.  This is the precursor
1581 // to recognizing a function prototype or function definition.
1582 //
1583 void HlslParseContext::handleFunctionDeclarator(const TSourceLoc& loc, TFunction& function, bool prototype)
1584 {
1585     //
1586     // Multiple declarations of the same function name are allowed.
1587     //
1588     // If this is a definition, the definition production code will check for redefinitions
1589     // (we don't know at this point if it's a definition or not).
1590     //
1591     bool builtIn;
1592     TSymbol* symbol = symbolTable.find(function.getMangledName(), &builtIn);
1593     const TFunction* prevDec = symbol ? symbol->getAsFunction() : 0;
1594
1595     if (prototype) {
1596         // All built-in functions are defined, even though they don't have a body.
1597         // Count their prototype as a definition instead.
1598         if (symbolTable.atBuiltInLevel())
1599             function.setDefined();
1600         else {
1601             if (prevDec && ! builtIn)
1602                 symbol->getAsFunction()->setPrototyped();  // need a writable one, but like having prevDec as a const
1603             function.setPrototyped();
1604         }
1605     }
1606
1607     // This insert won't actually insert it if it's a duplicate signature, but it will still check for
1608     // other forms of name collisions.
1609     if (! symbolTable.insert(function))
1610         error(loc, "function name is redeclaration of existing name", function.getName().c_str(), "");
1611 }
1612
1613 // For struct buffers with counters, we must pass the counter buffer as hidden parameter.
1614 // This adds the hidden parameter to the parameter list in 'paramNodes' if needed.
1615 // Otherwise, it's a no-op
1616 void HlslParseContext::addStructBufferHiddenCounterParam(const TSourceLoc& loc, TParameter& param,
1617                                                          TIntermAggregate*& paramNodes)
1618 {
1619     if (! hasStructBuffCounter(*param.type))
1620         return;
1621
1622     const TString counterBlockName(intermediate.addCounterBufferName(*param.name));
1623
1624     TType counterType;
1625     counterBufferType(loc, counterType);
1626     TVariable *variable = makeInternalVariable(counterBlockName, counterType);
1627
1628     if (! symbolTable.insert(*variable))
1629         error(loc, "redefinition", variable->getName().c_str(), "");
1630
1631     paramNodes = intermediate.growAggregate(paramNodes,
1632                                             intermediate.addSymbol(*variable, loc),
1633                                             loc);
1634 }
1635
1636 //
1637 // Handle seeing the function prototype in front of a function definition in the grammar.
1638 // The body is handled after this function returns.
1639 //
1640 // Returns an aggregate of parameter-symbol nodes.
1641 //
1642 TIntermAggregate* HlslParseContext::handleFunctionDefinition(const TSourceLoc& loc, TFunction& function,
1643                                                              const TAttributes& attributes,
1644                                                              TIntermNode*& entryPointTree)
1645 {
1646     currentCaller = function.getMangledName();
1647     TSymbol* symbol = symbolTable.find(function.getMangledName());
1648     TFunction* prevDec = symbol ? symbol->getAsFunction() : nullptr;
1649
1650     if (prevDec == nullptr)
1651         error(loc, "can't find function", function.getName().c_str(), "");
1652     // Note:  'prevDec' could be 'function' if this is the first time we've seen function
1653     // as it would have just been put in the symbol table.  Otherwise, we're looking up
1654     // an earlier occurrence.
1655
1656     if (prevDec && prevDec->isDefined()) {
1657         // Then this function already has a body.
1658         error(loc, "function already has a body", function.getName().c_str(), "");
1659     }
1660     if (prevDec && ! prevDec->isDefined()) {
1661         prevDec->setDefined();
1662
1663         // Remember the return type for later checking for RETURN statements.
1664         currentFunctionType = &(prevDec->getType());
1665     } else
1666         currentFunctionType = new TType(EbtVoid);
1667     functionReturnsValue = false;
1668
1669     // Entry points need different I/O and other handling, transform it so the
1670     // rest of this function doesn't care.
1671     entryPointTree = transformEntryPoint(loc, function, attributes);
1672
1673     //
1674     // New symbol table scope for body of function plus its arguments
1675     //
1676     pushScope();
1677
1678     //
1679     // Insert parameters into the symbol table.
1680     // If the parameter has no name, it's not an error, just don't insert it
1681     // (could be used for unused args).
1682     //
1683     // Also, accumulate the list of parameters into the AST, so lower level code
1684     // knows where to find parameters.
1685     //
1686     TIntermAggregate* paramNodes = new TIntermAggregate;
1687     for (int i = 0; i < function.getParamCount(); i++) {
1688         TParameter& param = function[i];
1689         if (param.name != nullptr) {
1690             TVariable *variable = new TVariable(param.name, *param.type);
1691
1692             if (i == 0 && function.hasImplicitThis()) {
1693                 // Anonymous 'this' members are already in a symbol-table level,
1694                 // and we need to know what function parameter to map them to.
1695                 symbolTable.makeInternalVariable(*variable);
1696                 pushImplicitThis(variable);
1697             }
1698
1699             // Insert the parameters with name in the symbol table.
1700             if (! symbolTable.insert(*variable))
1701                 error(loc, "redefinition", variable->getName().c_str(), "");
1702
1703             // Add parameters to the AST list.
1704             if (shouldFlatten(variable->getType(), variable->getType().getQualifier().storage, true)) {
1705                 // Expand the AST parameter nodes (but not the name mangling or symbol table view)
1706                 // for structures that need to be flattened.
1707                 flatten(*variable, false);
1708                 const TTypeList* structure = variable->getType().getStruct();
1709                 for (int mem = 0; mem < (int)structure->size(); ++mem) {
1710                     paramNodes = intermediate.growAggregate(paramNodes,
1711                                                             flattenAccess(variable->getUniqueId(), mem,
1712                                                                           variable->getType().getQualifier().storage,
1713                                                                           *(*structure)[mem].type),
1714                                                             loc);
1715                 }
1716             } else {
1717                 // Add the parameter to the AST
1718                 paramNodes = intermediate.growAggregate(paramNodes,
1719                                                         intermediate.addSymbol(*variable, loc),
1720                                                         loc);
1721             }
1722
1723             // Add hidden AST parameter for struct buffer counters, if needed.
1724             addStructBufferHiddenCounterParam(loc, param, paramNodes);
1725         } else
1726             paramNodes = intermediate.growAggregate(paramNodes, intermediate.addSymbol(*param.type, loc), loc);
1727     }
1728     if (function.hasIllegalImplicitThis())
1729         pushImplicitThis(nullptr);
1730
1731     intermediate.setAggregateOperator(paramNodes, EOpParameters, TType(EbtVoid), loc);
1732     loopNestingLevel = 0;
1733     controlFlowNestingLevel = 0;
1734     postEntryPointReturn = false;
1735
1736     return paramNodes;
1737 }
1738
1739 // Handle all [attrib] attribute for the shader entry point
1740 void HlslParseContext::handleEntryPointAttributes(const TSourceLoc& loc, const TAttributes& attributes)
1741 {
1742     for (auto it = attributes.begin(); it != attributes.end(); ++it) {
1743         switch (it->name) {
1744         case EatNumThreads:
1745         {
1746             const TIntermSequence& sequence = it->args->getSequence();
1747             for (int lid = 0; lid < int(sequence.size()); ++lid)
1748                 intermediate.setLocalSize(lid, sequence[lid]->getAsConstantUnion()->getConstArray()[0].getIConst());
1749             break;
1750         }
1751         case EatMaxVertexCount:
1752         {
1753             int maxVertexCount;
1754
1755             if (! it->getInt(maxVertexCount)) {
1756                 error(loc, "invalid maxvertexcount", "", "");
1757             } else {
1758                 if (! intermediate.setVertices(maxVertexCount))
1759                     error(loc, "cannot change previously set maxvertexcount attribute", "", "");
1760             }
1761             break;
1762         }
1763         case EatPatchConstantFunc:
1764         {
1765             TString pcfName;
1766             if (! it->getString(pcfName, 0, false)) {
1767                 error(loc, "invalid patch constant function", "", "");
1768             } else {
1769                 patchConstantFunctionName = pcfName;
1770             }
1771             break;
1772         }
1773         case EatDomain:
1774         {
1775             // Handle [domain("...")]
1776             TString domainStr;
1777             if (! it->getString(domainStr)) {
1778                 error(loc, "invalid domain", "", "");
1779             } else {
1780                 TLayoutGeometry domain = ElgNone;
1781
1782                 if (domainStr == "tri") {
1783                     domain = ElgTriangles;
1784                 } else if (domainStr == "quad") {
1785                     domain = ElgQuads;
1786                 } else if (domainStr == "isoline") {
1787                     domain = ElgIsolines;
1788                 } else {
1789                     error(loc, "unsupported domain type", domainStr.c_str(), "");
1790                 }
1791
1792                 if (language == EShLangTessEvaluation) {
1793                     if (! intermediate.setInputPrimitive(domain))
1794                         error(loc, "cannot change previously set domain", TQualifier::getGeometryString(domain), "");
1795                 } else {
1796                     if (! intermediate.setOutputPrimitive(domain))
1797                         error(loc, "cannot change previously set domain", TQualifier::getGeometryString(domain), "");
1798                 }
1799             }
1800             break;
1801         }
1802         case EatOutputTopology:
1803         {
1804             // Handle [outputtopology("...")]
1805             TString topologyStr;
1806             if (! it->getString(topologyStr)) {
1807                 error(loc, "invalid outputtopology", "", "");
1808             } else {
1809                 TVertexOrder vertexOrder = EvoNone;
1810                 TLayoutGeometry primitive = ElgNone;
1811
1812                 if (topologyStr == "point") {
1813                     intermediate.setPointMode();
1814                 } else if (topologyStr == "line") {
1815                     primitive = ElgIsolines;
1816                 } else if (topologyStr == "triangle_cw") {
1817                     vertexOrder = EvoCw;
1818                     primitive = ElgTriangles;
1819                 } else if (topologyStr == "triangle_ccw") {
1820                     vertexOrder = EvoCcw;
1821                     primitive = ElgTriangles;
1822                 } else {
1823                     error(loc, "unsupported outputtopology type", topologyStr.c_str(), "");
1824                 }
1825
1826                 if (vertexOrder != EvoNone) {
1827                     if (! intermediate.setVertexOrder(vertexOrder)) {
1828                         error(loc, "cannot change previously set outputtopology",
1829                               TQualifier::getVertexOrderString(vertexOrder), "");
1830                     }
1831                 }
1832                 if (primitive != ElgNone)
1833                     intermediate.setOutputPrimitive(primitive);
1834             }
1835             break;
1836         }
1837         case EatPartitioning:
1838         {
1839             // Handle [partitioning("...")]
1840             TString partitionStr;
1841             if (! it->getString(partitionStr)) {
1842                 error(loc, "invalid partitioning", "", "");
1843             } else {
1844                 TVertexSpacing partitioning = EvsNone;
1845                 
1846                 if (partitionStr == "integer") {
1847                     partitioning = EvsEqual;
1848                 } else if (partitionStr == "fractional_even") {
1849                     partitioning = EvsFractionalEven;
1850                 } else if (partitionStr == "fractional_odd") {
1851                     partitioning = EvsFractionalOdd;
1852                     //} else if (partition == "pow2") { // TODO: currently nothing to map this to.
1853                 } else {
1854                     error(loc, "unsupported partitioning type", partitionStr.c_str(), "");
1855                 }
1856
1857                 if (! intermediate.setVertexSpacing(partitioning))
1858                     error(loc, "cannot change previously set partitioning",
1859                           TQualifier::getVertexSpacingString(partitioning), "");
1860             }
1861             break;
1862         }
1863         case EatOutputControlPoints:
1864         {
1865             // Handle [outputcontrolpoints("...")]
1866             int ctrlPoints;
1867             if (! it->getInt(ctrlPoints)) {
1868                 error(loc, "invalid outputcontrolpoints", "", "");
1869             } else {
1870                 if (! intermediate.setVertices(ctrlPoints)) {
1871                     error(loc, "cannot change previously set outputcontrolpoints attribute", "", "");
1872                 }
1873             }
1874             break;
1875         }
1876         case EatBuiltIn:
1877         case EatLocation:
1878             // tolerate these because of dual use of entrypoint and type attributes
1879             break;
1880         default:
1881             warn(loc, "attribute does not apply to entry point", "", "");
1882             break;
1883         }
1884     }
1885 }
1886
1887 // Update the given type with any type-like attribute information in the
1888 // attributes.
1889 void HlslParseContext::transferTypeAttributes(const TSourceLoc& loc, const TAttributes& attributes, TType& type,
1890     bool allowEntry)
1891 {
1892     if (attributes.size() == 0)
1893         return;
1894
1895     int value;
1896     TString builtInString;
1897     for (auto it = attributes.begin(); it != attributes.end(); ++it) {
1898         switch (it->name) {
1899         case EatLocation:
1900             // location
1901             if (it->getInt(value))
1902                 type.getQualifier().layoutLocation = value;
1903             break;
1904         case EatBinding:
1905             // binding
1906             if (it->getInt(value)) {
1907                 type.getQualifier().layoutBinding = value;
1908                 type.getQualifier().layoutSet = 0;
1909             }
1910             // set
1911             if (it->getInt(value, 1))
1912                 type.getQualifier().layoutSet = value;
1913             break;
1914         case EatGlobalBinding:
1915             // global cbuffer binding
1916             if (it->getInt(value))
1917                 globalUniformBinding = value;
1918             // global cbuffer binding
1919             if (it->getInt(value, 1))
1920                 globalUniformSet = value;
1921             break;
1922         case EatInputAttachment:
1923             // input attachment
1924             if (it->getInt(value))
1925                 type.getQualifier().layoutAttachment = value;
1926             break;
1927         case EatBuiltIn:
1928             // PointSize built-in
1929             if (it->getString(builtInString, 0, false)) {
1930                 if (builtInString == "PointSize")
1931                     type.getQualifier().builtIn = EbvPointSize;
1932             }
1933             break;
1934         case EatPushConstant:
1935             // push_constant
1936             type.getQualifier().layoutPushConstant = true;
1937             break;
1938         case EatConstantId:
1939             // specialization constant
1940             if (it->getInt(value)) {
1941                 TSourceLoc loc;
1942                 loc.init();
1943                 setSpecConstantId(loc, type.getQualifier(), value);
1944             }
1945             break;
1946         default:
1947             if (! allowEntry)
1948                 warn(loc, "attribute does not apply to a type", "", "");
1949             break;
1950         }
1951     }
1952 }
1953
1954 //
1955 // Do all special handling for the entry point, including wrapping
1956 // the shader's entry point with the official entry point that will call it.
1957 //
1958 // The following:
1959 //
1960 //    retType shaderEntryPoint(args...) // shader declared entry point
1961 //    { body }
1962 //
1963 // Becomes
1964 //
1965 //    out retType ret;
1966 //    in iargs<that are input>...;
1967 //    out oargs<that are output> ...;
1968 //
1969 //    void shaderEntryPoint()    // synthesized, but official, entry point
1970 //    {
1971 //        args<that are input> = iargs...;
1972 //        ret = @shaderEntryPoint(args...);
1973 //        oargs = args<that are output>...;
1974 //    }
1975 //    retType @shaderEntryPoint(args...)
1976 //    { body }
1977 //
1978 // The symbol table will still map the original entry point name to the
1979 // the modified function and its new name:
1980 //
1981 //    symbol table:  shaderEntryPoint  ->   @shaderEntryPoint
1982 //
1983 // Returns nullptr if no entry-point tree was built, otherwise, returns
1984 // a subtree that creates the entry point.
1985 //
1986 TIntermNode* HlslParseContext::transformEntryPoint(const TSourceLoc& loc, TFunction& userFunction,
1987                                                    const TAttributes& attributes)
1988 {
1989     // Return true if this is a tessellation patch constant function input to a domain shader.
1990     const auto isDsPcfInput = [this](const TType& type) {
1991         return language == EShLangTessEvaluation &&
1992         type.contains([](const TType* t) {
1993                 return t->getQualifier().builtIn == EbvTessLevelOuter ||
1994                        t->getQualifier().builtIn == EbvTessLevelInner;
1995             });
1996     };
1997
1998     // if we aren't in the entry point, fix the IO as such and exit
1999     if (userFunction.getName().compare(intermediate.getEntryPointName().c_str()) != 0) {
2000         remapNonEntryPointIO(userFunction);
2001         return nullptr;
2002     }
2003
2004     entryPointFunction = &userFunction; // needed in finish()
2005
2006     // Handle entry point attributes
2007     handleEntryPointAttributes(loc, attributes);
2008
2009     // entry point logic...
2010
2011     // Move parameters and return value to shader in/out
2012     TVariable* entryPointOutput; // gets created in remapEntryPointIO
2013     TVector<TVariable*> inputs;
2014     TVector<TVariable*> outputs;
2015     remapEntryPointIO(userFunction, entryPointOutput, inputs, outputs);
2016
2017     // Further this return/in/out transform by flattening, splitting, and assigning locations
2018     const auto makeVariableInOut = [&](TVariable& variable) {
2019         if (variable.getType().isStruct()) {
2020             if (variable.getType().getQualifier().isArrayedIo(language)) {
2021                 if (variable.getType().containsBuiltIn())
2022                     split(variable);
2023             } else if (shouldFlatten(variable.getType(), EvqVaryingIn /* not assigned yet, but close enough */, true))
2024                 flatten(variable, false /* don't track linkage here, it will be tracked in assignToInterface() */);
2025         }
2026         // TODO: flatten arrays too
2027         // TODO: flatten everything in I/O
2028         // TODO: replace all split with flatten, make all paths can create flattened I/O, then split code can be removed
2029
2030         // For clip and cull distance, multiple output variables potentially get merged
2031         // into one in assignClipCullDistance.  That code in assignClipCullDistance
2032         // handles the interface logic, so we avoid it here in that case.
2033         if (!isClipOrCullDistance(variable.getType()))
2034             assignToInterface(variable);
2035     };
2036     if (entryPointOutput != nullptr)
2037         makeVariableInOut(*entryPointOutput);
2038     for (auto it = inputs.begin(); it != inputs.end(); ++it)
2039         if (!isDsPcfInput((*it)->getType()))  // wait until the end for PCF input (see comment below)
2040             makeVariableInOut(*(*it));
2041     for (auto it = outputs.begin(); it != outputs.end(); ++it)
2042         makeVariableInOut(*(*it));
2043
2044     // In the domain shader, PCF input must be at the end of the linkage.  That's because in the
2045     // hull shader there is no ordering: the output comes from the separate PCF, which does not
2046     // participate in the argument list.  That is always put at the end of the HS linkage, so the
2047     // input side of the DS must match.  The argument may be in any position in the DS argument list
2048     // however, so this ensures the linkage is built in the correct order regardless of argument order.
2049     if (language == EShLangTessEvaluation) {
2050         for (auto it = inputs.begin(); it != inputs.end(); ++it)
2051             if (isDsPcfInput((*it)->getType()))
2052                 makeVariableInOut(*(*it));
2053     }
2054
2055     // Synthesize the call
2056
2057     pushScope(); // matches the one in handleFunctionBody()
2058
2059     // new signature
2060     TType voidType(EbtVoid);
2061     TFunction synthEntryPoint(&userFunction.getName(), voidType);
2062     TIntermAggregate* synthParams = new TIntermAggregate();
2063     intermediate.setAggregateOperator(synthParams, EOpParameters, voidType, loc);
2064     intermediate.setEntryPointMangledName(synthEntryPoint.getMangledName().c_str());
2065     intermediate.incrementEntryPointCount();
2066     TFunction callee(&userFunction.getName(), voidType); // call based on old name, which is still in the symbol table
2067
2068     // change original name
2069     userFunction.addPrefix("@");                         // change the name in the function, but not in the symbol table
2070
2071     // Copy inputs (shader-in -> calling arg), while building up the call node
2072     TVector<TVariable*> argVars;
2073     TIntermAggregate* synthBody = new TIntermAggregate();
2074     auto inputIt = inputs.begin();
2075     TIntermTyped* callingArgs = nullptr;
2076
2077     for (int i = 0; i < userFunction.getParamCount(); i++) {
2078         TParameter& param = userFunction[i];
2079         argVars.push_back(makeInternalVariable(*param.name, *param.type));
2080         argVars.back()->getWritableType().getQualifier().makeTemporary();
2081
2082         // Track the input patch, which is the only non-builtin supported by hull shader PCF.
2083         if (param.getDeclaredBuiltIn() == EbvInputPatch)
2084             inputPatch = argVars.back();
2085
2086         TIntermSymbol* arg = intermediate.addSymbol(*argVars.back());
2087         handleFunctionArgument(&callee, callingArgs, arg);
2088         if (param.type->getQualifier().isParamInput()) {
2089             intermediate.growAggregate(synthBody, handleAssign(loc, EOpAssign, arg,
2090                                                                intermediate.addSymbol(**inputIt)));
2091             inputIt++;
2092         }
2093     }
2094
2095     // Call
2096     currentCaller = synthEntryPoint.getMangledName();
2097     TIntermTyped* callReturn = handleFunctionCall(loc, &callee, callingArgs);
2098     currentCaller = userFunction.getMangledName();
2099
2100     // Return value
2101     if (entryPointOutput) {
2102         TIntermTyped* returnAssign;
2103
2104         // For hull shaders, the wrapped entry point return value is written to
2105         // an array element as indexed by invocation ID, which we might have to make up.
2106         // This is required to match SPIR-V semantics.
2107         if (language == EShLangTessControl) {
2108             TIntermSymbol* invocationIdSym = findTessLinkageSymbol(EbvInvocationId);
2109
2110             // If there is no user declared invocation ID, we must make one.
2111             if (invocationIdSym == nullptr) {
2112                 TType invocationIdType(EbtUint, EvqIn, 1);
2113                 TString* invocationIdName = NewPoolTString("InvocationId");
2114                 invocationIdType.getQualifier().builtIn = EbvInvocationId;
2115
2116                 TVariable* variable = makeInternalVariable(*invocationIdName, invocationIdType);
2117
2118                 globalQualifierFix(loc, variable->getWritableType().getQualifier());
2119                 trackLinkage(*variable);
2120
2121                 invocationIdSym = intermediate.addSymbol(*variable);
2122             }
2123
2124             TIntermTyped* element = intermediate.addIndex(EOpIndexIndirect, intermediate.addSymbol(*entryPointOutput),
2125                                                           invocationIdSym, loc);
2126
2127             // Set the type of the array element being dereferenced
2128             const TType derefElementType(entryPointOutput->getType(), 0);
2129             element->setType(derefElementType);
2130
2131             returnAssign = handleAssign(loc, EOpAssign, element, callReturn);
2132         } else {
2133             returnAssign = handleAssign(loc, EOpAssign, intermediate.addSymbol(*entryPointOutput), callReturn);
2134         }
2135         intermediate.growAggregate(synthBody, returnAssign);
2136     } else
2137         intermediate.growAggregate(synthBody, callReturn);
2138
2139     // Output copies
2140     auto outputIt = outputs.begin();
2141     for (int i = 0; i < userFunction.getParamCount(); i++) {
2142         TParameter& param = userFunction[i];
2143
2144         // GS outputs are via emit, so we do not copy them here.
2145         if (param.type->getQualifier().isParamOutput()) {
2146             if (param.getDeclaredBuiltIn() == EbvGsOutputStream) {
2147                 // GS output stream does not assign outputs here: it's the Append() method
2148                 // which writes to the output, probably multiple times separated by Emit.
2149                 // We merely remember the output to use, here.
2150                 gsStreamOutput = *outputIt;
2151             } else {
2152                 intermediate.growAggregate(synthBody, handleAssign(loc, EOpAssign,
2153                                                                    intermediate.addSymbol(**outputIt),
2154                                                                    intermediate.addSymbol(*argVars[i])));
2155             }
2156
2157             outputIt++;
2158         }
2159     }
2160
2161     // Put the pieces together to form a full function subtree
2162     // for the synthesized entry point.
2163     synthBody->setOperator(EOpSequence);
2164     TIntermNode* synthFunctionDef = synthParams;
2165     handleFunctionBody(loc, synthEntryPoint, synthBody, synthFunctionDef);
2166
2167     entryPointFunctionBody = synthBody;
2168
2169     return synthFunctionDef;
2170 }
2171
2172 void HlslParseContext::handleFunctionBody(const TSourceLoc& loc, TFunction& function, TIntermNode* functionBody,
2173                                           TIntermNode*& node)
2174 {
2175     node = intermediate.growAggregate(node, functionBody);
2176     intermediate.setAggregateOperator(node, EOpFunction, function.getType(), loc);
2177     node->getAsAggregate()->setName(function.getMangledName().c_str());
2178
2179     popScope();
2180     if (function.hasImplicitThis())
2181         popImplicitThis();
2182
2183     if (function.getType().getBasicType() != EbtVoid && ! functionReturnsValue)
2184         error(loc, "function does not return a value:", "", function.getName().c_str());
2185 }
2186
2187 // AST I/O is done through shader globals declared in the 'in' or 'out'
2188 // storage class.  An HLSL entry point has a return value, input parameters
2189 // and output parameters.  These need to get remapped to the AST I/O.
2190 void HlslParseContext::remapEntryPointIO(TFunction& function, TVariable*& returnValue,
2191     TVector<TVariable*>& inputs, TVector<TVariable*>& outputs)
2192 {
2193     // We might have in input structure type with no decorations that caused it
2194     // to look like an input type, yet it has (e.g.) interpolation types that
2195     // must be modified that turn it into an input type.
2196     // Hence, a missing ioTypeMap for 'input' might need to be synthesized.
2197     const auto synthesizeEditedInput = [this](TType& type) {
2198         // True if a type needs to be 'flat'
2199         const auto needsFlat = [](const TType& type) {
2200             return type.containsBasicType(EbtInt) ||
2201                     type.containsBasicType(EbtUint) ||
2202                     type.containsBasicType(EbtInt64) ||
2203                     type.containsBasicType(EbtUint64) ||
2204                     type.containsBasicType(EbtBool) ||
2205                     type.containsBasicType(EbtDouble);
2206         };
2207
2208         if (language == EShLangFragment && needsFlat(type)) {
2209             if (type.isStruct()) {
2210                 TTypeList* finalList = nullptr;
2211                 auto it = ioTypeMap.find(type.getStruct());
2212                 if (it == ioTypeMap.end() || it->second.input == nullptr) {
2213                     // Getting here means we have no input struct, but we need one.
2214                     auto list = new TTypeList;
2215                     for (auto member = type.getStruct()->begin(); member != type.getStruct()->end(); ++member) {
2216                         TType* newType = new TType;
2217                         newType->shallowCopy(*member->type);
2218                         TTypeLoc typeLoc = { newType, member->loc };
2219                         list->push_back(typeLoc);
2220                     }
2221                     // install the new input type
2222                     if (it == ioTypeMap.end()) {
2223                         tIoKinds newLists = { list, nullptr, nullptr };
2224                         ioTypeMap[type.getStruct()] = newLists;
2225                     } else
2226                         it->second.input = list;
2227                     finalList = list;
2228                 } else
2229                     finalList = it->second.input;
2230                 // edit for 'flat'
2231                 for (auto member = finalList->begin(); member != finalList->end(); ++member) {
2232                     if (needsFlat(*member->type)) {
2233                         member->type->getQualifier().clearInterpolation();
2234                         member->type->getQualifier().flat = true;
2235                     }
2236                 }
2237             } else {
2238                 type.getQualifier().clearInterpolation();
2239                 type.getQualifier().flat = true;
2240             }
2241         }
2242     };
2243
2244     // Do the actual work to make a type be a shader input or output variable,
2245     // and clear the original to be non-IO (for use as a normal function parameter/return).
2246     const auto makeIoVariable = [this](const char* name, TType& type, TStorageQualifier storage) -> TVariable* {
2247         TVariable* ioVariable = makeInternalVariable(name, type);
2248         clearUniformInputOutput(type.getQualifier());
2249         if (type.isStruct()) {
2250             auto newLists = ioTypeMap.find(ioVariable->getType().getStruct());
2251             if (newLists != ioTypeMap.end()) {
2252                 if (storage == EvqVaryingIn && newLists->second.input)
2253                     ioVariable->getWritableType().setStruct(newLists->second.input);
2254                 else if (storage == EvqVaryingOut && newLists->second.output)
2255                     ioVariable->getWritableType().setStruct(newLists->second.output);
2256             }
2257         }
2258         if (storage == EvqVaryingIn) {
2259             correctInput(ioVariable->getWritableType().getQualifier());
2260             if (language == EShLangTessEvaluation)
2261                 if (!ioVariable->getType().isArray())
2262                     ioVariable->getWritableType().getQualifier().patch = true;
2263         } else {
2264             correctOutput(ioVariable->getWritableType().getQualifier());
2265         }
2266         ioVariable->getWritableType().getQualifier().storage = storage;
2267
2268         fixBuiltInIoType(ioVariable->getWritableType());
2269
2270         return ioVariable;
2271     };
2272
2273     // return value is actually a shader-scoped output (out)
2274     if (function.getType().getBasicType() == EbtVoid) {
2275         returnValue = nullptr;
2276     } else {
2277         if (language == EShLangTessControl) {
2278             // tessellation evaluation in HLSL writes a per-ctrl-pt value, but it needs to be an
2279             // array in SPIR-V semantics.  We'll write to it indexed by invocation ID.
2280
2281             returnValue = makeIoVariable("@entryPointOutput", function.getWritableType(), EvqVaryingOut);
2282
2283             TType outputType;
2284             outputType.shallowCopy(function.getType());
2285
2286             // vertices has necessarily already been set when handling entry point attributes.
2287             TArraySizes* arraySizes = new TArraySizes;
2288             arraySizes->addInnerSize(intermediate.getVertices());
2289             outputType.transferArraySizes(arraySizes);
2290
2291             clearUniformInputOutput(function.getWritableType().getQualifier());
2292             returnValue = makeIoVariable("@entryPointOutput", outputType, EvqVaryingOut);
2293         } else {
2294             returnValue = makeIoVariable("@entryPointOutput", function.getWritableType(), EvqVaryingOut);
2295         }
2296     }
2297
2298     // parameters are actually shader-scoped inputs and outputs (in or out)
2299     for (int i = 0; i < function.getParamCount(); i++) {
2300         TType& paramType = *function[i].type;
2301         if (paramType.getQualifier().isParamInput()) {
2302             synthesizeEditedInput(paramType);
2303             TVariable* argAsGlobal = makeIoVariable(function[i].name->c_str(), paramType, EvqVaryingIn);
2304             inputs.push_back(argAsGlobal);
2305         }
2306         if (paramType.getQualifier().isParamOutput()) {
2307             TVariable* argAsGlobal = makeIoVariable(function[i].name->c_str(), paramType, EvqVaryingOut);
2308             outputs.push_back(argAsGlobal);
2309         }
2310     }
2311 }
2312
2313 // An HLSL function that looks like an entry point, but is not,
2314 // declares entry point IO built-ins, but these have to be undone.
2315 void HlslParseContext::remapNonEntryPointIO(TFunction& function)
2316 {
2317     // return value
2318     if (function.getType().getBasicType() != EbtVoid)
2319         clearUniformInputOutput(function.getWritableType().getQualifier());
2320
2321     // parameters.
2322     // References to structuredbuffer types are left unmodified
2323     for (int i = 0; i < function.getParamCount(); i++)
2324         if (!isReference(*function[i].type))
2325             clearUniformInputOutput(function[i].type->getQualifier());
2326 }
2327
2328 // Handle function returns, including type conversions to the function return type
2329 // if necessary.
2330 TIntermNode* HlslParseContext::handleReturnValue(const TSourceLoc& loc, TIntermTyped* value)
2331 {
2332     functionReturnsValue = true;
2333
2334     if (currentFunctionType->getBasicType() == EbtVoid) {
2335         error(loc, "void function cannot return a value", "return", "");
2336         return intermediate.addBranch(EOpReturn, loc);
2337     } else if (*currentFunctionType != value->getType()) {
2338         value = intermediate.addConversion(EOpReturn, *currentFunctionType, value);
2339         if (value && *currentFunctionType != value->getType())
2340             value = intermediate.addUniShapeConversion(EOpReturn, *currentFunctionType, value);
2341         if (value == nullptr || *currentFunctionType != value->getType()) {
2342             error(loc, "type does not match, or is not convertible to, the function's return type", "return", "");
2343             return value;
2344         }
2345     }
2346
2347     return intermediate.addBranch(EOpReturn, value, loc);
2348 }
2349
2350 void HlslParseContext::handleFunctionArgument(TFunction* function,
2351                                               TIntermTyped*& arguments, TIntermTyped* newArg)
2352 {
2353     TParameter param = { 0, new TType, nullptr };
2354     param.type->shallowCopy(newArg->getType());
2355
2356     function->addParameter(param);
2357     if (arguments)
2358         arguments = intermediate.growAggregate(arguments, newArg);
2359     else
2360         arguments = newArg;
2361 }
2362
2363 // Position may require special handling: we can optionally invert Y.
2364 // See: https://github.com/KhronosGroup/glslang/issues/1173
2365 //      https://github.com/KhronosGroup/glslang/issues/494
2366 TIntermTyped* HlslParseContext::assignPosition(const TSourceLoc& loc, TOperator op,
2367                                                TIntermTyped* left, TIntermTyped* right)
2368 {
2369     // If we are not asked for Y inversion, use a plain old assign.
2370     if (!intermediate.getInvertY())
2371         return intermediate.addAssign(op, left, right, loc);
2372
2373     // If we get here, we should invert Y.
2374     TIntermAggregate* assignList = nullptr;
2375
2376     // If this is a complex rvalue, we don't want to dereference it many times.  Create a temporary.
2377     TVariable* rhsTempVar = nullptr;
2378     rhsTempVar = makeInternalVariable("@position", right->getType());
2379     rhsTempVar->getWritableType().getQualifier().makeTemporary();
2380
2381     {
2382         TIntermTyped* rhsTempSym = intermediate.addSymbol(*rhsTempVar, loc);
2383         assignList = intermediate.growAggregate(assignList,
2384                                                 intermediate.addAssign(EOpAssign, rhsTempSym, right, loc), loc);
2385     }
2386
2387     // pos.y = -pos.y
2388     {
2389         const int Y = 1;
2390
2391         TIntermTyped* tempSymL = intermediate.addSymbol(*rhsTempVar, loc);
2392         TIntermTyped* tempSymR = intermediate.addSymbol(*rhsTempVar, loc);
2393         TIntermTyped* index = intermediate.addConstantUnion(Y, loc);
2394
2395         TIntermTyped* lhsElement = intermediate.addIndex(EOpIndexDirect, tempSymL, index, loc);
2396         TIntermTyped* rhsElement = intermediate.addIndex(EOpIndexDirect, tempSymR, index, loc);
2397
2398         const TType derefType(right->getType(), 0);
2399     
2400         lhsElement->setType(derefType);
2401         rhsElement->setType(derefType);
2402
2403         TIntermTyped* yNeg = intermediate.addUnaryMath(EOpNegative, rhsElement, loc);
2404
2405         assignList = intermediate.growAggregate(assignList, intermediate.addAssign(EOpAssign, lhsElement, yNeg, loc));
2406     }
2407
2408     // Assign the rhs temp (now with Y inversion) to the final output
2409     {
2410         TIntermTyped* rhsTempSym = intermediate.addSymbol(*rhsTempVar, loc);
2411         assignList = intermediate.growAggregate(assignList, intermediate.addAssign(op, left, rhsTempSym, loc));
2412     }
2413
2414     assert(assignList != nullptr);
2415     assignList->setOperator(EOpSequence);
2416
2417     return assignList;
2418 }
2419     
2420 // Clip and cull distance require special handling due to a semantic mismatch.  In HLSL,
2421 // these can be float scalar, float vector, or arrays of float scalar or float vector.
2422 // In SPIR-V, they are arrays of scalar floats in all cases.  We must copy individual components
2423 // (e.g, both x and y components of a float2) out into the destination float array.
2424 //
2425 // The values are assigned to sequential members of the output array.  The inner dimension
2426 // is vector components.  The outer dimension is array elements.
2427 TIntermAggregate* HlslParseContext::assignClipCullDistance(const TSourceLoc& loc, TOperator op, int semanticId,
2428                                                            TIntermTyped* left, TIntermTyped* right)
2429 {
2430     switch (language) {
2431     case EShLangFragment:
2432     case EShLangVertex:
2433     case EShLangGeometry:
2434         break;
2435     default:
2436         error(loc, "unimplemented: clip/cull not currently implemented for this stage", "", "");
2437         return nullptr;
2438     }
2439
2440     TVariable** clipCullVar = nullptr;
2441
2442     // Figure out if we are assigning to, or from, clip or cull distance.
2443     const bool isOutput = isClipOrCullDistance(left->getType());
2444
2445     // This is the rvalue or lvalue holding the clip or cull distance.
2446     TIntermTyped* clipCullNode = isOutput ? left : right;
2447     // This is the value going into or out of the clip or cull distance.
2448     TIntermTyped* internalNode = isOutput ? right : left;
2449
2450     const TBuiltInVariable builtInType = clipCullNode->getQualifier().builtIn;
2451
2452     decltype(clipSemanticNSizeIn)* semanticNSize = nullptr;
2453
2454     // Refer to either the clip or the cull distance, depending on semantic.
2455     switch (builtInType) {
2456     case EbvClipDistance:
2457         clipCullVar = isOutput ? &clipDistanceOutput : &clipDistanceInput;
2458         semanticNSize = isOutput ? &clipSemanticNSizeOut : &clipSemanticNSizeIn;
2459         break;
2460     case EbvCullDistance:
2461         clipCullVar = isOutput ? &cullDistanceOutput : &cullDistanceInput;
2462         semanticNSize = isOutput ? &cullSemanticNSizeOut : &cullSemanticNSizeIn;
2463         break;
2464
2465     // called invalidly: we expected a clip or a cull distance.
2466     // static compile time problem: should not happen.
2467     default: assert(0); return nullptr;
2468     }
2469
2470     // This is the offset in the destination array of a given semantic's data
2471     std::array<int, maxClipCullRegs> semanticOffset;
2472
2473     // Calculate offset of variable of semantic N in destination array
2474     int arrayLoc = 0;
2475     int vecItems = 0;
2476
2477     for (int x = 0; x < maxClipCullRegs; ++x) {
2478         // See if we overflowed the vec4 packing
2479         if ((vecItems + (*semanticNSize)[x]) > 4) {
2480             arrayLoc = (arrayLoc + 3) & (~0x3); // round up to next multiple of 4
2481             vecItems = 0;
2482         }
2483
2484         semanticOffset[x] = arrayLoc;
2485         vecItems += (*semanticNSize)[x];
2486         arrayLoc += (*semanticNSize)[x];
2487     }
2488  
2489
2490     // It can have up to 2 array dimensions (in the case of geometry shader inputs)
2491     const TArraySizes* const internalArraySizes = internalNode->getType().getArraySizes();
2492     const int internalArrayDims = internalNode->getType().isArray() ? internalArraySizes->getNumDims() : 0;
2493     // vector sizes:
2494     const int internalVectorSize = internalNode->getType().getVectorSize();
2495     // array sizes, or 1 if it's not an array:
2496     const int internalInnerArraySize = (internalArrayDims > 0 ? internalArraySizes->getDimSize(internalArrayDims-1) : 1);
2497     const int internalOuterArraySize = (internalArrayDims > 1 ? internalArraySizes->getDimSize(0) : 1);
2498
2499     // The created type may be an array of arrays, e.g, for geometry shader inputs.
2500     const bool isImplicitlyArrayed = (language == EShLangGeometry && !isOutput);
2501
2502     // If we haven't created the output already, create it now.
2503     if (*clipCullVar == nullptr) {
2504         // ClipDistance and CullDistance are handled specially in the entry point input/output copy
2505         // algorithm, because they may need to be unpacked from components of vectors (or a scalar)
2506         // into a float array, or vice versa.  Here, we make the array the right size and type,
2507         // which depends on the incoming data, which has several potential dimensions:
2508         //    * Semantic ID
2509         //    * vector size 
2510         //    * array size
2511         // Of those, semantic ID and array size cannot appear simultaneously.
2512         //
2513         // Also to note: for implicitly arrayed forms (e.g, geometry shader inputs), we need to create two
2514         // array dimensions.  The shader's declaration may have one or two array dimensions.  One is always
2515         // the geometry's dimension.
2516
2517         const bool useInnerSize = internalArrayDims > 1 || !isImplicitlyArrayed;
2518
2519         const int requiredInnerArraySize = arrayLoc * (useInnerSize ? internalInnerArraySize : 1);
2520         const int requiredOuterArraySize = (internalArrayDims > 0) ? internalArraySizes->getDimSize(0) : 1;
2521
2522         TType clipCullType(EbtFloat, clipCullNode->getType().getQualifier().storage, 1);
2523         clipCullType.getQualifier() = clipCullNode->getType().getQualifier();
2524
2525         // Create required array dimension
2526         TArraySizes* arraySizes = new TArraySizes;
2527         if (isImplicitlyArrayed)
2528             arraySizes->addInnerSize(requiredOuterArraySize);
2529         arraySizes->addInnerSize(requiredInnerArraySize);
2530         clipCullType.transferArraySizes(arraySizes);
2531
2532         // Obtain symbol name: we'll use that for the symbol we introduce.
2533         TIntermSymbol* sym = clipCullNode->getAsSymbolNode();
2534         assert(sym != nullptr);
2535
2536         // We are moving the semantic ID from the layout location, so it is no longer needed or
2537         // desired there.
2538         clipCullType.getQualifier().layoutLocation = TQualifier::layoutLocationEnd;
2539
2540         // Create variable and track its linkage
2541         *clipCullVar = makeInternalVariable(sym->getName().c_str(), clipCullType);
2542
2543         trackLinkage(**clipCullVar);
2544     }
2545
2546     // Create symbol for the clip or cull variable.
2547     TIntermSymbol* clipCullSym = intermediate.addSymbol(**clipCullVar);
2548
2549     // vector sizes:
2550     const int clipCullVectorSize = clipCullSym->getType().getVectorSize();
2551
2552     // array sizes, or 1 if it's not an array:
2553     const TArraySizes* const clipCullArraySizes = clipCullSym->getType().getArraySizes();
2554     const int clipCullOuterArraySize = isImplicitlyArrayed ? clipCullArraySizes->getDimSize(0) : 1;
2555     const int clipCullInnerArraySize = clipCullArraySizes->getDimSize(isImplicitlyArrayed ? 1 : 0);
2556
2557     // clipCullSym has got to be an array of scalar floats, per SPIR-V semantics.
2558     // fixBuiltInIoType() should have handled that upstream.
2559     assert(clipCullSym->getType().isArray());
2560     assert(clipCullSym->getType().getVectorSize() == 1);
2561     assert(clipCullSym->getType().getBasicType() == EbtFloat);
2562
2563     // We may be creating multiple sub-assignments.  This is an aggregate to hold them.
2564     // TODO: it would be possible to be clever sometimes and avoid the sequence node if not needed.
2565     TIntermAggregate* assignList = nullptr;
2566
2567     // Holds individual component assignments as we make them.
2568     TIntermTyped* clipCullAssign = nullptr;
2569
2570     // If the types are homomorphic, use a simple assign.  No need to mess about with 
2571     // individual components.
2572     if (clipCullSym->getType().isArray() == internalNode->getType().isArray() &&
2573         clipCullInnerArraySize == internalInnerArraySize &&
2574         clipCullOuterArraySize == internalOuterArraySize &&
2575         clipCullVectorSize == internalVectorSize) {
2576
2577         if (isOutput)
2578             clipCullAssign = intermediate.addAssign(op, clipCullSym, internalNode, loc);
2579         else
2580             clipCullAssign = intermediate.addAssign(op, internalNode, clipCullSym, loc);
2581
2582         assignList = intermediate.growAggregate(assignList, clipCullAssign);
2583         assignList->setOperator(EOpSequence);
2584
2585         return assignList;
2586     }
2587
2588     // We are going to copy each component of the internal (per array element if indicated) to sequential
2589     // array elements of the clipCullSym.  This tracks the lhs element we're writing to as we go along.
2590     // We may be starting in the middle - e.g, for a non-zero semantic ID calculated above.
2591     int clipCullInnerArrayPos = semanticOffset[semanticId];
2592     int clipCullOuterArrayPos = 0;
2593
2594     // Lambda to add an index to a node, set the type of the result, and return the new node.
2595     const auto addIndex = [this, &loc](TIntermTyped* node, int pos) -> TIntermTyped* {
2596         const TType derefType(node->getType(), 0);
2597         node = intermediate.addIndex(EOpIndexDirect, node, intermediate.addConstantUnion(pos, loc), loc);
2598         node->setType(derefType);
2599         return node;
2600     };
2601
2602     // Loop through every component of every element of the internal, and copy to or from the matching external.
2603     for (int internalOuterArrayPos = 0; internalOuterArrayPos < internalOuterArraySize; ++internalOuterArrayPos) {
2604         for (int internalInnerArrayPos = 0; internalInnerArrayPos < internalInnerArraySize; ++internalInnerArrayPos) {
2605             for (int internalComponent = 0; internalComponent < internalVectorSize; ++internalComponent) {
2606                 // clip/cull array member to read from / write to:
2607                 TIntermTyped* clipCullMember = clipCullSym;
2608
2609                 // If implicitly arrayed, there is an outer array dimension involved
2610                 if (isImplicitlyArrayed)
2611                     clipCullMember = addIndex(clipCullMember, clipCullOuterArrayPos);
2612
2613                 // Index into proper array position for clip cull member
2614                 clipCullMember = addIndex(clipCullMember, clipCullInnerArrayPos++);
2615
2616                 // if needed, start over with next outer array slice.
2617                 if (isImplicitlyArrayed && clipCullInnerArrayPos >= clipCullInnerArraySize) {
2618                     clipCullInnerArrayPos = semanticOffset[semanticId];
2619                     ++clipCullOuterArrayPos;
2620                 }
2621
2622                 // internal member to read from / write to:
2623                 TIntermTyped* internalMember = internalNode;
2624
2625                 // If internal node has outer array dimension, index appropriately.
2626                 if (internalArrayDims > 1)
2627                     internalMember = addIndex(internalMember, internalOuterArrayPos);
2628
2629                 // If internal node has inner array dimension, index appropriately.
2630                 if (internalArrayDims > 0)
2631                     internalMember = addIndex(internalMember, internalInnerArrayPos);
2632
2633                 // If internal node is a vector, extract the component of interest.
2634                 if (internalNode->getType().isVector())
2635                     internalMember = addIndex(internalMember, internalComponent);
2636
2637                 // Create an assignment: output from internal to clip cull, or input from clip cull to internal.
2638                 if (isOutput)
2639                     clipCullAssign = intermediate.addAssign(op, clipCullMember, internalMember, loc);
2640                 else
2641                     clipCullAssign = intermediate.addAssign(op, internalMember, clipCullMember, loc);
2642
2643                 // Track assignment in the sequence.
2644                 assignList = intermediate.growAggregate(assignList, clipCullAssign);
2645             }
2646         }
2647     }
2648
2649     assert(assignList != nullptr);
2650     assignList->setOperator(EOpSequence);
2651
2652     return assignList;
2653 }
2654
2655 // Some simple source assignments need to be flattened to a sequence
2656 // of AST assignments. Catch these and flatten, otherwise, pass through
2657 // to intermediate.addAssign().
2658 //
2659 // Also, assignment to matrix swizzles requires multiple component assignments,
2660 // intercept those as well.
2661 TIntermTyped* HlslParseContext::handleAssign(const TSourceLoc& loc, TOperator op, TIntermTyped* left,
2662                                              TIntermTyped* right)
2663 {
2664     if (left == nullptr || right == nullptr)
2665         return nullptr;
2666
2667     // writing to opaques will require fixing transforms
2668     if (left->getType().containsOpaque())
2669         intermediate.setNeedsLegalization();
2670
2671     if (left->getAsOperator() && left->getAsOperator()->getOp() == EOpMatrixSwizzle)
2672         return handleAssignToMatrixSwizzle(loc, op, left, right);
2673
2674     // Return true if the given node is an index operation into a split variable.
2675     const auto indexesSplit = [this](const TIntermTyped* node) -> bool {
2676         const TIntermBinary* binaryNode = node->getAsBinaryNode();
2677
2678         if (binaryNode == nullptr)
2679             return false;
2680
2681         return (binaryNode->getOp() == EOpIndexDirect || binaryNode->getOp() == EOpIndexIndirect) && 
2682                wasSplit(binaryNode->getLeft());
2683     };
2684
2685     // Return true if this stage assigns clip position with potentially inverted Y
2686     const auto assignsClipPos = [this](const TIntermTyped* node) -> bool {
2687         return node->getType().getQualifier().builtIn == EbvPosition &&
2688                (language == EShLangVertex || language == EShLangGeometry || language == EShLangTessEvaluation);
2689     };
2690
2691     const bool isSplitLeft    = wasSplit(left) || indexesSplit(left);
2692     const bool isSplitRight   = wasSplit(right) || indexesSplit(right);
2693
2694     const bool isFlattenLeft  = wasFlattened(left);
2695     const bool isFlattenRight = wasFlattened(right);
2696
2697     // OK to do a single assign if neither side is split or flattened.  Otherwise, 
2698     // fall through to a member-wise copy.
2699     if (!isFlattenLeft && !isFlattenRight && !isSplitLeft && !isSplitRight) {
2700         // Clip and cull distance requires more processing.  See comment above assignClipCullDistance.
2701         if (isClipOrCullDistance(left->getType()) || isClipOrCullDistance(right->getType())) {
2702             const bool isOutput = isClipOrCullDistance(left->getType());
2703
2704             const int semanticId = (isOutput ? left : right)->getType().getQualifier().layoutLocation;
2705             return assignClipCullDistance(loc, op, semanticId, left, right);
2706         } else if (assignsClipPos(left)) {
2707             // Position can require special handling: see comment above assignPosition
2708             return assignPosition(loc, op, left, right);
2709         } else if (left->getQualifier().builtIn == EbvSampleMask) {
2710             // Certain builtins are required to be arrayed outputs in SPIR-V, but may internally be scalars
2711             // in the shader.  Copy the scalar RHS into the LHS array element zero, if that happens.
2712             if (left->isArray() && !right->isArray()) {
2713                 const TType derefType(left->getType(), 0);
2714                 left = intermediate.addIndex(EOpIndexDirect, left, intermediate.addConstantUnion(0, loc), loc);
2715                 left->setType(derefType);
2716                 // Fall through to add assign.
2717             }
2718         }
2719
2720         return intermediate.addAssign(op, left, right, loc);
2721     }
2722
2723     TIntermAggregate* assignList = nullptr;
2724     const TVector<TVariable*>* leftVariables = nullptr;
2725     const TVector<TVariable*>* rightVariables = nullptr;
2726
2727     // A temporary to store the right node's value, so we don't keep indirecting into it
2728     // if it's not a simple symbol.
2729     TVariable* rhsTempVar = nullptr;
2730
2731     // If the RHS is a simple symbol node, we'll copy it for each member.
2732     TIntermSymbol* cloneSymNode = nullptr;
2733
2734     int memberCount = 0;
2735
2736     // Track how many items there are to copy.
2737     if (left->getType().isStruct())
2738         memberCount = (int)left->getType().getStruct()->size();
2739     if (left->getType().isArray())
2740         memberCount = left->getType().getCumulativeArraySize();
2741
2742     if (isFlattenLeft)
2743         leftVariables = &flattenMap.find(left->getAsSymbolNode()->getId())->second.members;
2744
2745     if (isFlattenRight) {
2746         rightVariables = &flattenMap.find(right->getAsSymbolNode()->getId())->second.members;
2747     } else {
2748         // The RHS is not flattened.  There are several cases:
2749         // 1. 1 item to copy:  Use the RHS directly.
2750         // 2. >1 item, simple symbol RHS: we'll create a new TIntermSymbol node for each, but no assign to temp.
2751         // 3. >1 item, complex RHS: assign it to a new temp variable, and create a TIntermSymbol for each member.
2752
2753         if (memberCount <= 1) {
2754             // case 1: we'll use the symbol directly below.  Nothing to do.
2755         } else {
2756             if (right->getAsSymbolNode() != nullptr) {
2757                 // case 2: we'll copy the symbol per iteration below.
2758                 cloneSymNode = right->getAsSymbolNode();
2759             } else {
2760                 // case 3: assign to a temp, and indirect into that.
2761                 rhsTempVar = makeInternalVariable("flattenTemp", right->getType());
2762                 rhsTempVar->getWritableType().getQualifier().makeTemporary();
2763                 TIntermTyped* noFlattenRHS = intermediate.addSymbol(*rhsTempVar, loc);
2764
2765                 // Add this to the aggregate being built.
2766                 assignList = intermediate.growAggregate(assignList,
2767                                                         intermediate.addAssign(op, noFlattenRHS, right, loc), loc);
2768             }
2769         }
2770     }
2771
2772     // When dealing with split arrayed structures of built-ins, the arrayness is moved to the extracted built-in
2773     // variables, which is awkward when copying between split and unsplit structures.  This variable tracks
2774     // array indirections so they can be percolated from outer structs to inner variables.
2775     std::vector <int> arrayElement;
2776
2777     TStorageQualifier leftStorage = left->getType().getQualifier().storage;
2778     TStorageQualifier rightStorage = right->getType().getQualifier().storage;
2779
2780     int leftOffset = findSubtreeOffset(*left);
2781     int rightOffset = findSubtreeOffset(*right);
2782
2783     const auto getMember = [&](bool isLeft, const TType& type, int member, TIntermTyped* splitNode, int splitMember,
2784                                bool flattened)
2785                            -> TIntermTyped * {
2786         const bool split     = isLeft ? isSplitLeft   : isSplitRight;
2787
2788         TIntermTyped* subTree;
2789         const TType derefType(type, member);
2790         const TVariable* builtInVar = nullptr;
2791         if ((flattened || split) && derefType.isBuiltIn()) {
2792             auto splitPair = splitBuiltIns.find(HlslParseContext::tInterstageIoData(
2793                                                    derefType.getQualifier().builtIn,
2794                                                    isLeft ? leftStorage : rightStorage));
2795             if (splitPair != splitBuiltIns.end())
2796                 builtInVar = splitPair->second;
2797         }
2798         if (builtInVar != nullptr) {
2799             // copy from interstage IO built-in if needed
2800             subTree = intermediate.addSymbol(*builtInVar);
2801
2802             if (subTree->getType().isArray()) {
2803                 // Arrayness of builtIn symbols isn't handled by the normal recursion:
2804                 // it's been extracted and moved to the built-in.
2805                 if (!arrayElement.empty()) {
2806                     const TType splitDerefType(subTree->getType(), arrayElement.back());
2807                     subTree = intermediate.addIndex(EOpIndexDirect, subTree,
2808                                                     intermediate.addConstantUnion(arrayElement.back(), loc), loc);
2809                     subTree->setType(splitDerefType);
2810                 } else if (splitNode->getAsOperator() != nullptr && (splitNode->getAsOperator()->getOp() == EOpIndexIndirect)) {
2811                     // This might also be a stage with arrayed outputs, in which case there's an index
2812                     // operation we should transfer to the output builtin.
2813
2814                     const TType splitDerefType(subTree->getType(), 0);
2815                     subTree = intermediate.addIndex(splitNode->getAsOperator()->getOp(), subTree,
2816                                                     splitNode->getAsBinaryNode()->getRight(), loc);
2817                     subTree->setType(splitDerefType);
2818                 }
2819             }
2820         } else if (flattened && !shouldFlatten(derefType, isLeft ? leftStorage : rightStorage, false)) {
2821             if (isLeft)
2822                 subTree = intermediate.addSymbol(*(*leftVariables)[leftOffset++]);
2823             else
2824                 subTree = intermediate.addSymbol(*(*rightVariables)[rightOffset++]);
2825         } else {
2826             // Index operator if it's an aggregate, else EOpNull
2827             const TOperator accessOp = type.isArray()  ? EOpIndexDirect
2828                                      : type.isStruct() ? EOpIndexDirectStruct
2829                                      : EOpNull;
2830             if (accessOp == EOpNull) {
2831                 subTree = splitNode;
2832             } else {
2833                 subTree = intermediate.addIndex(accessOp, splitNode, intermediate.addConstantUnion(splitMember, loc),
2834                                                 loc);
2835                 const TType splitDerefType(splitNode->getType(), splitMember);
2836                 subTree->setType(splitDerefType);
2837             }
2838         }
2839
2840         return subTree;
2841     };
2842
2843     // Use the proper RHS node: a new symbol from a TVariable, copy
2844     // of an TIntermSymbol node, or sometimes the right node directly.
2845     right = rhsTempVar != nullptr   ? intermediate.addSymbol(*rhsTempVar, loc) :
2846             cloneSymNode != nullptr ? intermediate.addSymbol(*cloneSymNode) :
2847             right;
2848
2849     // Cannot use auto here, because this is recursive, and auto can't work out the type without seeing the
2850     // whole thing.  So, we'll resort to an explicit type via std::function.
2851     const std::function<void(TIntermTyped* left, TIntermTyped* right, TIntermTyped* splitLeft, TIntermTyped* splitRight,
2852                              bool topLevel)>
2853     traverse = [&](TIntermTyped* left, TIntermTyped* right, TIntermTyped* splitLeft, TIntermTyped* splitRight,
2854                    bool topLevel) -> void {
2855         // If we get here, we are assigning to or from a whole array or struct that must be
2856         // flattened, so have to do member-by-member assignment:
2857
2858         bool shouldFlattenSubsetLeft = isFlattenLeft && shouldFlatten(left->getType(), leftStorage, topLevel);
2859         bool shouldFlattenSubsetRight = isFlattenRight && shouldFlatten(right->getType(), rightStorage, topLevel);
2860
2861         if ((left->getType().isArray() || right->getType().isArray()) &&
2862               (shouldFlattenSubsetLeft  || isSplitLeft ||
2863                shouldFlattenSubsetRight || isSplitRight)) {
2864             const int elementsL = left->getType().isArray()  ? left->getType().getOuterArraySize()  : 1;
2865             const int elementsR = right->getType().isArray() ? right->getType().getOuterArraySize() : 1;
2866
2867             // The arrays might not be the same size,
2868             // e.g., if the size has been forced for EbvTessLevelInner/Outer.
2869             const int elementsToCopy = std::min(elementsL, elementsR);
2870
2871             // array case
2872             for (int element = 0; element < elementsToCopy; ++element) {
2873                 arrayElement.push_back(element);
2874
2875                 // Add a new AST symbol node if we have a temp variable holding a complex RHS.
2876                 TIntermTyped* subLeft  = getMember(true,  left->getType(),  element, left, element,
2877                                                    shouldFlattenSubsetLeft);
2878                 TIntermTyped* subRight = getMember(false, right->getType(), element, right, element,
2879                                                    shouldFlattenSubsetRight);
2880
2881                 TIntermTyped* subSplitLeft =  isSplitLeft  ? getMember(true,  left->getType(),  element, splitLeft,
2882                                                                        element, shouldFlattenSubsetLeft)
2883                                                            : subLeft;
2884                 TIntermTyped* subSplitRight = isSplitRight ? getMember(false, right->getType(), element, splitRight,
2885                                                                        element, shouldFlattenSubsetRight)
2886                                                            : subRight;
2887
2888                 traverse(subLeft, subRight, subSplitLeft, subSplitRight, false);
2889
2890                 arrayElement.pop_back();
2891             }
2892         } else if (left->getType().isStruct() && (shouldFlattenSubsetLeft  || isSplitLeft ||
2893                                                   shouldFlattenSubsetRight || isSplitRight)) {
2894             // struct case
2895             const auto& membersL = *left->getType().getStruct();
2896             const auto& membersR = *right->getType().getStruct();
2897
2898             // These track the members in the split structures corresponding to the same in the unsplit structures,
2899             // which we traverse in parallel.
2900             int memberL = 0;
2901             int memberR = 0;
2902
2903             // Handle empty structure assignment
2904             if (int(membersL.size()) == 0 && int(membersR.size()) == 0)
2905                 assignList = intermediate.growAggregate(assignList, intermediate.addAssign(op, left, right, loc), loc);
2906
2907             for (int member = 0; member < int(membersL.size()); ++member) {
2908                 const TType& typeL = *membersL[member].type;
2909                 const TType& typeR = *membersR[member].type;
2910
2911                 TIntermTyped* subLeft  = getMember(true,  left->getType(), member, left, member,
2912                                                    shouldFlattenSubsetLeft);
2913                 TIntermTyped* subRight = getMember(false, right->getType(), member, right, member,
2914                                                    shouldFlattenSubsetRight);
2915
2916                 // If there is no splitting, use the same values to avoid inefficiency.
2917                 TIntermTyped* subSplitLeft =  isSplitLeft  ? getMember(true,  left->getType(),  member, splitLeft,
2918                                                                        memberL, shouldFlattenSubsetLeft)
2919                                                            : subLeft;
2920                 TIntermTyped* subSplitRight = isSplitRight ? getMember(false, right->getType(), member, splitRight,
2921                                                                        memberR, shouldFlattenSubsetRight)
2922                                                            : subRight;
2923
2924                 if (isClipOrCullDistance(subSplitLeft->getType()) || isClipOrCullDistance(subSplitRight->getType())) {
2925                     // Clip and cull distance built-in assignment is complex in its own right, and is handled in
2926                     // a separate function dedicated to that task.  See comment above assignClipCullDistance;
2927
2928                     const bool isOutput = isClipOrCullDistance(subSplitLeft->getType());
2929
2930                     // Since all clip/cull semantics boil down to the same built-in type, we need to get the
2931                     // semantic ID from the dereferenced type's layout location, to avoid an N-1 mapping.
2932                     const TType derefType((isOutput ? left : right)->getType(), member);
2933                     const int semanticId = derefType.getQualifier().layoutLocation;
2934
2935                     TIntermAggregate* clipCullAssign = assignClipCullDistance(loc, op, semanticId,
2936                                                                               subSplitLeft, subSplitRight);
2937
2938                     assignList = intermediate.growAggregate(assignList, clipCullAssign, loc);
2939                 } else if (assignsClipPos(subSplitLeft)) {
2940                     // Position can require special handling: see comment above assignPosition
2941                     TIntermTyped* positionAssign = assignPosition(loc, op, subSplitLeft, subSplitRight);
2942                     assignList = intermediate.growAggregate(assignList, positionAssign, loc);
2943                 } else if (!shouldFlattenSubsetLeft && !shouldFlattenSubsetRight &&
2944                            !typeL.containsBuiltIn() && !typeR.containsBuiltIn()) {
2945                     // If this is the final flattening (no nested types below to flatten)
2946                     // we'll copy the member, else recurse into the type hierarchy.
2947                     // However, if splitting the struct, that means we can copy a whole
2948                     // subtree here IFF it does not itself contain any interstage built-in
2949                     // IO variables, so we only have to recurse into it if there's something
2950                     // for splitting to do.  That can save a lot of AST verbosity for
2951                     // a bunch of memberwise copies.
2952
2953                     assignList = intermediate.growAggregate(assignList,
2954                                                             intermediate.addAssign(op, subSplitLeft, subSplitRight, loc),
2955                                                             loc);
2956                 } else {
2957                     traverse(subLeft, subRight, subSplitLeft, subSplitRight, false);
2958                 }
2959
2960                 memberL += (typeL.isBuiltIn() ? 0 : 1);
2961                 memberR += (typeR.isBuiltIn() ? 0 : 1);
2962             }
2963         } else {
2964             // Member copy
2965             assignList = intermediate.growAggregate(assignList, intermediate.addAssign(op, left, right, loc), loc);
2966         }
2967
2968     };
2969
2970     TIntermTyped* splitLeft  = left;
2971     TIntermTyped* splitRight = right;
2972
2973     // If either left or right was a split structure, we must read or write it, but still have to
2974     // parallel-recurse through the unsplit structure to identify the built-in IO vars.
2975     // The left can be either a symbol, or an index into a symbol (e.g, array reference)
2976     if (isSplitLeft) {
2977         if (indexesSplit(left)) {
2978             // Index case: Refer to the indexed symbol, if the left is an index operator.
2979             const TIntermSymbol* symNode = left->getAsBinaryNode()->getLeft()->getAsSymbolNode();
2980
2981             TIntermTyped* splitLeftNonIo = intermediate.addSymbol(*getSplitNonIoVar(symNode->getId()), loc);
2982
2983             splitLeft = intermediate.addIndex(left->getAsBinaryNode()->getOp(), splitLeftNonIo,
2984                                               left->getAsBinaryNode()->getRight(), loc);
2985
2986             const TType derefType(splitLeftNonIo->getType(), 0);
2987             splitLeft->setType(derefType);
2988         } else {
2989             // Symbol case: otherwise, if not indexed, we have the symbol directly.
2990             const TIntermSymbol* symNode = left->getAsSymbolNode();
2991             splitLeft = intermediate.addSymbol(*getSplitNonIoVar(symNode->getId()), loc);
2992         }
2993     }
2994
2995     if (isSplitRight)
2996         splitRight = intermediate.addSymbol(*getSplitNonIoVar(right->getAsSymbolNode()->getId()), loc);
2997
2998     // This makes the whole assignment, recursing through subtypes as needed.
2999     traverse(left, right, splitLeft, splitRight, true);
3000
3001     assert(assignList != nullptr);
3002     assignList->setOperator(EOpSequence);
3003
3004     return assignList;
3005 }
3006
3007 // An assignment to matrix swizzle must be decomposed into individual assignments.
3008 // These must be selected component-wise from the RHS and stored component-wise
3009 // into the LHS.
3010 TIntermTyped* HlslParseContext::handleAssignToMatrixSwizzle(const TSourceLoc& loc, TOperator op, TIntermTyped* left,
3011                                                             TIntermTyped* right)
3012 {
3013     assert(left->getAsOperator() && left->getAsOperator()->getOp() == EOpMatrixSwizzle);
3014
3015     if (op != EOpAssign)
3016         error(loc, "only simple assignment to non-simple matrix swizzle is supported", "assign", "");
3017
3018     // isolate the matrix and swizzle nodes
3019     TIntermTyped* matrix = left->getAsBinaryNode()->getLeft()->getAsTyped();
3020     const TIntermSequence& swizzle = left->getAsBinaryNode()->getRight()->getAsAggregate()->getSequence();
3021
3022     // if the RHS isn't already a simple vector, let's store into one
3023     TIntermSymbol* vector = right->getAsSymbolNode();
3024     TIntermTyped* vectorAssign = nullptr;
3025     if (vector == nullptr) {
3026         // create a new intermediate vector variable to assign to
3027         TType vectorType(matrix->getBasicType(), EvqTemporary, matrix->getQualifier().precision, (int)swizzle.size()/2);
3028         vector = intermediate.addSymbol(*makeInternalVariable("intermVec", vectorType), loc);
3029
3030         // assign the right to the new vector
3031         vectorAssign = handleAssign(loc, op, vector, right);
3032     }
3033
3034     // Assign the vector components to the matrix components.
3035     // Store this as a sequence, so a single aggregate node represents this
3036     // entire operation.
3037     TIntermAggregate* result = intermediate.makeAggregate(vectorAssign);
3038     TType columnType(matrix->getType(), 0);
3039     TType componentType(columnType, 0);
3040     TType indexType(EbtInt);
3041     for (int i = 0; i < (int)swizzle.size(); i += 2) {
3042         // the right component, single index into the RHS vector
3043         TIntermTyped* rightComp = intermediate.addIndex(EOpIndexDirect, vector,
3044                                     intermediate.addConstantUnion(i/2, loc), loc);
3045
3046         // the left component, double index into the LHS matrix
3047         TIntermTyped* leftComp = intermediate.addIndex(EOpIndexDirect, matrix,
3048                                     intermediate.addConstantUnion(swizzle[i]->getAsConstantUnion()->getConstArray(),
3049                                                                   indexType, loc),
3050                                     loc);
3051         leftComp->setType(columnType);
3052         leftComp = intermediate.addIndex(EOpIndexDirect, leftComp,
3053                                     intermediate.addConstantUnion(swizzle[i+1]->getAsConstantUnion()->getConstArray(),
3054                                                                   indexType, loc),
3055                                     loc);
3056         leftComp->setType(componentType);
3057
3058         // Add the assignment to the aggregate
3059         result = intermediate.growAggregate(result, intermediate.addAssign(op, leftComp, rightComp, loc));
3060     }
3061
3062     result->setOp(EOpSequence);
3063
3064     return result;
3065 }
3066
3067 //
3068 // HLSL atomic operations have slightly different arguments than
3069 // GLSL/AST/SPIRV.  The semantics are converted below in decomposeIntrinsic.
3070 // This provides the post-decomposition equivalent opcode.
3071 //
3072 TOperator HlslParseContext::mapAtomicOp(const TSourceLoc& loc, TOperator op, bool isImage)
3073 {
3074     switch (op) {
3075     case EOpInterlockedAdd:             return isImage ? EOpImageAtomicAdd      : EOpAtomicAdd;
3076     case EOpInterlockedAnd:             return isImage ? EOpImageAtomicAnd      : EOpAtomicAnd;
3077     case EOpInterlockedCompareExchange: return isImage ? EOpImageAtomicCompSwap : EOpAtomicCompSwap;
3078     case EOpInterlockedMax:             return isImage ? EOpImageAtomicMax      : EOpAtomicMax;
3079     case EOpInterlockedMin:             return isImage ? EOpImageAtomicMin      : EOpAtomicMin;
3080     case EOpInterlockedOr:              return isImage ? EOpImageAtomicOr       : EOpAtomicOr;
3081     case EOpInterlockedXor:             return isImage ? EOpImageAtomicXor      : EOpAtomicXor;
3082     case EOpInterlockedExchange:        return isImage ? EOpImageAtomicExchange : EOpAtomicExchange;
3083     case EOpInterlockedCompareStore:  // TODO: ...
3084     default:
3085         error(loc, "unknown atomic operation", "unknown op", "");
3086         return EOpNull;
3087     }
3088 }
3089
3090 //
3091 // Create a combined sampler/texture from separate sampler and texture.
3092 //
3093 TIntermAggregate* HlslParseContext::handleSamplerTextureCombine(const TSourceLoc& loc, TIntermTyped* argTex,
3094                                                                 TIntermTyped* argSampler)
3095 {
3096     TIntermAggregate* txcombine = new TIntermAggregate(EOpConstructTextureSampler);
3097
3098     txcombine->getSequence().push_back(argTex);
3099     txcombine->getSequence().push_back(argSampler);
3100
3101     TSampler samplerType = argTex->getType().getSampler();
3102     samplerType.combined = true;
3103
3104     // TODO:
3105     // This block exists until the spec no longer requires shadow modes on texture objects.
3106     // It can be deleted after that, along with the shadowTextureVariant member.
3107     {
3108         const bool shadowMode = argSampler->getType().getSampler().shadow;
3109
3110         TIntermSymbol* texSymbol = argTex->getAsSymbolNode();
3111
3112         if (texSymbol == nullptr)
3113             texSymbol = argTex->getAsBinaryNode()->getLeft()->getAsSymbolNode();
3114
3115         if (texSymbol == nullptr) {
3116             error(loc, "unable to find texture symbol", "", "");
3117             return nullptr;
3118         }
3119
3120         // This forces the texture's shadow state to be the sampler's
3121         // shadow state.  This depends on downstream optimization to
3122         // DCE one variant in [shadow, nonshadow] if both are present,
3123         // or the SPIR-V module would be invalid.
3124         int newId = texSymbol->getId();
3125
3126         // Check to see if this texture has been given a shadow mode already.
3127         // If so, look up the one we already have.
3128         const auto textureShadowEntry = textureShadowVariant.find(texSymbol->getId());
3129
3130         if (textureShadowEntry != textureShadowVariant.end())
3131             newId = textureShadowEntry->second->get(shadowMode);
3132         else
3133             textureShadowVariant[texSymbol->getId()] = NewPoolObject(tShadowTextureSymbols(), 1);
3134
3135         // Sometimes we have to create another symbol (if this texture has been seen before,
3136         // and we haven't created the form for this shadow mode).
3137         if (newId == -1) {
3138             TType texType;
3139             texType.shallowCopy(argTex->getType());
3140             texType.getSampler().shadow = shadowMode;  // set appropriate shadow mode.
3141             globalQualifierFix(loc, texType.getQualifier());
3142
3143             TVariable* newTexture = makeInternalVariable(texSymbol->getName(), texType);
3144
3145             trackLinkage(*newTexture);
3146
3147             newId = newTexture->getUniqueId();
3148         }
3149
3150         assert(newId != -1);
3151
3152         if (textureShadowVariant.find(newId) == textureShadowVariant.end())
3153             textureShadowVariant[newId] = textureShadowVariant[texSymbol->getId()];
3154
3155         textureShadowVariant[newId]->set(shadowMode, newId);
3156
3157         // Remember this shadow mode in the texture and the merged type.
3158         argTex->getWritableType().getSampler().shadow = shadowMode;
3159         samplerType.shadow = shadowMode;
3160
3161         texSymbol->switchId(newId);
3162     }
3163
3164     txcombine->setType(TType(samplerType, EvqTemporary));
3165     txcombine->setLoc(loc);
3166
3167     return txcombine;
3168 }
3169
3170 // Return true if this a buffer type that has an associated counter buffer.
3171 bool HlslParseContext::hasStructBuffCounter(const TType& type) const
3172 {
3173     switch (type.getQualifier().declaredBuiltIn) {
3174     case EbvAppendConsume:       // fall through...
3175     case EbvRWStructuredBuffer:  // ...
3176         return true;
3177     default:
3178         return false; // the other structuredbuffer types do not have a counter.
3179     }
3180 }
3181
3182 void HlslParseContext::counterBufferType(const TSourceLoc& loc, TType& type)
3183 {
3184     // Counter type
3185     TType* counterType = new TType(EbtUint, EvqBuffer);
3186     counterType->setFieldName(intermediate.implicitCounterName);
3187
3188     TTypeList* blockStruct = new TTypeList;
3189     TTypeLoc  member = { counterType, loc };
3190     blockStruct->push_back(member);
3191
3192     TType blockType(blockStruct, "", counterType->getQualifier());
3193     blockType.getQualifier().storage = EvqBuffer;
3194
3195     type.shallowCopy(blockType);
3196     shareStructBufferType(type);
3197 }
3198
3199 // declare counter for a structured buffer type
3200 void HlslParseContext::declareStructBufferCounter(const TSourceLoc& loc, const TType& bufferType, const TString& name)
3201 {
3202     // Bail out if not a struct buffer
3203     if (! isStructBufferType(bufferType))
3204         return;
3205
3206     if (! hasStructBuffCounter(bufferType))
3207         return;
3208
3209     TType blockType;
3210     counterBufferType(loc, blockType);
3211
3212     TString* blockName = NewPoolTString(intermediate.addCounterBufferName(name).c_str());
3213
3214     // Counter buffer is not yet in use
3215     structBufferCounter[*blockName] = false;
3216
3217     shareStructBufferType(blockType);
3218     declareBlock(loc, blockType, blockName);
3219 }
3220
3221 // return the counter that goes with a given structuredbuffer
3222 TIntermTyped* HlslParseContext::getStructBufferCounter(const TSourceLoc& loc, TIntermTyped* buffer)
3223 {
3224     // Bail out if not a struct buffer
3225     if (buffer == nullptr || ! isStructBufferType(buffer->getType()))
3226         return nullptr;
3227
3228     const TString counterBlockName(intermediate.addCounterBufferName(buffer->getAsSymbolNode()->getName()));
3229
3230     // Mark the counter as being used
3231     structBufferCounter[counterBlockName] = true;
3232
3233     TIntermTyped* counterVar = handleVariable(loc, &counterBlockName);  // find the block structure
3234     TIntermTyped* index = intermediate.addConstantUnion(0, loc); // index to counter inside block struct
3235
3236     TIntermTyped* counterMember = intermediate.addIndex(EOpIndexDirectStruct, counterVar, index, loc);
3237     counterMember->setType(TType(EbtUint));
3238     return counterMember;
3239 }
3240
3241 //
3242 // Decompose structure buffer methods into AST
3243 //
3244 void HlslParseContext::decomposeStructBufferMethods(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
3245 {
3246     if (node == nullptr || node->getAsOperator() == nullptr || arguments == nullptr)
3247         return;
3248
3249     const TOperator op  = node->getAsOperator()->getOp();
3250     TIntermAggregate* argAggregate = arguments->getAsAggregate();
3251
3252     // Buffer is the object upon which method is called, so always arg 0
3253     TIntermTyped* bufferObj = nullptr;
3254
3255     // The parameters can be an aggregate, or just a the object as a symbol if there are no fn params.
3256     if (argAggregate) {
3257         if (argAggregate->getSequence().empty())
3258             return;
3259                 if (argAggregate->getSequence()[0])
3260                 bufferObj = argAggregate->getSequence()[0]->getAsTyped();
3261     } else {
3262         bufferObj = arguments->getAsSymbolNode();
3263     }
3264
3265     if (bufferObj == nullptr || bufferObj->getAsSymbolNode() == nullptr)
3266         return;
3267
3268     // Some methods require a hidden internal counter, obtained via getStructBufferCounter().
3269     // This lambda adds something to it and returns the old value.
3270     const auto incDecCounter = [&](int incval) -> TIntermTyped* {
3271         TIntermTyped* incrementValue = intermediate.addConstantUnion(static_cast<unsigned int>(incval), loc, true);
3272         TIntermTyped* counter = getStructBufferCounter(loc, bufferObj); // obtain the counter member
3273
3274         if (counter == nullptr)
3275             return nullptr;
3276
3277         TIntermAggregate* counterIncrement = new TIntermAggregate(EOpAtomicAdd);
3278         counterIncrement->setType(TType(EbtUint, EvqTemporary));
3279         counterIncrement->setLoc(loc);
3280         counterIncrement->getSequence().push_back(counter);
3281         counterIncrement->getSequence().push_back(incrementValue);
3282
3283         return counterIncrement;
3284     };
3285
3286     // Index to obtain the runtime sized array out of the buffer.
3287     TIntermTyped* argArray = indexStructBufferContent(loc, bufferObj);
3288     if (argArray == nullptr)
3289         return;  // It might not be a struct buffer method.
3290
3291     switch (op) {
3292     case EOpMethodLoad:
3293         {
3294             TIntermTyped* argIndex = makeIntegerIndex(argAggregate->getSequence()[1]->getAsTyped());  // index
3295
3296             const TType& bufferType = bufferObj->getType();
3297
3298             const TBuiltInVariable builtInType = bufferType.getQualifier().declaredBuiltIn;
3299
3300             // Byte address buffers index in bytes (only multiples of 4 permitted... not so much a byte address
3301             // buffer then, but that's what it calls itself.
3302             const bool isByteAddressBuffer = (builtInType == EbvByteAddressBuffer   || 
3303                                               builtInType == EbvRWByteAddressBuffer);
3304                 
3305
3306             if (isByteAddressBuffer)
3307                 argIndex = intermediate.addBinaryNode(EOpRightShift, argIndex,
3308                                                       intermediate.addConstantUnion(2, loc, true),
3309                                                       loc, TType(EbtInt));
3310
3311             // Index into the array to find the item being loaded.
3312             const TOperator idxOp = (argIndex->getQualifier().storage == EvqConst) ? EOpIndexDirect : EOpIndexIndirect;
3313
3314             node = intermediate.addIndex(idxOp, argArray, argIndex, loc);
3315
3316             const TType derefType(argArray->getType(), 0);
3317             node->setType(derefType);
3318         }
3319         
3320         break;
3321
3322     case EOpMethodLoad2:
3323     case EOpMethodLoad3:
3324     case EOpMethodLoad4:
3325         {
3326             TIntermTyped* argIndex = makeIntegerIndex(argAggregate->getSequence()[1]->getAsTyped());  // index
3327
3328             TOperator constructOp = EOpNull;
3329             int size = 0;
3330
3331             switch (op) {
3332             case EOpMethodLoad2: size = 2; constructOp = EOpConstructVec2; break;
3333             case EOpMethodLoad3: size = 3; constructOp = EOpConstructVec3; break;
3334             case EOpMethodLoad4: size = 4; constructOp = EOpConstructVec4; break;
3335             default: assert(0);
3336             }
3337
3338             TIntermTyped* body = nullptr;
3339
3340             // First, we'll store the address in a variable to avoid multiple shifts
3341             // (we must convert the byte address to an item address)
3342             TIntermTyped* byteAddrIdx = intermediate.addBinaryNode(EOpRightShift, argIndex,
3343                                                                    intermediate.addConstantUnion(2, loc, true),
3344                                                                    loc, TType(EbtInt));
3345
3346             TVariable* byteAddrSym = makeInternalVariable("byteAddrTemp", TType(EbtInt, EvqTemporary));
3347             TIntermTyped* byteAddrIdxVar = intermediate.addSymbol(*byteAddrSym, loc);
3348
3349             body = intermediate.growAggregate(body, intermediate.addAssign(EOpAssign, byteAddrIdxVar, byteAddrIdx, loc));
3350
3351             TIntermTyped* vec = nullptr;
3352
3353             // These are only valid on (rw)byteaddressbuffers, so we can always perform the >>2
3354             // address conversion.
3355             for (int idx=0; idx<size; ++idx) {
3356                 TIntermTyped* offsetIdx = byteAddrIdxVar;
3357
3358                 // add index offset
3359                 if (idx != 0)
3360                     offsetIdx = intermediate.addBinaryNode(EOpAdd, offsetIdx,
3361                                                            intermediate.addConstantUnion(idx, loc, true),
3362                                                            loc, TType(EbtInt));
3363
3364                 const TOperator idxOp = (offsetIdx->getQualifier().storage == EvqConst) ? EOpIndexDirect
3365                                                                                         : EOpIndexIndirect;
3366
3367                 TIntermTyped* indexVal = intermediate.addIndex(idxOp, argArray, offsetIdx, loc);
3368
3369                 TType derefType(argArray->getType(), 0);
3370                 derefType.getQualifier().makeTemporary();
3371                 indexVal->setType(derefType);
3372
3373                 vec = intermediate.growAggregate(vec, indexVal);
3374             }
3375
3376             vec->setType(TType(argArray->getBasicType(), EvqTemporary, size));
3377             vec->getAsAggregate()->setOperator(constructOp);
3378
3379             body = intermediate.growAggregate(body, vec);
3380             body->setType(vec->getType());
3381             body->getAsAggregate()->setOperator(EOpSequence);
3382
3383             node = body;
3384         }
3385
3386         break;
3387
3388     case EOpMethodStore:
3389     case EOpMethodStore2:
3390     case EOpMethodStore3:
3391     case EOpMethodStore4:
3392         {
3393             TIntermTyped* argIndex = makeIntegerIndex(argAggregate->getSequence()[1]->getAsTyped());  // index
3394             TIntermTyped* argValue = argAggregate->getSequence()[2]->getAsTyped();  // value
3395
3396             // Index into the array to find the item being loaded.
3397             // Byte address buffers index in bytes (only multiples of 4 permitted... not so much a byte address
3398             // buffer then, but that's what it calls itself).
3399
3400             int size = 0;
3401
3402             switch (op) {
3403             case EOpMethodStore:  size = 1; break;
3404             case EOpMethodStore2: size = 2; break;
3405             case EOpMethodStore3: size = 3; break;
3406             case EOpMethodStore4: size = 4; break;
3407             default: assert(0);
3408             }
3409
3410             TIntermAggregate* body = nullptr;
3411
3412             // First, we'll store the address in a variable to avoid multiple shifts
3413             // (we must convert the byte address to an item address)
3414             TIntermTyped* byteAddrIdx = intermediate.addBinaryNode(EOpRightShift, argIndex,
3415                                                                    intermediate.addConstantUnion(2, loc, true), loc, TType(EbtInt));
3416
3417             TVariable* byteAddrSym = makeInternalVariable("byteAddrTemp", TType(EbtInt, EvqTemporary));
3418             TIntermTyped* byteAddrIdxVar = intermediate.addSymbol(*byteAddrSym, loc);
3419
3420             body = intermediate.growAggregate(body, intermediate.addAssign(EOpAssign, byteAddrIdxVar, byteAddrIdx, loc));
3421
3422             for (int idx=0; idx<size; ++idx) {
3423                 TIntermTyped* offsetIdx = byteAddrIdxVar;
3424                 TIntermTyped* idxConst = intermediate.addConstantUnion(idx, loc, true);
3425
3426                 // add index offset
3427                 if (idx != 0)
3428                     offsetIdx = intermediate.addBinaryNode(EOpAdd, offsetIdx, idxConst, loc, TType(EbtInt));
3429
3430                 const TOperator idxOp = (offsetIdx->getQualifier().storage == EvqConst) ? EOpIndexDirect
3431                                                                                         : EOpIndexIndirect;
3432
3433                 TIntermTyped* lValue = intermediate.addIndex(idxOp, argArray, offsetIdx, loc);
3434                 const TType derefType(argArray->getType(), 0);
3435                 lValue->setType(derefType);
3436
3437                 TIntermTyped* rValue;
3438                 if (size == 1) {
3439                     rValue = argValue;
3440                 } else {
3441                     rValue = intermediate.addIndex(EOpIndexDirect, argValue, idxConst, loc);
3442                     const TType indexType(argValue->getType(), 0);
3443                     rValue->setType(indexType);
3444                 }
3445                     
3446                 TIntermTyped* assign = intermediate.addAssign(EOpAssign, lValue, rValue, loc); 
3447
3448                 body = intermediate.growAggregate(body, assign);
3449             }
3450
3451             body->setOperator(EOpSequence);
3452             node = body;
3453         }
3454
3455         break;
3456
3457     case EOpMethodGetDimensions:
3458         {
3459             const int numArgs = (int)argAggregate->getSequence().size();
3460             TIntermTyped* argNumItems = argAggregate->getSequence()[1]->getAsTyped();  // out num items
3461             TIntermTyped* argStride   = numArgs > 2 ? argAggregate->getSequence()[2]->getAsTyped() : nullptr;  // out stride
3462
3463             TIntermAggregate* body = nullptr;
3464
3465             // Length output:
3466             if (argArray->getType().isSizedArray()) {
3467                 const int length = argArray->getType().getOuterArraySize();
3468                 TIntermTyped* assign = intermediate.addAssign(EOpAssign, argNumItems,
3469                                                               intermediate.addConstantUnion(length, loc, true), loc);
3470                 body = intermediate.growAggregate(body, assign, loc);
3471             } else {
3472                 TIntermTyped* lengthCall = intermediate.addBuiltInFunctionCall(loc, EOpArrayLength, true, argArray,
3473                                                                                argNumItems->getType());
3474                 TIntermTyped* assign = intermediate.addAssign(EOpAssign, argNumItems, lengthCall, loc);
3475                 body = intermediate.growAggregate(body, assign, loc);
3476             }
3477
3478             // Stride output:
3479             if (argStride != nullptr) {
3480                 int size;
3481                 int stride;
3482                 intermediate.getMemberAlignment(argArray->getType(), size, stride, argArray->getType().getQualifier().layoutPacking,
3483                                                 argArray->getType().getQualifier().layoutMatrix == ElmRowMajor);
3484
3485                 TIntermTyped* assign = intermediate.addAssign(EOpAssign, argStride,
3486                                                               intermediate.addConstantUnion(stride, loc, true), loc);
3487
3488                 body = intermediate.growAggregate(body, assign);
3489             }
3490
3491             body->setOperator(EOpSequence);
3492             node = body;
3493         }
3494
3495         break;
3496
3497     case EOpInterlockedAdd:
3498     case EOpInterlockedAnd:
3499     case EOpInterlockedExchange:
3500     case EOpInterlockedMax:
3501     case EOpInterlockedMin:
3502     case EOpInterlockedOr:
3503     case EOpInterlockedXor:
3504     case EOpInterlockedCompareExchange:
3505     case EOpInterlockedCompareStore:
3506         {
3507             // We'll replace the first argument with the block dereference, and let
3508             // downstream decomposition handle the rest.
3509
3510             TIntermSequence& sequence = argAggregate->getSequence();
3511
3512             TIntermTyped* argIndex     = makeIntegerIndex(sequence[1]->getAsTyped());  // index
3513             argIndex = intermediate.addBinaryNode(EOpRightShift, argIndex, intermediate.addConstantUnion(2, loc, true),
3514                                                   loc, TType(EbtInt));
3515
3516             const TOperator idxOp = (argIndex->getQualifier().storage == EvqConst) ? EOpIndexDirect : EOpIndexIndirect;
3517             TIntermTyped* element = intermediate.addIndex(idxOp, argArray, argIndex, loc);
3518
3519             const TType derefType(argArray->getType(), 0);
3520             element->setType(derefType);
3521
3522             // Replace the numeric byte offset parameter with array reference.
3523             sequence[1] = element;
3524             sequence.erase(sequence.begin(), sequence.begin()+1);
3525         }
3526         break;
3527
3528     case EOpMethodIncrementCounter:
3529         {
3530             node = incDecCounter(1);
3531             break;
3532         }
3533
3534     case EOpMethodDecrementCounter:
3535         {
3536             TIntermTyped* preIncValue = incDecCounter(-1); // result is original value
3537             node = intermediate.addBinaryNode(EOpAdd, preIncValue, intermediate.addConstantUnion(-1, loc, true), loc,
3538                                               preIncValue->getType());
3539             break;
3540         }
3541
3542     case EOpMethodAppend:
3543         {
3544             TIntermTyped* oldCounter = incDecCounter(1);
3545
3546             TIntermTyped* lValue = intermediate.addIndex(EOpIndexIndirect, argArray, oldCounter, loc);
3547             TIntermTyped* rValue = argAggregate->getSequence()[1]->getAsTyped();
3548
3549             const TType derefType(argArray->getType(), 0);
3550             lValue->setType(derefType);
3551
3552             node = intermediate.addAssign(EOpAssign, lValue, rValue, loc);
3553
3554             break;
3555         }
3556
3557     case EOpMethodConsume:
3558         {
3559             TIntermTyped* oldCounter = incDecCounter(-1);
3560
3561             TIntermTyped* newCounter = intermediate.addBinaryNode(EOpAdd, oldCounter,
3562                                                                   intermediate.addConstantUnion(-1, loc, true), loc,
3563                                                                   oldCounter->getType());
3564
3565             node = intermediate.addIndex(EOpIndexIndirect, argArray, newCounter, loc);
3566
3567             const TType derefType(argArray->getType(), 0);
3568             node->setType(derefType);
3569
3570             break;
3571         }
3572
3573     default:
3574         break; // most pass through unchanged
3575     }
3576 }
3577
3578 // Create array of standard sample positions for given sample count.
3579 // TODO: remove when a real method to query sample pos exists in SPIR-V.
3580 TIntermConstantUnion* HlslParseContext::getSamplePosArray(int count)
3581 {
3582     struct tSamplePos { float x, y; };
3583
3584     static const tSamplePos pos1[] = {
3585         { 0.0/16.0,  0.0/16.0 },
3586     };
3587
3588     // standard sample positions for 2, 4, 8, and 16 samples.
3589     static const tSamplePos pos2[] = {
3590         { 4.0/16.0,  4.0/16.0 }, {-4.0/16.0, -4.0/16.0 },
3591     };
3592
3593     static const tSamplePos pos4[] = {
3594         {-2.0/16.0, -6.0/16.0 }, { 6.0/16.0, -2.0/16.0 }, {-6.0/16.0,  2.0/16.0 }, { 2.0/16.0,  6.0/16.0 },
3595     };
3596
3597     static const tSamplePos pos8[] = {
3598         { 1.0/16.0, -3.0/16.0 }, {-1.0/16.0,  3.0/16.0 }, { 5.0/16.0,  1.0/16.0 }, {-3.0/16.0, -5.0/16.0 },
3599         {-5.0/16.0,  5.0/16.0 }, {-7.0/16.0, -1.0/16.0 }, { 3.0/16.0,  7.0/16.0 }, { 7.0/16.0, -7.0/16.0 },
3600     };
3601
3602     static const tSamplePos pos16[] = {
3603         { 1.0/16.0,  1.0/16.0 }, {-1.0/16.0, -3.0/16.0 }, {-3.0/16.0,  2.0/16.0 }, { 4.0/16.0, -1.0/16.0 },
3604         {-5.0/16.0, -2.0/16.0 }, { 2.0/16.0,  5.0/16.0 }, { 5.0/16.0,  3.0/16.0 }, { 3.0/16.0, -5.0/16.0 },
3605         {-2.0/16.0,  6.0/16.0 }, { 0.0/16.0, -7.0/16.0 }, {-4.0/16.0, -6.0/16.0 }, {-6.0/16.0,  4.0/16.0 },
3606         {-8.0/16.0,  0.0/16.0 }, { 7.0/16.0, -4.0/16.0 }, { 6.0/16.0,  7.0/16.0 }, {-7.0/16.0, -8.0/16.0 },
3607     };
3608
3609     const tSamplePos* sampleLoc = nullptr;
3610     int numSamples = count;
3611
3612     switch (count) {
3613     case 2:  sampleLoc = pos2;  break;
3614     case 4:  sampleLoc = pos4;  break;
3615     case 8:  sampleLoc = pos8;  break;
3616     case 16: sampleLoc = pos16; break;
3617     default:
3618         sampleLoc = pos1;
3619         numSamples = 1;
3620     }
3621
3622     TConstUnionArray* values = new TConstUnionArray(numSamples*2);
3623     
3624     for (int pos=0; pos<count; ++pos) {
3625         TConstUnion x, y;
3626         x.setDConst(sampleLoc[pos].x);
3627         y.setDConst(sampleLoc[pos].y);
3628
3629         (*values)[pos*2+0] = x;
3630         (*values)[pos*2+1] = y;
3631     }
3632
3633     TType retType(EbtFloat, EvqConst, 2);
3634
3635     if (numSamples != 1) {
3636         TArraySizes* arraySizes = new TArraySizes;
3637         arraySizes->addInnerSize(numSamples);
3638         retType.transferArraySizes(arraySizes);
3639     }
3640
3641     return new TIntermConstantUnion(*values, retType);
3642 }
3643
3644 //
3645 // Decompose DX9 and DX10 sample intrinsics & object methods into AST
3646 //
3647 void HlslParseContext::decomposeSampleMethods(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
3648 {
3649     if (node == nullptr || !node->getAsOperator())
3650         return;
3651
3652     // Sampler return must always be a vec4, but we can construct a shorter vector or a structure from it.
3653     const auto convertReturn = [&loc, &node, this](TIntermTyped* result, const TSampler& sampler) -> TIntermTyped* {
3654         result->setType(TType(node->getType().getBasicType(), EvqTemporary, node->getVectorSize()));
3655
3656         TIntermTyped* convertedResult = nullptr;
3657         
3658         TType retType;
3659         getTextureReturnType(sampler, retType);
3660
3661         if (retType.isStruct()) {
3662             // For type convenience, conversionAggregate points to the convertedResult (we know it's an aggregate here)
3663             TIntermAggregate* conversionAggregate = new TIntermAggregate;
3664             convertedResult = conversionAggregate;
3665
3666             // Convert vector output to return structure.  We will need a temp symbol to copy the results to.
3667             TVariable* structVar = makeInternalVariable("@sampleStructTemp", retType);
3668
3669             // We also need a temp symbol to hold the result of the texture.  We don't want to re-fetch the
3670             // sample each time we'll index into the result, so we'll copy to this, and index into the copy.
3671             TVariable* sampleShadow = makeInternalVariable("@sampleResultShadow", result->getType());
3672
3673             // Initial copy from texture to our sample result shadow.
3674             TIntermTyped* shadowCopy = intermediate.addAssign(EOpAssign, intermediate.addSymbol(*sampleShadow, loc),
3675                                                               result, loc);
3676
3677             conversionAggregate->getSequence().push_back(shadowCopy);
3678
3679             unsigned vec4Pos = 0;
3680
3681             for (unsigned m = 0; m < unsigned(retType.getStruct()->size()); ++m) {
3682                 const TType memberType(retType, m); // dereferenced type of the member we're about to assign.
3683                 
3684                 // Check for bad struct members.  This should have been caught upstream.  Complain, because
3685                 // wwe don't know what to do with it.  This algorithm could be generalized to handle
3686                 // other things, e.g, sub-structures, but HLSL doesn't allow them.
3687                 if (!memberType.isVector() && !memberType.isScalar()) {
3688                     error(loc, "expected: scalar or vector type in texture structure", "", "");
3689                     return nullptr;
3690                 }
3691                     
3692                 // Index into the struct variable to find the member to assign.
3693                 TIntermTyped* structMember = intermediate.addIndex(EOpIndexDirectStruct,
3694                                                                    intermediate.addSymbol(*structVar, loc),
3695                                                                    intermediate.addConstantUnion(m, loc), loc);
3696
3697                 structMember->setType(memberType);
3698
3699                 // Assign each component of (possible) vector in struct member.
3700                 for (int component = 0; component < memberType.getVectorSize(); ++component) {
3701                     TIntermTyped* vec4Member = intermediate.addIndex(EOpIndexDirect,
3702                                                                      intermediate.addSymbol(*sampleShadow, loc),
3703                                                                      intermediate.addConstantUnion(vec4Pos++, loc), loc);
3704                     vec4Member->setType(TType(memberType.getBasicType(), EvqTemporary, 1));
3705
3706                     TIntermTyped* memberAssign = nullptr;
3707
3708                     if (memberType.isVector()) {
3709                         // Vector member: we need to create an access chain to the vector component.
3710
3711                         TIntermTyped* structVecComponent = intermediate.addIndex(EOpIndexDirect, structMember,
3712                                                                                  intermediate.addConstantUnion(component, loc), loc);
3713                         
3714                         memberAssign = intermediate.addAssign(EOpAssign, structVecComponent, vec4Member, loc);
3715                     } else {
3716                         // Scalar member: we can assign to it directly.
3717                         memberAssign = intermediate.addAssign(EOpAssign, structMember, vec4Member, loc);
3718                     }
3719
3720                     
3721                     conversionAggregate->getSequence().push_back(memberAssign);
3722                 }
3723             }
3724
3725             // Add completed variable so the expression results in the whole struct value we just built.
3726             conversionAggregate->getSequence().push_back(intermediate.addSymbol(*structVar, loc));
3727
3728             // Make it a sequence.
3729             intermediate.setAggregateOperator(conversionAggregate, EOpSequence, retType, loc);
3730         } else {
3731             // vector clamp the output if template vector type is smaller than sample result.
3732             if (retType.getVectorSize() < node->getVectorSize()) {
3733                 // Too many components.  Construct shorter vector from it.
3734                 const TOperator op = intermediate.mapTypeToConstructorOp(retType);
3735
3736                 convertedResult = constructBuiltIn(retType, op, result, loc, false);
3737             } else {
3738                 // Enough components.  Use directly.
3739                 convertedResult = result;
3740             }
3741         }
3742
3743         convertedResult->setLoc(loc);
3744         return convertedResult;
3745     };
3746
3747     const TOperator op  = node->getAsOperator()->getOp();
3748     const TIntermAggregate* argAggregate = arguments ? arguments->getAsAggregate() : nullptr;
3749
3750     // Bail out if not a sampler method.
3751     // Note though this is odd to do before checking the op, because the op
3752     // could be something that takes the arguments, and the function in question
3753     // takes the result of the op.  So, this is not the final word.
3754     if (arguments != nullptr) {
3755         if (argAggregate == nullptr) {
3756             if (arguments->getAsTyped()->getBasicType() != EbtSampler)
3757                 return;
3758         } else {
3759             if (argAggregate->getSequence().size() == 0 || 
3760                                 argAggregate->getSequence()[0] == nullptr ||
3761                 argAggregate->getSequence()[0]->getAsTyped()->getBasicType() != EbtSampler)
3762                 return;
3763         }
3764     }
3765
3766     switch (op) {
3767     // **** DX9 intrinsics: ****
3768     case EOpTexture:
3769         {
3770             // Texture with ddx & ddy is really gradient form in HLSL
3771             if (argAggregate->getSequence().size() == 4)
3772                 node->getAsAggregate()->setOperator(EOpTextureGrad);
3773
3774             break;
3775         }
3776     case EOpTextureLod: //is almost EOpTextureBias (only args & operations are different)
3777         {
3778             TIntermTyped *argSamp = argAggregate->getSequence()[0]->getAsTyped();   // sampler
3779             TIntermTyped *argCoord = argAggregate->getSequence()[1]->getAsTyped();  // coord
3780
3781             assert(argCoord->getVectorSize() == 4);
3782             TIntermTyped *w = intermediate.addConstantUnion(3, loc, true);
3783             TIntermTyped *argLod = intermediate.addIndex(EOpIndexDirect, argCoord, w, loc);
3784
3785             TOperator constructOp = EOpNull;
3786             const TSampler &sampler = argSamp->getType().getSampler();
3787             int coordSize = 0;
3788
3789             switch (sampler.dim)
3790             {
3791             case Esd1D:   constructOp = EOpConstructFloat; coordSize = 1; break; // 1D
3792             case Esd2D:   constructOp = EOpConstructVec2;  coordSize = 2; break; // 2D
3793             case Esd3D:   constructOp = EOpConstructVec3;  coordSize = 3; break; // 3D
3794             case EsdCube: constructOp = EOpConstructVec3;  coordSize = 3; break; // also 3D
3795             default:
3796                 break;
3797             }
3798
3799             TIntermAggregate *constructCoord = new TIntermAggregate(constructOp);
3800             constructCoord->getSequence().push_back(argCoord);
3801             constructCoord->setLoc(loc);
3802             constructCoord->setType(TType(argCoord->getBasicType(), EvqTemporary, coordSize));
3803
3804             TIntermAggregate *tex = new TIntermAggregate(EOpTextureLod);
3805             tex->getSequence().push_back(argSamp);        // sampler
3806             tex->getSequence().push_back(constructCoord); // coordinate
3807             tex->getSequence().push_back(argLod);         // lod
3808
3809             node = convertReturn(tex, sampler);
3810
3811             break;
3812         }
3813
3814     case EOpTextureBias:
3815         {
3816             TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();  // sampler
3817             TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();  // coord
3818
3819             // HLSL puts bias in W component of coordinate.  We extract it and add it to
3820             // the argument list, instead
3821             TIntermTyped* w = intermediate.addConstantUnion(3, loc, true);
3822             TIntermTyped* bias = intermediate.addIndex(EOpIndexDirect, arg1, w, loc);
3823
3824             TOperator constructOp = EOpNull;
3825             const TSampler& sampler = arg0->getType().getSampler();
3826
3827             switch (sampler.dim) {
3828             case Esd1D:   constructOp = EOpConstructFloat; break; // 1D
3829             case Esd2D:   constructOp = EOpConstructVec2;  break; // 2D
3830             case Esd3D:   constructOp = EOpConstructVec3;  break; // 3D
3831             case EsdCube: constructOp = EOpConstructVec3;  break; // also 3D
3832             default: break;
3833             }
3834
3835             TIntermAggregate* constructCoord = new TIntermAggregate(constructOp);
3836             constructCoord->getSequence().push_back(arg1);
3837             constructCoord->setLoc(loc);
3838
3839             // The input vector should never be less than 2, since there's always a bias.
3840             // The max is for safety, and should be a no-op.
3841             constructCoord->setType(TType(arg1->getBasicType(), EvqTemporary, std::max(arg1->getVectorSize() - 1, 0)));
3842
3843             TIntermAggregate* tex = new TIntermAggregate(EOpTexture);
3844             tex->getSequence().push_back(arg0);           // sampler
3845             tex->getSequence().push_back(constructCoord); // coordinate
3846             tex->getSequence().push_back(bias);           // bias
3847
3848             node = convertReturn(tex, sampler);
3849
3850             break;
3851         }
3852
3853     // **** DX10 methods: ****
3854     case EOpMethodSample:     // fall through
3855     case EOpMethodSampleBias: // ...
3856         {
3857             TIntermTyped* argTex    = argAggregate->getSequence()[0]->getAsTyped();
3858             TIntermTyped* argSamp   = argAggregate->getSequence()[1]->getAsTyped();
3859             TIntermTyped* argCoord  = argAggregate->getSequence()[2]->getAsTyped();
3860             TIntermTyped* argBias   = nullptr;
3861             TIntermTyped* argOffset = nullptr;
3862             const TSampler& sampler = argTex->getType().getSampler();
3863
3864             int nextArg = 3;
3865
3866             if (op == EOpMethodSampleBias)  // SampleBias has a bias arg
3867                 argBias = argAggregate->getSequence()[nextArg++]->getAsTyped();
3868
3869             TOperator textureOp = EOpTexture;
3870
3871             if ((int)argAggregate->getSequence().size() == (nextArg+1)) { // last parameter is offset form
3872                 textureOp = EOpTextureOffset;
3873                 argOffset = argAggregate->getSequence()[nextArg++]->getAsTyped();
3874             }
3875
3876             TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
3877
3878             TIntermAggregate* txsample = new TIntermAggregate(textureOp);
3879             txsample->getSequence().push_back(txcombine);
3880             txsample->getSequence().push_back(argCoord);
3881
3882             if (argBias != nullptr)
3883                 txsample->getSequence().push_back(argBias);
3884
3885             if (argOffset != nullptr)
3886                 txsample->getSequence().push_back(argOffset);
3887
3888             node = convertReturn(txsample, sampler);
3889
3890             break;
3891         }
3892
3893     case EOpMethodSampleGrad: // ...
3894         {
3895             TIntermTyped* argTex    = argAggregate->getSequence()[0]->getAsTyped();
3896             TIntermTyped* argSamp   = argAggregate->getSequence()[1]->getAsTyped();
3897             TIntermTyped* argCoord  = argAggregate->getSequence()[2]->getAsTyped();
3898             TIntermTyped* argDDX    = argAggregate->getSequence()[3]->getAsTyped();
3899             TIntermTyped* argDDY    = argAggregate->getSequence()[4]->getAsTyped();
3900             TIntermTyped* argOffset = nullptr;
3901             const TSampler& sampler = argTex->getType().getSampler();
3902
3903             TOperator textureOp = EOpTextureGrad;
3904
3905             if (argAggregate->getSequence().size() == 6) { // last parameter is offset form
3906                 textureOp = EOpTextureGradOffset;
3907                 argOffset = argAggregate->getSequence()[5]->getAsTyped();
3908             }
3909
3910             TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
3911
3912             TIntermAggregate* txsample = new TIntermAggregate(textureOp);
3913             txsample->getSequence().push_back(txcombine);
3914             txsample->getSequence().push_back(argCoord);
3915             txsample->getSequence().push_back(argDDX);
3916             txsample->getSequence().push_back(argDDY);
3917
3918             if (argOffset != nullptr)
3919                 txsample->getSequence().push_back(argOffset);
3920
3921             node = convertReturn(txsample, sampler);
3922
3923             break;
3924         }
3925
3926     case EOpMethodGetDimensions:
3927         {
3928             // AST returns a vector of results, which we break apart component-wise into
3929             // separate values to assign to the HLSL method's outputs, ala:
3930             //  tx . GetDimensions(width, height);
3931             //      float2 sizeQueryTemp = EOpTextureQuerySize
3932             //      width = sizeQueryTemp.X;
3933             //      height = sizeQueryTemp.Y;
3934
3935             TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
3936             const TType& texType = argTex->getType();
3937
3938             assert(texType.getBasicType() == EbtSampler);
3939
3940             const TSampler& sampler = texType.getSampler();
3941             const TSamplerDim dim = sampler.dim;
3942             const bool isImage = sampler.isImage();
3943             const bool isMs = sampler.isMultiSample();
3944             const int numArgs = (int)argAggregate->getSequence().size();
3945
3946             int numDims = 0;
3947
3948             switch (dim) {
3949             case Esd1D:     numDims = 1; break; // W
3950             case Esd2D:     numDims = 2; break; // W, H
3951             case Esd3D:     numDims = 3; break; // W, H, D
3952             case EsdCube:   numDims = 2; break; // W, H (cube)
3953             case EsdBuffer: numDims = 1; break; // W (buffers)
3954             case EsdRect:   numDims = 2; break; // W, H (rect)
3955             default:
3956                 assert(0 && "unhandled texture dimension");
3957             }
3958
3959             // Arrayed adds another dimension for the number of array elements
3960             if (sampler.isArrayed())
3961                 ++numDims;
3962
3963             // Establish whether the method itself is querying mip levels.  This can be false even
3964             // if the underlying query requires a MIP level, due to the available HLSL method overloads.
3965             const bool mipQuery = (numArgs > (numDims + 1 + (isMs ? 1 : 0)));
3966
3967             // Establish whether we must use the LOD form of query (even if the method did not supply a mip level to query).
3968             // True if:
3969             //   1. 1D/2D/3D/Cube AND multisample==0 AND NOT image (those can be sent to the non-LOD query)
3970             // or,
3971             //   2. There is a LOD (because the non-LOD query cannot be used in that case, per spec)
3972             const bool mipRequired =
3973                 ((dim == Esd1D || dim == Esd2D || dim == Esd3D || dim == EsdCube) && !isMs && !isImage) || // 1...
3974                 mipQuery; // 2...
3975
3976             // AST assumes integer return.  Will be converted to float if required.
3977             TIntermAggregate* sizeQuery = new TIntermAggregate(isImage ? EOpImageQuerySize : EOpTextureQuerySize);
3978             sizeQuery->getSequence().push_back(argTex);
3979
3980             // If we're building an LOD query, add the LOD.
3981             if (mipRequired) {
3982                 // If the base HLSL query had no MIP level given, use level 0.
3983                 TIntermTyped* queryLod = mipQuery ? argAggregate->getSequence()[1]->getAsTyped() :
3984                     intermediate.addConstantUnion(0, loc, true);
3985                 sizeQuery->getSequence().push_back(queryLod);
3986             }
3987
3988             sizeQuery->setType(TType(EbtUint, EvqTemporary, numDims));
3989             sizeQuery->setLoc(loc);
3990
3991             // Return value from size query
3992             TVariable* tempArg = makeInternalVariable("sizeQueryTemp", sizeQuery->getType());
3993             tempArg->getWritableType().getQualifier().makeTemporary();
3994             TIntermTyped* sizeQueryAssign = intermediate.addAssign(EOpAssign,
3995                                                                    intermediate.addSymbol(*tempArg, loc),
3996                                                                    sizeQuery, loc);
3997
3998             // Compound statement for assigning outputs
3999             TIntermAggregate* compoundStatement = intermediate.makeAggregate(sizeQueryAssign, loc);
4000             // Index of first output parameter
4001             const int outParamBase = mipQuery ? 2 : 1;
4002
4003             for (int compNum = 0; compNum < numDims; ++compNum) {
4004                 TIntermTyped* indexedOut = nullptr;
4005                 TIntermSymbol* sizeQueryReturn = intermediate.addSymbol(*tempArg, loc);
4006
4007                 if (numDims > 1) {
4008                     TIntermTyped* component = intermediate.addConstantUnion(compNum, loc, true);
4009                     indexedOut = intermediate.addIndex(EOpIndexDirect, sizeQueryReturn, component, loc);
4010                     indexedOut->setType(TType(EbtUint, EvqTemporary, 1));
4011                     indexedOut->setLoc(loc);
4012                 } else {
4013                     indexedOut = sizeQueryReturn;
4014                 }
4015
4016                 TIntermTyped* outParam = argAggregate->getSequence()[outParamBase + compNum]->getAsTyped();
4017                 TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, outParam, indexedOut, loc);
4018
4019                 compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
4020             }
4021
4022             // handle mip level parameter
4023             if (mipQuery) {
4024                 TIntermTyped* outParam = argAggregate->getSequence()[outParamBase + numDims]->getAsTyped();
4025
4026                 TIntermAggregate* levelsQuery = new TIntermAggregate(EOpTextureQueryLevels);
4027                 levelsQuery->getSequence().push_back(argTex);
4028                 levelsQuery->setType(TType(EbtUint, EvqTemporary, 1));
4029                 levelsQuery->setLoc(loc);
4030
4031                 TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, outParam, levelsQuery, loc);
4032                 compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
4033             }
4034
4035             // 2DMS formats query # samples, which needs a different query op
4036             if (sampler.isMultiSample()) {
4037                 TIntermTyped* outParam = argAggregate->getSequence()[outParamBase + numDims]->getAsTyped();
4038
4039                 TIntermAggregate* samplesQuery = new TIntermAggregate(EOpImageQuerySamples);
4040                 samplesQuery->getSequence().push_back(argTex);
4041                 samplesQuery->setType(TType(EbtUint, EvqTemporary, 1));
4042                 samplesQuery->setLoc(loc);
4043
4044                 TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, outParam, samplesQuery, loc);
4045                 compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
4046             }
4047
4048             compoundStatement->setOperator(EOpSequence);
4049             compoundStatement->setLoc(loc);
4050             compoundStatement->setType(TType(EbtVoid));
4051
4052             node = compoundStatement;
4053
4054             break;
4055         }
4056
4057     case EOpMethodSampleCmp:  // fall through...
4058     case EOpMethodSampleCmpLevelZero:
4059         {
4060             TIntermTyped* argTex    = argAggregate->getSequence()[0]->getAsTyped();
4061             TIntermTyped* argSamp   = argAggregate->getSequence()[1]->getAsTyped();
4062             TIntermTyped* argCoord  = argAggregate->getSequence()[2]->getAsTyped();
4063             TIntermTyped* argCmpVal = argAggregate->getSequence()[3]->getAsTyped();
4064             TIntermTyped* argOffset = nullptr;
4065
4066             // Sampler argument should be a sampler.
4067             if (argSamp->getType().getBasicType() != EbtSampler) {
4068                 error(loc, "expected: sampler type", "", "");
4069                 return;
4070             }
4071
4072             // Sampler should be a SamplerComparisonState
4073             if (! argSamp->getType().getSampler().isShadow()) {
4074                 error(loc, "expected: SamplerComparisonState", "", "");
4075                 return;
4076             }
4077
4078             // optional offset value
4079             if (argAggregate->getSequence().size() > 4)
4080                 argOffset = argAggregate->getSequence()[4]->getAsTyped();
4081
4082             const int coordDimWithCmpVal = argCoord->getType().getVectorSize() + 1; // +1 for cmp
4083
4084             // AST wants comparison value as one of the texture coordinates
4085             TOperator constructOp = EOpNull;
4086             switch (coordDimWithCmpVal) {
4087             // 1D can't happen: there's always at least 1 coordinate dimension + 1 cmp val
4088             case 2: constructOp = EOpConstructVec2;  break;
4089             case 3: constructOp = EOpConstructVec3;  break;
4090             case 4: constructOp = EOpConstructVec4;  break;
4091             case 5: constructOp = EOpConstructVec4;  break; // cubeArrayShadow, cmp value is separate arg.
4092             default: assert(0); break;
4093             }
4094
4095             TIntermAggregate* coordWithCmp = new TIntermAggregate(constructOp);
4096             coordWithCmp->getSequence().push_back(argCoord);
4097             if (coordDimWithCmpVal != 5) // cube array shadow is special.
4098                 coordWithCmp->getSequence().push_back(argCmpVal);
4099             coordWithCmp->setLoc(loc);
4100             coordWithCmp->setType(TType(argCoord->getBasicType(), EvqTemporary, std::min(coordDimWithCmpVal, 4)));
4101
4102             TOperator textureOp = (op == EOpMethodSampleCmpLevelZero ? EOpTextureLod : EOpTexture);
4103             if (argOffset != nullptr)
4104                 textureOp = (op == EOpMethodSampleCmpLevelZero ? EOpTextureLodOffset : EOpTextureOffset);
4105
4106             // Create combined sampler & texture op
4107             TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
4108             TIntermAggregate* txsample = new TIntermAggregate(textureOp);
4109             txsample->getSequence().push_back(txcombine);
4110             txsample->getSequence().push_back(coordWithCmp);
4111
4112             if (coordDimWithCmpVal == 5) // cube array shadow is special: cmp val follows coord.
4113                 txsample->getSequence().push_back(argCmpVal);
4114
4115             // the LevelZero form uses 0 as an explicit LOD
4116             if (op == EOpMethodSampleCmpLevelZero)
4117                 txsample->getSequence().push_back(intermediate.addConstantUnion(0.0, EbtFloat, loc, true));
4118
4119             // Add offset if present
4120             if (argOffset != nullptr)
4121                 txsample->getSequence().push_back(argOffset);
4122
4123             txsample->setType(node->getType());
4124             txsample->setLoc(loc);
4125             node = txsample;
4126
4127             break;
4128         }
4129
4130     case EOpMethodLoad:
4131         {
4132             TIntermTyped* argTex    = argAggregate->getSequence()[0]->getAsTyped();
4133             TIntermTyped* argCoord  = argAggregate->getSequence()[1]->getAsTyped();
4134             TIntermTyped* argOffset = nullptr;
4135             TIntermTyped* lodComponent = nullptr;
4136             TIntermTyped* coordSwizzle = nullptr;
4137
4138             const TSampler& sampler = argTex->getType().getSampler();
4139             const bool isMS = sampler.isMultiSample();
4140             const bool isBuffer = sampler.dim == EsdBuffer;
4141             const bool isImage = sampler.isImage();
4142             const TBasicType coordBaseType = argCoord->getType().getBasicType();
4143
4144             // Last component of coordinate is the mip level, for non-MS.  we separate them here:
4145             if (isMS || isBuffer || isImage) {
4146                 // MS, Buffer, and Image have no LOD
4147                 coordSwizzle = argCoord;
4148             } else {
4149                 // Extract coordinate
4150                 int swizzleSize = argCoord->getType().getVectorSize() - (isMS ? 0 : 1);
4151                 TSwizzleSelectors<TVectorSelector> coordFields;
4152                 for (int i = 0; i < swizzleSize; ++i)
4153                     coordFields.push_back(i);
4154                 TIntermTyped* coordIdx = intermediate.addSwizzle(coordFields, loc);
4155                 coordSwizzle = intermediate.addIndex(EOpVectorSwizzle, argCoord, coordIdx, loc);
4156                 coordSwizzle->setType(TType(coordBaseType, EvqTemporary, coordFields.size()));
4157
4158                 // Extract LOD
4159                 TIntermTyped* lodIdx = intermediate.addConstantUnion(coordFields.size(), loc, true);
4160                 lodComponent = intermediate.addIndex(EOpIndexDirect, argCoord, lodIdx, loc);
4161                 lodComponent->setType(TType(coordBaseType, EvqTemporary, 1));
4162             }
4163
4164             const int numArgs    = (int)argAggregate->getSequence().size();
4165             const bool hasOffset = ((!isMS && numArgs == 3) || (isMS && numArgs == 4));
4166
4167             // Create texel fetch
4168             const TOperator fetchOp = (isImage   ? EOpImageLoad :
4169                                        hasOffset ? EOpTextureFetchOffset :
4170                                        EOpTextureFetch);
4171             TIntermAggregate* txfetch = new TIntermAggregate(fetchOp);
4172
4173             // Build up the fetch
4174             txfetch->getSequence().push_back(argTex);
4175             txfetch->getSequence().push_back(coordSwizzle);
4176
4177             if (isMS) {
4178                 // add 2DMS sample index
4179                 TIntermTyped* argSampleIdx  = argAggregate->getSequence()[2]->getAsTyped();
4180                 txfetch->getSequence().push_back(argSampleIdx);
4181             } else if (isBuffer) {
4182                 // Nothing else to do for buffers.
4183             } else if (isImage) {
4184                 // Nothing else to do for images.
4185             } else {
4186                 // 2DMS and buffer have no LOD, but everything else does.
4187                 txfetch->getSequence().push_back(lodComponent);
4188             }
4189
4190             // Obtain offset arg, if there is one.
4191             if (hasOffset) {
4192                 const int offsetPos  = (isMS ? 3 : 2);
4193                 argOffset = argAggregate->getSequence()[offsetPos]->getAsTyped();
4194                 txfetch->getSequence().push_back(argOffset);
4195             }
4196
4197             node = convertReturn(txfetch, sampler);
4198
4199             break;
4200         }
4201
4202     case EOpMethodSampleLevel:
4203         {
4204             TIntermTyped* argTex    = argAggregate->getSequence()[0]->getAsTyped();
4205             TIntermTyped* argSamp   = argAggregate->getSequence()[1]->getAsTyped();
4206             TIntermTyped* argCoord  = argAggregate->getSequence()[2]->getAsTyped();
4207             TIntermTyped* argLod    = argAggregate->getSequence()[3]->getAsTyped();
4208             TIntermTyped* argOffset = nullptr;
4209             const TSampler& sampler = argTex->getType().getSampler();
4210
4211             const int  numArgs = (int)argAggregate->getSequence().size();
4212
4213             if (numArgs == 5) // offset, if present
4214                 argOffset = argAggregate->getSequence()[4]->getAsTyped();
4215
4216             const TOperator textureOp = (argOffset == nullptr ? EOpTextureLod : EOpTextureLodOffset);
4217             TIntermAggregate* txsample = new TIntermAggregate(textureOp);
4218
4219             TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
4220
4221             txsample->getSequence().push_back(txcombine);
4222             txsample->getSequence().push_back(argCoord);
4223             txsample->getSequence().push_back(argLod);
4224
4225             if (argOffset != nullptr)
4226                 txsample->getSequence().push_back(argOffset);
4227
4228             node = convertReturn(txsample, sampler);
4229
4230             break;
4231         }
4232
4233     case EOpMethodGather:
4234         {
4235             TIntermTyped* argTex    = argAggregate->getSequence()[0]->getAsTyped();
4236             TIntermTyped* argSamp   = argAggregate->getSequence()[1]->getAsTyped();
4237             TIntermTyped* argCoord  = argAggregate->getSequence()[2]->getAsTyped();
4238             TIntermTyped* argOffset = nullptr;
4239
4240             // Offset is optional
4241             if (argAggregate->getSequence().size() > 3)
4242                 argOffset = argAggregate->getSequence()[3]->getAsTyped();
4243
4244             const TOperator textureOp = (argOffset == nullptr ? EOpTextureGather : EOpTextureGatherOffset);
4245             TIntermAggregate* txgather = new TIntermAggregate(textureOp);
4246
4247             TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
4248
4249             txgather->getSequence().push_back(txcombine);
4250             txgather->getSequence().push_back(argCoord);
4251             // Offset if not given is implicitly channel 0 (red)
4252
4253             if (argOffset != nullptr)
4254                 txgather->getSequence().push_back(argOffset);
4255
4256             txgather->setType(node->getType());
4257             txgather->setLoc(loc);
4258             node = txgather;
4259
4260             break;
4261         }
4262
4263     case EOpMethodGatherRed:      // fall through...
4264     case EOpMethodGatherGreen:    // ...
4265     case EOpMethodGatherBlue:     // ...
4266     case EOpMethodGatherAlpha:    // ...
4267     case EOpMethodGatherCmpRed:   // ...
4268     case EOpMethodGatherCmpGreen: // ...
4269     case EOpMethodGatherCmpBlue:  // ...
4270     case EOpMethodGatherCmpAlpha: // ...
4271         {
4272             int channel = 0;    // the channel we are gathering
4273             int cmpValues = 0;  // 1 if there is a compare value (handier than a bool below)
4274
4275             switch (op) {
4276             case EOpMethodGatherCmpRed:   cmpValues = 1;  // fall through
4277             case EOpMethodGatherRed:      channel = 0; break;
4278             case EOpMethodGatherCmpGreen: cmpValues = 1;  // fall through
4279             case EOpMethodGatherGreen:    channel = 1; break;
4280             case EOpMethodGatherCmpBlue:  cmpValues = 1;  // fall through
4281             case EOpMethodGatherBlue:     channel = 2; break;
4282             case EOpMethodGatherCmpAlpha: cmpValues = 1;  // fall through
4283             case EOpMethodGatherAlpha:    channel = 3; break;
4284             default:                      assert(0);   break;
4285             }
4286
4287             // For now, we have nothing to map the component-wise comparison forms
4288             // to, because neither GLSL nor SPIR-V has such an opcode.  Issue an
4289             // unimplemented error instead.  Most of the machinery is here if that
4290             // should ever become available.  However, red can be passed through
4291             // to OpImageDrefGather.  G/B/A cannot, because that opcode does not
4292             // accept a component.
4293             if (cmpValues != 0 && op != EOpMethodGatherCmpRed) {
4294                 error(loc, "unimplemented: component-level gather compare", "", "");
4295                 return;
4296             }
4297
4298             int arg = 0;
4299
4300             TIntermTyped* argTex        = argAggregate->getSequence()[arg++]->getAsTyped();
4301             TIntermTyped* argSamp       = argAggregate->getSequence()[arg++]->getAsTyped();
4302             TIntermTyped* argCoord      = argAggregate->getSequence()[arg++]->getAsTyped();
4303             TIntermTyped* argOffset     = nullptr;
4304             TIntermTyped* argOffsets[4] = { nullptr, nullptr, nullptr, nullptr };
4305             // TIntermTyped* argStatus     = nullptr; // TODO: residency
4306             TIntermTyped* argCmp        = nullptr;
4307
4308             const TSamplerDim dim = argTex->getType().getSampler().dim;
4309
4310             const int  argSize = (int)argAggregate->getSequence().size();
4311             bool hasStatus     = (argSize == (5+cmpValues) || argSize == (8+cmpValues));
4312             bool hasOffset1    = false;
4313             bool hasOffset4    = false;
4314
4315             // Sampler argument should be a sampler.
4316             if (argSamp->getType().getBasicType() != EbtSampler) {
4317                 error(loc, "expected: sampler type", "", "");
4318                 return;
4319             }
4320
4321             // Cmp forms require SamplerComparisonState
4322             if (cmpValues > 0 && ! argSamp->getType().getSampler().isShadow()) {
4323                 error(loc, "expected: SamplerComparisonState", "", "");
4324                 return;
4325             }
4326
4327             // Only 2D forms can have offsets.  Discover if we have 0, 1 or 4 offsets.
4328             if (dim == Esd2D) {
4329                 hasOffset1 = (argSize == (4+cmpValues) || argSize == (5+cmpValues));
4330                 hasOffset4 = (argSize == (7+cmpValues) || argSize == (8+cmpValues));
4331             }
4332
4333             assert(!(hasOffset1 && hasOffset4));
4334
4335             TOperator textureOp = EOpTextureGather;
4336
4337             // Compare forms have compare value
4338             if (cmpValues != 0)
4339                 argCmp = argOffset = argAggregate->getSequence()[arg++]->getAsTyped();
4340
4341             // Some forms have single offset
4342             if (hasOffset1) {
4343                 textureOp = EOpTextureGatherOffset;   // single offset form
4344                 argOffset = argAggregate->getSequence()[arg++]->getAsTyped();
4345             }
4346
4347             // Some forms have 4 gather offsets
4348             if (hasOffset4) {
4349                 textureOp = EOpTextureGatherOffsets;  // note plural, for 4 offset form
4350                 for (int offsetNum = 0; offsetNum < 4; ++offsetNum)
4351                     argOffsets[offsetNum] = argAggregate->getSequence()[arg++]->getAsTyped();
4352             }
4353
4354             // Residency status
4355             if (hasStatus) {
4356                 // argStatus = argAggregate->getSequence()[arg++]->getAsTyped();
4357                 error(loc, "unimplemented: residency status", "", "");
4358                 return;
4359             }
4360
4361             TIntermAggregate* txgather = new TIntermAggregate(textureOp);
4362             TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
4363
4364             TIntermTyped* argChannel = intermediate.addConstantUnion(channel, loc, true);
4365
4366             txgather->getSequence().push_back(txcombine);
4367             txgather->getSequence().push_back(argCoord);
4368
4369             // AST wants an array of 4 offsets, where HLSL has separate args.  Here
4370             // we construct an array from the separate args.
4371             if (hasOffset4) {
4372                 TType arrayType(EbtInt, EvqTemporary, 2);
4373                 TArraySizes* arraySizes = new TArraySizes;
4374                 arraySizes->addInnerSize(4);
4375                 arrayType.transferArraySizes(arraySizes);
4376
4377                 TIntermAggregate* initList = new TIntermAggregate(EOpNull);
4378
4379                 for (int offsetNum = 0; offsetNum < 4; ++offsetNum)
4380                     initList->getSequence().push_back(argOffsets[offsetNum]);
4381
4382                 argOffset = addConstructor(loc, initList, arrayType);
4383             }
4384
4385             // Add comparison value if we have one
4386             if (argCmp != nullptr)
4387                 txgather->getSequence().push_back(argCmp);
4388
4389             // Add offset (either 1, or an array of 4) if we have one
4390             if (argOffset != nullptr)
4391                 txgather->getSequence().push_back(argOffset);
4392
4393             // Add channel value if the sampler is not shadow
4394             if (! argSamp->getType().getSampler().isShadow())
4395                 txgather->getSequence().push_back(argChannel);
4396
4397             txgather->setType(node->getType());
4398             txgather->setLoc(loc);
4399             node = txgather;
4400
4401             break;
4402         }
4403
4404     case EOpMethodCalculateLevelOfDetail:
4405     case EOpMethodCalculateLevelOfDetailUnclamped:
4406         {
4407             TIntermTyped* argTex    = argAggregate->getSequence()[0]->getAsTyped();
4408             TIntermTyped* argSamp   = argAggregate->getSequence()[1]->getAsTyped();
4409             TIntermTyped* argCoord  = argAggregate->getSequence()[2]->getAsTyped();
4410
4411             TIntermAggregate* txquerylod = new TIntermAggregate(EOpTextureQueryLod);
4412
4413             TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
4414             txquerylod->getSequence().push_back(txcombine);
4415             txquerylod->getSequence().push_back(argCoord);
4416
4417             TIntermTyped* lodComponent = intermediate.addConstantUnion(
4418                 op == EOpMethodCalculateLevelOfDetail ? 0 : 1,
4419                 loc, true);
4420             TIntermTyped* lodComponentIdx = intermediate.addIndex(EOpIndexDirect, txquerylod, lodComponent, loc);
4421             lodComponentIdx->setType(TType(EbtFloat, EvqTemporary, 1));
4422             node = lodComponentIdx;
4423
4424             break;
4425         }
4426
4427     case EOpMethodGetSamplePosition:
4428         {
4429             // TODO: this entire decomposition exists because there is not yet a way to query
4430             // the sample position directly through SPIR-V.  Instead, we return fixed sample
4431             // positions for common cases.  *** If the sample positions are set differently,
4432             // this will be wrong. ***
4433
4434             TIntermTyped* argTex     = argAggregate->getSequence()[0]->getAsTyped();
4435             TIntermTyped* argSampIdx = argAggregate->getSequence()[1]->getAsTyped();
4436
4437             TIntermAggregate* samplesQuery = new TIntermAggregate(EOpImageQuerySamples);
4438             samplesQuery->getSequence().push_back(argTex);
4439             samplesQuery->setType(TType(EbtUint, EvqTemporary, 1));
4440             samplesQuery->setLoc(loc);
4441
4442             TIntermAggregate* compoundStatement = nullptr;
4443
4444             TVariable* outSampleCount = makeInternalVariable("@sampleCount", TType(EbtUint));
4445             outSampleCount->getWritableType().getQualifier().makeTemporary();
4446             TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, intermediate.addSymbol(*outSampleCount, loc),
4447                                                               samplesQuery, loc);
4448             compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
4449
4450             TIntermTyped* idxtest[4];
4451
4452             // Create tests against 2, 4, 8, and 16 sample values
4453             int count = 0;
4454             for (int val = 2; val <= 16; val *= 2)
4455                 idxtest[count++] =
4456                     intermediate.addBinaryNode(EOpEqual, 
4457                                                intermediate.addSymbol(*outSampleCount, loc),
4458                                                intermediate.addConstantUnion(val, loc),
4459                                                loc, TType(EbtBool));
4460
4461             const TOperator idxOp = (argSampIdx->getQualifier().storage == EvqConst) ? EOpIndexDirect : EOpIndexIndirect;
4462             
4463             // Create index ops into position arrays given sample index.
4464             // TODO: should it be clamped?
4465             TIntermTyped* index[4];
4466             count = 0;
4467             for (int val = 2; val <= 16; val *= 2) {
4468                 index[count] = intermediate.addIndex(idxOp, getSamplePosArray(val), argSampIdx, loc);
4469                 index[count++]->setType(TType(EbtFloat, EvqTemporary, 2));
4470             }
4471
4472             // Create expression as:
4473             // (sampleCount == 2)  ? pos2[idx] :
4474             // (sampleCount == 4)  ? pos4[idx] :
4475             // (sampleCount == 8)  ? pos8[idx] :
4476             // (sampleCount == 16) ? pos16[idx] : float2(0,0);
4477             TIntermTyped* test = 
4478                 intermediate.addSelection(idxtest[0], index[0], 
4479                     intermediate.addSelection(idxtest[1], index[1], 
4480                         intermediate.addSelection(idxtest[2], index[2],
4481                             intermediate.addSelection(idxtest[3], index[3], 
4482                                                       getSamplePosArray(1), loc), loc), loc), loc);
4483                                          
4484             compoundStatement = intermediate.growAggregate(compoundStatement, test);
4485             compoundStatement->setOperator(EOpSequence);
4486             compoundStatement->setLoc(loc);
4487             compoundStatement->setType(TType(EbtFloat, EvqTemporary, 2));
4488
4489             node = compoundStatement;
4490
4491             break;
4492         }
4493
4494     case EOpSubpassLoad:
4495         {
4496             const TIntermTyped* argSubpass = 
4497                 argAggregate ? argAggregate->getSequence()[0]->getAsTyped() :
4498                 arguments->getAsTyped();
4499
4500             const TSampler& sampler = argSubpass->getType().getSampler();
4501
4502             // subpass load: the multisample form is overloaded.  Here, we convert that to
4503             // the EOpSubpassLoadMS opcode.
4504             if (argAggregate != nullptr && argAggregate->getSequence().size() > 1)
4505                 node->getAsOperator()->setOp(EOpSubpassLoadMS);
4506
4507             node = convertReturn(node, sampler);
4508
4509             break;
4510         }
4511         
4512
4513     default:
4514         break; // most pass through unchanged
4515     }
4516 }
4517
4518 //
4519 // Decompose geometry shader methods
4520 //
4521 void HlslParseContext::decomposeGeometryMethods(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
4522 {
4523     if (node == nullptr || !node->getAsOperator())
4524         return;
4525
4526     const TOperator op  = node->getAsOperator()->getOp();
4527     const TIntermAggregate* argAggregate = arguments ? arguments->getAsAggregate() : nullptr;
4528
4529     switch (op) {
4530     case EOpMethodAppend:
4531         if (argAggregate) {
4532             // Don't emit these for non-GS stage, since we won't have the gsStreamOutput symbol.
4533             if (language != EShLangGeometry) {
4534                 node = nullptr;
4535                 return;
4536             }
4537
4538             TIntermAggregate* sequence = nullptr;
4539             TIntermAggregate* emit = new TIntermAggregate(EOpEmitVertex);
4540
4541             emit->setLoc(loc);
4542             emit->setType(TType(EbtVoid));
4543
4544             TIntermTyped* data = argAggregate->getSequence()[1]->getAsTyped();
4545
4546             // This will be patched in finalization during finalizeAppendMethods()
4547             sequence = intermediate.growAggregate(sequence, data, loc);
4548             sequence = intermediate.growAggregate(sequence, emit);
4549
4550             sequence->setOperator(EOpSequence);
4551             sequence->setLoc(loc);
4552             sequence->setType(TType(EbtVoid));
4553
4554             gsAppends.push_back({sequence, loc});
4555
4556             node = sequence;
4557         }
4558         break;
4559
4560     case EOpMethodRestartStrip:
4561         {
4562             // Don't emit these for non-GS stage, since we won't have the gsStreamOutput symbol.
4563             if (language != EShLangGeometry) {
4564                 node = nullptr;
4565                 return;
4566             }
4567
4568             TIntermAggregate* cut = new TIntermAggregate(EOpEndPrimitive);
4569             cut->setLoc(loc);
4570             cut->setType(TType(EbtVoid));
4571             node = cut;
4572         }
4573         break;
4574
4575     default:
4576         break; // most pass through unchanged
4577     }
4578 }
4579
4580 //
4581 // Optionally decompose intrinsics to AST opcodes.
4582 //
4583 void HlslParseContext::decomposeIntrinsic(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
4584 {
4585     // Helper to find image data for image atomics:
4586     // OpImageLoad(image[idx])
4587     // We take the image load apart and add its params to the atomic op aggregate node
4588     const auto imageAtomicParams = [this, &loc, &node](TIntermAggregate* atomic, TIntermTyped* load) {
4589         TIntermAggregate* loadOp = load->getAsAggregate();
4590         if (loadOp == nullptr) {
4591             error(loc, "unknown image type in atomic operation", "", "");
4592             node = nullptr;
4593             return;
4594         }
4595
4596         atomic->getSequence().push_back(loadOp->getSequence()[0]);
4597         atomic->getSequence().push_back(loadOp->getSequence()[1]);
4598     };
4599
4600     // Return true if this is an imageLoad, which we will change to an image atomic.
4601     const auto isImageParam = [](TIntermTyped* image) -> bool {
4602         TIntermAggregate* imageAggregate = image->getAsAggregate();
4603         return imageAggregate != nullptr && imageAggregate->getOp() == EOpImageLoad;
4604     };
4605
4606     const auto lookupBuiltinVariable = [&](const char* name, TBuiltInVariable builtin, TType& type) -> TIntermTyped* {
4607         TSymbol* symbol = symbolTable.find(name);
4608         if (nullptr == symbol) {
4609             type.getQualifier().builtIn = builtin;
4610
4611             TVariable* variable = new TVariable(new TString(name), type);
4612
4613             symbolTable.insert(*variable);
4614
4615             symbol = symbolTable.find(name);
4616             assert(symbol && "Inserted symbol could not be found!");
4617         }
4618
4619         return intermediate.addSymbol(*(symbol->getAsVariable()), loc);
4620     };
4621
4622     // HLSL intrinsics can be pass through to native AST opcodes, or decomposed here to existing AST
4623     // opcodes for compatibility with existing software stacks.
4624     static const bool decomposeHlslIntrinsics = true;
4625
4626     if (!decomposeHlslIntrinsics || !node || !node->getAsOperator())
4627         return;
4628
4629     const TIntermAggregate* argAggregate = arguments ? arguments->getAsAggregate() : nullptr;
4630     TIntermUnary* fnUnary = node->getAsUnaryNode();
4631     const TOperator op  = node->getAsOperator()->getOp();
4632
4633     switch (op) {
4634     case EOpGenMul:
4635         {
4636             // mul(a,b) -> MatrixTimesMatrix, MatrixTimesVector, MatrixTimesScalar, VectorTimesScalar, Dot, Mul
4637             // Since we are treating HLSL rows like GLSL columns (the first matrix indirection),
4638             // we must reverse the operand order here.  Hence, arg0 gets sequence[1], etc.
4639             TIntermTyped* arg0 = argAggregate->getSequence()[1]->getAsTyped();
4640             TIntermTyped* arg1 = argAggregate->getSequence()[0]->getAsTyped();
4641
4642             if (arg0->isVector() && arg1->isVector()) {  // vec * vec
4643                 node->getAsAggregate()->setOperator(EOpDot);
4644             } else {
4645                 node = handleBinaryMath(loc, "mul", EOpMul, arg0, arg1);
4646             }
4647
4648             break;
4649         }
4650
4651     case EOpRcp:
4652         {
4653             // rcp(a) -> 1 / a
4654             TIntermTyped* arg0 = fnUnary->getOperand();
4655             TBasicType   type0 = arg0->getBasicType();
4656             TIntermTyped* one  = intermediate.addConstantUnion(1, type0, loc, true);
4657             node  = handleBinaryMath(loc, "rcp", EOpDiv, one, arg0);
4658
4659             break;
4660         }
4661
4662     case EOpAny: // fall through
4663     case EOpAll:
4664         {
4665             TIntermTyped* typedArg = arguments->getAsTyped();
4666
4667             // HLSL allows float/etc types here, and the SPIR-V opcode requires a bool.
4668             // We'll convert here.  Note that for efficiency, we could add a smarter
4669             // decomposition for some type cases, e.g, maybe by decomposing a dot product.
4670             if (typedArg->getType().getBasicType() != EbtBool) {
4671                 const TType boolType(EbtBool, EvqTemporary,
4672                                      typedArg->getVectorSize(),
4673                                      typedArg->getMatrixCols(),
4674                                      typedArg->getMatrixRows(),
4675                                      typedArg->isVector());
4676
4677                 typedArg = intermediate.addConversion(EOpConstructBool, boolType, typedArg);
4678                 node->getAsUnaryNode()->setOperand(typedArg);
4679             }
4680
4681             break;
4682         }
4683
4684     case EOpSaturate:
4685         {
4686             // saturate(a) -> clamp(a,0,1)
4687             TIntermTyped* arg0 = fnUnary->getOperand();
4688             TBasicType   type0 = arg0->getBasicType();
4689             TIntermAggregate* clamp = new TIntermAggregate(EOpClamp);
4690
4691             clamp->getSequence().push_back(arg0);
4692             clamp->getSequence().push_back(intermediate.addConstantUnion(0, type0, loc, true));
4693             clamp->getSequence().push_back(intermediate.addConstantUnion(1, type0, loc, true));
4694             clamp->setLoc(loc);
4695             clamp->setType(node->getType());
4696             clamp->getWritableType().getQualifier().makeTemporary();
4697             node = clamp;
4698
4699             break;
4700         }
4701
4702     case EOpSinCos:
4703         {
4704             // sincos(a,b,c) -> b = sin(a), c = cos(a)
4705             TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
4706             TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
4707             TIntermTyped* arg2 = argAggregate->getSequence()[2]->getAsTyped();
4708
4709             TIntermTyped* sinStatement = handleUnaryMath(loc, "sin", EOpSin, arg0);
4710             TIntermTyped* cosStatement = handleUnaryMath(loc, "cos", EOpCos, arg0);
4711             TIntermTyped* sinAssign    = intermediate.addAssign(EOpAssign, arg1, sinStatement, loc);
4712             TIntermTyped* cosAssign    = intermediate.addAssign(EOpAssign, arg2, cosStatement, loc);
4713
4714             TIntermAggregate* compoundStatement = intermediate.makeAggregate(sinAssign, loc);
4715             compoundStatement = intermediate.growAggregate(compoundStatement, cosAssign);
4716             compoundStatement->setOperator(EOpSequence);
4717             compoundStatement->setLoc(loc);
4718             compoundStatement->setType(TType(EbtVoid));
4719
4720             node = compoundStatement;
4721
4722             break;
4723         }
4724
4725     case EOpClip:
4726         {
4727             // clip(a) -> if (any(a<0)) discard;
4728             TIntermTyped*  arg0 = fnUnary->getOperand();
4729             TBasicType     type0 = arg0->getBasicType();
4730             TIntermTyped*  compareNode = nullptr;
4731
4732             // For non-scalars: per experiment with FXC compiler, discard if any component < 0.
4733             if (!arg0->isScalar()) {
4734                 // component-wise compare: a < 0
4735                 TIntermAggregate* less = new TIntermAggregate(EOpLessThan);
4736                 less->getSequence().push_back(arg0);
4737                 less->setLoc(loc);
4738
4739                 // make vec or mat of bool matching dimensions of input
4740                 less->setType(TType(EbtBool, EvqTemporary,
4741                                     arg0->getType().getVectorSize(),
4742                                     arg0->getType().getMatrixCols(),
4743                                     arg0->getType().getMatrixRows(),
4744                                     arg0->getType().isVector()));
4745
4746                 // calculate # of components for comparison const
4747                 const int constComponentCount =
4748                     std::max(arg0->getType().getVectorSize(), 1) *
4749                     std::max(arg0->getType().getMatrixCols(), 1) *
4750                     std::max(arg0->getType().getMatrixRows(), 1);
4751
4752                 TConstUnion zero;
4753                 if (arg0->getType().isIntegerDomain())
4754                     zero.setDConst(0);
4755                 else
4756                     zero.setDConst(0.0);
4757                 TConstUnionArray zeros(constComponentCount, zero);
4758
4759                 less->getSequence().push_back(intermediate.addConstantUnion(zeros, arg0->getType(), loc, true));
4760
4761                 compareNode = intermediate.addBuiltInFunctionCall(loc, EOpAny, true, less, TType(EbtBool));
4762             } else {
4763                 TIntermTyped* zero;
4764                 if (arg0->getType().isIntegerDomain())
4765                     zero = intermediate.addConstantUnion(0, loc, true);
4766                 else
4767                     zero = intermediate.addConstantUnion(0.0, type0, loc, true);
4768                 compareNode = handleBinaryMath(loc, "clip", EOpLessThan, arg0, zero);
4769             }
4770
4771             TIntermBranch* killNode = intermediate.addBranch(EOpKill, loc);
4772
4773             node = new TIntermSelection(compareNode, killNode, nullptr);
4774             node->setLoc(loc);
4775
4776             break;
4777         }
4778
4779     case EOpLog10:
4780         {
4781             // log10(a) -> log2(a) * 0.301029995663981  (== 1/log2(10))
4782             TIntermTyped* arg0 = fnUnary->getOperand();
4783             TIntermTyped* log2 = handleUnaryMath(loc, "log2", EOpLog2, arg0);
4784             TIntermTyped* base = intermediate.addConstantUnion(0.301029995663981f, EbtFloat, loc, true);
4785
4786             node  = handleBinaryMath(loc, "mul", EOpMul, log2, base);
4787
4788             break;
4789         }
4790
4791     case EOpDst:
4792         {
4793             // dest.x = 1;
4794             // dest.y = src0.y * src1.y;
4795             // dest.z = src0.z;
4796             // dest.w = src1.w;
4797
4798             TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
4799             TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
4800
4801             TIntermTyped* y = intermediate.addConstantUnion(1, loc, true);
4802             TIntermTyped* z = intermediate.addConstantUnion(2, loc, true);
4803             TIntermTyped* w = intermediate.addConstantUnion(3, loc, true);
4804
4805             TIntermTyped* src0y = intermediate.addIndex(EOpIndexDirect, arg0, y, loc);
4806             TIntermTyped* src1y = intermediate.addIndex(EOpIndexDirect, arg1, y, loc);
4807             TIntermTyped* src0z = intermediate.addIndex(EOpIndexDirect, arg0, z, loc);
4808             TIntermTyped* src1w = intermediate.addIndex(EOpIndexDirect, arg1, w, loc);
4809
4810             TIntermAggregate* dst = new TIntermAggregate(EOpConstructVec4);
4811
4812             dst->getSequence().push_back(intermediate.addConstantUnion(1.0, EbtFloat, loc, true));
4813             dst->getSequence().push_back(handleBinaryMath(loc, "mul", EOpMul, src0y, src1y));
4814             dst->getSequence().push_back(src0z);
4815             dst->getSequence().push_back(src1w);
4816             dst->setType(TType(EbtFloat, EvqTemporary, 4));
4817             dst->setLoc(loc);
4818             node = dst;
4819
4820             break;
4821         }
4822
4823     case EOpInterlockedAdd: // optional last argument (if present) is assigned from return value
4824     case EOpInterlockedMin: // ...
4825     case EOpInterlockedMax: // ...
4826     case EOpInterlockedAnd: // ...
4827     case EOpInterlockedOr:  // ...
4828     case EOpInterlockedXor: // ...
4829     case EOpInterlockedExchange: // always has output arg
4830         {
4831             TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();  // dest
4832             TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();  // value
4833             TIntermTyped* arg2 = nullptr;
4834
4835             if (argAggregate->getSequence().size() > 2)
4836                 arg2 = argAggregate->getSequence()[2]->getAsTyped();
4837
4838             const bool isImage = isImageParam(arg0);
4839             const TOperator atomicOp = mapAtomicOp(loc, op, isImage);
4840             TIntermAggregate* atomic = new TIntermAggregate(atomicOp);
4841             atomic->setType(arg0->getType());
4842             atomic->getWritableType().getQualifier().makeTemporary();
4843             atomic->setLoc(loc);
4844
4845             if (isImage) {
4846                 // orig_value = imageAtomicOp(image, loc, data)
4847                 imageAtomicParams(atomic, arg0);
4848                 atomic->getSequence().push_back(arg1);
4849
4850                 if (argAggregate->getSequence().size() > 2) {
4851                     node = intermediate.addAssign(EOpAssign, arg2, atomic, loc);
4852                 } else {
4853                     node = atomic; // no assignment needed, as there was no out var.
4854                 }
4855             } else {
4856                 // Normal memory variable:
4857                 // arg0 = mem, arg1 = data, arg2(optional,out) = orig_value
4858                 if (argAggregate->getSequence().size() > 2) {
4859                     // optional output param is present.  return value goes to arg2.
4860                     atomic->getSequence().push_back(arg0);
4861                     atomic->getSequence().push_back(arg1);
4862
4863                     node = intermediate.addAssign(EOpAssign, arg2, atomic, loc);
4864                 } else {
4865                     // Set the matching operator.  Since output is absent, this is all we need to do.
4866                     node->getAsAggregate()->setOperator(atomicOp);
4867                     node->setType(atomic->getType());
4868                 }
4869             }
4870
4871             break;
4872         }
4873
4874     case EOpInterlockedCompareExchange:
4875         {
4876             TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();  // dest
4877             TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();  // cmp
4878             TIntermTyped* arg2 = argAggregate->getSequence()[2]->getAsTyped();  // value
4879             TIntermTyped* arg3 = argAggregate->getSequence()[3]->getAsTyped();  // orig
4880
4881             const bool isImage = isImageParam(arg0);
4882             TIntermAggregate* atomic = new TIntermAggregate(mapAtomicOp(loc, op, isImage));
4883             atomic->setLoc(loc);
4884             atomic->setType(arg2->getType());
4885             atomic->getWritableType().getQualifier().makeTemporary();
4886
4887             if (isImage) {
4888                 imageAtomicParams(atomic, arg0);
4889             } else {
4890                 atomic->getSequence().push_back(arg0);
4891             }
4892
4893             atomic->getSequence().push_back(arg1);
4894             atomic->getSequence().push_back(arg2);
4895             node = intermediate.addAssign(EOpAssign, arg3, atomic, loc);
4896
4897             break;
4898         }
4899
4900     case EOpEvaluateAttributeSnapped:
4901         {
4902             // SPIR-V InterpolateAtOffset uses float vec2 offset in pixels
4903             // HLSL uses int2 offset on a 16x16 grid in [-8..7] on x & y:
4904             //   iU = (iU<<28)>>28
4905             //   fU = ((float)iU)/16
4906             // Targets might handle this natively, in which case they can disable
4907             // decompositions.
4908
4909             TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();  // value
4910             TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();  // offset
4911
4912             TIntermTyped* i28 = intermediate.addConstantUnion(28, loc, true);
4913             TIntermTyped* iU = handleBinaryMath(loc, ">>", EOpRightShift,
4914                                                 handleBinaryMath(loc, "<<", EOpLeftShift, arg1, i28),
4915                                                 i28);
4916
4917             TIntermTyped* recip16 = intermediate.addConstantUnion((1.0/16.0), EbtFloat, loc, true);
4918             TIntermTyped* floatOffset = handleBinaryMath(loc, "mul", EOpMul,
4919                                                          intermediate.addConversion(EOpConstructFloat,
4920                                                                                     TType(EbtFloat, EvqTemporary, 2), iU),
4921                                                          recip16);
4922
4923             TIntermAggregate* interp = new TIntermAggregate(EOpInterpolateAtOffset);
4924             interp->getSequence().push_back(arg0);
4925             interp->getSequence().push_back(floatOffset);
4926             interp->setLoc(loc);
4927             interp->setType(arg0->getType());
4928             interp->getWritableType().getQualifier().makeTemporary();
4929
4930             node = interp;
4931
4932             break;
4933         }
4934
4935     case EOpLit:
4936         {
4937             TIntermTyped* n_dot_l = argAggregate->getSequence()[0]->getAsTyped();
4938             TIntermTyped* n_dot_h = argAggregate->getSequence()[1]->getAsTyped();
4939             TIntermTyped* m = argAggregate->getSequence()[2]->getAsTyped();
4940
4941             TIntermAggregate* dst = new TIntermAggregate(EOpConstructVec4);
4942
4943             // Ambient
4944             dst->getSequence().push_back(intermediate.addConstantUnion(1.0, EbtFloat, loc, true));
4945
4946             // Diffuse:
4947             TIntermTyped* zero = intermediate.addConstantUnion(0.0, EbtFloat, loc, true);
4948             TIntermAggregate* diffuse = new TIntermAggregate(EOpMax);
4949             diffuse->getSequence().push_back(n_dot_l);
4950             diffuse->getSequence().push_back(zero);
4951             diffuse->setLoc(loc);
4952             diffuse->setType(TType(EbtFloat));
4953             dst->getSequence().push_back(diffuse);
4954
4955             // Specular:
4956             TIntermAggregate* min_ndot = new TIntermAggregate(EOpMin);
4957             min_ndot->getSequence().push_back(n_dot_l);
4958             min_ndot->getSequence().push_back(n_dot_h);
4959             min_ndot->setLoc(loc);
4960             min_ndot->setType(TType(EbtFloat));
4961
4962             TIntermTyped* compare = handleBinaryMath(loc, "<", EOpLessThan, min_ndot, zero);
4963             TIntermTyped* n_dot_h_m = handleBinaryMath(loc, "mul", EOpMul, n_dot_h, m);  // n_dot_h * m
4964
4965             dst->getSequence().push_back(intermediate.addSelection(compare, zero, n_dot_h_m, loc));
4966
4967             // One:
4968             dst->getSequence().push_back(intermediate.addConstantUnion(1.0, EbtFloat, loc, true));
4969
4970             dst->setLoc(loc);
4971             dst->setType(TType(EbtFloat, EvqTemporary, 4));
4972             node = dst;
4973             break;
4974         }
4975
4976     case EOpAsDouble:
4977         {
4978             // asdouble accepts two 32 bit ints.  we can use EOpUint64BitsToDouble, but must
4979             // first construct a uint64.
4980             TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
4981             TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
4982
4983             if (arg0->getType().isVector()) { // TODO: ...
4984                 error(loc, "double2 conversion not implemented", "asdouble", "");
4985                 break;
4986             }
4987
4988             TIntermAggregate* uint64 = new TIntermAggregate(EOpConstructUVec2);
4989
4990             uint64->getSequence().push_back(arg0);
4991             uint64->getSequence().push_back(arg1);
4992             uint64->setType(TType(EbtUint, EvqTemporary, 2));  // convert 2 uints to a uint2
4993             uint64->setLoc(loc);
4994
4995             // bitcast uint2 to a double
4996             TIntermTyped* convert = new TIntermUnary(EOpUint64BitsToDouble);
4997             convert->getAsUnaryNode()->setOperand(uint64);
4998             convert->setLoc(loc);
4999             convert->setType(TType(EbtDouble, EvqTemporary));
5000             node = convert;
5001
5002             break;
5003         }
5004
5005     case EOpF16tof32:
5006         {
5007             // input uvecN with low 16 bits of each component holding a float16.  convert to float32.
5008             TIntermTyped* argValue = node->getAsUnaryNode()->getOperand();
5009             TIntermTyped* zero = intermediate.addConstantUnion(0, loc, true);
5010             const int vecSize = argValue->getType().getVectorSize();
5011
5012             TOperator constructOp = EOpNull;
5013             switch (vecSize) {
5014             case 1: constructOp = EOpNull;          break; // direct use, no construct needed
5015             case 2: constructOp = EOpConstructVec2; break;
5016             case 3: constructOp = EOpConstructVec3; break;
5017             case 4: constructOp = EOpConstructVec4; break;
5018             default: assert(0); break;
5019             }
5020
5021             // For scalar case, we don't need to construct another type.
5022             TIntermAggregate* result = (vecSize > 1) ? new TIntermAggregate(constructOp) : nullptr;
5023
5024             if (result) {
5025                 result->setType(TType(EbtFloat, EvqTemporary, vecSize));
5026                 result->setLoc(loc);
5027             }
5028
5029             for (int idx = 0; idx < vecSize; ++idx) {
5030                 TIntermTyped* idxConst = intermediate.addConstantUnion(idx, loc, true);
5031                 TIntermTyped* component = argValue->getType().isVector() ? 
5032                     intermediate.addIndex(EOpIndexDirect, argValue, idxConst, loc) : argValue;
5033
5034                 if (component != argValue)
5035                     component->setType(TType(argValue->getBasicType(), EvqTemporary));
5036
5037                 TIntermTyped* unpackOp  = new TIntermUnary(EOpUnpackHalf2x16);
5038                 unpackOp->setType(TType(EbtFloat, EvqTemporary, 2));
5039                 unpackOp->getAsUnaryNode()->setOperand(component);
5040                 unpackOp->setLoc(loc);
5041
5042                 TIntermTyped* lowOrder  = intermediate.addIndex(EOpIndexDirect, unpackOp, zero, loc);
5043                 
5044                 if (result != nullptr) {
5045                     result->getSequence().push_back(lowOrder);
5046                     node = result;
5047                 } else {
5048                     node = lowOrder;
5049                 }
5050             }
5051             
5052             break;
5053         }
5054
5055     case EOpF32tof16:
5056         {
5057             // input floatN converted to 16 bit float in low order bits of each component of uintN
5058             TIntermTyped* argValue = node->getAsUnaryNode()->getOperand();
5059
5060             TIntermTyped* zero = intermediate.addConstantUnion(0.0, EbtFloat, loc, true);
5061             const int vecSize = argValue->getType().getVectorSize();
5062
5063             TOperator constructOp = EOpNull;
5064             switch (vecSize) {
5065             case 1: constructOp = EOpNull;           break; // direct use, no construct needed
5066             case 2: constructOp = EOpConstructUVec2; break;
5067             case 3: constructOp = EOpConstructUVec3; break;
5068             case 4: constructOp = EOpConstructUVec4; break;
5069             default: assert(0); break;
5070             }
5071
5072             // For scalar case, we don't need to construct another type.
5073             TIntermAggregate* result = (vecSize > 1) ? new TIntermAggregate(constructOp) : nullptr;
5074
5075             if (result) {
5076                 result->setType(TType(EbtUint, EvqTemporary, vecSize));
5077                 result->setLoc(loc);
5078             }
5079
5080             for (int idx = 0; idx < vecSize; ++idx) {
5081                 TIntermTyped* idxConst = intermediate.addConstantUnion(idx, loc, true);
5082                 TIntermTyped* component = argValue->getType().isVector() ? 
5083                     intermediate.addIndex(EOpIndexDirect, argValue, idxConst, loc) : argValue;
5084
5085                 if (component != argValue)
5086                     component->setType(TType(argValue->getBasicType(), EvqTemporary));
5087
5088                 TIntermAggregate* vec2ComponentAndZero = new TIntermAggregate(EOpConstructVec2);
5089                 vec2ComponentAndZero->getSequence().push_back(component);
5090                 vec2ComponentAndZero->getSequence().push_back(zero);
5091                 vec2ComponentAndZero->setType(TType(EbtFloat, EvqTemporary, 2));
5092                 vec2ComponentAndZero->setLoc(loc);
5093                 
5094                 TIntermTyped* packOp = new TIntermUnary(EOpPackHalf2x16);
5095                 packOp->getAsUnaryNode()->setOperand(vec2ComponentAndZero);
5096                 packOp->setLoc(loc);
5097                 packOp->setType(TType(EbtUint, EvqTemporary));
5098
5099                 if (result != nullptr) {
5100                     result->getSequence().push_back(packOp);
5101                     node = result;
5102                 } else {
5103                     node = packOp;
5104                 }
5105             }
5106
5107             break;
5108         }
5109
5110     case EOpD3DCOLORtoUBYTE4:
5111         {
5112             // ivec4 ( x.zyxw * 255.001953 );
5113             TIntermTyped* arg0 = node->getAsUnaryNode()->getOperand();
5114             TSwizzleSelectors<TVectorSelector> selectors;
5115             selectors.push_back(2);
5116             selectors.push_back(1);
5117             selectors.push_back(0);
5118             selectors.push_back(3);
5119             TIntermTyped* swizzleIdx = intermediate.addSwizzle(selectors, loc);
5120             TIntermTyped* swizzled = intermediate.addIndex(EOpVectorSwizzle, arg0, swizzleIdx, loc);
5121             swizzled->setType(arg0->getType());
5122             swizzled->getWritableType().getQualifier().makeTemporary();
5123
5124             TIntermTyped* conversion = intermediate.addConstantUnion(255.001953f, EbtFloat, loc, true);
5125             TIntermTyped* rangeConverted = handleBinaryMath(loc, "mul", EOpMul, conversion, swizzled);
5126             rangeConverted->setType(arg0->getType());
5127             rangeConverted->getWritableType().getQualifier().makeTemporary();
5128
5129             node = intermediate.addConversion(EOpConstructInt, TType(EbtInt, EvqTemporary, 4), rangeConverted);
5130             node->setLoc(loc);
5131             node->setType(TType(EbtInt, EvqTemporary, 4));
5132             break;
5133         }
5134
5135     case EOpIsFinite:
5136         {
5137             // Since OPIsFinite in SPIR-V is only supported with the Kernel capability, we translate
5138             // it to !isnan && !isinf
5139
5140             TIntermTyped* arg0 = node->getAsUnaryNode()->getOperand();
5141
5142             // We'll make a temporary in case the RHS is cmoplex
5143             TVariable* tempArg = makeInternalVariable("@finitetmp", arg0->getType());
5144             tempArg->getWritableType().getQualifier().makeTemporary();
5145
5146             TIntermTyped* tmpArgAssign = intermediate.addAssign(EOpAssign,
5147                                                                 intermediate.addSymbol(*tempArg, loc),
5148                                                                 arg0, loc);
5149
5150             TIntermAggregate* compoundStatement = intermediate.makeAggregate(tmpArgAssign, loc);
5151
5152             const TType boolType(EbtBool, EvqTemporary, arg0->getVectorSize(), arg0->getMatrixCols(),
5153                                  arg0->getMatrixRows());
5154
5155             TIntermTyped* isnan = handleUnaryMath(loc, "isnan", EOpIsNan, intermediate.addSymbol(*tempArg, loc));
5156             isnan->setType(boolType);
5157
5158             TIntermTyped* notnan = handleUnaryMath(loc, "!", EOpLogicalNot, isnan);
5159             notnan->setType(boolType);
5160
5161             TIntermTyped* isinf = handleUnaryMath(loc, "isinf", EOpIsInf, intermediate.addSymbol(*tempArg, loc));
5162             isinf->setType(boolType);
5163
5164             TIntermTyped* notinf = handleUnaryMath(loc, "!", EOpLogicalNot, isinf);
5165             notinf->setType(boolType);
5166             
5167             TIntermTyped* andNode = handleBinaryMath(loc, "and", EOpLogicalAnd, notnan, notinf);
5168             andNode->setType(boolType);
5169
5170             compoundStatement = intermediate.growAggregate(compoundStatement, andNode);
5171             compoundStatement->setOperator(EOpSequence);
5172             compoundStatement->setLoc(loc);
5173             compoundStatement->setType(boolType);
5174
5175             node = compoundStatement;
5176
5177             break;
5178         }
5179     case EOpWaveGetLaneCount:
5180         {
5181             // Mapped to gl_SubgroupSize builtin (We preprend @ to the symbol
5182             // so that it inhabits the symbol table, but has a user-invalid name
5183             // in-case some source HLSL defined the symbol also).
5184             TType type(EbtUint, EvqVaryingIn);
5185             node = lookupBuiltinVariable("@gl_SubgroupSize", EbvSubgroupSize2, type);
5186             break;
5187         }
5188     case EOpWaveGetLaneIndex:
5189         {
5190             // Mapped to gl_SubgroupInvocationID builtin (We preprend @ to the
5191             // symbol so that it inhabits the symbol table, but has a
5192             // user-invalid name in-case some source HLSL defined the symbol
5193             // also).
5194             TType type(EbtUint, EvqVaryingIn);
5195             node = lookupBuiltinVariable("@gl_SubgroupInvocationID", EbvSubgroupInvocation2, type);
5196             break;
5197         }
5198     case EOpWaveActiveCountBits:
5199         {
5200             // Mapped to subgroupBallotBitCount(subgroupBallot()) builtin
5201
5202             // uvec4 type.
5203             TType uvec4Type(EbtUint, EvqTemporary, 4);
5204
5205             // Get the uvec4 return from subgroupBallot().
5206             TIntermTyped* res = intermediate.addBuiltInFunctionCall(loc,
5207                 EOpSubgroupBallot, true, arguments, uvec4Type);
5208
5209             // uint type.
5210             TType uintType(EbtUint, EvqTemporary);
5211
5212             node = intermediate.addBuiltInFunctionCall(loc,
5213                 EOpSubgroupBallotBitCount, true, res, uintType);
5214
5215             break;
5216         }
5217     case EOpWavePrefixCountBits:
5218         {
5219             // Mapped to subgroupBallotInclusiveBitCount(subgroupBallot())
5220             // builtin
5221
5222             // uvec4 type.
5223             TType uvec4Type(EbtUint, EvqTemporary, 4);
5224
5225             // Get the uvec4 return from subgroupBallot().
5226             TIntermTyped* res = intermediate.addBuiltInFunctionCall(loc,
5227                 EOpSubgroupBallot, true, arguments, uvec4Type);
5228
5229             // uint type.
5230             TType uintType(EbtUint, EvqTemporary);
5231
5232             node = intermediate.addBuiltInFunctionCall(loc,
5233                 EOpSubgroupBallotInclusiveBitCount, true, res, uintType);
5234
5235             break;
5236         }
5237
5238     default:
5239         break; // most pass through unchanged
5240     }
5241 }
5242
5243 //
5244 // Handle seeing function call syntax in the grammar, which could be any of
5245 //  - .length() method
5246 //  - constructor
5247 //  - a call to a built-in function mapped to an operator
5248 //  - a call to a built-in function that will remain a function call (e.g., texturing)
5249 //  - user function
5250 //  - subroutine call (not implemented yet)
5251 //
5252 TIntermTyped* HlslParseContext::handleFunctionCall(const TSourceLoc& loc, TFunction* function, TIntermTyped* arguments)
5253 {
5254     TIntermTyped* result = nullptr;
5255
5256     TOperator op = function->getBuiltInOp();
5257     if (op != EOpNull) {
5258         //
5259         // Then this should be a constructor.
5260         // Don't go through the symbol table for constructors.
5261         // Their parameters will be verified algorithmically.
5262         //
5263         TType type(EbtVoid);  // use this to get the type back
5264         if (! constructorError(loc, arguments, *function, op, type)) {
5265             //
5266             // It's a constructor, of type 'type'.
5267             //
5268             result = handleConstructor(loc, arguments, type);
5269             if (result == nullptr) {
5270                 error(loc, "cannot construct with these arguments", type.getCompleteString().c_str(), "");
5271                 return nullptr;
5272             }
5273         }
5274     } else {
5275         //
5276         // Find it in the symbol table.
5277         //
5278         const TFunction* fnCandidate = nullptr;
5279         bool builtIn = false;
5280         int thisDepth = 0;
5281
5282         // For mat mul, the situation is unusual: we have to compare vector sizes to mat row or col sizes,
5283         // and clamp the opposite arg.  Since that's complex, we farm it off to a separate method.
5284         // It doesn't naturally fall out of processing an argument at a time in isolation.
5285         if (function->getName() == "mul")
5286             addGenMulArgumentConversion(loc, *function, arguments);
5287
5288         TIntermAggregate* aggregate = arguments ? arguments->getAsAggregate() : nullptr;
5289
5290         // TODO: this needs improvement: there's no way at present to look up a signature in
5291         // the symbol table for an arbitrary type.  This is a temporary hack until that ability exists.
5292         // It will have false positives, since it doesn't check arg counts or types.
5293         if (arguments) {
5294             // Check if first argument is struct buffer type.  It may be an aggregate or a symbol, so we
5295             // look for either case.
5296
5297             TIntermTyped* arg0 = nullptr;
5298
5299             if (aggregate && aggregate->getSequence().size() > 0 && aggregate->getSequence()[0])
5300                 arg0 = aggregate->getSequence()[0]->getAsTyped();
5301             else if (arguments->getAsSymbolNode())
5302                 arg0 = arguments->getAsSymbolNode();
5303
5304             if (arg0 != nullptr && isStructBufferType(arg0->getType())) {
5305                 static const int methodPrefixSize = sizeof(BUILTIN_PREFIX)-1;
5306
5307                 if (function->getName().length() > methodPrefixSize &&
5308                     isStructBufferMethod(function->getName().substr(methodPrefixSize))) {
5309                     const TString mangle = function->getName() + "(";
5310                     TSymbol* symbol = symbolTable.find(mangle, &builtIn);
5311
5312                     if (symbol)
5313                         fnCandidate = symbol->getAsFunction();
5314                 }
5315             }
5316         }
5317
5318         if (fnCandidate == nullptr)
5319             fnCandidate = findFunction(loc, *function, builtIn, thisDepth, arguments);
5320
5321         if (fnCandidate) {
5322             // This is a declared function that might map to
5323             //  - a built-in operator,
5324             //  - a built-in function not mapped to an operator, or
5325             //  - a user function.
5326
5327             // Error check for a function requiring specific extensions present.
5328             if (builtIn && fnCandidate->getNumExtensions())
5329                 requireExtensions(loc, fnCandidate->getNumExtensions(), fnCandidate->getExtensions(),
5330                                   fnCandidate->getName().c_str());
5331
5332             // turn an implicit member-function resolution into an explicit call
5333             TString callerName;
5334             if (thisDepth == 0)
5335                 callerName = fnCandidate->getMangledName();
5336             else {
5337                 // get the explicit (full) name of the function
5338                 callerName = currentTypePrefix[currentTypePrefix.size() - thisDepth];
5339                 callerName += fnCandidate->getMangledName();
5340                 // insert the implicit calling argument
5341                 pushFrontArguments(intermediate.addSymbol(*getImplicitThis(thisDepth)), arguments);
5342             }
5343
5344             // Convert 'in' arguments, so that types match.
5345             // However, skip those that need expansion, that is covered next.
5346             if (arguments)
5347                 addInputArgumentConversions(*fnCandidate, arguments);
5348
5349             // Expand arguments.  Some arguments must physically expand to a different set
5350             // than what the shader declared and passes.
5351             if (arguments && !builtIn)
5352                 expandArguments(loc, *fnCandidate, arguments);
5353
5354             // Expansion may have changed the form of arguments
5355             aggregate = arguments ? arguments->getAsAggregate() : nullptr;
5356
5357             op = fnCandidate->getBuiltInOp();
5358             if (builtIn && op != EOpNull) {
5359                 // A function call mapped to a built-in operation.
5360                 result = intermediate.addBuiltInFunctionCall(loc, op, fnCandidate->getParamCount() == 1, arguments,
5361                                                              fnCandidate->getType());
5362                 if (result == nullptr)  {
5363                     error(arguments->getLoc(), " wrong operand type", "Internal Error",
5364                         "built in unary operator function.  Type: %s",
5365                         static_cast<TIntermTyped*>(arguments)->getCompleteString().c_str());
5366                 } else if (result->getAsOperator()) {
5367                     builtInOpCheck(loc, *fnCandidate, *result->getAsOperator());
5368                 }
5369             } else {
5370                 // This is a function call not mapped to built-in operator.
5371                 // It could still be a built-in function, but only if PureOperatorBuiltins == false.
5372                 result = intermediate.setAggregateOperator(arguments, EOpFunctionCall, fnCandidate->getType(), loc);
5373                 TIntermAggregate* call = result->getAsAggregate();
5374                 call->setName(callerName);
5375
5376                 // this is how we know whether the given function is a built-in function or a user-defined function
5377                 // if builtIn == false, it's a userDefined -> could be an overloaded built-in function also
5378                 // if builtIn == true, it's definitely a built-in function with EOpNull
5379                 if (! builtIn) {
5380                     call->setUserDefined();
5381                     intermediate.addToCallGraph(infoSink, currentCaller, callerName);
5382                 }
5383             }
5384
5385             // for decompositions, since we want to operate on the function node, not the aggregate holding
5386             // output conversions.
5387             const TIntermTyped* fnNode = result;
5388
5389             decomposeStructBufferMethods(loc, result, arguments); // HLSL->AST struct buffer method decompositions
5390             decomposeIntrinsic(loc, result, arguments);           // HLSL->AST intrinsic decompositions
5391             decomposeSampleMethods(loc, result, arguments);       // HLSL->AST sample method decompositions
5392             decomposeGeometryMethods(loc, result, arguments);     // HLSL->AST geometry method decompositions
5393
5394             // Create the qualifier list, carried in the AST for the call.
5395             // Because some arguments expand to multiple arguments, the qualifier list will
5396             // be longer than the formal parameter list.
5397             if (result == fnNode && result->getAsAggregate()) {
5398                 TQualifierList& qualifierList = result->getAsAggregate()->getQualifierList();
5399                 for (int i = 0; i < fnCandidate->getParamCount(); ++i) {
5400                     TStorageQualifier qual = (*fnCandidate)[i].type->getQualifier().storage;
5401                     if (hasStructBuffCounter(*(*fnCandidate)[i].type)) {
5402                         // add buffer and counter buffer argument qualifier
5403                         qualifierList.push_back(qual);
5404                         qualifierList.push_back(qual);
5405                     } else if (shouldFlatten(*(*fnCandidate)[i].type, (*fnCandidate)[i].type->getQualifier().storage,
5406                                              true)) {
5407                         // add structure member expansion
5408                         for (int memb = 0; memb < (int)(*fnCandidate)[i].type->getStruct()->size(); ++memb)
5409                             qualifierList.push_back(qual);
5410                     } else {
5411                         // Normal 1:1 case
5412                         qualifierList.push_back(qual);
5413                     }
5414                 }
5415             }
5416
5417             // Convert 'out' arguments.  If it was a constant folded built-in, it won't be an aggregate anymore.
5418             // Built-ins with a single argument aren't called with an aggregate, but they also don't have an output.
5419             // Also, build the qualifier list for user function calls, which are always called with an aggregate.
5420             // We don't do this is if there has been a decomposition, which will have added its own conversions
5421             // for output parameters.
5422             if (result == fnNode && result->getAsAggregate())
5423                 result = addOutputArgumentConversions(*fnCandidate, *result->getAsOperator());
5424         }
5425     }
5426
5427     // generic error recovery
5428     // TODO: simplification: localize all the error recoveries that look like this, and taking type into account to
5429     //       reduce cascades
5430     if (result == nullptr)
5431         result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
5432
5433     return result;
5434 }
5435
5436 // An initial argument list is difficult: it can be null, or a single node,
5437 // or an aggregate if more than one argument.  Add one to the front, maintaining
5438 // this lack of uniformity.
5439 void HlslParseContext::pushFrontArguments(TIntermTyped* front, TIntermTyped*& arguments)
5440 {
5441     if (arguments == nullptr)
5442         arguments = front;
5443     else if (arguments->getAsAggregate() != nullptr)
5444         arguments->getAsAggregate()->getSequence().insert(arguments->getAsAggregate()->getSequence().begin(), front);
5445     else
5446         arguments = intermediate.growAggregate(front, arguments);
5447 }
5448
5449 //
5450 // HLSL allows mismatched dimensions on vec*mat, mat*vec, vec*vec, and mat*mat.  This is a
5451 // situation not well suited to resolution in intrinsic selection, but we can do so here, since we
5452 // can look at both arguments insert explicit shape changes if required.
5453 //
5454 void HlslParseContext::addGenMulArgumentConversion(const TSourceLoc& loc, TFunction& call, TIntermTyped*& args)
5455 {
5456     TIntermAggregate* argAggregate = args ? args->getAsAggregate() : nullptr;
5457
5458     if (argAggregate == nullptr || argAggregate->getSequence().size() != 2) {
5459         // It really ought to have two arguments.
5460         error(loc, "expected: mul arguments", "", "");
5461         return;
5462     }
5463
5464     TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
5465     TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
5466
5467     if (arg0->isVector() && arg1->isVector()) {
5468         // For:
5469         //    vec * vec: it's handled during intrinsic selection, so while we could do it here,
5470         //               we can also ignore it, which is easier.
5471     } else if (arg0->isVector() && arg1->isMatrix()) {
5472         // vec * mat: we clamp the vec if the mat col is smaller, else clamp the mat col.
5473         if (arg0->getVectorSize() < arg1->getMatrixCols()) {
5474             // vec is smaller, so truncate larger mat dimension
5475             const TType truncType(arg1->getBasicType(), arg1->getQualifier().storage, arg1->getQualifier().precision,
5476                                   0, arg0->getVectorSize(), arg1->getMatrixRows());
5477             arg1 = addConstructor(loc, arg1, truncType);
5478         } else if (arg0->getVectorSize() > arg1->getMatrixCols()) {
5479             // vec is larger, so truncate vec to mat size
5480             const TType truncType(arg0->getBasicType(), arg0->getQualifier().storage, arg0->getQualifier().precision,
5481                                   arg1->getMatrixCols());
5482             arg0 = addConstructor(loc, arg0, truncType);
5483         }
5484     } else if (arg0->isMatrix() && arg1->isVector()) {
5485         // mat * vec: we clamp the vec if the mat col is smaller, else clamp the mat col.
5486         if (arg1->getVectorSize() < arg0->getMatrixRows()) {
5487             // vec is smaller, so truncate larger mat dimension
5488             const TType truncType(arg0->getBasicType(), arg0->getQualifier().storage, arg0->getQualifier().precision,
5489                                   0, arg0->getMatrixCols(), arg1->getVectorSize());
5490             arg0 = addConstructor(loc, arg0, truncType);
5491         } else if (arg1->getVectorSize() > arg0->getMatrixRows()) {
5492             // vec is larger, so truncate vec to mat size
5493             const TType truncType(arg1->getBasicType(), arg1->getQualifier().storage, arg1->getQualifier().precision,
5494                                   arg0->getMatrixRows());
5495             arg1 = addConstructor(loc, arg1, truncType);
5496         }
5497     } else if (arg0->isMatrix() && arg1->isMatrix()) {
5498         // mat * mat: we clamp the smaller inner dimension to match the other matrix size.
5499         // Remember, HLSL Mrc = GLSL/SPIRV Mcr.
5500         if (arg0->getMatrixRows() > arg1->getMatrixCols()) {
5501             const TType truncType(arg0->getBasicType(), arg0->getQualifier().storage, arg0->getQualifier().precision,
5502                                   0, arg0->getMatrixCols(), arg1->getMatrixCols());
5503             arg0 = addConstructor(loc, arg0, truncType);
5504         } else if (arg0->getMatrixRows() < arg1->getMatrixCols()) {
5505             const TType truncType(arg1->getBasicType(), arg1->getQualifier().storage, arg1->getQualifier().precision,
5506                                   0, arg0->getMatrixRows(), arg1->getMatrixRows());
5507             arg1 = addConstructor(loc, arg1, truncType);
5508         }
5509     } else {
5510         // It's something with scalars: we'll just leave it alone.  Function selection will handle it
5511         // downstream.
5512     }
5513
5514     // Warn if we altered one of the arguments
5515     if (arg0 != argAggregate->getSequence()[0] || arg1 != argAggregate->getSequence()[1])
5516         warn(loc, "mul() matrix size mismatch", "", "");
5517
5518     // Put arguments back.  (They might be unchanged, in which case this is harmless).
5519     argAggregate->getSequence()[0] = arg0;
5520     argAggregate->getSequence()[1] = arg1;
5521
5522     call[0].type = &arg0->getWritableType();
5523     call[1].type = &arg1->getWritableType();
5524 }
5525
5526 //
5527 // Add any needed implicit conversions for function-call arguments to input parameters.
5528 //
5529 void HlslParseContext::addInputArgumentConversions(const TFunction& function, TIntermTyped*& arguments)
5530 {
5531     TIntermAggregate* aggregate = arguments->getAsAggregate();
5532
5533     // Replace a single argument with a single argument.
5534     const auto setArg = [&](int paramNum, TIntermTyped* arg) {
5535         if (function.getParamCount() == 1)
5536             arguments = arg;
5537         else {
5538             if (aggregate == nullptr)
5539                 arguments = arg;
5540             else
5541                 aggregate->getSequence()[paramNum] = arg;
5542         }
5543     };
5544
5545     // Process each argument's conversion
5546     for (int param = 0; param < function.getParamCount(); ++param) {
5547         if (! function[param].type->getQualifier().isParamInput())
5548             continue;
5549
5550         // At this early point there is a slight ambiguity between whether an aggregate 'arguments'
5551         // is the single argument itself or its children are the arguments.  Only one argument
5552         // means take 'arguments' itself as the one argument.
5553         TIntermTyped* arg = function.getParamCount() == 1
5554                                    ? arguments->getAsTyped()
5555                                    : (aggregate ? 
5556                                         aggregate->getSequence()[param]->getAsTyped() :
5557                                         arguments->getAsTyped());
5558         if (*function[param].type != arg->getType()) {
5559             // In-qualified arguments just need an extra node added above the argument to
5560             // convert to the correct type.
5561             TIntermTyped* convArg = intermediate.addConversion(EOpFunctionCall, *function[param].type, arg);
5562             if (convArg != nullptr)
5563                 convArg = intermediate.addUniShapeConversion(EOpFunctionCall, *function[param].type, convArg);
5564             if (convArg != nullptr)
5565                 setArg(param, convArg);
5566             else
5567                 error(arg->getLoc(), "cannot convert input argument, argument", "", "%d", param);
5568         } else {
5569             if (wasFlattened(arg)) {
5570                 // If both formal and calling arg are to be flattened, leave that to argument
5571                 // expansion, not conversion.
5572                 if (!shouldFlatten(*function[param].type, function[param].type->getQualifier().storage, true)) {
5573                     // Will make a two-level subtree.
5574                     // The deepest will copy member-by-member to build the structure to pass.
5575                     // The level above that will be a two-operand EOpComma sequence that follows the copy by the
5576                     // object itself.
5577                     TVariable* internalAggregate = makeInternalVariable("aggShadow", *function[param].type);
5578                     internalAggregate->getWritableType().getQualifier().makeTemporary();
5579                     TIntermSymbol* internalSymbolNode = new TIntermSymbol(internalAggregate->getUniqueId(),
5580                                                                           internalAggregate->getName(),
5581                                                                           internalAggregate->getType());
5582                     internalSymbolNode->setLoc(arg->getLoc());
5583                     // This makes the deepest level, the member-wise copy
5584                     TIntermAggregate* assignAgg = handleAssign(arg->getLoc(), EOpAssign,
5585                                                                internalSymbolNode, arg)->getAsAggregate();
5586
5587                     // Now, pair that with the resulting aggregate.
5588                     assignAgg = intermediate.growAggregate(assignAgg, internalSymbolNode, arg->getLoc());
5589                     assignAgg->setOperator(EOpComma);
5590                     assignAgg->setType(internalAggregate->getType());
5591                     setArg(param, assignAgg);
5592                 }
5593             }
5594         }
5595     }
5596 }
5597
5598 //
5599 // Add any needed implicit expansion of calling arguments from what the shader listed to what's
5600 // internally needed for the AST (given the constraints downstream).
5601 //
5602 void HlslParseContext::expandArguments(const TSourceLoc& loc, const TFunction& function, TIntermTyped*& arguments)
5603 {
5604     TIntermAggregate* aggregate = arguments->getAsAggregate();
5605     int functionParamNumberOffset = 0;
5606
5607     // Replace a single argument with a single argument.
5608     const auto setArg = [&](int paramNum, TIntermTyped* arg) {
5609         if (function.getParamCount() + functionParamNumberOffset == 1)
5610             arguments = arg;
5611         else {
5612             if (aggregate == nullptr)
5613                 arguments = arg;
5614             else
5615                 aggregate->getSequence()[paramNum] = arg;
5616         }
5617     };
5618
5619     // Replace a single argument with a list of arguments
5620     const auto setArgList = [&](int paramNum, const TVector<TIntermTyped*>& args) {
5621         if (args.size() == 1)
5622             setArg(paramNum, args.front());
5623         else if (args.size() > 1) {
5624             if (function.getParamCount() + functionParamNumberOffset == 1) {
5625                 arguments = intermediate.makeAggregate(args.front());
5626                 std::for_each(args.begin() + 1, args.end(), 
5627                     [&](TIntermTyped* arg) {
5628                         arguments = intermediate.growAggregate(arguments, arg);
5629                     });
5630             } else {
5631                 auto it = aggregate->getSequence().erase(aggregate->getSequence().begin() + paramNum);
5632                 aggregate->getSequence().insert(it, args.begin(), args.end());
5633             }
5634             functionParamNumberOffset += (int)(args.size() - 1);
5635         }
5636     };
5637
5638     // Process each argument's conversion
5639     for (int param = 0; param < function.getParamCount(); ++param) {
5640         // At this early point there is a slight ambiguity between whether an aggregate 'arguments'
5641         // is the single argument itself or its children are the arguments.  Only one argument
5642         // means take 'arguments' itself as the one argument.
5643         TIntermTyped* arg = function.getParamCount() == 1
5644                                    ? arguments->getAsTyped()
5645                                    : (aggregate ? 
5646                                         aggregate->getSequence()[param + functionParamNumberOffset]->getAsTyped() :
5647                                         arguments->getAsTyped());
5648
5649         if (wasFlattened(arg) && shouldFlatten(*function[param].type, function[param].type->getQualifier().storage, true)) {
5650             // Need to pass the structure members instead of the structure.
5651             TVector<TIntermTyped*> memberArgs;
5652             for (int memb = 0; memb < (int)arg->getType().getStruct()->size(); ++memb)
5653                 memberArgs.push_back(flattenAccess(arg, memb));
5654             setArgList(param + functionParamNumberOffset, memberArgs);
5655         }
5656     }
5657
5658     // TODO: if we need both hidden counter args (below) and struct expansion (above)
5659     // the two algorithms need to be merged: Each assumes the list starts out 1:1 between
5660     // parameters and arguments.
5661
5662     // If any argument is a pass-by-reference struct buffer with an associated counter
5663     // buffer, we have to add another hidden parameter for that counter.
5664     if (aggregate)
5665         addStructBuffArguments(loc, aggregate);
5666 }
5667
5668 //
5669 // Add any needed implicit output conversions for function-call arguments.  This
5670 // can require a new tree topology, complicated further by whether the function
5671 // has a return value.
5672 //
5673 // Returns a node of a subtree that evaluates to the return value of the function.
5674 //
5675 TIntermTyped* HlslParseContext::addOutputArgumentConversions(const TFunction& function, TIntermOperator& intermNode)
5676 {
5677     assert (intermNode.getAsAggregate() != nullptr || intermNode.getAsUnaryNode() != nullptr);
5678
5679     const TSourceLoc& loc = intermNode.getLoc();
5680
5681     TIntermSequence argSequence; // temp sequence for unary node args
5682
5683     if (intermNode.getAsUnaryNode())
5684         argSequence.push_back(intermNode.getAsUnaryNode()->getOperand());
5685
5686     TIntermSequence& arguments = argSequence.empty() ? intermNode.getAsAggregate()->getSequence() : argSequence;
5687
5688     const auto needsConversion = [&](int argNum) {
5689         return function[argNum].type->getQualifier().isParamOutput() &&
5690                (*function[argNum].type != arguments[argNum]->getAsTyped()->getType() ||
5691                 shouldConvertLValue(arguments[argNum]) ||
5692                 wasFlattened(arguments[argNum]->getAsTyped()));
5693     };
5694
5695     // Will there be any output conversions?
5696     bool outputConversions = false;
5697     for (int i = 0; i < function.getParamCount(); ++i) {
5698         if (needsConversion(i)) {
5699             outputConversions = true;
5700             break;
5701         }
5702     }
5703
5704     if (! outputConversions)
5705         return &intermNode;
5706
5707     // Setup for the new tree, if needed:
5708     //
5709     // Output conversions need a different tree topology.
5710     // Out-qualified arguments need a temporary of the correct type, with the call
5711     // followed by an assignment of the temporary to the original argument:
5712     //     void: function(arg, ...)  ->        (          function(tempArg, ...), arg = tempArg, ...)
5713     //     ret = function(arg, ...)  ->  ret = (tempRet = function(tempArg, ...), arg = tempArg, ..., tempRet)
5714     // Where the "tempArg" type needs no conversion as an argument, but will convert on assignment.
5715     TIntermTyped* conversionTree = nullptr;
5716     TVariable* tempRet = nullptr;
5717     if (intermNode.getBasicType() != EbtVoid) {
5718         // do the "tempRet = function(...), " bit from above
5719         tempRet = makeInternalVariable("tempReturn", intermNode.getType());
5720         TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, loc);
5721         conversionTree = intermediate.addAssign(EOpAssign, tempRetNode, &intermNode, loc);
5722     } else
5723         conversionTree = &intermNode;
5724
5725     conversionTree = intermediate.makeAggregate(conversionTree);
5726
5727     // Process each argument's conversion
5728     for (int i = 0; i < function.getParamCount(); ++i) {
5729         if (needsConversion(i)) {
5730             // Out-qualified arguments needing conversion need to use the topology setup above.
5731             // Do the " ...(tempArg, ...), arg = tempArg" bit from above.
5732
5733             // Make a temporary for what the function expects the argument to look like.
5734             TVariable* tempArg = makeInternalVariable("tempArg", *function[i].type);
5735             tempArg->getWritableType().getQualifier().makeTemporary();
5736             TIntermSymbol* tempArgNode = intermediate.addSymbol(*tempArg, loc);
5737
5738             // This makes the deepest level, the member-wise copy
5739             TIntermTyped* tempAssign = handleAssign(arguments[i]->getLoc(), EOpAssign, arguments[i]->getAsTyped(),
5740                                                     tempArgNode);
5741             tempAssign = handleLvalue(arguments[i]->getLoc(), "assign", tempAssign);
5742             conversionTree = intermediate.growAggregate(conversionTree, tempAssign, arguments[i]->getLoc());
5743
5744             // replace the argument with another node for the same tempArg variable
5745             arguments[i] = intermediate.addSymbol(*tempArg, loc);
5746         }
5747     }
5748
5749     // Finalize the tree topology (see bigger comment above).
5750     if (tempRet) {
5751         // do the "..., tempRet" bit from above
5752         TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, loc);
5753         conversionTree = intermediate.growAggregate(conversionTree, tempRetNode, loc);
5754     }
5755
5756     conversionTree = intermediate.setAggregateOperator(conversionTree, EOpComma, intermNode.getType(), loc);
5757
5758     return conversionTree;
5759 }
5760
5761 //
5762 // Add any needed "hidden" counter buffer arguments for function calls.
5763 //
5764 // Modifies the 'aggregate' argument if needed.  Otherwise, is no-op.
5765 //
5766 void HlslParseContext::addStructBuffArguments(const TSourceLoc& loc, TIntermAggregate*& aggregate)
5767 {
5768     // See if there are any SB types with counters.
5769     const bool hasStructBuffArg =
5770         std::any_of(aggregate->getSequence().begin(),
5771                     aggregate->getSequence().end(),
5772                     [this](const TIntermNode* node) {
5773                         return (node && node->getAsTyped() != nullptr) && hasStructBuffCounter(node->getAsTyped()->getType());
5774                     });
5775
5776     // Nothing to do, if we didn't find one.
5777     if (! hasStructBuffArg)
5778         return;
5779
5780     TIntermSequence argsWithCounterBuffers;
5781
5782     for (int param = 0; param < int(aggregate->getSequence().size()); ++param) {
5783         argsWithCounterBuffers.push_back(aggregate->getSequence()[param]);
5784
5785         if (hasStructBuffCounter(aggregate->getSequence()[param]->getAsTyped()->getType())) {
5786             const TIntermSymbol* blockSym = aggregate->getSequence()[param]->getAsSymbolNode();
5787             if (blockSym != nullptr) {
5788                 TType counterType;
5789                 counterBufferType(loc, counterType);
5790
5791                 const TString counterBlockName(intermediate.addCounterBufferName(blockSym->getName()));
5792
5793                 TVariable* variable = makeInternalVariable(counterBlockName, counterType);
5794
5795                 // Mark this buffer's counter block as being in use
5796                 structBufferCounter[counterBlockName] = true;
5797
5798                 TIntermSymbol* sym = intermediate.addSymbol(*variable, loc);
5799                 argsWithCounterBuffers.push_back(sym);
5800             }
5801         }
5802     }
5803
5804     // Swap with the temp list we've built up.
5805     aggregate->getSequence().swap(argsWithCounterBuffers);
5806 }
5807
5808
5809 //
5810 // Do additional checking of built-in function calls that is not caught
5811 // by normal semantic checks on argument type, extension tagging, etc.
5812 //
5813 // Assumes there has been a semantically correct match to a built-in function prototype.
5814 //
5815 void HlslParseContext::builtInOpCheck(const TSourceLoc& loc, const TFunction& fnCandidate, TIntermOperator& callNode)
5816 {
5817     // Set up convenience accessors to the argument(s).  There is almost always
5818     // multiple arguments for the cases below, but when there might be one,
5819     // check the unaryArg first.
5820     const TIntermSequence* argp = nullptr;   // confusing to use [] syntax on a pointer, so this is to help get a reference
5821     const TIntermTyped* unaryArg = nullptr;
5822     const TIntermTyped* arg0 = nullptr;
5823     if (callNode.getAsAggregate()) {
5824         argp = &callNode.getAsAggregate()->getSequence();
5825         if (argp->size() > 0)
5826             arg0 = (*argp)[0]->getAsTyped();
5827     } else {
5828         assert(callNode.getAsUnaryNode());
5829         unaryArg = callNode.getAsUnaryNode()->getOperand();
5830         arg0 = unaryArg;
5831     }
5832     const TIntermSequence& aggArgs = *argp;  // only valid when unaryArg is nullptr
5833
5834     switch (callNode.getOp()) {
5835     case EOpTextureGather:
5836     case EOpTextureGatherOffset:
5837     case EOpTextureGatherOffsets:
5838     {
5839         // Figure out which variants are allowed by what extensions,
5840         // and what arguments must be constant for which situations.
5841
5842         TString featureString = fnCandidate.getName() + "(...)";
5843         const char* feature = featureString.c_str();
5844         int compArg = -1;  // track which argument, if any, is the constant component argument
5845         switch (callNode.getOp()) {
5846         case EOpTextureGather:
5847             // More than two arguments needs gpu_shader5, and rectangular or shadow needs gpu_shader5,
5848             // otherwise, need GL_ARB_texture_gather.
5849             if (fnCandidate.getParamCount() > 2 || fnCandidate[0].type->getSampler().dim == EsdRect ||
5850                 fnCandidate[0].type->getSampler().shadow) {
5851                 if (! fnCandidate[0].type->getSampler().shadow)
5852                     compArg = 2;
5853             }
5854             break;
5855         case EOpTextureGatherOffset:
5856             // GL_ARB_texture_gather is good enough for 2D non-shadow textures with no component argument
5857             if (! fnCandidate[0].type->getSampler().shadow)
5858                 compArg = 3;
5859             break;
5860         case EOpTextureGatherOffsets:
5861             if (! fnCandidate[0].type->getSampler().shadow)
5862                 compArg = 3;
5863             break;
5864         default:
5865             break;
5866         }
5867
5868         if (compArg > 0 && compArg < fnCandidate.getParamCount()) {
5869             if (aggArgs[compArg]->getAsConstantUnion()) {
5870                 int value = aggArgs[compArg]->getAsConstantUnion()->getConstArray()[0].getIConst();
5871                 if (value < 0 || value > 3)
5872                     error(loc, "must be 0, 1, 2, or 3:", feature, "component argument");
5873             } else
5874                 error(loc, "must be a compile-time constant:", feature, "component argument");
5875         }
5876
5877         break;
5878     }
5879
5880     case EOpTextureOffset:
5881     case EOpTextureFetchOffset:
5882     case EOpTextureProjOffset:
5883     case EOpTextureLodOffset:
5884     case EOpTextureProjLodOffset:
5885     case EOpTextureGradOffset:
5886     case EOpTextureProjGradOffset:
5887     {
5888         // Handle texture-offset limits checking
5889         // Pick which argument has to hold constant offsets
5890         int arg = -1;
5891         switch (callNode.getOp()) {
5892         case EOpTextureOffset:          arg = 2;  break;
5893         case EOpTextureFetchOffset:     arg = (arg0->getType().getSampler().dim != EsdRect) ? 3 : 2; break;
5894         case EOpTextureProjOffset:      arg = 2;  break;
5895         case EOpTextureLodOffset:       arg = 3;  break;
5896         case EOpTextureProjLodOffset:   arg = 3;  break;
5897         case EOpTextureGradOffset:      arg = 4;  break;
5898         case EOpTextureProjGradOffset:  arg = 4;  break;
5899         default:
5900             assert(0);
5901             break;
5902         }
5903
5904         if (arg > 0) {
5905             if (aggArgs[arg]->getAsConstantUnion() == nullptr)
5906                 error(loc, "argument must be compile-time constant", "texel offset", "");
5907             else {
5908                 const TType& type = aggArgs[arg]->getAsTyped()->getType();
5909                 for (int c = 0; c < type.getVectorSize(); ++c) {
5910                     int offset = aggArgs[arg]->getAsConstantUnion()->getConstArray()[c].getIConst();
5911                     if (offset > resources.maxProgramTexelOffset || offset < resources.minProgramTexelOffset)
5912                         error(loc, "value is out of range:", "texel offset",
5913                               "[gl_MinProgramTexelOffset, gl_MaxProgramTexelOffset]");
5914                 }
5915             }
5916         }
5917
5918         break;
5919     }
5920
5921     case EOpTextureQuerySamples:
5922     case EOpImageQuerySamples:
5923         break;
5924
5925     case EOpImageAtomicAdd:
5926     case EOpImageAtomicMin:
5927     case EOpImageAtomicMax:
5928     case EOpImageAtomicAnd:
5929     case EOpImageAtomicOr:
5930     case EOpImageAtomicXor:
5931     case EOpImageAtomicExchange:
5932     case EOpImageAtomicCompSwap:
5933         break;
5934
5935     case EOpInterpolateAtCentroid:
5936     case EOpInterpolateAtSample:
5937     case EOpInterpolateAtOffset:
5938         // Make sure the first argument is an interpolant, or an array element of an interpolant
5939         if (arg0->getType().getQualifier().storage != EvqVaryingIn) {
5940             // It might still be an array element.
5941             //
5942             // We could check more, but the semantics of the first argument are already met; the
5943             // only way to turn an array into a float/vec* is array dereference and swizzle.
5944             //
5945             // ES and desktop 4.3 and earlier:  swizzles may not be used
5946             // desktop 4.4 and later: swizzles may be used
5947             const TIntermTyped* base = TIntermediate::findLValueBase(arg0, true);
5948             if (base == nullptr || base->getType().getQualifier().storage != EvqVaryingIn)
5949                 error(loc, "first argument must be an interpolant, or interpolant-array element",
5950                       fnCandidate.getName().c_str(), "");
5951         }
5952         break;
5953
5954     default:
5955         break;
5956     }
5957 }
5958
5959 //
5960 // Handle seeing something in a grammar production that can be done by calling
5961 // a constructor.
5962 //
5963 // The constructor still must be "handled" by handleFunctionCall(), which will
5964 // then call handleConstructor().
5965 //
5966 TFunction* HlslParseContext::makeConstructorCall(const TSourceLoc& loc, const TType& type)
5967 {
5968     TOperator op = intermediate.mapTypeToConstructorOp(type);
5969
5970     if (op == EOpNull) {
5971         error(loc, "cannot construct this type", type.getBasicString(), "");
5972         return nullptr;
5973     }
5974
5975     TString empty("");
5976
5977     return new TFunction(&empty, type, op);
5978 }
5979
5980 //
5981 // Handle seeing a "COLON semantic" at the end of a type declaration,
5982 // by updating the type according to the semantic.
5983 //
5984 void HlslParseContext::handleSemantic(TSourceLoc loc, TQualifier& qualifier, TBuiltInVariable builtIn,
5985                                       const TString& upperCase)
5986 {
5987     // Parse and return semantic number.  If limit is 0, it will be ignored.  Otherwise, if the parsed
5988     // semantic number is >= limit, errorMsg is issued and 0 is returned.
5989     // TODO: it would be nicer if limit and errorMsg had default parameters, but some compilers don't yet
5990     // accept those in lambda functions.
5991     const auto getSemanticNumber = [this, loc](const TString& semantic, unsigned int limit, const char* errorMsg) -> unsigned int {
5992         size_t pos = semantic.find_last_not_of("0123456789");
5993         if (pos == std::string::npos)
5994             return 0u;
5995
5996         unsigned int semanticNum = (unsigned int)atoi(semantic.c_str() + pos + 1);
5997
5998         if (limit != 0 && semanticNum >= limit) {
5999             error(loc, errorMsg, semantic.c_str(), "");
6000             return 0u;
6001         }
6002
6003         return semanticNum;
6004     };
6005
6006     switch(builtIn) {
6007     case EbvNone:
6008         // Get location numbers from fragment outputs, instead of
6009         // auto-assigning them.
6010         if (language == EShLangFragment && upperCase.compare(0, 9, "SV_TARGET") == 0) {
6011             qualifier.layoutLocation = getSemanticNumber(upperCase, 0, nullptr);
6012             nextOutLocation = std::max(nextOutLocation, qualifier.layoutLocation + 1u);
6013         } else if (upperCase.compare(0, 15, "SV_CLIPDISTANCE") == 0) {
6014             builtIn = EbvClipDistance;
6015             qualifier.layoutLocation = getSemanticNumber(upperCase, maxClipCullRegs, "invalid clip semantic");
6016         } else if (upperCase.compare(0, 15, "SV_CULLDISTANCE") == 0) {
6017             builtIn = EbvCullDistance;
6018             qualifier.layoutLocation = getSemanticNumber(upperCase, maxClipCullRegs, "invalid cull semantic");
6019         }
6020         break;
6021     case EbvPosition:
6022         // adjust for stage in/out
6023         if (language == EShLangFragment)
6024             builtIn = EbvFragCoord;
6025         break;
6026     case EbvFragStencilRef:
6027         error(loc, "unimplemented; need ARB_shader_stencil_export", "SV_STENCILREF", "");
6028         break;
6029     case EbvTessLevelInner:
6030     case EbvTessLevelOuter:
6031         qualifier.patch = true;
6032         break;
6033     default:
6034         break;
6035     }
6036
6037     if (qualifier.builtIn == EbvNone)
6038         qualifier.builtIn = builtIn;
6039     qualifier.semanticName = intermediate.addSemanticName(upperCase);
6040 }
6041
6042 //
6043 // Handle seeing something like "PACKOFFSET LEFT_PAREN c[Subcomponent][.component] RIGHT_PAREN"
6044 //
6045 // 'location' has the "c[Subcomponent]" part.
6046 // 'component' points to the "component" part, or nullptr if not present.
6047 //
6048 void HlslParseContext::handlePackOffset(const TSourceLoc& loc, TQualifier& qualifier, const glslang::TString& location,
6049                                         const glslang::TString* component)
6050 {
6051     if (location.size() == 0 || location[0] != 'c') {
6052         error(loc, "expected 'c'", "packoffset", "");
6053         return;
6054     }
6055     if (location.size() == 1)
6056         return;
6057     if (! isdigit(location[1])) {
6058         error(loc, "expected number after 'c'", "packoffset", "");
6059         return;
6060     }
6061
6062     qualifier.layoutOffset = 16 * atoi(location.substr(1, location.size()).c_str());
6063     if (component != nullptr) {
6064         int componentOffset = 0;
6065         switch ((*component)[0]) {
6066         case 'x': componentOffset =  0; break;
6067         case 'y': componentOffset =  4; break;
6068         case 'z': componentOffset =  8; break;
6069         case 'w': componentOffset = 12; break;
6070         default:
6071             componentOffset = -1;
6072             break;
6073         }
6074         if (componentOffset < 0 || component->size() > 1) {
6075             error(loc, "expected {x, y, z, w} for component", "packoffset", "");
6076             return;
6077         }
6078         qualifier.layoutOffset += componentOffset;
6079     }
6080 }
6081
6082 //
6083 // Handle seeing something like "REGISTER LEFT_PAREN [shader_profile,] Type# RIGHT_PAREN"
6084 //
6085 // 'profile' points to the shader_profile part, or nullptr if not present.
6086 // 'desc' is the type# part.
6087 //
6088 void HlslParseContext::handleRegister(const TSourceLoc& loc, TQualifier& qualifier, const glslang::TString* profile,
6089                                       const glslang::TString& desc, int subComponent, const glslang::TString* spaceDesc)
6090 {
6091     if (profile != nullptr)
6092         warn(loc, "ignoring shader_profile", "register", "");
6093
6094     if (desc.size() < 1) {
6095         error(loc, "expected register type", "register", "");
6096         return;
6097     }
6098
6099     int regNumber = 0;
6100     if (desc.size() > 1) {
6101         if (isdigit(desc[1]))
6102             regNumber = atoi(desc.substr(1, desc.size()).c_str());
6103         else {
6104             error(loc, "expected register number after register type", "register", "");
6105             return;
6106         }
6107     }
6108
6109     // more information about register types see
6110     // https://docs.microsoft.com/en-us/windows/desktop/direct3dhlsl/dx-graphics-hlsl-variable-register
6111     const std::vector<std::string>& resourceInfo = intermediate.getResourceSetBinding();
6112     switch (std::tolower(desc[0])) {
6113     case 'c':
6114         // c register is the register slot in the global const buffer
6115         // each slot is a vector of 4 32 bit components
6116         qualifier.layoutOffset = regNumber * 4 * 4;
6117         break;
6118         // const buffer register slot
6119     case 'b':
6120         // textrues and structured buffers
6121     case 't':
6122         // samplers
6123     case 's':
6124         // uav resources
6125     case 'u':
6126         // if nothing else has set the binding, do so now
6127         // (other mechanisms override this one)
6128         if (!qualifier.hasBinding())
6129             qualifier.layoutBinding = regNumber + subComponent;
6130
6131         // This handles per-register layout sets numbers.  For the global mode which sets
6132         // every symbol to the same value, see setLinkageLayoutSets().
6133         if ((resourceInfo.size() % 3) == 0) {
6134             // Apply per-symbol resource set and binding.
6135             for (auto it = resourceInfo.cbegin(); it != resourceInfo.cend(); it = it + 3) {
6136                 if (strcmp(desc.c_str(), it[0].c_str()) == 0) {
6137                     qualifier.layoutSet = atoi(it[1].c_str());
6138                     qualifier.layoutBinding = atoi(it[2].c_str()) + subComponent;
6139                     break;
6140                 }
6141             }
6142         }
6143         break;
6144     default:
6145         warn(loc, "ignoring unrecognized register type", "register", "%c", desc[0]);
6146         break;
6147     }
6148
6149     // space
6150     unsigned int setNumber;
6151     const auto crackSpace = [&]() -> bool {
6152         const int spaceLen = 5;
6153         if (spaceDesc->size() < spaceLen + 1)
6154             return false;
6155         if (spaceDesc->compare(0, spaceLen, "space") != 0)
6156             return false;
6157         if (! isdigit((*spaceDesc)[spaceLen]))
6158             return false;
6159         setNumber = atoi(spaceDesc->substr(spaceLen, spaceDesc->size()).c_str());
6160         return true;
6161     };
6162
6163     // if nothing else has set the set, do so now
6164     // (other mechanisms override this one)
6165     if (spaceDesc && !qualifier.hasSet()) {
6166         if (! crackSpace()) {
6167             error(loc, "expected spaceN", "register", "");
6168             return;
6169         }
6170         qualifier.layoutSet = setNumber;
6171     }
6172 }
6173
6174 // Convert to a scalar boolean, or if not allowed by HLSL semantics,
6175 // report an error and return nullptr.
6176 TIntermTyped* HlslParseContext::convertConditionalExpression(const TSourceLoc& loc, TIntermTyped* condition,
6177                                                              bool mustBeScalar)
6178 {
6179     if (mustBeScalar && !condition->getType().isScalarOrVec1()) {
6180         error(loc, "requires a scalar", "conditional expression", "");
6181         return nullptr;
6182     }
6183
6184     return intermediate.addConversion(EOpConstructBool, TType(EbtBool, EvqTemporary, condition->getVectorSize()),
6185                                       condition);
6186 }
6187
6188 //
6189 // Same error message for all places assignments don't work.
6190 //
6191 void HlslParseContext::assignError(const TSourceLoc& loc, const char* op, TString left, TString right)
6192 {
6193     error(loc, "", op, "cannot convert from '%s' to '%s'",
6194         right.c_str(), left.c_str());
6195 }
6196
6197 //
6198 // Same error message for all places unary operations don't work.
6199 //
6200 void HlslParseContext::unaryOpError(const TSourceLoc& loc, const char* op, TString operand)
6201 {
6202     error(loc, " wrong operand type", op,
6203         "no operation '%s' exists that takes an operand of type %s (or there is no acceptable conversion)",
6204         op, operand.c_str());
6205 }
6206
6207 //
6208 // Same error message for all binary operations don't work.
6209 //
6210 void HlslParseContext::binaryOpError(const TSourceLoc& loc, const char* op, TString left, TString right)
6211 {
6212     error(loc, " wrong operand types:", op,
6213         "no operation '%s' exists that takes a left-hand operand of type '%s' and "
6214         "a right operand of type '%s' (or there is no acceptable conversion)",
6215         op, left.c_str(), right.c_str());
6216 }
6217
6218 //
6219 // A basic type of EbtVoid is a key that the name string was seen in the source, but
6220 // it was not found as a variable in the symbol table.  If so, give the error
6221 // message and insert a dummy variable in the symbol table to prevent future errors.
6222 //
6223 void HlslParseContext::variableCheck(TIntermTyped*& nodePtr)
6224 {
6225     TIntermSymbol* symbol = nodePtr->getAsSymbolNode();
6226     if (! symbol)
6227         return;
6228
6229     if (symbol->getType().getBasicType() == EbtVoid) {
6230         error(symbol->getLoc(), "undeclared identifier", symbol->getName().c_str(), "");
6231
6232         // Add to symbol table to prevent future error messages on the same name
6233         if (symbol->getName().size() > 0) {
6234             TVariable* fakeVariable = new TVariable(&symbol->getName(), TType(EbtFloat));
6235             symbolTable.insert(*fakeVariable);
6236
6237             // substitute a symbol node for this new variable
6238             nodePtr = intermediate.addSymbol(*fakeVariable, symbol->getLoc());
6239         }
6240     }
6241 }
6242
6243 //
6244 // Both test, and if necessary spit out an error, to see if the node is really
6245 // a constant.
6246 //
6247 void HlslParseContext::constantValueCheck(TIntermTyped* node, const char* token)
6248 {
6249     if (node->getQualifier().storage != EvqConst)
6250         error(node->getLoc(), "constant expression required", token, "");
6251 }
6252
6253 //
6254 // Both test, and if necessary spit out an error, to see if the node is really
6255 // an integer.
6256 //
6257 void HlslParseContext::integerCheck(const TIntermTyped* node, const char* token)
6258 {
6259     if ((node->getBasicType() == EbtInt || node->getBasicType() == EbtUint) && node->isScalar())
6260         return;
6261
6262     error(node->getLoc(), "scalar integer expression required", token, "");
6263 }
6264
6265 //
6266 // Both test, and if necessary spit out an error, to see if we are currently
6267 // globally scoped.
6268 //
6269 void HlslParseContext::globalCheck(const TSourceLoc& loc, const char* token)
6270 {
6271     if (! symbolTable.atGlobalLevel())
6272         error(loc, "not allowed in nested scope", token, "");
6273 }
6274
6275 bool HlslParseContext::builtInName(const TString& /*identifier*/)
6276 {
6277     return false;
6278 }
6279
6280 //
6281 // Make sure there is enough data and not too many arguments provided to the
6282 // constructor to build something of the type of the constructor.  Also returns
6283 // the type of the constructor.
6284 //
6285 // Returns true if there was an error in construction.
6286 //
6287 bool HlslParseContext::constructorError(const TSourceLoc& loc, TIntermNode* node, TFunction& function,
6288                                         TOperator op, TType& type)
6289 {
6290     type.shallowCopy(function.getType());
6291
6292     bool constructingMatrix = false;
6293     switch (op) {
6294     case EOpConstructTextureSampler:
6295         error(loc, "unhandled texture constructor", "constructor", "");
6296         return true;
6297     case EOpConstructMat2x2:
6298     case EOpConstructMat2x3:
6299     case EOpConstructMat2x4:
6300     case EOpConstructMat3x2:
6301     case EOpConstructMat3x3:
6302     case EOpConstructMat3x4:
6303     case EOpConstructMat4x2:
6304     case EOpConstructMat4x3:
6305     case EOpConstructMat4x4:
6306     case EOpConstructDMat2x2:
6307     case EOpConstructDMat2x3:
6308     case EOpConstructDMat2x4:
6309     case EOpConstructDMat3x2:
6310     case EOpConstructDMat3x3:
6311     case EOpConstructDMat3x4:
6312     case EOpConstructDMat4x2:
6313     case EOpConstructDMat4x3:
6314     case EOpConstructDMat4x4:
6315     case EOpConstructIMat2x2:
6316     case EOpConstructIMat2x3:
6317     case EOpConstructIMat2x4:
6318     case EOpConstructIMat3x2:
6319     case EOpConstructIMat3x3:
6320     case EOpConstructIMat3x4:
6321     case EOpConstructIMat4x2:
6322     case EOpConstructIMat4x3:
6323     case EOpConstructIMat4x4:
6324     case EOpConstructUMat2x2:
6325     case EOpConstructUMat2x3:
6326     case EOpConstructUMat2x4:
6327     case EOpConstructUMat3x2:
6328     case EOpConstructUMat3x3:
6329     case EOpConstructUMat3x4:
6330     case EOpConstructUMat4x2:
6331     case EOpConstructUMat4x3:
6332     case EOpConstructUMat4x4:
6333     case EOpConstructBMat2x2:
6334     case EOpConstructBMat2x3:
6335     case EOpConstructBMat2x4:
6336     case EOpConstructBMat3x2:
6337     case EOpConstructBMat3x3:
6338     case EOpConstructBMat3x4:
6339     case EOpConstructBMat4x2:
6340     case EOpConstructBMat4x3:
6341     case EOpConstructBMat4x4:
6342         constructingMatrix = true;
6343         break;
6344     default:
6345         break;
6346     }
6347
6348     //
6349     // Walk the arguments for first-pass checks and collection of information.
6350     //
6351
6352     int size = 0;
6353     bool constType = true;
6354     bool full = false;
6355     bool overFull = false;
6356     bool matrixInMatrix = false;
6357     bool arrayArg = false;
6358     for (int arg = 0; arg < function.getParamCount(); ++arg) {
6359         if (function[arg].type->isArray()) {
6360             if (function[arg].type->isUnsizedArray()) {
6361                 // Can't construct from an unsized array.
6362                 error(loc, "array argument must be sized", "constructor", "");
6363                 return true;
6364             }
6365             arrayArg = true;
6366         }
6367         if (constructingMatrix && function[arg].type->isMatrix())
6368             matrixInMatrix = true;
6369
6370         // 'full' will go to true when enough args have been seen.  If we loop
6371         // again, there is an extra argument.
6372         if (full) {
6373             // For vectors and matrices, it's okay to have too many components
6374             // available, but not okay to have unused arguments.
6375             overFull = true;
6376         }
6377
6378         size += function[arg].type->computeNumComponents();
6379         if (op != EOpConstructStruct && ! type.isArray() && size >= type.computeNumComponents())
6380             full = true;
6381
6382         if (function[arg].type->getQualifier().storage != EvqConst)
6383             constType = false;
6384     }
6385
6386     if (constType)
6387         type.getQualifier().storage = EvqConst;
6388
6389     if (type.isArray()) {
6390         if (function.getParamCount() == 0) {
6391             error(loc, "array constructor must have at least one argument", "constructor", "");
6392             return true;
6393         }
6394
6395         if (type.isUnsizedArray()) {
6396             // auto adapt the constructor type to the number of arguments
6397             type.changeOuterArraySize(function.getParamCount());
6398         } else if (type.getOuterArraySize() != function.getParamCount() && type.computeNumComponents() > size) {
6399             error(loc, "array constructor needs one argument per array element", "constructor", "");
6400             return true;
6401         }
6402
6403         if (type.isArrayOfArrays()) {
6404             // Types have to match, but we're still making the type.
6405             // Finish making the type, and the comparison is done later
6406             // when checking for conversion.
6407             TArraySizes& arraySizes = *type.getArraySizes();
6408
6409             // At least the dimensionalities have to match.
6410             if (! function[0].type->isArray() ||
6411                 arraySizes.getNumDims() != function[0].type->getArraySizes()->getNumDims() + 1) {
6412                 error(loc, "array constructor argument not correct type to construct array element", "constructor", "");
6413                 return true;
6414             }
6415
6416             if (arraySizes.isInnerUnsized()) {
6417                 // "Arrays of arrays ..., and the size for any dimension is optional"
6418                 // That means we need to adopt (from the first argument) the other array sizes into the type.
6419                 for (int d = 1; d < arraySizes.getNumDims(); ++d) {
6420                     if (arraySizes.getDimSize(d) == UnsizedArraySize) {
6421                         arraySizes.setDimSize(d, function[0].type->getArraySizes()->getDimSize(d - 1));
6422                     }
6423                 }
6424             }
6425         }
6426     }
6427
6428     // Some array -> array type casts are okay
6429     if (arrayArg && function.getParamCount() == 1 && op != EOpConstructStruct && type.isArray() &&
6430         !type.isArrayOfArrays() && !function[0].type->isArrayOfArrays() &&
6431         type.getVectorSize() >= 1 && function[0].type->getVectorSize() >= 1)
6432         return false;
6433
6434     if (arrayArg && op != EOpConstructStruct && ! type.isArrayOfArrays()) {
6435         error(loc, "constructing non-array constituent from array argument", "constructor", "");
6436         return true;
6437     }
6438
6439     if (matrixInMatrix && ! type.isArray()) {
6440         return false;
6441     }
6442
6443     if (overFull) {
6444         error(loc, "too many arguments", "constructor", "");
6445         return true;
6446     }
6447
6448     if (op == EOpConstructStruct && ! type.isArray()) {
6449         if (isScalarConstructor(node))
6450             return false;
6451
6452         // Self-type construction: e.g, we can construct a struct from a single identically typed object.
6453         if (function.getParamCount() == 1 && type == *function[0].type)
6454             return false;
6455
6456         if ((int)type.getStruct()->size() != function.getParamCount()) {
6457             error(loc, "Number of constructor parameters does not match the number of structure fields", "constructor", "");
6458             return true;
6459         }
6460     }
6461
6462     if ((op != EOpConstructStruct && size != 1 && size < type.computeNumComponents()) ||
6463         (op == EOpConstructStruct && size < type.computeNumComponents())) {
6464         error(loc, "not enough data provided for construction", "constructor", "");
6465         return true;
6466     }
6467
6468     return false;
6469 }
6470
6471 // See if 'node', in the context of constructing aggregates, is a scalar argument
6472 // to a constructor.
6473 //
6474 bool HlslParseContext::isScalarConstructor(const TIntermNode* node)
6475 {
6476     // Obviously, it must be a scalar, but an aggregate node might not be fully
6477     // completed yet: holding a sequence of initializers under an aggregate
6478     // would not yet be typed, so don't check it's type.  This corresponds to
6479     // the aggregate operator also not being set yet. (An aggregate operation
6480     // that legitimately yields a scalar will have a getOp() of that operator,
6481     // not EOpNull.)
6482
6483     return node->getAsTyped() != nullptr &&
6484            node->getAsTyped()->isScalar() &&
6485            (node->getAsAggregate() == nullptr || node->getAsAggregate()->getOp() != EOpNull);
6486 }
6487
6488 // Checks to see if a void variable has been declared and raise an error message for such a case
6489 //
6490 // returns true in case of an error
6491 //
6492 bool HlslParseContext::voidErrorCheck(const TSourceLoc& loc, const TString& identifier, const TBasicType basicType)
6493 {
6494     if (basicType == EbtVoid) {
6495         error(loc, "illegal use of type 'void'", identifier.c_str(), "");
6496         return true;
6497     }
6498
6499     return false;
6500 }
6501
6502 //
6503 // Fix just a full qualifier (no variables or types yet, but qualifier is complete) at global level.
6504 //
6505 void HlslParseContext::globalQualifierFix(const TSourceLoc&, TQualifier& qualifier)
6506 {
6507     // move from parameter/unknown qualifiers to pipeline in/out qualifiers
6508     switch (qualifier.storage) {
6509     case EvqIn:
6510         qualifier.storage = EvqVaryingIn;
6511         break;
6512     case EvqOut:
6513         qualifier.storage = EvqVaryingOut;
6514         break;
6515     default:
6516         break;
6517     }
6518 }
6519
6520 //
6521 // Merge characteristics of the 'src' qualifier into the 'dst'.
6522 // If there is duplication, issue error messages, unless 'force'
6523 // is specified, which means to just override default settings.
6524 //
6525 // Also, when force is false, it will be assumed that 'src' follows
6526 // 'dst', for the purpose of error checking order for versions
6527 // that require specific orderings of qualifiers.
6528 //
6529 void HlslParseContext::mergeQualifiers(TQualifier& dst, const TQualifier& src)
6530 {
6531     // Storage qualification
6532     if (dst.storage == EvqTemporary || dst.storage == EvqGlobal)
6533         dst.storage = src.storage;
6534     else if ((dst.storage == EvqIn  && src.storage == EvqOut) ||
6535              (dst.storage == EvqOut && src.storage == EvqIn))
6536         dst.storage = EvqInOut;
6537     else if ((dst.storage == EvqIn    && src.storage == EvqConst) ||
6538              (dst.storage == EvqConst && src.storage == EvqIn))
6539         dst.storage = EvqConstReadOnly;
6540
6541     // Layout qualifiers
6542     mergeObjectLayoutQualifiers(dst, src, false);
6543
6544     // individual qualifiers
6545     bool repeated = false;
6546 #define MERGE_SINGLETON(field) repeated |= dst.field && src.field; dst.field |= src.field;
6547     MERGE_SINGLETON(invariant);
6548     MERGE_SINGLETON(noContraction);
6549     MERGE_SINGLETON(centroid);
6550     MERGE_SINGLETON(smooth);
6551     MERGE_SINGLETON(flat);
6552     MERGE_SINGLETON(nopersp);
6553     MERGE_SINGLETON(patch);
6554     MERGE_SINGLETON(sample);
6555     MERGE_SINGLETON(coherent);
6556     MERGE_SINGLETON(volatil);
6557     MERGE_SINGLETON(restrict);
6558     MERGE_SINGLETON(readonly);
6559     MERGE_SINGLETON(writeonly);
6560     MERGE_SINGLETON(specConstant);
6561     MERGE_SINGLETON(nonUniform);
6562 }
6563
6564 // used to flatten the sampler type space into a single dimension
6565 // correlates with the declaration of defaultSamplerPrecision[]
6566 int HlslParseContext::computeSamplerTypeIndex(TSampler& sampler)
6567 {
6568     int arrayIndex = sampler.arrayed ? 1 : 0;
6569     int shadowIndex = sampler.shadow ? 1 : 0;
6570     int externalIndex = sampler.external ? 1 : 0;
6571
6572     return EsdNumDims *
6573            (EbtNumTypes * (2 * (2 * arrayIndex + shadowIndex) + externalIndex) + sampler.type) + sampler.dim;
6574 }
6575
6576 //
6577 // Do size checking for an array type's size.
6578 //
6579 void HlslParseContext::arraySizeCheck(const TSourceLoc& loc, TIntermTyped* expr, TArraySize& sizePair)
6580 {
6581     bool isConst = false;
6582     sizePair.size = 1;
6583     sizePair.node = nullptr;
6584
6585     TIntermConstantUnion* constant = expr->getAsConstantUnion();
6586     if (constant) {
6587         // handle true (non-specialization) constant
6588         sizePair.size = constant->getConstArray()[0].getIConst();
6589         isConst = true;
6590     } else {
6591         // see if it's a specialization constant instead
6592         if (expr->getQualifier().isSpecConstant()) {
6593             isConst = true;
6594             sizePair.node = expr;
6595             TIntermSymbol* symbol = expr->getAsSymbolNode();
6596             if (symbol && symbol->getConstArray().size() > 0)
6597                 sizePair.size = symbol->getConstArray()[0].getIConst();
6598         }
6599     }
6600
6601     if (! isConst || (expr->getBasicType() != EbtInt && expr->getBasicType() != EbtUint)) {
6602         error(loc, "array size must be a constant integer expression", "", "");
6603         return;
6604     }
6605
6606     if (sizePair.size <= 0) {
6607         error(loc, "array size must be a positive integer", "", "");
6608         return;
6609     }
6610 }
6611
6612 //
6613 // Require array to be completely sized
6614 //
6615 void HlslParseContext::arraySizeRequiredCheck(const TSourceLoc& loc, const TArraySizes& arraySizes)
6616 {
6617     if (arraySizes.hasUnsized())
6618         error(loc, "array size required", "", "");
6619 }
6620
6621 void HlslParseContext::structArrayCheck(const TSourceLoc& /*loc*/, const TType& type)
6622 {
6623     const TTypeList& structure = *type.getStruct();
6624     for (int m = 0; m < (int)structure.size(); ++m) {
6625         const TType& member = *structure[m].type;
6626         if (member.isArray())
6627             arraySizeRequiredCheck(structure[m].loc, *member.getArraySizes());
6628     }
6629 }
6630
6631 //
6632 // Do all the semantic checking for declaring or redeclaring an array, with and
6633 // without a size, and make the right changes to the symbol table.
6634 //
6635 void HlslParseContext::declareArray(const TSourceLoc& loc, const TString& identifier, const TType& type,
6636                                     TSymbol*& symbol, bool track)
6637 {
6638     if (symbol == nullptr) {
6639         bool currentScope;
6640         symbol = symbolTable.find(identifier, nullptr, &currentScope);
6641
6642         if (symbol && builtInName(identifier) && ! symbolTable.atBuiltInLevel()) {
6643             // bad shader (errors already reported) trying to redeclare a built-in name as an array
6644             return;
6645         }
6646         if (symbol == nullptr || ! currentScope) {
6647             //
6648             // Successfully process a new definition.
6649             // (Redeclarations have to take place at the same scope; otherwise they are hiding declarations)
6650             //
6651             symbol = new TVariable(&identifier, type);
6652             symbolTable.insert(*symbol);
6653             if (track && symbolTable.atGlobalLevel())
6654                 trackLinkage(*symbol);
6655
6656             return;
6657         }
6658         if (symbol->getAsAnonMember()) {
6659             error(loc, "cannot redeclare a user-block member array", identifier.c_str(), "");
6660             symbol = nullptr;
6661             return;
6662         }
6663     }
6664
6665     //
6666     // Process a redeclaration.
6667     //
6668
6669     if (symbol == nullptr) {
6670         error(loc, "array variable name expected", identifier.c_str(), "");
6671         return;
6672     }
6673
6674     // redeclareBuiltinVariable() should have already done the copyUp()
6675     TType& existingType = symbol->getWritableType();
6676
6677     if (existingType.isSizedArray()) {
6678         // be more lenient for input arrays to geometry shaders and tessellation control outputs,
6679         // where the redeclaration is the same size
6680         return;
6681     }
6682
6683     existingType.updateArraySizes(type);
6684 }
6685
6686 //
6687 // Enforce non-initializer type/qualifier rules.
6688 //
6689 void HlslParseContext::fixConstInit(const TSourceLoc& loc, const TString& identifier, TType& type,
6690                                     TIntermTyped*& initializer)
6691 {
6692     //
6693     // Make the qualifier make sense, given that there is an initializer.
6694     //
6695     if (initializer == nullptr) {
6696         if (type.getQualifier().storage == EvqConst ||
6697             type.getQualifier().storage == EvqConstReadOnly) {
6698             initializer = intermediate.makeAggregate(loc);
6699             warn(loc, "variable with qualifier 'const' not initialized; zero initializing", identifier.c_str(), "");
6700         }
6701     }
6702 }
6703
6704 //
6705 // See if the identifier is a built-in symbol that can be redeclared, and if so,
6706 // copy the symbol table's read-only built-in variable to the current
6707 // global level, where it can be modified based on the passed in type.
6708 //
6709 // Returns nullptr if no redeclaration took place; meaning a normal declaration still
6710 // needs to occur for it, not necessarily an error.
6711 //
6712 // Returns a redeclared and type-modified variable if a redeclared occurred.
6713 //
6714 TSymbol* HlslParseContext::redeclareBuiltinVariable(const TSourceLoc& /*loc*/, const TString& identifier,
6715                                                     const TQualifier& /*qualifier*/,
6716                                                     const TShaderQualifiers& /*publicType*/)
6717 {
6718     if (! builtInName(identifier) || symbolTable.atBuiltInLevel() || ! symbolTable.atGlobalLevel())
6719         return nullptr;
6720
6721     return nullptr;
6722 }
6723
6724 //
6725 // Generate index to the array element in a structure buffer (SSBO)
6726 //
6727 TIntermTyped* HlslParseContext::indexStructBufferContent(const TSourceLoc& loc, TIntermTyped* buffer) const
6728 {
6729     // Bail out if not a struct buffer
6730     if (buffer == nullptr || ! isStructBufferType(buffer->getType()))
6731         return nullptr;
6732
6733     // Runtime sized array is always the last element.
6734     const TTypeList* bufferStruct = buffer->getType().getStruct();
6735     TIntermTyped* arrayPosition = intermediate.addConstantUnion(unsigned(bufferStruct->size()-1), loc);
6736
6737     TIntermTyped* argArray = intermediate.addIndex(EOpIndexDirectStruct, buffer, arrayPosition, loc);
6738     argArray->setType(*(*bufferStruct)[bufferStruct->size()-1].type);
6739
6740     return argArray;
6741 }
6742
6743 //
6744 // IFF type is a structuredbuffer/byteaddressbuffer type, return the content
6745 // (template) type.   E.g, StructuredBuffer<MyType> -> MyType.  Else return nullptr.
6746 //
6747 TType* HlslParseContext::getStructBufferContentType(const TType& type) const
6748 {
6749     if (type.getBasicType() != EbtBlock || type.getQualifier().storage != EvqBuffer)
6750         return nullptr;
6751
6752     const int memberCount = (int)type.getStruct()->size();
6753     assert(memberCount > 0);
6754
6755     TType* contentType = (*type.getStruct())[memberCount-1].type;
6756
6757     return contentType->isUnsizedArray() ? contentType : nullptr;
6758 }
6759
6760 //
6761 // If an existing struct buffer has a sharable type, then share it.
6762 //
6763 void HlslParseContext::shareStructBufferType(TType& type)
6764 {
6765     // PackOffset must be equivalent to share types on a per-member basis.
6766     // Note: cannot use auto type due to recursion.  Thus, this is a std::function.
6767     const std::function<bool(TType& lhs, TType& rhs)>
6768     compareQualifiers = [&](TType& lhs, TType& rhs) -> bool {
6769         if (lhs.getQualifier().layoutOffset != rhs.getQualifier().layoutOffset)
6770             return false;
6771
6772         if (lhs.isStruct() != rhs.isStruct())
6773             return false;
6774
6775         if (lhs.isStruct() && rhs.isStruct()) {
6776             if (lhs.getStruct()->size() != rhs.getStruct()->size())
6777                 return false;
6778
6779             for (int i = 0; i < int(lhs.getStruct()->size()); ++i)
6780                 if (!compareQualifiers(*(*lhs.getStruct())[i].type, *(*rhs.getStruct())[i].type))
6781                     return false;
6782         }
6783
6784         return true;
6785     };
6786
6787     // We need to compare certain qualifiers in addition to the type.
6788     const auto typeEqual = [compareQualifiers](TType& lhs, TType& rhs) -> bool {
6789         if (lhs.getQualifier().readonly != rhs.getQualifier().readonly)
6790             return false;
6791
6792         // If both are structures, recursively look for packOffset equality
6793         // as well as type equality.
6794         return compareQualifiers(lhs, rhs) && lhs == rhs;
6795     };
6796
6797     // This is an exhaustive O(N) search, but real world shaders have
6798     // only a small number of these.
6799     for (int idx = 0; idx < int(structBufferTypes.size()); ++idx) {
6800         // If the deep structure matches, modulo qualifiers, use it
6801         if (typeEqual(*structBufferTypes[idx], type)) {
6802             type.shallowCopy(*structBufferTypes[idx]);
6803             return;
6804         }
6805     }
6806
6807     // Otherwise, remember it:
6808     TType* typeCopy = new TType;
6809     typeCopy->shallowCopy(type);
6810     structBufferTypes.push_back(typeCopy);
6811 }
6812
6813 void HlslParseContext::paramFix(TType& type)
6814 {
6815     switch (type.getQualifier().storage) {
6816     case EvqConst:
6817         type.getQualifier().storage = EvqConstReadOnly;
6818         break;
6819     case EvqGlobal:
6820     case EvqUniform:
6821     case EvqTemporary:
6822         type.getQualifier().storage = EvqIn;
6823         break;
6824     case EvqBuffer:
6825         {
6826             // SSBO parameter.  These do not go through the declareBlock path since they are fn parameters.
6827             correctUniform(type.getQualifier());
6828             TQualifier bufferQualifier = globalBufferDefaults;
6829             mergeObjectLayoutQualifiers(bufferQualifier, type.getQualifier(), true);
6830             bufferQualifier.storage = type.getQualifier().storage;
6831             bufferQualifier.readonly = type.getQualifier().readonly;
6832             bufferQualifier.coherent = type.getQualifier().coherent;
6833             bufferQualifier.declaredBuiltIn = type.getQualifier().declaredBuiltIn;
6834             type.getQualifier() = bufferQualifier;
6835             break;
6836         }
6837     default:
6838         break;
6839     }
6840 }
6841
6842 void HlslParseContext::specializationCheck(const TSourceLoc& loc, const TType& type, const char* op)
6843 {
6844     if (type.containsSpecializationSize())
6845         error(loc, "can't use with types containing arrays sized with a specialization constant", op, "");
6846 }
6847
6848 //
6849 // Layout qualifier stuff.
6850 //
6851
6852 // Put the id's layout qualification into the public type, for qualifiers not having a number set.
6853 // This is before we know any type information for error checking.
6854 void HlslParseContext::setLayoutQualifier(const TSourceLoc& loc, TQualifier& qualifier, TString& id)
6855 {
6856     std::transform(id.begin(), id.end(), id.begin(), ::tolower);
6857
6858     if (id == TQualifier::getLayoutMatrixString(ElmColumnMajor)) {
6859         qualifier.layoutMatrix = ElmRowMajor;
6860         return;
6861     }
6862     if (id == TQualifier::getLayoutMatrixString(ElmRowMajor)) {
6863         qualifier.layoutMatrix = ElmColumnMajor;
6864         return;
6865     }
6866     if (id == "push_constant") {
6867         requireVulkan(loc, "push_constant");
6868         qualifier.layoutPushConstant = true;
6869         return;
6870     }
6871     if (language == EShLangGeometry || language == EShLangTessEvaluation) {
6872         if (id == TQualifier::getGeometryString(ElgTriangles)) {
6873             // publicType.shaderQualifiers.geometry = ElgTriangles;
6874             warn(loc, "ignored", id.c_str(), "");
6875             return;
6876         }
6877         if (language == EShLangGeometry) {
6878             if (id == TQualifier::getGeometryString(ElgPoints)) {
6879                 // publicType.shaderQualifiers.geometry = ElgPoints;
6880                 warn(loc, "ignored", id.c_str(), "");
6881                 return;
6882             }
6883             if (id == TQualifier::getGeometryString(ElgLineStrip)) {
6884                 // publicType.shaderQualifiers.geometry = ElgLineStrip;
6885                 warn(loc, "ignored", id.c_str(), "");
6886                 return;
6887             }
6888             if (id == TQualifier::getGeometryString(ElgLines)) {
6889                 // publicType.shaderQualifiers.geometry = ElgLines;
6890                 warn(loc, "ignored", id.c_str(), "");
6891                 return;
6892             }
6893             if (id == TQualifier::getGeometryString(ElgLinesAdjacency)) {
6894                 // publicType.shaderQualifiers.geometry = ElgLinesAdjacency;
6895                 warn(loc, "ignored", id.c_str(), "");
6896                 return;
6897             }
6898             if (id == TQualifier::getGeometryString(ElgTrianglesAdjacency)) {
6899                 // publicType.shaderQualifiers.geometry = ElgTrianglesAdjacency;
6900                 warn(loc, "ignored", id.c_str(), "");
6901                 return;
6902             }
6903             if (id == TQualifier::getGeometryString(ElgTriangleStrip)) {
6904                 // publicType.shaderQualifiers.geometry = ElgTriangleStrip;
6905                 warn(loc, "ignored", id.c_str(), "");
6906                 return;
6907             }
6908         } else {
6909             assert(language == EShLangTessEvaluation);
6910
6911             // input primitive
6912             if (id == TQualifier::getGeometryString(ElgTriangles)) {
6913                 // publicType.shaderQualifiers.geometry = ElgTriangles;
6914                 warn(loc, "ignored", id.c_str(), "");
6915                 return;
6916             }
6917             if (id == TQualifier::getGeometryString(ElgQuads)) {
6918                 // publicType.shaderQualifiers.geometry = ElgQuads;
6919                 warn(loc, "ignored", id.c_str(), "");
6920                 return;
6921             }
6922             if (id == TQualifier::getGeometryString(ElgIsolines)) {
6923                 // publicType.shaderQualifiers.geometry = ElgIsolines;
6924                 warn(loc, "ignored", id.c_str(), "");
6925                 return;
6926             }
6927
6928             // vertex spacing
6929             if (id == TQualifier::getVertexSpacingString(EvsEqual)) {
6930                 // publicType.shaderQualifiers.spacing = EvsEqual;
6931                 warn(loc, "ignored", id.c_str(), "");
6932                 return;
6933             }
6934             if (id == TQualifier::getVertexSpacingString(EvsFractionalEven)) {
6935                 // publicType.shaderQualifiers.spacing = EvsFractionalEven;
6936                 warn(loc, "ignored", id.c_str(), "");
6937                 return;
6938             }
6939             if (id == TQualifier::getVertexSpacingString(EvsFractionalOdd)) {
6940                 // publicType.shaderQualifiers.spacing = EvsFractionalOdd;
6941                 warn(loc, "ignored", id.c_str(), "");
6942                 return;
6943             }
6944
6945             // triangle order
6946             if (id == TQualifier::getVertexOrderString(EvoCw)) {
6947                 // publicType.shaderQualifiers.order = EvoCw;
6948                 warn(loc, "ignored", id.c_str(), "");
6949                 return;
6950             }
6951             if (id == TQualifier::getVertexOrderString(EvoCcw)) {
6952                 // publicType.shaderQualifiers.order = EvoCcw;
6953                 warn(loc, "ignored", id.c_str(), "");
6954                 return;
6955             }
6956
6957             // point mode
6958             if (id == "point_mode") {
6959                 // publicType.shaderQualifiers.pointMode = true;
6960                 warn(loc, "ignored", id.c_str(), "");
6961                 return;
6962             }
6963         }
6964     }
6965     if (language == EShLangFragment) {
6966         if (id == "origin_upper_left") {
6967             // publicType.shaderQualifiers.originUpperLeft = true;
6968             warn(loc, "ignored", id.c_str(), "");
6969             return;
6970         }
6971         if (id == "pixel_center_integer") {
6972             // publicType.shaderQualifiers.pixelCenterInteger = true;
6973             warn(loc, "ignored", id.c_str(), "");
6974             return;
6975         }
6976         if (id == "early_fragment_tests") {
6977             // publicType.shaderQualifiers.earlyFragmentTests = true;
6978             warn(loc, "ignored", id.c_str(), "");
6979             return;
6980         }
6981         for (TLayoutDepth depth = (TLayoutDepth)(EldNone + 1); depth < EldCount; depth = (TLayoutDepth)(depth + 1)) {
6982             if (id == TQualifier::getLayoutDepthString(depth)) {
6983                 // publicType.shaderQualifiers.layoutDepth = depth;
6984                 warn(loc, "ignored", id.c_str(), "");
6985                 return;
6986             }
6987         }
6988         if (id.compare(0, 13, "blend_support") == 0) {
6989             bool found = false;
6990             for (TBlendEquationShift be = (TBlendEquationShift)0; be < EBlendCount; be = (TBlendEquationShift)(be + 1)) {
6991                 if (id == TQualifier::getBlendEquationString(be)) {
6992                     requireExtensions(loc, 1, &E_GL_KHR_blend_equation_advanced, "blend equation");
6993                     intermediate.addBlendEquation(be);
6994                     // publicType.shaderQualifiers.blendEquation = true;
6995                     warn(loc, "ignored", id.c_str(), "");
6996                     found = true;
6997                     break;
6998                 }
6999             }
7000             if (! found)
7001                 error(loc, "unknown blend equation", "blend_support", "");
7002             return;
7003         }
7004     }
7005     error(loc, "unrecognized layout identifier, or qualifier requires assignment (e.g., binding = 4)", id.c_str(), "");
7006 }
7007
7008 // Put the id's layout qualifier value into the public type, for qualifiers having a number set.
7009 // This is before we know any type information for error checking.
7010 void HlslParseContext::setLayoutQualifier(const TSourceLoc& loc, TQualifier& qualifier, TString& id,
7011                                           const TIntermTyped* node)
7012 {
7013     const char* feature = "layout-id value";
7014     // const char* nonLiteralFeature = "non-literal layout-id value";
7015
7016     integerCheck(node, feature);
7017     const TIntermConstantUnion* constUnion = node->getAsConstantUnion();
7018     int value = 0;
7019     if (constUnion) {
7020         value = constUnion->getConstArray()[0].getIConst();
7021     }
7022
7023     std::transform(id.begin(), id.end(), id.begin(), ::tolower);
7024
7025     if (id == "offset") {
7026         qualifier.layoutOffset = value;
7027         return;
7028     } else if (id == "align") {
7029         // "The specified alignment must be a power of 2, or a compile-time error results."
7030         if (! IsPow2(value))
7031             error(loc, "must be a power of 2", "align", "");
7032         else
7033             qualifier.layoutAlign = value;
7034         return;
7035     } else if (id == "location") {
7036         if ((unsigned int)value >= TQualifier::layoutLocationEnd)
7037             error(loc, "location is too large", id.c_str(), "");
7038         else
7039             qualifier.layoutLocation = value;
7040         return;
7041     } else if (id == "set") {
7042         if ((unsigned int)value >= TQualifier::layoutSetEnd)
7043             error(loc, "set is too large", id.c_str(), "");
7044         else
7045             qualifier.layoutSet = value;
7046         return;
7047     } else if (id == "binding") {
7048         if ((unsigned int)value >= TQualifier::layoutBindingEnd)
7049             error(loc, "binding is too large", id.c_str(), "");
7050         else
7051             qualifier.layoutBinding = value;
7052         return;
7053     } else if (id == "component") {
7054         if ((unsigned)value >= TQualifier::layoutComponentEnd)
7055             error(loc, "component is too large", id.c_str(), "");
7056         else
7057             qualifier.layoutComponent = value;
7058         return;
7059     } else if (id.compare(0, 4, "xfb_") == 0) {
7060         // "Any shader making any static use (after preprocessing) of any of these
7061         // *xfb_* qualifiers will cause the shader to be in a transform feedback
7062         // capturing mode and hence responsible for describing the transform feedback
7063         // setup."
7064         intermediate.setXfbMode();
7065         if (id == "xfb_buffer") {
7066             // "It is a compile-time error to specify an *xfb_buffer* that is greater than
7067             // the implementation-dependent constant gl_MaxTransformFeedbackBuffers."
7068             if (value >= resources.maxTransformFeedbackBuffers)
7069                 error(loc, "buffer is too large:", id.c_str(), "gl_MaxTransformFeedbackBuffers is %d",
7070                       resources.maxTransformFeedbackBuffers);
7071             if (value >= (int)TQualifier::layoutXfbBufferEnd)
7072                 error(loc, "buffer is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbBufferEnd - 1);
7073             else
7074                 qualifier.layoutXfbBuffer = value;
7075             return;
7076         } else if (id == "xfb_offset") {
7077             if (value >= (int)TQualifier::layoutXfbOffsetEnd)
7078                 error(loc, "offset is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbOffsetEnd - 1);
7079             else
7080                 qualifier.layoutXfbOffset = value;
7081             return;
7082         } else if (id == "xfb_stride") {
7083             // "The resulting stride (implicit or explicit), when divided by 4, must be less than or equal to the
7084             // implementation-dependent constant gl_MaxTransformFeedbackInterleavedComponents."
7085             if (value > 4 * resources.maxTransformFeedbackInterleavedComponents)
7086                 error(loc, "1/4 stride is too large:", id.c_str(), "gl_MaxTransformFeedbackInterleavedComponents is %d",
7087                       resources.maxTransformFeedbackInterleavedComponents);
7088             else if (value >= (int)TQualifier::layoutXfbStrideEnd)
7089                 error(loc, "stride is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbStrideEnd - 1);
7090             if (value < (int)TQualifier::layoutXfbStrideEnd)
7091                 qualifier.layoutXfbStride = value;
7092             return;
7093         }
7094     }
7095
7096     if (id == "input_attachment_index") {
7097         requireVulkan(loc, "input_attachment_index");
7098         if (value >= (int)TQualifier::layoutAttachmentEnd)
7099             error(loc, "attachment index is too large", id.c_str(), "");
7100         else
7101             qualifier.layoutAttachment = value;
7102         return;
7103     }
7104     if (id == "constant_id") {
7105         setSpecConstantId(loc, qualifier, value);
7106         return;
7107     }
7108
7109     switch (language) {
7110     case EShLangVertex:
7111         break;
7112
7113     case EShLangTessControl:
7114         if (id == "vertices") {
7115             if (value == 0)
7116                 error(loc, "must be greater than 0", "vertices", "");
7117             else
7118                 // publicType.shaderQualifiers.vertices = value;
7119                 warn(loc, "ignored", id.c_str(), "");
7120             return;
7121         }
7122         break;
7123
7124     case EShLangTessEvaluation:
7125         break;
7126
7127     case EShLangGeometry:
7128         if (id == "invocations") {
7129             if (value == 0)
7130                 error(loc, "must be at least 1", "invocations", "");
7131             else
7132                 // publicType.shaderQualifiers.invocations = value;
7133                 warn(loc, "ignored", id.c_str(), "");
7134             return;
7135         }
7136         if (id == "max_vertices") {
7137             // publicType.shaderQualifiers.vertices = value;
7138             warn(loc, "ignored", id.c_str(), "");
7139             if (value > resources.maxGeometryOutputVertices)
7140                 error(loc, "too large, must be less than gl_MaxGeometryOutputVertices", "max_vertices", "");
7141             return;
7142         }
7143         if (id == "stream") {
7144             qualifier.layoutStream = value;
7145             return;
7146         }
7147         break;
7148
7149     case EShLangFragment:
7150         if (id == "index") {
7151             qualifier.layoutIndex = value;
7152             return;
7153         }
7154         break;
7155
7156     case EShLangCompute:
7157         if (id.compare(0, 11, "local_size_") == 0) {
7158             if (id == "local_size_x") {
7159                 // publicType.shaderQualifiers.localSize[0] = value;
7160                 warn(loc, "ignored", id.c_str(), "");
7161                 return;
7162             }
7163             if (id == "local_size_y") {
7164                 // publicType.shaderQualifiers.localSize[1] = value;
7165                 warn(loc, "ignored", id.c_str(), "");
7166                 return;
7167             }
7168             if (id == "local_size_z") {
7169                 // publicType.shaderQualifiers.localSize[2] = value;
7170                 warn(loc, "ignored", id.c_str(), "");
7171                 return;
7172             }
7173             if (spvVersion.spv != 0) {
7174                 if (id == "local_size_x_id") {
7175                     // publicType.shaderQualifiers.localSizeSpecId[0] = value;
7176                     warn(loc, "ignored", id.c_str(), "");
7177                     return;
7178                 }
7179                 if (id == "local_size_y_id") {
7180                     // publicType.shaderQualifiers.localSizeSpecId[1] = value;
7181                     warn(loc, "ignored", id.c_str(), "");
7182                     return;
7183                 }
7184                 if (id == "local_size_z_id") {
7185                     // publicType.shaderQualifiers.localSizeSpecId[2] = value;
7186                     warn(loc, "ignored", id.c_str(), "");
7187                     return;
7188                 }
7189             }
7190         }
7191         break;
7192
7193     default:
7194         break;
7195     }
7196
7197     error(loc, "there is no such layout identifier for this stage taking an assigned value", id.c_str(), "");
7198 }
7199
7200 void HlslParseContext::setSpecConstantId(const TSourceLoc& loc, TQualifier& qualifier, int value)
7201 {
7202     if (value >= (int)TQualifier::layoutSpecConstantIdEnd) {
7203         error(loc, "specialization-constant id is too large", "constant_id", "");
7204     } else {
7205         qualifier.layoutSpecConstantId = value;
7206         qualifier.specConstant = true;
7207         if (! intermediate.addUsedConstantId(value))
7208             error(loc, "specialization-constant id already used", "constant_id", "");
7209     }
7210     return;
7211 }
7212
7213 // Merge any layout qualifier information from src into dst, leaving everything else in dst alone
7214 //
7215 // "More than one layout qualifier may appear in a single declaration.
7216 // Additionally, the same layout-qualifier-name can occur multiple times
7217 // within a layout qualifier or across multiple layout qualifiers in the
7218 // same declaration. When the same layout-qualifier-name occurs
7219 // multiple times, in a single declaration, the last occurrence overrides
7220 // the former occurrence(s).  Further, if such a layout-qualifier-name
7221 // will effect subsequent declarations or other observable behavior, it
7222 // is only the last occurrence that will have any effect, behaving as if
7223 // the earlier occurrence(s) within the declaration are not present.
7224 // This is also true for overriding layout-qualifier-names, where one
7225 // overrides the other (e.g., row_major vs. column_major); only the last
7226 // occurrence has any effect."
7227 //
7228 void HlslParseContext::mergeObjectLayoutQualifiers(TQualifier& dst, const TQualifier& src, bool inheritOnly)
7229 {
7230     if (src.hasMatrix())
7231         dst.layoutMatrix = src.layoutMatrix;
7232     if (src.hasPacking())
7233         dst.layoutPacking = src.layoutPacking;
7234
7235     if (src.hasStream())
7236         dst.layoutStream = src.layoutStream;
7237
7238     if (src.hasFormat())
7239         dst.layoutFormat = src.layoutFormat;
7240
7241     if (src.hasXfbBuffer())
7242         dst.layoutXfbBuffer = src.layoutXfbBuffer;
7243
7244     if (src.hasAlign())
7245         dst.layoutAlign = src.layoutAlign;
7246
7247     if (! inheritOnly) {
7248         if (src.hasLocation())
7249             dst.layoutLocation = src.layoutLocation;
7250         if (src.hasComponent())
7251             dst.layoutComponent = src.layoutComponent;
7252         if (src.hasIndex())
7253             dst.layoutIndex = src.layoutIndex;
7254
7255         if (src.hasOffset())
7256             dst.layoutOffset = src.layoutOffset;
7257
7258         if (src.hasSet())
7259             dst.layoutSet = src.layoutSet;
7260         if (src.layoutBinding != TQualifier::layoutBindingEnd)
7261             dst.layoutBinding = src.layoutBinding;
7262
7263         if (src.hasXfbStride())
7264             dst.layoutXfbStride = src.layoutXfbStride;
7265         if (src.hasXfbOffset())
7266             dst.layoutXfbOffset = src.layoutXfbOffset;
7267         if (src.hasAttachment())
7268             dst.layoutAttachment = src.layoutAttachment;
7269         if (src.hasSpecConstantId())
7270             dst.layoutSpecConstantId = src.layoutSpecConstantId;
7271
7272         if (src.layoutPushConstant)
7273             dst.layoutPushConstant = true;
7274     }
7275 }
7276
7277
7278 //
7279 // Look up a function name in the symbol table, and make sure it is a function.
7280 //
7281 // First, look for an exact match.  If there is none, use the generic selector
7282 // TParseContextBase::selectFunction() to find one, parameterized by the
7283 // convertible() and better() predicates defined below.
7284 //
7285 // Return the function symbol if found, otherwise nullptr.
7286 //
7287 const TFunction* HlslParseContext::findFunction(const TSourceLoc& loc, TFunction& call, bool& builtIn, int& thisDepth,
7288                                                 TIntermTyped*& args)
7289 {
7290     if (symbolTable.isFunctionNameVariable(call.getName())) {
7291         error(loc, "can't use function syntax on variable", call.getName().c_str(), "");
7292         return nullptr;
7293     }
7294
7295     // first, look for an exact match
7296     bool dummyScope;
7297     TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn, &dummyScope, &thisDepth);
7298     if (symbol)
7299         return symbol->getAsFunction();
7300
7301     // no exact match, use the generic selector, parameterized by the GLSL rules
7302
7303     // create list of candidates to send
7304     TVector<const TFunction*> candidateList;
7305     symbolTable.findFunctionNameList(call.getMangledName(), candidateList, builtIn);
7306
7307     // These built-in ops can accept any type, so we bypass the argument selection
7308     if (candidateList.size() == 1 && builtIn &&
7309         (candidateList[0]->getBuiltInOp() == EOpMethodAppend ||
7310          candidateList[0]->getBuiltInOp() == EOpMethodRestartStrip ||
7311          candidateList[0]->getBuiltInOp() == EOpMethodIncrementCounter ||
7312          candidateList[0]->getBuiltInOp() == EOpMethodDecrementCounter ||
7313          candidateList[0]->getBuiltInOp() == EOpMethodAppend ||
7314          candidateList[0]->getBuiltInOp() == EOpMethodConsume)) {
7315         return candidateList[0];
7316     }
7317
7318     bool allowOnlyUpConversions = true;
7319
7320     // can 'from' convert to 'to'?
7321     const auto convertible = [&](const TType& from, const TType& to, TOperator op, int arg) -> bool {
7322         if (from == to)
7323             return true;
7324
7325         // no aggregate conversions
7326         if (from.isArray()  || to.isArray() ||
7327             from.isStruct() || to.isStruct())
7328             return false;
7329
7330         switch (op) {
7331         case EOpInterlockedAdd:
7332         case EOpInterlockedAnd:
7333         case EOpInterlockedCompareExchange:
7334         case EOpInterlockedCompareStore:
7335         case EOpInterlockedExchange:
7336         case EOpInterlockedMax:
7337         case EOpInterlockedMin:
7338         case EOpInterlockedOr:
7339         case EOpInterlockedXor:
7340             // We do not promote the texture or image type for these ocodes.  Normally that would not
7341             // be an issue because it's a buffer, but we haven't decomposed the opcode yet, and at this
7342             // stage it's merely e.g, a basic integer type.
7343             //
7344             // Instead, we want to promote other arguments, but stay within the same family.  In other
7345             // words, InterlockedAdd(RWBuffer<int>, ...) will always use the int flavor, never the uint flavor,
7346             // but it is allowed to promote its other arguments.
7347             if (arg == 0)
7348                 return false;
7349             break;
7350         case EOpMethodSample:
7351         case EOpMethodSampleBias:
7352         case EOpMethodSampleCmp:
7353         case EOpMethodSampleCmpLevelZero:
7354         case EOpMethodSampleGrad:
7355         case EOpMethodSampleLevel:
7356         case EOpMethodLoad:
7357         case EOpMethodGetDimensions:
7358         case EOpMethodGetSamplePosition:
7359         case EOpMethodGather:
7360         case EOpMethodCalculateLevelOfDetail:
7361         case EOpMethodCalculateLevelOfDetailUnclamped:
7362         case EOpMethodGatherRed:
7363         case EOpMethodGatherGreen:
7364         case EOpMethodGatherBlue:
7365         case EOpMethodGatherAlpha:
7366         case EOpMethodGatherCmp:
7367         case EOpMethodGatherCmpRed:
7368         case EOpMethodGatherCmpGreen:
7369         case EOpMethodGatherCmpBlue:
7370         case EOpMethodGatherCmpAlpha:
7371         case EOpMethodAppend:
7372         case EOpMethodRestartStrip:
7373             // those are method calls, the object type can not be changed
7374             // they are equal if the dim and type match (is dim sufficient?)
7375             if (arg == 0)
7376                 return from.getSampler().type == to.getSampler().type &&
7377                        from.getSampler().arrayed == to.getSampler().arrayed &&
7378                        from.getSampler().shadow == to.getSampler().shadow &&
7379                        from.getSampler().ms == to.getSampler().ms &&
7380                        from.getSampler().dim == to.getSampler().dim;
7381             break;
7382         default:
7383             break;
7384         }
7385
7386         // basic types have to be convertible
7387         if (allowOnlyUpConversions)
7388             if (! intermediate.canImplicitlyPromote(from.getBasicType(), to.getBasicType(), EOpFunctionCall))
7389                 return false;
7390
7391         // shapes have to be convertible
7392         if ((from.isScalarOrVec1() && to.isScalarOrVec1()) ||
7393             (from.isScalarOrVec1() && to.isVector())    ||
7394             (from.isScalarOrVec1() && to.isMatrix())    ||
7395             (from.isVector() && to.isVector() && from.getVectorSize() >= to.getVectorSize()))
7396             return true;
7397
7398         // TODO: what are the matrix rules? they go here
7399
7400         return false;
7401     };
7402
7403     // Is 'to2' a better conversion than 'to1'?
7404     // Ties should not be considered as better.
7405     // Assumes 'convertible' already said true.
7406     const auto better = [](const TType& from, const TType& to1, const TType& to2) -> bool {
7407         // exact match is always better than mismatch
7408         if (from == to2)
7409             return from != to1;
7410         if (from == to1)
7411             return false;
7412
7413         // shape changes are always worse
7414         if (from.isScalar() || from.isVector()) {
7415             if (from.getVectorSize() == to2.getVectorSize() &&
7416                 from.getVectorSize() != to1.getVectorSize())
7417                 return true;
7418             if (from.getVectorSize() == to1.getVectorSize() &&
7419                 from.getVectorSize() != to2.getVectorSize())
7420                 return false;
7421         }
7422
7423         // Handle sampler betterness: An exact sampler match beats a non-exact match.
7424         // (If we just looked at basic type, all EbtSamplers would look the same).
7425         // If any type is not a sampler, just use the linearize function below.
7426         if (from.getBasicType() == EbtSampler && to1.getBasicType() == EbtSampler && to2.getBasicType() == EbtSampler) {
7427             // We can ignore the vector size in the comparison.
7428             TSampler to1Sampler = to1.getSampler();
7429             TSampler to2Sampler = to2.getSampler();
7430
7431             to1Sampler.vectorSize = to2Sampler.vectorSize = from.getSampler().vectorSize;
7432
7433             if (from.getSampler() == to2Sampler)
7434                 return from.getSampler() != to1Sampler;
7435             if (from.getSampler() == to1Sampler)
7436                 return false;
7437         }
7438
7439         // Might or might not be changing shape, which means basic type might
7440         // or might not match, so within that, the question is how big a
7441         // basic-type conversion is being done.
7442         //
7443         // Use a hierarchy of domains, translated to order of magnitude
7444         // in a linearized view:
7445         //   - floating-point vs. integer
7446         //     - 32 vs. 64 bit (or width in general)
7447         //       - bool vs. non bool
7448         //         - signed vs. not signed
7449         const auto linearize = [](const TBasicType& basicType) -> int {
7450             switch (basicType) {
7451             case EbtBool:     return 1;
7452             case EbtInt:      return 10;
7453             case EbtUint:     return 11;
7454             case EbtInt64:    return 20;
7455             case EbtUint64:   return 21;
7456             case EbtFloat:    return 100;
7457             case EbtDouble:   return 110;
7458             default:          return 0;
7459             }
7460         };
7461
7462         return abs(linearize(to2.getBasicType()) - linearize(from.getBasicType())) <
7463                abs(linearize(to1.getBasicType()) - linearize(from.getBasicType()));
7464     };
7465
7466     // for ambiguity reporting
7467     bool tie = false;
7468
7469     // send to the generic selector
7470     const TFunction* bestMatch = selectFunction(candidateList, call, convertible, better, tie);
7471
7472     if (bestMatch == nullptr) {
7473         // If there is nothing selected by allowing only up-conversions (to a larger linearize() value),
7474         // we instead try down-conversions, which are valid in HLSL, but not preferred if there are any
7475         // upconversions possible.
7476         allowOnlyUpConversions = false;
7477         bestMatch = selectFunction(candidateList, call, convertible, better, tie);
7478     }
7479
7480     if (bestMatch == nullptr) {
7481         error(loc, "no matching overloaded function found", call.getName().c_str(), "");
7482         return nullptr;
7483     }
7484
7485     // For built-ins, we can convert across the arguments.  This will happen in several steps:
7486     // Step 1:  If there's an exact match, use it.
7487     // Step 2a: Otherwise, get the operator from the best match and promote arguments:
7488     // Step 2b: reconstruct the TFunction based on the new arg types
7489     // Step 3:  Re-select after type promotion is applied, to find proper candidate.
7490     if (builtIn) {
7491         // Step 1: If there's an exact match, use it.
7492         if (call.getMangledName() == bestMatch->getMangledName())
7493             return bestMatch;
7494
7495         // Step 2a: Otherwise, get the operator from the best match and promote arguments as if we
7496         // are that kind of operator.
7497         if (args != nullptr) {
7498             // The arg list can be a unary node, or an aggregate.  We have to handle both.
7499             // We will use the normal promote() facilities, which require an interm node.
7500             TIntermOperator* promote = nullptr;
7501
7502             if (call.getParamCount() == 1) {
7503                 promote = new TIntermUnary(bestMatch->getBuiltInOp());
7504                 promote->getAsUnaryNode()->setOperand(args->getAsTyped());
7505             } else {
7506                 promote = new TIntermAggregate(bestMatch->getBuiltInOp());
7507                 promote->getAsAggregate()->getSequence().swap(args->getAsAggregate()->getSequence());
7508             }
7509
7510             if (! intermediate.promote(promote))
7511                 return nullptr;
7512
7513             // Obtain the promoted arg list.
7514             if (call.getParamCount() == 1) {
7515                 args = promote->getAsUnaryNode()->getOperand();
7516             } else {
7517                 promote->getAsAggregate()->getSequence().swap(args->getAsAggregate()->getSequence());
7518             }
7519         }
7520
7521         // Step 2b: reconstruct the TFunction based on the new arg types
7522         TFunction convertedCall(&call.getName(), call.getType(), call.getBuiltInOp());
7523
7524         if (args->getAsAggregate()) {
7525             // Handle aggregates: put all args into the new function call
7526             for (int arg=0; arg<int(args->getAsAggregate()->getSequence().size()); ++arg) {
7527                 // TODO: But for constness, we could avoid the new & shallowCopy, and use the pointer directly.
7528                 TParameter param = { 0, new TType, nullptr };
7529                 param.type->shallowCopy(args->getAsAggregate()->getSequence()[arg]->getAsTyped()->getType());
7530                 convertedCall.addParameter(param);
7531             }
7532         } else if (args->getAsUnaryNode()) {
7533             // Handle unaries: put all args into the new function call
7534             TParameter param = { 0, new TType, nullptr };
7535             param.type->shallowCopy(args->getAsUnaryNode()->getOperand()->getAsTyped()->getType());
7536             convertedCall.addParameter(param);
7537         } else if (args->getAsTyped()) {
7538             // Handle bare e.g, floats, not in an aggregate.
7539             TParameter param = { 0, new TType, nullptr };
7540             param.type->shallowCopy(args->getAsTyped()->getType());
7541             convertedCall.addParameter(param);
7542         } else {
7543             assert(0); // unknown argument list.
7544             return nullptr;
7545         }
7546
7547         // Step 3: Re-select after type promotion, to find proper candidate
7548         // send to the generic selector
7549         bestMatch = selectFunction(candidateList, convertedCall, convertible, better, tie);
7550
7551         // At this point, there should be no tie.
7552     }
7553
7554     if (tie)
7555         error(loc, "ambiguous best function under implicit type conversion", call.getName().c_str(), "");
7556
7557     // Append default parameter values if needed
7558     if (!tie && bestMatch != nullptr) {
7559         for (int defParam = call.getParamCount(); defParam < bestMatch->getParamCount(); ++defParam) {
7560             handleFunctionArgument(&call, args, (*bestMatch)[defParam].defaultValue);
7561         }
7562     }
7563
7564     return bestMatch;
7565 }
7566
7567 //
7568 // Do everything necessary to handle a typedef declaration, for a single symbol.
7569 //
7570 // 'parseType' is the type part of the declaration (to the left)
7571 // 'arraySizes' is the arrayness tagged on the identifier (to the right)
7572 //
7573 void HlslParseContext::declareTypedef(const TSourceLoc& loc, const TString& identifier, const TType& parseType)
7574 {
7575     TVariable* typeSymbol = new TVariable(&identifier, parseType, true);
7576     if (! symbolTable.insert(*typeSymbol))
7577         error(loc, "name already defined", "typedef", identifier.c_str());
7578 }
7579
7580 // Do everything necessary to handle a struct declaration, including
7581 // making IO aliases because HLSL allows mixed IO in a struct that specializes
7582 // based on the usage (input, output, uniform, none).
7583 void HlslParseContext::declareStruct(const TSourceLoc& loc, TString& structName, TType& type)
7584 {
7585     // If it was named, which means the type can be reused later, add
7586     // it to the symbol table.  (Unless it's a block, in which
7587     // case the name is not a type.)
7588     if (type.getBasicType() == EbtBlock || structName.size() == 0)
7589         return;
7590
7591     TVariable* userTypeDef = new TVariable(&structName, type, true);
7592     if (! symbolTable.insert(*userTypeDef)) {
7593         error(loc, "redefinition", structName.c_str(), "struct");
7594         return;
7595     }
7596
7597     // See if we need IO aliases for the structure typeList
7598
7599     const auto condAlloc = [](bool pred, TTypeList*& list) {
7600         if (pred && list == nullptr)
7601             list = new TTypeList;
7602     };
7603
7604     tIoKinds newLists = { nullptr, nullptr, nullptr }; // allocate for each kind found
7605     for (auto member = type.getStruct()->begin(); member != type.getStruct()->end(); ++member) {
7606         condAlloc(hasUniform(member->type->getQualifier()), newLists.uniform);
7607         condAlloc(  hasInput(member->type->getQualifier()), newLists.input);
7608         condAlloc( hasOutput(member->type->getQualifier()), newLists.output);
7609
7610         if (member->type->isStruct()) {
7611             auto it = ioTypeMap.find(member->type->getStruct());
7612             if (it != ioTypeMap.end()) {
7613                 condAlloc(it->second.uniform != nullptr, newLists.uniform);
7614                 condAlloc(it->second.input   != nullptr, newLists.input);
7615                 condAlloc(it->second.output  != nullptr, newLists.output);
7616             }
7617         }
7618     }
7619     if (newLists.uniform == nullptr &&
7620         newLists.input   == nullptr &&
7621         newLists.output  == nullptr) {
7622         // Won't do any IO caching, clear up the type and get out now.
7623         for (auto member = type.getStruct()->begin(); member != type.getStruct()->end(); ++member)
7624             clearUniformInputOutput(member->type->getQualifier());
7625         return;
7626     }
7627
7628     // We have IO involved.
7629
7630     // Make a pure typeList for the symbol table, and cache side copies of IO versions.
7631     for (auto member = type.getStruct()->begin(); member != type.getStruct()->end(); ++member) {
7632         const auto inheritStruct = [&](TTypeList* s, TTypeLoc& ioMember) {
7633             if (s != nullptr) {
7634                 ioMember.type = new TType;
7635                 ioMember.type->shallowCopy(*member->type);
7636                 ioMember.type->setStruct(s);
7637             }
7638         };
7639         const auto newMember = [&](TTypeLoc& m) {
7640             if (m.type == nullptr) {
7641                 m.type = new TType;
7642                 m.type->shallowCopy(*member->type);
7643             }
7644         };
7645
7646         TTypeLoc newUniformMember = { nullptr, member->loc };
7647         TTypeLoc newInputMember   = { nullptr, member->loc };
7648         TTypeLoc newOutputMember  = { nullptr, member->loc };
7649         if (member->type->isStruct()) {
7650             // swap in an IO child if there is one
7651             auto it = ioTypeMap.find(member->type->getStruct());
7652             if (it != ioTypeMap.end()) {
7653                 inheritStruct(it->second.uniform, newUniformMember);
7654                 inheritStruct(it->second.input,   newInputMember);
7655                 inheritStruct(it->second.output,  newOutputMember);
7656             }
7657         }
7658         if (newLists.uniform) {
7659             newMember(newUniformMember);
7660
7661             // inherit default matrix layout (changeable via #pragma pack_matrix), if none given.
7662             if (member->type->isMatrix() && member->type->getQualifier().layoutMatrix == ElmNone)
7663                 newUniformMember.type->getQualifier().layoutMatrix = globalUniformDefaults.layoutMatrix;
7664
7665             correctUniform(newUniformMember.type->getQualifier());
7666             newLists.uniform->push_back(newUniformMember);
7667         }
7668         if (newLists.input) {
7669             newMember(newInputMember);
7670             correctInput(newInputMember.type->getQualifier());
7671             newLists.input->push_back(newInputMember);
7672         }
7673         if (newLists.output) {
7674             newMember(newOutputMember);
7675             correctOutput(newOutputMember.type->getQualifier());
7676             newLists.output->push_back(newOutputMember);
7677         }
7678
7679         // make original pure
7680         clearUniformInputOutput(member->type->getQualifier());
7681     }
7682     ioTypeMap[type.getStruct()] = newLists;
7683 }
7684
7685 // Lookup a user-type by name.
7686 // If found, fill in the type and return the defining symbol.
7687 // If not found, return nullptr.
7688 TSymbol* HlslParseContext::lookupUserType(const TString& typeName, TType& type)
7689 {
7690     TSymbol* symbol = symbolTable.find(typeName);
7691     if (symbol && symbol->getAsVariable() && symbol->getAsVariable()->isUserType()) {
7692         type.shallowCopy(symbol->getType());
7693         return symbol;
7694     } else
7695         return nullptr;
7696 }
7697
7698 //
7699 // Do everything necessary to handle a variable (non-block) declaration.
7700 // Either redeclaring a variable, or making a new one, updating the symbol
7701 // table, and all error checking.
7702 //
7703 // Returns a subtree node that computes an initializer, if needed.
7704 // Returns nullptr if there is no code to execute for initialization.
7705 //
7706 // 'parseType' is the type part of the declaration (to the left)
7707 // 'arraySizes' is the arrayness tagged on the identifier (to the right)
7708 //
7709 TIntermNode* HlslParseContext::declareVariable(const TSourceLoc& loc, const TString& identifier, TType& type,
7710                                                TIntermTyped* initializer)
7711 {
7712     if (voidErrorCheck(loc, identifier, type.getBasicType()))
7713         return nullptr;
7714
7715     // Global consts with initializers that are non-const act like EvqGlobal in HLSL.
7716     // This test is implicitly recursive, because initializers propagate constness
7717     // up the aggregate node tree during creation.  E.g, for:
7718     //    { { 1, 2 }, { 3, 4 } }
7719     // the initializer list is marked EvqConst at the top node, and remains so here.  However:
7720     //    { 1, { myvar, 2 }, 3 }
7721     // is not a const intializer, and still becomes EvqGlobal here.
7722
7723     const bool nonConstInitializer = (initializer != nullptr && initializer->getQualifier().storage != EvqConst);
7724
7725     if (type.getQualifier().storage == EvqConst && symbolTable.atGlobalLevel() && nonConstInitializer) {
7726         // Force to global
7727         type.getQualifier().storage = EvqGlobal;
7728     }
7729
7730     // make const and initialization consistent
7731     fixConstInit(loc, identifier, type, initializer);
7732
7733     // Check for redeclaration of built-ins and/or attempting to declare a reserved name
7734     TSymbol* symbol = nullptr;
7735
7736     inheritGlobalDefaults(type.getQualifier());
7737
7738     const bool flattenVar = shouldFlatten(type, type.getQualifier().storage, true);
7739
7740     // correct IO in the type
7741     switch (type.getQualifier().storage) {
7742     case EvqGlobal:
7743     case EvqTemporary:
7744         clearUniformInputOutput(type.getQualifier());
7745         break;
7746     case EvqUniform:
7747     case EvqBuffer:
7748         correctUniform(type.getQualifier());
7749         if (type.isStruct()) {
7750             auto it = ioTypeMap.find(type.getStruct());
7751             if (it != ioTypeMap.end())
7752                 type.setStruct(it->second.uniform);
7753         }
7754
7755         break;
7756     default:
7757         break;
7758     }
7759
7760     // Declare the variable
7761     if (type.isArray()) {
7762         // array case
7763         declareArray(loc, identifier, type, symbol, !flattenVar);
7764     } else {
7765         // non-array case
7766         if (symbol == nullptr)
7767             symbol = declareNonArray(loc, identifier, type, !flattenVar);
7768         else if (type != symbol->getType())
7769             error(loc, "cannot change the type of", "redeclaration", symbol->getName().c_str());
7770     }
7771
7772     if (symbol == nullptr)
7773         return nullptr;
7774
7775     if (flattenVar)
7776         flatten(*symbol->getAsVariable(), symbolTable.atGlobalLevel());
7777
7778     if (initializer == nullptr)
7779         return nullptr;
7780
7781     // Deal with initializer
7782     TVariable* variable = symbol->getAsVariable();
7783     if (variable == nullptr) {
7784         error(loc, "initializer requires a variable, not a member", identifier.c_str(), "");
7785         return nullptr;
7786     }
7787     return executeInitializer(loc, initializer, variable);
7788 }
7789
7790 // Pick up global defaults from the provide global defaults into dst.
7791 void HlslParseContext::inheritGlobalDefaults(TQualifier& dst) const
7792 {
7793     if (dst.storage == EvqVaryingOut) {
7794         if (! dst.hasStream() && language == EShLangGeometry)
7795             dst.layoutStream = globalOutputDefaults.layoutStream;
7796         if (! dst.hasXfbBuffer())
7797             dst.layoutXfbBuffer = globalOutputDefaults.layoutXfbBuffer;
7798     }
7799 }
7800
7801 //
7802 // Make an internal-only variable whose name is for debug purposes only
7803 // and won't be searched for.  Callers will only use the return value to use
7804 // the variable, not the name to look it up.  It is okay if the name
7805 // is the same as other names; there won't be any conflict.
7806 //
7807 TVariable* HlslParseContext::makeInternalVariable(const char* name, const TType& type) const
7808 {
7809     TString* nameString = NewPoolTString(name);
7810     TVariable* variable = new TVariable(nameString, type);
7811     symbolTable.makeInternalVariable(*variable);
7812
7813     return variable;
7814 }
7815
7816 // Make a symbol node holding a new internal temporary variable.
7817 TIntermSymbol* HlslParseContext::makeInternalVariableNode(const TSourceLoc& loc, const char* name,
7818                                                           const TType& type) const
7819 {
7820     TVariable* tmpVar = makeInternalVariable(name, type);
7821     tmpVar->getWritableType().getQualifier().makeTemporary();
7822
7823     return intermediate.addSymbol(*tmpVar, loc);
7824 }
7825
7826 //
7827 // Declare a non-array variable, the main point being there is no redeclaration
7828 // for resizing allowed.
7829 //
7830 // Return the successfully declared variable.
7831 //
7832 TVariable* HlslParseContext::declareNonArray(const TSourceLoc& loc, const TString& identifier, const TType& type,
7833                                              bool track)
7834 {
7835     // make a new variable
7836     TVariable* variable = new TVariable(&identifier, type);
7837
7838     // add variable to symbol table
7839     if (symbolTable.insert(*variable)) {
7840         if (track && symbolTable.atGlobalLevel())
7841             trackLinkage(*variable);
7842         return variable;
7843     }
7844
7845     error(loc, "redefinition", variable->getName().c_str(), "");
7846     return nullptr;
7847 }
7848
7849 //
7850 // Handle all types of initializers from the grammar.
7851 //
7852 // Returning nullptr just means there is no code to execute to handle the
7853 // initializer, which will, for example, be the case for constant initializers.
7854 //
7855 // Returns a subtree that accomplished the initialization.
7856 //
7857 TIntermNode* HlslParseContext::executeInitializer(const TSourceLoc& loc, TIntermTyped* initializer, TVariable* variable)
7858 {
7859     //
7860     // Identifier must be of type constant, a global, or a temporary, and
7861     // starting at version 120, desktop allows uniforms to have initializers.
7862     //
7863     TStorageQualifier qualifier = variable->getType().getQualifier().storage;
7864
7865     //
7866     // If the initializer was from braces { ... }, we convert the whole subtree to a
7867     // constructor-style subtree, allowing the rest of the code to operate
7868     // identically for both kinds of initializers.
7869     //
7870     //
7871     // Type can't be deduced from the initializer list, so a skeletal type to
7872     // follow has to be passed in.  Constness and specialization-constness
7873     // should be deduced bottom up, not dictated by the skeletal type.
7874     //
7875     TType skeletalType;
7876     skeletalType.shallowCopy(variable->getType());
7877     skeletalType.getQualifier().makeTemporary();
7878     if (initializer->getAsAggregate() && initializer->getAsAggregate()->getOp() == EOpNull)
7879         initializer = convertInitializerList(loc, skeletalType, initializer, nullptr);
7880     if (initializer == nullptr) {
7881         // error recovery; don't leave const without constant values
7882         if (qualifier == EvqConst)
7883             variable->getWritableType().getQualifier().storage = EvqTemporary;
7884         return nullptr;
7885     }
7886
7887     // Fix outer arrayness if variable is unsized, getting size from the initializer
7888     if (initializer->getType().isSizedArray() && variable->getType().isUnsizedArray())
7889         variable->getWritableType().changeOuterArraySize(initializer->getType().getOuterArraySize());
7890
7891     // Inner arrayness can also get set by an initializer
7892     if (initializer->getType().isArrayOfArrays() && variable->getType().isArrayOfArrays() &&
7893         initializer->getType().getArraySizes()->getNumDims() ==
7894         variable->getType().getArraySizes()->getNumDims()) {
7895         // adopt unsized sizes from the initializer's sizes
7896         for (int d = 1; d < variable->getType().getArraySizes()->getNumDims(); ++d) {
7897             if (variable->getType().getArraySizes()->getDimSize(d) == UnsizedArraySize) {
7898                 variable->getWritableType().getArraySizes()->setDimSize(d,
7899                     initializer->getType().getArraySizes()->getDimSize(d));
7900             }
7901         }
7902     }
7903
7904     // Uniform and global consts require a constant initializer
7905     if (qualifier == EvqUniform && initializer->getType().getQualifier().storage != EvqConst) {
7906         error(loc, "uniform initializers must be constant", "=", "'%s'", variable->getType().getCompleteString().c_str());
7907         variable->getWritableType().getQualifier().storage = EvqTemporary;
7908         return nullptr;
7909     }
7910
7911     // Const variables require a constant initializer
7912     if (qualifier == EvqConst) {
7913         if (initializer->getType().getQualifier().storage != EvqConst) {
7914             variable->getWritableType().getQualifier().storage = EvqConstReadOnly;
7915             qualifier = EvqConstReadOnly;
7916         }
7917     }
7918
7919     if (qualifier == EvqConst || qualifier == EvqUniform) {
7920         // Compile-time tagging of the variable with its constant value...
7921
7922         initializer = intermediate.addConversion(EOpAssign, variable->getType(), initializer);
7923         if (initializer != nullptr && variable->getType() != initializer->getType())
7924             initializer = intermediate.addUniShapeConversion(EOpAssign, variable->getType(), initializer);
7925         if (initializer == nullptr || !initializer->getAsConstantUnion() ||
7926                                       variable->getType() != initializer->getType()) {
7927             error(loc, "non-matching or non-convertible constant type for const initializer",
7928                 variable->getType().getStorageQualifierString(), "");
7929             variable->getWritableType().getQualifier().storage = EvqTemporary;
7930             return nullptr;
7931         }
7932
7933         variable->setConstArray(initializer->getAsConstantUnion()->getConstArray());
7934     } else {
7935         // normal assigning of a value to a variable...
7936         specializationCheck(loc, initializer->getType(), "initializer");
7937         TIntermSymbol* intermSymbol = intermediate.addSymbol(*variable, loc);
7938         TIntermNode* initNode = handleAssign(loc, EOpAssign, intermSymbol, initializer);
7939         if (initNode == nullptr)
7940             assignError(loc, "=", intermSymbol->getCompleteString(), initializer->getCompleteString());
7941         return initNode;
7942     }
7943
7944     return nullptr;
7945 }
7946
7947 //
7948 // Reprocess any initializer-list { ... } parts of the initializer.
7949 // Need to hierarchically assign correct types and implicit
7950 // conversions. Will do this mimicking the same process used for
7951 // creating a constructor-style initializer, ensuring we get the
7952 // same form.
7953 //
7954 // Returns a node representing an expression for the initializer list expressed
7955 // as the correct type.
7956 //
7957 // Returns nullptr if there is an error.
7958 //
7959 TIntermTyped* HlslParseContext::convertInitializerList(const TSourceLoc& loc, const TType& type,
7960                                                        TIntermTyped* initializer, TIntermTyped* scalarInit)
7961 {
7962     // Will operate recursively.  Once a subtree is found that is constructor style,
7963     // everything below it is already good: Only the "top part" of the initializer
7964     // can be an initializer list, where "top part" can extend for several (or all) levels.
7965
7966     // see if we have bottomed out in the tree within the initializer-list part
7967     TIntermAggregate* initList = initializer->getAsAggregate();
7968     if (initList == nullptr || initList->getOp() != EOpNull) {
7969         // We don't have a list, but if it's a scalar and the 'type' is a
7970         // composite, we need to lengthen below to make it useful.
7971         // Otherwise, this is an already formed object to initialize with.
7972         if (type.isScalar() || !initializer->getType().isScalar())
7973             return initializer;
7974         else
7975             initList = intermediate.makeAggregate(initializer);
7976     }
7977
7978     // Of the initializer-list set of nodes, need to process bottom up,
7979     // so recurse deep, then process on the way up.
7980
7981     // Go down the tree here...
7982     if (type.isArray()) {
7983         // The type's array might be unsized, which could be okay, so base sizes on the size of the aggregate.
7984         // Later on, initializer execution code will deal with array size logic.
7985         TType arrayType;
7986         arrayType.shallowCopy(type);                     // sharing struct stuff is fine
7987         arrayType.copyArraySizes(*type.getArraySizes()); // but get a fresh copy of the array information, to edit below
7988
7989         // edit array sizes to fill in unsized dimensions
7990         if (type.isUnsizedArray())
7991             arrayType.changeOuterArraySize((int)initList->getSequence().size());
7992
7993         // set unsized array dimensions that can be derived from the initializer's first element
7994         if (arrayType.isArrayOfArrays() && initList->getSequence().size() > 0) {
7995             TIntermTyped* firstInit = initList->getSequence()[0]->getAsTyped();
7996             if (firstInit->getType().isArray() &&
7997                 arrayType.getArraySizes()->getNumDims() == firstInit->getType().getArraySizes()->getNumDims() + 1) {
7998                 for (int d = 1; d < arrayType.getArraySizes()->getNumDims(); ++d) {
7999                     if (arrayType.getArraySizes()->getDimSize(d) == UnsizedArraySize)
8000                         arrayType.getArraySizes()->setDimSize(d, firstInit->getType().getArraySizes()->getDimSize(d - 1));
8001                 }
8002             }
8003         }
8004
8005         // lengthen list to be long enough
8006         lengthenList(loc, initList->getSequence(), arrayType.getOuterArraySize(), scalarInit);
8007
8008         // recursively process each element
8009         TType elementType(arrayType, 0); // dereferenced type
8010         for (int i = 0; i < arrayType.getOuterArraySize(); ++i) {
8011             initList->getSequence()[i] = convertInitializerList(loc, elementType,
8012                                                                 initList->getSequence()[i]->getAsTyped(), scalarInit);
8013             if (initList->getSequence()[i] == nullptr)
8014                 return nullptr;
8015         }
8016
8017         return addConstructor(loc, initList, arrayType);
8018     } else if (type.isStruct()) {
8019         // do we have implicit assignments to opaques?
8020         for (size_t i = initList->getSequence().size(); i < type.getStruct()->size(); ++i) {
8021             if ((*type.getStruct())[i].type->containsOpaque()) {
8022                 error(loc, "cannot implicitly initialize opaque members", "initializer list", "");
8023                 return nullptr;
8024             }
8025         }
8026
8027         // lengthen list to be long enough
8028         lengthenList(loc, initList->getSequence(), static_cast<int>(type.getStruct()->size()), scalarInit);
8029
8030         if (type.getStruct()->size() != initList->getSequence().size()) {
8031             error(loc, "wrong number of structure members", "initializer list", "");
8032             return nullptr;
8033         }
8034         for (size_t i = 0; i < type.getStruct()->size(); ++i) {
8035             initList->getSequence()[i] = convertInitializerList(loc, *(*type.getStruct())[i].type,
8036                                                                 initList->getSequence()[i]->getAsTyped(), scalarInit);
8037             if (initList->getSequence()[i] == nullptr)
8038                 return nullptr;
8039         }
8040     } else if (type.isMatrix()) {
8041         if (type.computeNumComponents() == (int)initList->getSequence().size()) {
8042             // This means the matrix is initialized component-wise, rather than as
8043             // a series of rows and columns.  We can just use the list directly as
8044             // a constructor; no further processing needed.
8045         } else {
8046             // lengthen list to be long enough
8047             lengthenList(loc, initList->getSequence(), type.getMatrixCols(), scalarInit);
8048
8049             if (type.getMatrixCols() != (int)initList->getSequence().size()) {
8050                 error(loc, "wrong number of matrix columns:", "initializer list", type.getCompleteString().c_str());
8051                 return nullptr;
8052             }
8053             TType vectorType(type, 0); // dereferenced type
8054             for (int i = 0; i < type.getMatrixCols(); ++i) {
8055                 initList->getSequence()[i] = convertInitializerList(loc, vectorType,
8056                                                                     initList->getSequence()[i]->getAsTyped(), scalarInit);
8057                 if (initList->getSequence()[i] == nullptr)
8058                     return nullptr;
8059             }
8060         }
8061     } else if (type.isVector()) {
8062         // lengthen list to be long enough
8063         lengthenList(loc, initList->getSequence(), type.getVectorSize(), scalarInit);
8064
8065         // error check; we're at bottom, so work is finished below
8066         if (type.getVectorSize() != (int)initList->getSequence().size()) {
8067             error(loc, "wrong vector size (or rows in a matrix column):", "initializer list",
8068                   type.getCompleteString().c_str());
8069             return nullptr;
8070         }
8071     } else if (type.isScalar()) {
8072         // lengthen list to be long enough
8073         lengthenList(loc, initList->getSequence(), 1, scalarInit);
8074
8075         if ((int)initList->getSequence().size() != 1) {
8076             error(loc, "scalar expected one element:", "initializer list", type.getCompleteString().c_str());
8077             return nullptr;
8078         }
8079     } else {
8080         error(loc, "unexpected initializer-list type:", "initializer list", type.getCompleteString().c_str());
8081         return nullptr;
8082     }
8083
8084     // Now that the subtree is processed, process this node as if the
8085     // initializer list is a set of arguments to a constructor.
8086     TIntermTyped* emulatedConstructorArguments;
8087     if (initList->getSequence().size() == 1)
8088         emulatedConstructorArguments = initList->getSequence()[0]->getAsTyped();
8089     else
8090         emulatedConstructorArguments = initList;
8091
8092     return addConstructor(loc, emulatedConstructorArguments, type);
8093 }
8094
8095 // Lengthen list to be long enough to cover any gap from the current list size
8096 // to 'size'. If the list is longer, do nothing.
8097 // The value to lengthen with is the default for short lists.
8098 //
8099 // By default, lists that are too short due to lack of initializers initialize to zero.
8100 // Alternatively, it could be a scalar initializer for a structure. Both cases are handled,
8101 // based on whether something is passed in as 'scalarInit'.
8102 //
8103 // 'scalarInit' must be safe to use each time this is called (no side effects replication).
8104 //
8105 void HlslParseContext::lengthenList(const TSourceLoc& loc, TIntermSequence& list, int size, TIntermTyped* scalarInit)
8106 {
8107     for (int c = (int)list.size(); c < size; ++c) {
8108         if (scalarInit == nullptr)
8109             list.push_back(intermediate.addConstantUnion(0, loc));
8110         else
8111             list.push_back(scalarInit);
8112     }
8113 }
8114
8115 //
8116 // Test for the correctness of the parameters passed to various constructor functions
8117 // and also convert them to the right data type, if allowed and required.
8118 //
8119 // Returns nullptr for an error or the constructed node (aggregate or typed) for no error.
8120 //
8121 TIntermTyped* HlslParseContext::handleConstructor(const TSourceLoc& loc, TIntermTyped* node, const TType& type)
8122 {
8123     if (node == nullptr)
8124         return nullptr;
8125
8126     // Construct identical type
8127     if (type == node->getType())
8128         return node;
8129
8130     // Handle the idiom "(struct type)<scalar value>"
8131     if (type.isStruct() && isScalarConstructor(node)) {
8132         // 'node' will almost always get used multiple times, so should not be used directly,
8133         // it would create a DAG instead of a tree, which might be okay (would
8134         // like to formalize that for constants and symbols), but if it has
8135         // side effects, they would get executed multiple times, which is not okay.
8136         if (node->getAsConstantUnion() == nullptr && node->getAsSymbolNode() == nullptr) {
8137             TIntermAggregate* seq = intermediate.makeAggregate(loc);
8138             TIntermSymbol* copy = makeInternalVariableNode(loc, "scalarCopy", node->getType());
8139             seq = intermediate.growAggregate(seq, intermediate.addBinaryNode(EOpAssign, copy, node, loc));
8140             seq = intermediate.growAggregate(seq, convertInitializerList(loc, type, intermediate.makeAggregate(loc), copy));
8141             seq->setOp(EOpComma);
8142             seq->setType(type);
8143             return seq;
8144         } else
8145             return convertInitializerList(loc, type, intermediate.makeAggregate(loc), node);
8146     }
8147
8148     return addConstructor(loc, node, type);
8149 }
8150
8151 // Add a constructor, either from the grammar, or other programmatic reasons.
8152 //
8153 // 'node' is what to construct from.
8154 // 'type' is what type to construct.
8155 //
8156 // Returns the constructed object.
8157 // Return nullptr if it can't be done.
8158 //
8159 TIntermTyped* HlslParseContext::addConstructor(const TSourceLoc& loc, TIntermTyped* node, const TType& type)
8160 {
8161     TIntermAggregate* aggrNode = node->getAsAggregate();
8162     TOperator op = intermediate.mapTypeToConstructorOp(type);
8163
8164     if (op == EOpConstructTextureSampler)
8165         return intermediate.setAggregateOperator(aggrNode, op, type, loc);
8166
8167     TTypeList::const_iterator memberTypes;
8168     if (op == EOpConstructStruct)
8169         memberTypes = type.getStruct()->begin();
8170
8171     TType elementType;
8172     if (type.isArray()) {
8173         TType dereferenced(type, 0);
8174         elementType.shallowCopy(dereferenced);
8175     } else
8176         elementType.shallowCopy(type);
8177
8178     bool singleArg;
8179     if (aggrNode != nullptr) {
8180         if (aggrNode->getOp() != EOpNull)
8181             singleArg = true;
8182         else
8183             singleArg = false;
8184     } else
8185         singleArg = true;
8186
8187     TIntermTyped *newNode;
8188     if (singleArg) {
8189         // Handle array -> array conversion
8190         // Constructing an array of one type from an array of another type is allowed,
8191         // assuming there are enough components available (semantic-checked earlier).
8192         if (type.isArray() && node->isArray())
8193             newNode = convertArray(node, type);
8194
8195         // If structure constructor or array constructor is being called
8196         // for only one parameter inside the aggregate, we need to call constructAggregate function once.
8197         else if (type.isArray())
8198             newNode = constructAggregate(node, elementType, 1, node->getLoc());
8199         else if (op == EOpConstructStruct)
8200             newNode = constructAggregate(node, *(*memberTypes).type, 1, node->getLoc());
8201         else {
8202             // shape conversion for matrix constructor from scalar.  HLSL semantics are: scalar
8203             // is replicated into every element of the matrix (not just the diagnonal), so
8204             // that is handled specially here.
8205             if (type.isMatrix() && node->getType().isScalarOrVec1())
8206                 node = intermediate.addShapeConversion(type, node);
8207
8208             newNode = constructBuiltIn(type, op, node, node->getLoc(), false);
8209         }
8210
8211         if (newNode && (type.isArray() || op == EOpConstructStruct))
8212             newNode = intermediate.setAggregateOperator(newNode, EOpConstructStruct, type, loc);
8213
8214         return newNode;
8215     }
8216
8217     //
8218     // Handle list of arguments.
8219     //
8220     TIntermSequence& sequenceVector = aggrNode->getSequence();    // Stores the information about the parameter to the constructor
8221     // if the structure constructor contains more than one parameter, then construct
8222     // each parameter
8223
8224     int paramCount = 0;  // keeps a track of the constructor parameter number being checked
8225
8226     // for each parameter to the constructor call, check to see if the right type is passed or convert them
8227     // to the right type if possible (and allowed).
8228     // for structure constructors, just check if the right type is passed, no conversion is allowed.
8229
8230     for (TIntermSequence::iterator p = sequenceVector.begin();
8231         p != sequenceVector.end(); p++, paramCount++) {
8232         if (type.isArray())
8233             newNode = constructAggregate(*p, elementType, paramCount + 1, node->getLoc());
8234         else if (op == EOpConstructStruct)
8235             newNode = constructAggregate(*p, *(memberTypes[paramCount]).type, paramCount + 1, node->getLoc());
8236         else
8237             newNode = constructBuiltIn(type, op, (*p)->getAsTyped(), node->getLoc(), true);
8238
8239         if (newNode)
8240             *p = newNode;
8241         else
8242             return nullptr;
8243     }
8244
8245     TIntermTyped* constructor = intermediate.setAggregateOperator(aggrNode, op, type, loc);
8246
8247     return constructor;
8248 }
8249
8250 // Function for constructor implementation. Calls addUnaryMath with appropriate EOp value
8251 // for the parameter to the constructor (passed to this function). Essentially, it converts
8252 // the parameter types correctly. If a constructor expects an int (like ivec2) and is passed a
8253 // float, then float is converted to int.
8254 //
8255 // Returns nullptr for an error or the constructed node.
8256 //
8257 TIntermTyped* HlslParseContext::constructBuiltIn(const TType& type, TOperator op, TIntermTyped* node,
8258                                                  const TSourceLoc& loc, bool subset)
8259 {
8260     TIntermTyped* newNode;
8261     TOperator basicOp;
8262
8263     //
8264     // First, convert types as needed.
8265     //
8266     switch (op) {
8267     case EOpConstructF16Vec2:
8268     case EOpConstructF16Vec3:
8269     case EOpConstructF16Vec4:
8270     case EOpConstructF16Mat2x2:
8271     case EOpConstructF16Mat2x3:
8272     case EOpConstructF16Mat2x4:
8273     case EOpConstructF16Mat3x2:
8274     case EOpConstructF16Mat3x3:
8275     case EOpConstructF16Mat3x4:
8276     case EOpConstructF16Mat4x2:
8277     case EOpConstructF16Mat4x3:
8278     case EOpConstructF16Mat4x4:
8279     case EOpConstructFloat16:
8280         basicOp = EOpConstructFloat16;
8281         break;
8282
8283     case EOpConstructVec2:
8284     case EOpConstructVec3:
8285     case EOpConstructVec4:
8286     case EOpConstructMat2x2:
8287     case EOpConstructMat2x3:
8288     case EOpConstructMat2x4:
8289     case EOpConstructMat3x2:
8290     case EOpConstructMat3x3:
8291     case EOpConstructMat3x4:
8292     case EOpConstructMat4x2:
8293     case EOpConstructMat4x3:
8294     case EOpConstructMat4x4:
8295     case EOpConstructFloat:
8296         basicOp = EOpConstructFloat;
8297         break;
8298
8299     case EOpConstructDVec2:
8300     case EOpConstructDVec3:
8301     case EOpConstructDVec4:
8302     case EOpConstructDMat2x2:
8303     case EOpConstructDMat2x3:
8304     case EOpConstructDMat2x4:
8305     case EOpConstructDMat3x2:
8306     case EOpConstructDMat3x3:
8307     case EOpConstructDMat3x4:
8308     case EOpConstructDMat4x2:
8309     case EOpConstructDMat4x3:
8310     case EOpConstructDMat4x4:
8311     case EOpConstructDouble:
8312         basicOp = EOpConstructDouble;
8313         break;
8314
8315     case EOpConstructI16Vec2:
8316     case EOpConstructI16Vec3:
8317     case EOpConstructI16Vec4:
8318     case EOpConstructInt16:
8319         basicOp = EOpConstructInt16;
8320         break;
8321
8322     case EOpConstructIVec2:
8323     case EOpConstructIVec3:
8324     case EOpConstructIVec4:
8325     case EOpConstructIMat2x2:
8326     case EOpConstructIMat2x3:
8327     case EOpConstructIMat2x4:
8328     case EOpConstructIMat3x2:
8329     case EOpConstructIMat3x3:
8330     case EOpConstructIMat3x4:
8331     case EOpConstructIMat4x2:
8332     case EOpConstructIMat4x3:
8333     case EOpConstructIMat4x4:
8334     case EOpConstructInt:
8335         basicOp = EOpConstructInt;
8336         break;
8337
8338     case EOpConstructU16Vec2:
8339     case EOpConstructU16Vec3:
8340     case EOpConstructU16Vec4:
8341     case EOpConstructUint16:
8342         basicOp = EOpConstructUint16;
8343         break;
8344
8345     case EOpConstructUVec2:
8346     case EOpConstructUVec3:
8347     case EOpConstructUVec4:
8348     case EOpConstructUMat2x2:
8349     case EOpConstructUMat2x3:
8350     case EOpConstructUMat2x4:
8351     case EOpConstructUMat3x2:
8352     case EOpConstructUMat3x3:
8353     case EOpConstructUMat3x4:
8354     case EOpConstructUMat4x2:
8355     case EOpConstructUMat4x3:
8356     case EOpConstructUMat4x4:
8357     case EOpConstructUint:
8358         basicOp = EOpConstructUint;
8359         break;
8360
8361     case EOpConstructBVec2:
8362     case EOpConstructBVec3:
8363     case EOpConstructBVec4:
8364     case EOpConstructBMat2x2:
8365     case EOpConstructBMat2x3:
8366     case EOpConstructBMat2x4:
8367     case EOpConstructBMat3x2:
8368     case EOpConstructBMat3x3:
8369     case EOpConstructBMat3x4:
8370     case EOpConstructBMat4x2:
8371     case EOpConstructBMat4x3:
8372     case EOpConstructBMat4x4:
8373     case EOpConstructBool:
8374         basicOp = EOpConstructBool;
8375         break;
8376
8377     default:
8378         error(loc, "unsupported construction", "", "");
8379
8380         return nullptr;
8381     }
8382     newNode = intermediate.addUnaryMath(basicOp, node, node->getLoc());
8383     if (newNode == nullptr) {
8384         error(loc, "can't convert", "constructor", "");
8385         return nullptr;
8386     }
8387
8388     //
8389     // Now, if there still isn't an operation to do the construction, and we need one, add one.
8390     //
8391
8392     // Otherwise, skip out early.
8393     if (subset || (newNode != node && newNode->getType() == type))
8394         return newNode;
8395
8396     // setAggregateOperator will insert a new node for the constructor, as needed.
8397     return intermediate.setAggregateOperator(newNode, op, type, loc);
8398 }
8399
8400 // Convert the array in node to the requested type, which is also an array.
8401 // Returns nullptr on failure, otherwise returns aggregate holding the list of
8402 // elements needed to construct the array.
8403 TIntermTyped* HlslParseContext::convertArray(TIntermTyped* node, const TType& type)
8404 {
8405     assert(node->isArray() && type.isArray());
8406     if (node->getType().computeNumComponents() < type.computeNumComponents())
8407         return nullptr;
8408
8409     // TODO: write an argument replicator, for the case the argument should not be
8410     // executed multiple times, yet multiple copies are needed.
8411
8412     TIntermTyped* constructee = node->getAsTyped();
8413     // track where we are in consuming the argument
8414     int constructeeElement = 0;
8415     int constructeeComponent = 0;
8416
8417     // bump up to the next component to consume
8418     const auto getNextComponent = [&]() {
8419         TIntermTyped* component;
8420         component = handleBracketDereference(node->getLoc(), constructee, 
8421                                              intermediate.addConstantUnion(constructeeElement, node->getLoc()));
8422         if (component->isVector())
8423             component = handleBracketDereference(node->getLoc(), component,
8424                                                  intermediate.addConstantUnion(constructeeComponent, node->getLoc()));
8425         // bump component pointer up
8426         ++constructeeComponent;
8427         if (constructeeComponent == constructee->getVectorSize()) {
8428             constructeeComponent = 0;
8429             ++constructeeElement;
8430         }
8431         return component;
8432     };
8433
8434     // make one subnode per constructed array element
8435     TIntermAggregate* constructor = nullptr;
8436     TType derefType(type, 0);
8437     TType speculativeComponentType(derefType, 0);
8438     TType* componentType = derefType.isVector() ? &speculativeComponentType : &derefType;
8439     TOperator componentOp = intermediate.mapTypeToConstructorOp(*componentType);
8440     TType crossType(node->getBasicType(), EvqTemporary, type.getVectorSize());
8441     for (int e = 0; e < type.getOuterArraySize(); ++e) {
8442         // construct an element
8443         TIntermTyped* elementArg;
8444         if (type.getVectorSize() == constructee->getVectorSize()) {
8445             // same element shape
8446             elementArg = handleBracketDereference(node->getLoc(), constructee,
8447                                                   intermediate.addConstantUnion(e, node->getLoc()));
8448         } else {
8449             // mismatched element shapes
8450             if (type.getVectorSize() == 1)
8451                 elementArg = getNextComponent();
8452             else {
8453                 // make a vector
8454                 TIntermAggregate* elementConstructee = nullptr;
8455                 for (int c = 0; c < type.getVectorSize(); ++c)
8456                     elementConstructee = intermediate.growAggregate(elementConstructee, getNextComponent());
8457                 elementArg = addConstructor(node->getLoc(), elementConstructee, crossType);
8458             }
8459         }
8460         // convert basic types
8461         elementArg = intermediate.addConversion(componentOp, derefType, elementArg);
8462         if (elementArg == nullptr)
8463             return nullptr;
8464         // combine with top-level constructor
8465         constructor = intermediate.growAggregate(constructor, elementArg);
8466     }
8467
8468     return constructor;
8469 }
8470
8471 // This function tests for the type of the parameters to the structure or array constructor. Raises
8472 // an error message if the expected type does not match the parameter passed to the constructor.
8473 //
8474 // Returns nullptr for an error or the input node itself if the expected and the given parameter types match.
8475 //
8476 TIntermTyped* HlslParseContext::constructAggregate(TIntermNode* node, const TType& type, int paramCount,
8477                                                    const TSourceLoc& loc)
8478 {
8479     // Handle cases that map more 1:1 between constructor arguments and constructed.
8480     TIntermTyped* converted = intermediate.addConversion(EOpConstructStruct, type, node->getAsTyped());
8481     if (converted == nullptr || converted->getType() != type) {
8482         error(loc, "", "constructor", "cannot convert parameter %d from '%s' to '%s'", paramCount,
8483             node->getAsTyped()->getType().getCompleteString().c_str(), type.getCompleteString().c_str());
8484
8485         return nullptr;
8486     }
8487
8488     return converted;
8489 }
8490
8491 //
8492 // Do everything needed to add an interface block.
8493 //
8494 void HlslParseContext::declareBlock(const TSourceLoc& loc, TType& type, const TString* instanceName)
8495 {
8496     assert(type.getWritableStruct() != nullptr);
8497
8498     // Clean up top-level decorations that don't belong.
8499     switch (type.getQualifier().storage) {
8500     case EvqUniform:
8501     case EvqBuffer:
8502         correctUniform(type.getQualifier());
8503         break;
8504     case EvqVaryingIn:
8505         correctInput(type.getQualifier());
8506         break;
8507     case EvqVaryingOut:
8508         correctOutput(type.getQualifier());
8509         break;
8510     default:
8511         break;
8512     }
8513
8514     TTypeList& typeList = *type.getWritableStruct();
8515     // fix and check for member storage qualifiers and types that don't belong within a block
8516     for (unsigned int member = 0; member < typeList.size(); ++member) {
8517         TType& memberType = *typeList[member].type;
8518         TQualifier& memberQualifier = memberType.getQualifier();
8519         const TSourceLoc& memberLoc = typeList[member].loc;
8520         globalQualifierFix(memberLoc, memberQualifier);
8521         memberQualifier.storage = type.getQualifier().storage;
8522
8523         if (memberType.isStruct()) {
8524             // clean up and pick up the right set of decorations
8525             auto it = ioTypeMap.find(memberType.getStruct());
8526             switch (type.getQualifier().storage) {
8527             case EvqUniform:
8528             case EvqBuffer:
8529                 correctUniform(type.getQualifier());
8530                 if (it != ioTypeMap.end() && it->second.uniform)
8531                     memberType.setStruct(it->second.uniform);
8532                 break;
8533             case EvqVaryingIn:
8534                 correctInput(type.getQualifier());
8535                 if (it != ioTypeMap.end() && it->second.input)
8536                     memberType.setStruct(it->second.input);
8537                 break;
8538             case EvqVaryingOut:
8539                 correctOutput(type.getQualifier());
8540                 if (it != ioTypeMap.end() && it->second.output)
8541                     memberType.setStruct(it->second.output);
8542                 break;
8543             default:
8544                 break;
8545             }
8546         }
8547     }
8548
8549     // Make default block qualification, and adjust the member qualifications
8550
8551     TQualifier defaultQualification;
8552     switch (type.getQualifier().storage) {
8553     case EvqUniform:    defaultQualification = globalUniformDefaults;    break;
8554     case EvqBuffer:     defaultQualification = globalBufferDefaults;     break;
8555     case EvqVaryingIn:  defaultQualification = globalInputDefaults;      break;
8556     case EvqVaryingOut: defaultQualification = globalOutputDefaults;     break;
8557     default:            defaultQualification.clear();                    break;
8558     }
8559
8560     // Special case for "push_constant uniform", which has a default of std430,
8561     // contrary to normal uniform defaults, and can't have a default tracked for it.
8562     if (type.getQualifier().layoutPushConstant && ! type.getQualifier().hasPacking())
8563         type.getQualifier().layoutPacking = ElpStd430;
8564
8565     // fix and check for member layout qualifiers
8566
8567     mergeObjectLayoutQualifiers(defaultQualification, type.getQualifier(), true);
8568
8569     bool memberWithLocation = false;
8570     bool memberWithoutLocation = false;
8571     for (unsigned int member = 0; member < typeList.size(); ++member) {
8572         TQualifier& memberQualifier = typeList[member].type->getQualifier();
8573         const TSourceLoc& memberLoc = typeList[member].loc;
8574         if (memberQualifier.hasStream()) {
8575             if (defaultQualification.layoutStream != memberQualifier.layoutStream)
8576                 error(memberLoc, "member cannot contradict block", "stream", "");
8577         }
8578
8579         // "This includes a block's inheritance of the
8580         // current global default buffer, a block member's inheritance of the block's
8581         // buffer, and the requirement that any *xfb_buffer* declared on a block
8582         // member must match the buffer inherited from the block."
8583         if (memberQualifier.hasXfbBuffer()) {
8584             if (defaultQualification.layoutXfbBuffer != memberQualifier.layoutXfbBuffer)
8585                 error(memberLoc, "member cannot contradict block (or what block inherited from global)", "xfb_buffer", "");
8586         }
8587
8588         if (memberQualifier.hasLocation()) {
8589             switch (type.getQualifier().storage) {
8590             case EvqVaryingIn:
8591             case EvqVaryingOut:
8592                 memberWithLocation = true;
8593                 break;
8594             default:
8595                 break;
8596             }
8597         } else
8598             memberWithoutLocation = true;
8599
8600         TQualifier newMemberQualification = defaultQualification;
8601         mergeQualifiers(newMemberQualification, memberQualifier);
8602         memberQualifier = newMemberQualification;
8603     }
8604
8605     // Process the members
8606     fixBlockLocations(loc, type.getQualifier(), typeList, memberWithLocation, memberWithoutLocation);
8607     fixXfbOffsets(type.getQualifier(), typeList);
8608     fixBlockUniformOffsets(type.getQualifier(), typeList);
8609
8610     // reverse merge, so that currentBlockQualifier now has all layout information
8611     // (can't use defaultQualification directly, it's missing other non-layout-default-class qualifiers)
8612     mergeObjectLayoutQualifiers(type.getQualifier(), defaultQualification, true);
8613
8614     //
8615     // Build and add the interface block as a new type named 'blockName'
8616     //
8617
8618     // Use the instance name as the interface name if one exists, else the block name.
8619     const TString& interfaceName = (instanceName && !instanceName->empty()) ? *instanceName : type.getTypeName();
8620
8621     TType blockType(&typeList, interfaceName, type.getQualifier());
8622     if (type.isArray())
8623         blockType.transferArraySizes(type.getArraySizes());
8624
8625     // Add the variable, as anonymous or named instanceName.
8626     // Make an anonymous variable if no name was provided.
8627     if (instanceName == nullptr)
8628         instanceName = NewPoolTString("");
8629
8630     TVariable& variable = *new TVariable(instanceName, blockType);
8631     if (! symbolTable.insert(variable)) {
8632         if (*instanceName == "")
8633             error(loc, "nameless block contains a member that already has a name at global scope",
8634                   "" /* blockName->c_str() */, "");
8635         else
8636             error(loc, "block instance name redefinition", variable.getName().c_str(), "");
8637
8638         return;
8639     }
8640
8641     // Save it in the AST for linker use.
8642     if (symbolTable.atGlobalLevel())
8643         trackLinkage(variable);
8644 }
8645
8646 //
8647 // "For a block, this process applies to the entire block, or until the first member
8648 // is reached that has a location layout qualifier. When a block member is declared with a location
8649 // qualifier, its location comes from that qualifier: The member's location qualifier overrides the block-level
8650 // declaration. Subsequent members are again assigned consecutive locations, based on the newest location,
8651 // until the next member declared with a location qualifier. The values used for locations do not have to be
8652 // declared in increasing order."
8653 void HlslParseContext::fixBlockLocations(const TSourceLoc& loc, TQualifier& qualifier, TTypeList& typeList, bool memberWithLocation, bool memberWithoutLocation)
8654 {
8655     // "If a block has no block-level location layout qualifier, it is required that either all or none of its members
8656     // have a location layout qualifier, or a compile-time error results."
8657     if (! qualifier.hasLocation() && memberWithLocation && memberWithoutLocation)
8658         error(loc, "either the block needs a location, or all members need a location, or no members have a location", "location", "");
8659     else {
8660         if (memberWithLocation) {
8661             // remove any block-level location and make it per *every* member
8662             int nextLocation = 0;  // by the rule above, initial value is not relevant
8663             if (qualifier.hasAnyLocation()) {
8664                 nextLocation = qualifier.layoutLocation;
8665                 qualifier.layoutLocation = TQualifier::layoutLocationEnd;
8666                 if (qualifier.hasComponent()) {
8667                     // "It is a compile-time error to apply the *component* qualifier to a ... block"
8668                     error(loc, "cannot apply to a block", "component", "");
8669                 }
8670                 if (qualifier.hasIndex()) {
8671                     error(loc, "cannot apply to a block", "index", "");
8672                 }
8673             }
8674             for (unsigned int member = 0; member < typeList.size(); ++member) {
8675                 TQualifier& memberQualifier = typeList[member].type->getQualifier();
8676                 const TSourceLoc& memberLoc = typeList[member].loc;
8677                 if (! memberQualifier.hasLocation()) {
8678                     if (nextLocation >= (int)TQualifier::layoutLocationEnd)
8679                         error(memberLoc, "location is too large", "location", "");
8680                     memberQualifier.layoutLocation = nextLocation;
8681                     memberQualifier.layoutComponent = 0;
8682                 }
8683                 nextLocation = memberQualifier.layoutLocation +
8684                                intermediate.computeTypeLocationSize(*typeList[member].type, language);
8685             }
8686         }
8687     }
8688 }
8689
8690 void HlslParseContext::fixXfbOffsets(TQualifier& qualifier, TTypeList& typeList)
8691 {
8692     // "If a block is qualified with xfb_offset, all its
8693     // members are assigned transform feedback buffer offsets. If a block is not qualified with xfb_offset, any
8694     // members of that block not qualified with an xfb_offset will not be assigned transform feedback buffer
8695     // offsets."
8696
8697     if (! qualifier.hasXfbBuffer() || ! qualifier.hasXfbOffset())
8698         return;
8699
8700     int nextOffset = qualifier.layoutXfbOffset;
8701     for (unsigned int member = 0; member < typeList.size(); ++member) {
8702         TQualifier& memberQualifier = typeList[member].type->getQualifier();
8703         bool contains64BitType = false;
8704         int memberSize = intermediate.computeTypeXfbSize(*typeList[member].type, contains64BitType);
8705         // see if we need to auto-assign an offset to this member
8706         if (! memberQualifier.hasXfbOffset()) {
8707             // "if applied to an aggregate containing a double or 64-bit integer, the offset must also be a multiple of 8"
8708             if (contains64BitType)
8709                 RoundToPow2(nextOffset, 8);
8710             memberQualifier.layoutXfbOffset = nextOffset;
8711         } else
8712             nextOffset = memberQualifier.layoutXfbOffset;
8713         nextOffset += memberSize;
8714     }
8715
8716     // The above gave all block members an offset, so we can take it off the block now,
8717     // which will avoid double counting the offset usage.
8718     qualifier.layoutXfbOffset = TQualifier::layoutXfbOffsetEnd;
8719 }
8720
8721 // Calculate and save the offset of each block member, using the recursively
8722 // defined block offset rules and the user-provided offset and align.
8723 //
8724 // Also, compute and save the total size of the block. For the block's size, arrayness
8725 // is not taken into account, as each element is backed by a separate buffer.
8726 //
8727 void HlslParseContext::fixBlockUniformOffsets(const TQualifier& qualifier, TTypeList& typeList)
8728 {
8729     if (! qualifier.isUniformOrBuffer())
8730         return;
8731     if (qualifier.layoutPacking != ElpStd140 && qualifier.layoutPacking != ElpStd430 && qualifier.layoutPacking != ElpScalar)
8732         return;
8733
8734     int offset = 0;
8735     int memberSize;
8736     for (unsigned int member = 0; member < typeList.size(); ++member) {
8737         TQualifier& memberQualifier = typeList[member].type->getQualifier();
8738         const TSourceLoc& memberLoc = typeList[member].loc;
8739
8740         // "When align is applied to an array, it effects only the start of the array, not the array's internal stride."
8741
8742         // modify just the children's view of matrix layout, if there is one for this member
8743         TLayoutMatrix subMatrixLayout = typeList[member].type->getQualifier().layoutMatrix;
8744         int dummyStride;
8745         int memberAlignment = intermediate.getMemberAlignment(*typeList[member].type, memberSize, dummyStride,
8746                                                               qualifier.layoutPacking,
8747                                                               subMatrixLayout != ElmNone
8748                                                                   ? subMatrixLayout == ElmRowMajor
8749                                                                   : qualifier.layoutMatrix == ElmRowMajor);
8750         if (memberQualifier.hasOffset()) {
8751             // "The specified offset must be a multiple
8752             // of the base alignment of the type of the block member it qualifies, or a compile-time error results."
8753             if (! IsMultipleOfPow2(memberQualifier.layoutOffset, memberAlignment))
8754                 error(memberLoc, "must be a multiple of the member's alignment", "offset", "");
8755
8756             // "The offset qualifier forces the qualified member to start at or after the specified
8757             // integral-constant expression, which will be its byte offset from the beginning of the buffer.
8758             // "The actual offset of a member is computed as
8759             // follows: If offset was declared, start with that offset, otherwise start with the next available offset."
8760             offset = std::max(offset, memberQualifier.layoutOffset);
8761         }
8762
8763         // "The actual alignment of a member will be the greater of the specified align alignment and the standard
8764         // (e.g., std140) base alignment for the member's type."
8765         if (memberQualifier.hasAlign())
8766             memberAlignment = std::max(memberAlignment, memberQualifier.layoutAlign);
8767
8768         // "If the resulting offset is not a multiple of the actual alignment,
8769         // increase it to the first offset that is a multiple of
8770         // the actual alignment."
8771         RoundToPow2(offset, memberAlignment);
8772         typeList[member].type->getQualifier().layoutOffset = offset;
8773         offset += memberSize;
8774     }
8775 }
8776
8777 // For an identifier that is already declared, add more qualification to it.
8778 void HlslParseContext::addQualifierToExisting(const TSourceLoc& loc, TQualifier qualifier, const TString& identifier)
8779 {
8780     TSymbol* symbol = symbolTable.find(identifier);
8781     if (symbol == nullptr) {
8782         error(loc, "identifier not previously declared", identifier.c_str(), "");
8783         return;
8784     }
8785     if (symbol->getAsFunction()) {
8786         error(loc, "cannot re-qualify a function name", identifier.c_str(), "");
8787         return;
8788     }
8789
8790     if (qualifier.isAuxiliary() ||
8791         qualifier.isMemory() ||
8792         qualifier.isInterpolation() ||
8793         qualifier.hasLayout() ||
8794         qualifier.storage != EvqTemporary ||
8795         qualifier.precision != EpqNone) {
8796         error(loc, "cannot add storage, auxiliary, memory, interpolation, layout, or precision qualifier to an existing variable", identifier.c_str(), "");
8797         return;
8798     }
8799
8800     // For read-only built-ins, add a new symbol for holding the modified qualifier.
8801     // This will bring up an entire block, if a block type has to be modified (e.g., gl_Position inside a block)
8802     if (symbol->isReadOnly())
8803         symbol = symbolTable.copyUp(symbol);
8804
8805     if (qualifier.invariant) {
8806         if (intermediate.inIoAccessed(identifier))
8807             error(loc, "cannot change qualification after use", "invariant", "");
8808         symbol->getWritableType().getQualifier().invariant = true;
8809     } else if (qualifier.noContraction) {
8810         if (intermediate.inIoAccessed(identifier))
8811             error(loc, "cannot change qualification after use", "precise", "");
8812         symbol->getWritableType().getQualifier().noContraction = true;
8813     } else if (qualifier.specConstant) {
8814         symbol->getWritableType().getQualifier().makeSpecConstant();
8815         if (qualifier.hasSpecConstantId())
8816             symbol->getWritableType().getQualifier().layoutSpecConstantId = qualifier.layoutSpecConstantId;
8817     } else
8818         warn(loc, "unknown requalification", "", "");
8819 }
8820
8821 void HlslParseContext::addQualifierToExisting(const TSourceLoc& loc, TQualifier qualifier, TIdentifierList& identifiers)
8822 {
8823     for (unsigned int i = 0; i < identifiers.size(); ++i)
8824         addQualifierToExisting(loc, qualifier, *identifiers[i]);
8825 }
8826
8827 //
8828 // Update the intermediate for the given input geometry
8829 //
8830 bool HlslParseContext::handleInputGeometry(const TSourceLoc& loc, const TLayoutGeometry& geometry)
8831 {
8832     switch (geometry) {
8833     case ElgPoints:             // fall through
8834     case ElgLines:              // ...
8835     case ElgTriangles:          // ...
8836     case ElgLinesAdjacency:     // ...
8837     case ElgTrianglesAdjacency: // ...
8838         if (! intermediate.setInputPrimitive(geometry)) {
8839             error(loc, "input primitive geometry redefinition", TQualifier::getGeometryString(geometry), "");
8840             return false;
8841         }
8842         break;
8843
8844     default:
8845         error(loc, "cannot apply to 'in'", TQualifier::getGeometryString(geometry), "");
8846         return false;
8847     }
8848
8849     return true;
8850 }
8851
8852 //
8853 // Update the intermediate for the given output geometry
8854 //
8855 bool HlslParseContext::handleOutputGeometry(const TSourceLoc& loc, const TLayoutGeometry& geometry)
8856 {
8857     // If this is not a geometry shader, ignore.  It might be a mixed shader including several stages.
8858     // Since that's an OK situation, return true for success.
8859     if (language != EShLangGeometry)
8860         return true;
8861
8862     switch (geometry) {
8863     case ElgPoints:
8864     case ElgLineStrip:
8865     case ElgTriangleStrip:
8866         if (! intermediate.setOutputPrimitive(geometry)) {
8867             error(loc, "output primitive geometry redefinition", TQualifier::getGeometryString(geometry), "");
8868             return false;
8869         }
8870         break;
8871     default:
8872         error(loc, "cannot apply to 'out'", TQualifier::getGeometryString(geometry), "");
8873         return false;
8874     }
8875
8876     return true;
8877 }
8878
8879 //
8880 // Selection attributes
8881 //
8882 void HlslParseContext::handleSelectionAttributes(const TSourceLoc& loc, TIntermSelection* selection,
8883     const TAttributes& attributes)
8884 {
8885     if (selection == nullptr)
8886         return;
8887
8888     for (auto it = attributes.begin(); it != attributes.end(); ++it) {
8889         switch (it->name) {
8890         case EatFlatten:
8891             selection->setFlatten();
8892             break;
8893         case EatBranch:
8894             selection->setDontFlatten();
8895             break;
8896         default:
8897             warn(loc, "attribute does not apply to a selection", "", "");
8898             break;
8899         }
8900     }
8901 }
8902
8903 //
8904 // Switch attributes
8905 //
8906 void HlslParseContext::handleSwitchAttributes(const TSourceLoc& loc, TIntermSwitch* selection,
8907     const TAttributes& attributes)
8908 {
8909     if (selection == nullptr)
8910         return;
8911
8912     for (auto it = attributes.begin(); it != attributes.end(); ++it) {
8913         switch (it->name) {
8914         case EatFlatten:
8915             selection->setFlatten();
8916             break;
8917         case EatBranch:
8918             selection->setDontFlatten();
8919             break;
8920         default:
8921             warn(loc, "attribute does not apply to a switch", "", "");
8922             break;
8923         }
8924     }
8925 }
8926
8927 //
8928 // Loop attributes
8929 //
8930 void HlslParseContext::handleLoopAttributes(const TSourceLoc& loc, TIntermLoop* loop,
8931     const TAttributes& attributes)
8932 {
8933     if (loop == nullptr)
8934         return;
8935
8936     for (auto it = attributes.begin(); it != attributes.end(); ++it) {
8937         switch (it->name) {
8938         case EatUnroll:
8939             loop->setUnroll();
8940             break;
8941         case EatLoop:
8942             loop->setDontUnroll();
8943             break;
8944         default:
8945             warn(loc, "attribute does not apply to a loop", "", "");
8946             break;
8947         }
8948     }
8949 }
8950
8951 //
8952 // Updating default qualifier for the case of a declaration with just a qualifier,
8953 // no type, block, or identifier.
8954 //
8955 void HlslParseContext::updateStandaloneQualifierDefaults(const TSourceLoc& loc, const TPublicType& publicType)
8956 {
8957     if (publicType.shaderQualifiers.vertices != TQualifier::layoutNotSet) {
8958         assert(language == EShLangTessControl || language == EShLangGeometry);
8959         // const char* id = (language == EShLangTessControl) ? "vertices" : "max_vertices";
8960     }
8961     if (publicType.shaderQualifiers.invocations != TQualifier::layoutNotSet) {
8962         if (! intermediate.setInvocations(publicType.shaderQualifiers.invocations))
8963             error(loc, "cannot change previously set layout value", "invocations", "");
8964     }
8965     if (publicType.shaderQualifiers.geometry != ElgNone) {
8966         if (publicType.qualifier.storage == EvqVaryingIn) {
8967             switch (publicType.shaderQualifiers.geometry) {
8968             case ElgPoints:
8969             case ElgLines:
8970             case ElgLinesAdjacency:
8971             case ElgTriangles:
8972             case ElgTrianglesAdjacency:
8973             case ElgQuads:
8974             case ElgIsolines:
8975                 break;
8976             default:
8977                 error(loc, "cannot apply to input", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry),
8978                       "");
8979             }
8980         } else if (publicType.qualifier.storage == EvqVaryingOut) {
8981             handleOutputGeometry(loc, publicType.shaderQualifiers.geometry);
8982         } else
8983             error(loc, "cannot apply to:", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry),
8984                   GetStorageQualifierString(publicType.qualifier.storage));
8985     }
8986     if (publicType.shaderQualifiers.spacing != EvsNone)
8987         intermediate.setVertexSpacing(publicType.shaderQualifiers.spacing);
8988     if (publicType.shaderQualifiers.order != EvoNone)
8989         intermediate.setVertexOrder(publicType.shaderQualifiers.order);
8990     if (publicType.shaderQualifiers.pointMode)
8991         intermediate.setPointMode();
8992     for (int i = 0; i < 3; ++i) {
8993         if (publicType.shaderQualifiers.localSize[i] > 1) {
8994             int max = 0;
8995             switch (i) {
8996             case 0: max = resources.maxComputeWorkGroupSizeX; break;
8997             case 1: max = resources.maxComputeWorkGroupSizeY; break;
8998             case 2: max = resources.maxComputeWorkGroupSizeZ; break;
8999             default: break;
9000             }
9001             if (intermediate.getLocalSize(i) > (unsigned int)max)
9002                 error(loc, "too large; see gl_MaxComputeWorkGroupSize", "local_size", "");
9003
9004             // Fix the existing constant gl_WorkGroupSize with this new information.
9005             TVariable* workGroupSize = getEditableVariable("gl_WorkGroupSize");
9006             workGroupSize->getWritableConstArray()[i].setUConst(intermediate.getLocalSize(i));
9007         }
9008         if (publicType.shaderQualifiers.localSizeSpecId[i] != TQualifier::layoutNotSet) {
9009             intermediate.setLocalSizeSpecId(i, publicType.shaderQualifiers.localSizeSpecId[i]);
9010             // Set the workgroup built-in variable as a specialization constant
9011             TVariable* workGroupSize = getEditableVariable("gl_WorkGroupSize");
9012             workGroupSize->getWritableType().getQualifier().specConstant = true;
9013         }
9014     }
9015     if (publicType.shaderQualifiers.earlyFragmentTests)
9016         intermediate.setEarlyFragmentTests();
9017
9018     const TQualifier& qualifier = publicType.qualifier;
9019
9020     switch (qualifier.storage) {
9021     case EvqUniform:
9022         if (qualifier.hasMatrix())
9023             globalUniformDefaults.layoutMatrix = qualifier.layoutMatrix;
9024         if (qualifier.hasPacking())
9025             globalUniformDefaults.layoutPacking = qualifier.layoutPacking;
9026         break;
9027     case EvqBuffer:
9028         if (qualifier.hasMatrix())
9029             globalBufferDefaults.layoutMatrix = qualifier.layoutMatrix;
9030         if (qualifier.hasPacking())
9031             globalBufferDefaults.layoutPacking = qualifier.layoutPacking;
9032         break;
9033     case EvqVaryingIn:
9034         break;
9035     case EvqVaryingOut:
9036         if (qualifier.hasStream())
9037             globalOutputDefaults.layoutStream = qualifier.layoutStream;
9038         if (qualifier.hasXfbBuffer())
9039             globalOutputDefaults.layoutXfbBuffer = qualifier.layoutXfbBuffer;
9040         if (globalOutputDefaults.hasXfbBuffer() && qualifier.hasXfbStride()) {
9041             if (! intermediate.setXfbBufferStride(globalOutputDefaults.layoutXfbBuffer, qualifier.layoutXfbStride))
9042                 error(loc, "all stride settings must match for xfb buffer", "xfb_stride", "%d",
9043                       qualifier.layoutXfbBuffer);
9044         }
9045         break;
9046     default:
9047         error(loc, "default qualifier requires 'uniform', 'buffer', 'in', or 'out' storage qualification", "", "");
9048         return;
9049     }
9050 }
9051
9052 //
9053 // Take the sequence of statements that has been built up since the last case/default,
9054 // put it on the list of top-level nodes for the current (inner-most) switch statement,
9055 // and follow that by the case/default we are on now.  (See switch topology comment on
9056 // TIntermSwitch.)
9057 //
9058 void HlslParseContext::wrapupSwitchSubsequence(TIntermAggregate* statements, TIntermNode* branchNode)
9059 {
9060     TIntermSequence* switchSequence = switchSequenceStack.back();
9061
9062     if (statements) {
9063         statements->setOperator(EOpSequence);
9064         switchSequence->push_back(statements);
9065     }
9066     if (branchNode) {
9067         // check all previous cases for the same label (or both are 'default')
9068         for (unsigned int s = 0; s < switchSequence->size(); ++s) {
9069             TIntermBranch* prevBranch = (*switchSequence)[s]->getAsBranchNode();
9070             if (prevBranch) {
9071                 TIntermTyped* prevExpression = prevBranch->getExpression();
9072                 TIntermTyped* newExpression = branchNode->getAsBranchNode()->getExpression();
9073                 if (prevExpression == nullptr && newExpression == nullptr)
9074                     error(branchNode->getLoc(), "duplicate label", "default", "");
9075                 else if (prevExpression != nullptr &&
9076                     newExpression != nullptr &&
9077                     prevExpression->getAsConstantUnion() &&
9078                     newExpression->getAsConstantUnion() &&
9079                     prevExpression->getAsConstantUnion()->getConstArray()[0].getIConst() ==
9080                     newExpression->getAsConstantUnion()->getConstArray()[0].getIConst())
9081                     error(branchNode->getLoc(), "duplicated value", "case", "");
9082             }
9083         }
9084         switchSequence->push_back(branchNode);
9085     }
9086 }
9087
9088 //
9089 // Turn the top-level node sequence built up of wrapupSwitchSubsequence
9090 // into a switch node.
9091 //
9092 TIntermNode* HlslParseContext::addSwitch(const TSourceLoc& loc, TIntermTyped* expression,
9093                                          TIntermAggregate* lastStatements, const TAttributes& attributes)
9094 {
9095     wrapupSwitchSubsequence(lastStatements, nullptr);
9096
9097     if (expression == nullptr ||
9098         (expression->getBasicType() != EbtInt && expression->getBasicType() != EbtUint) ||
9099         expression->getType().isArray() || expression->getType().isMatrix() || expression->getType().isVector())
9100         error(loc, "condition must be a scalar integer expression", "switch", "");
9101
9102     // If there is nothing to do, drop the switch but still execute the expression
9103     TIntermSequence* switchSequence = switchSequenceStack.back();
9104     if (switchSequence->size() == 0)
9105         return expression;
9106
9107     if (lastStatements == nullptr) {
9108         // emulate a break for error recovery
9109         lastStatements = intermediate.makeAggregate(intermediate.addBranch(EOpBreak, loc));
9110         lastStatements->setOperator(EOpSequence);
9111         switchSequence->push_back(lastStatements);
9112     }
9113
9114     TIntermAggregate* body = new TIntermAggregate(EOpSequence);
9115     body->getSequence() = *switchSequenceStack.back();
9116     body->setLoc(loc);
9117
9118     TIntermSwitch* switchNode = new TIntermSwitch(expression, body);
9119     switchNode->setLoc(loc);
9120     handleSwitchAttributes(loc, switchNode, attributes);
9121
9122     return switchNode;
9123 }
9124
9125 // Make a new symbol-table level that is made out of the members of a structure.
9126 // This should be done as an anonymous struct (name is "") so that the symbol table
9127 // finds the members with no explicit reference to a 'this' variable.
9128 void HlslParseContext::pushThisScope(const TType& thisStruct, const TVector<TFunctionDeclarator>& functionDeclarators)
9129 {
9130     // member variables
9131     TVariable& thisVariable = *new TVariable(NewPoolTString(""), thisStruct);
9132     symbolTable.pushThis(thisVariable);
9133
9134     // member functions
9135     for (auto it = functionDeclarators.begin(); it != functionDeclarators.end(); ++it) {
9136         // member should have a prefix matching currentTypePrefix.back()
9137         // but, symbol lookup within the class scope will just use the
9138         // unprefixed name. Hence, there are two: one fully prefixed and
9139         // one with no prefix.
9140         TFunction& member = *it->function->clone();
9141         member.removePrefix(currentTypePrefix.back());
9142         symbolTable.insert(member);
9143     }
9144 }
9145
9146 // Track levels of class/struct/namespace nesting with a prefix string using
9147 // the type names separated by the scoping operator. E.g., two levels
9148 // would look like:
9149 //
9150 //   outer::inner
9151 //
9152 // The string is empty when at normal global level.
9153 //
9154 void HlslParseContext::pushNamespace(const TString& typeName)
9155 {
9156     // make new type prefix
9157     TString newPrefix;
9158     if (currentTypePrefix.size() > 0)
9159         newPrefix = currentTypePrefix.back();
9160     newPrefix.append(typeName);
9161     newPrefix.append(scopeMangler);
9162     currentTypePrefix.push_back(newPrefix);
9163 }
9164
9165 // Opposite of pushNamespace(), see above
9166 void HlslParseContext::popNamespace()
9167 {
9168     currentTypePrefix.pop_back();
9169 }
9170
9171 // Use the class/struct nesting string to create a global name for
9172 // a member of a class/struct.
9173 void HlslParseContext::getFullNamespaceName(TString*& name) const
9174 {
9175     if (currentTypePrefix.size() == 0)
9176         return;
9177
9178     TString* fullName = NewPoolTString(currentTypePrefix.back().c_str());
9179     fullName->append(*name);
9180     name = fullName;
9181 }
9182
9183 // Helper function to add the namespace scope mangling syntax to a string.
9184 void HlslParseContext::addScopeMangler(TString& name)
9185 {
9186     name.append(scopeMangler);
9187 }
9188
9189 // Return true if this has uniform-interface like decorations.
9190 bool HlslParseContext::hasUniform(const TQualifier& qualifier) const
9191 {
9192     return qualifier.hasUniformLayout() ||
9193            qualifier.layoutPushConstant;
9194 }
9195
9196 // Potentially not the opposite of hasUniform(), as if some characteristic is
9197 // ever used for more than one thing (e.g., uniform or input), hasUniform() should
9198 // say it exists, but clearUniform() should leave it in place.
9199 void HlslParseContext::clearUniform(TQualifier& qualifier)
9200 {
9201     qualifier.clearUniformLayout();
9202     qualifier.layoutPushConstant = false;
9203 }
9204
9205 // Return false if builtIn by itself doesn't force this qualifier to be an input qualifier.
9206 bool HlslParseContext::isInputBuiltIn(const TQualifier& qualifier) const
9207 {
9208     switch (qualifier.builtIn) {
9209     case EbvPosition:
9210     case EbvPointSize:
9211         return language != EShLangVertex && language != EShLangCompute && language != EShLangFragment;
9212     case EbvClipDistance:
9213     case EbvCullDistance:
9214         return language != EShLangVertex && language != EShLangCompute;
9215     case EbvFragCoord:
9216     case EbvFace:
9217     case EbvHelperInvocation:
9218     case EbvLayer:
9219     case EbvPointCoord:
9220     case EbvSampleId:
9221     case EbvSampleMask:
9222     case EbvSamplePosition:
9223     case EbvViewportIndex:
9224         return language == EShLangFragment;
9225     case EbvGlobalInvocationId:
9226     case EbvLocalInvocationIndex:
9227     case EbvLocalInvocationId:
9228     case EbvNumWorkGroups:
9229     case EbvWorkGroupId:
9230     case EbvWorkGroupSize:
9231         return language == EShLangCompute;
9232     case EbvInvocationId:
9233         return language == EShLangTessControl || language == EShLangTessEvaluation || language == EShLangGeometry;
9234     case EbvPatchVertices:
9235         return language == EShLangTessControl || language == EShLangTessEvaluation;
9236     case EbvInstanceId:
9237     case EbvInstanceIndex:
9238     case EbvVertexId:
9239     case EbvVertexIndex:
9240         return language == EShLangVertex;
9241     case EbvPrimitiveId:
9242         return language == EShLangGeometry || language == EShLangFragment || language == EShLangTessControl;
9243     case EbvTessLevelInner:
9244     case EbvTessLevelOuter:
9245         return language == EShLangTessEvaluation;
9246     case EbvTessCoord:
9247         return language == EShLangTessEvaluation;
9248     default:
9249         return false;
9250     }
9251 }
9252
9253 // Return true if there are decorations to preserve for input-like storage.
9254 bool HlslParseContext::hasInput(const TQualifier& qualifier) const
9255 {
9256     if (qualifier.hasAnyLocation())
9257         return true;
9258
9259     if (language == EShLangFragment && (qualifier.isInterpolation() || qualifier.centroid || qualifier.sample))
9260         return true;
9261
9262     if (language == EShLangTessEvaluation && qualifier.patch)
9263         return true;
9264
9265     if (isInputBuiltIn(qualifier))
9266         return true;
9267
9268     return false;
9269 }
9270
9271 // Return false if builtIn by itself doesn't force this qualifier to be an output qualifier.
9272 bool HlslParseContext::isOutputBuiltIn(const TQualifier& qualifier) const
9273 {
9274     switch (qualifier.builtIn) {
9275     case EbvPosition:
9276     case EbvPointSize:
9277     case EbvClipVertex:
9278     case EbvClipDistance:
9279     case EbvCullDistance:
9280         return language != EShLangFragment && language != EShLangCompute;
9281     case EbvFragDepth:
9282     case EbvFragDepthGreater:
9283     case EbvFragDepthLesser:
9284     case EbvSampleMask:
9285         return language == EShLangFragment;
9286     case EbvLayer:
9287     case EbvViewportIndex:
9288         return language == EShLangGeometry || language == EShLangVertex;
9289     case EbvPrimitiveId:
9290         return language == EShLangGeometry;
9291     case EbvTessLevelInner:
9292     case EbvTessLevelOuter:
9293         return language == EShLangTessControl;
9294     default:
9295         return false;
9296     }
9297 }
9298
9299 // Return true if there are decorations to preserve for output-like storage.
9300 bool HlslParseContext::hasOutput(const TQualifier& qualifier) const
9301 {
9302     if (qualifier.hasAnyLocation())
9303         return true;
9304
9305     if (language != EShLangFragment && language != EShLangCompute && qualifier.hasXfb())
9306         return true;
9307
9308     if (language == EShLangTessControl && qualifier.patch)
9309         return true;
9310
9311     if (language == EShLangGeometry && qualifier.hasStream())
9312         return true;
9313
9314     if (isOutputBuiltIn(qualifier))
9315         return true;
9316
9317     return false;
9318 }
9319
9320 // Make the IO decorations etc. be appropriate only for an input interface.
9321 void HlslParseContext::correctInput(TQualifier& qualifier)
9322 {
9323     clearUniform(qualifier);
9324     if (language == EShLangVertex)
9325         qualifier.clearInterstage();
9326     if (language != EShLangTessEvaluation)
9327         qualifier.patch = false;
9328     if (language != EShLangFragment) {
9329         qualifier.clearInterpolation();
9330         qualifier.sample = false;
9331     }
9332
9333     qualifier.clearStreamLayout();
9334     qualifier.clearXfbLayout();
9335
9336     if (! isInputBuiltIn(qualifier))
9337         qualifier.builtIn = EbvNone;
9338 }
9339
9340 // Make the IO decorations etc. be appropriate only for an output interface.
9341 void HlslParseContext::correctOutput(TQualifier& qualifier)
9342 {
9343     clearUniform(qualifier);
9344     if (language == EShLangFragment)
9345         qualifier.clearInterstage();
9346     if (language != EShLangGeometry)
9347         qualifier.clearStreamLayout();
9348     if (language == EShLangFragment)
9349         qualifier.clearXfbLayout();
9350     if (language != EShLangTessControl)
9351         qualifier.patch = false;
9352
9353     switch (qualifier.builtIn) {
9354     case EbvFragDepth:
9355         intermediate.setDepthReplacing();
9356         intermediate.setDepth(EldAny);
9357         break;
9358     case EbvFragDepthGreater:
9359         intermediate.setDepthReplacing();
9360         intermediate.setDepth(EldGreater);
9361         qualifier.builtIn = EbvFragDepth;
9362         break;
9363     case EbvFragDepthLesser:
9364         intermediate.setDepthReplacing();
9365         intermediate.setDepth(EldLess);
9366         qualifier.builtIn = EbvFragDepth;
9367         break;
9368     default:
9369         break;
9370     }
9371
9372     if (! isOutputBuiltIn(qualifier))
9373         qualifier.builtIn = EbvNone;
9374 }
9375
9376 // Make the IO decorations etc. be appropriate only for uniform type interfaces.
9377 void HlslParseContext::correctUniform(TQualifier& qualifier)
9378 {
9379     if (qualifier.declaredBuiltIn == EbvNone)
9380         qualifier.declaredBuiltIn = qualifier.builtIn;
9381
9382     qualifier.builtIn = EbvNone;
9383     qualifier.clearInterstage();
9384     qualifier.clearInterstageLayout();
9385 }
9386
9387 // Clear out all IO/Uniform stuff, so this has nothing to do with being an IO interface.
9388 void HlslParseContext::clearUniformInputOutput(TQualifier& qualifier)
9389 {
9390     clearUniform(qualifier);
9391     correctUniform(qualifier);
9392 }
9393
9394
9395 // Set texture return type.  Returns success (not all types are valid).
9396 bool HlslParseContext::setTextureReturnType(TSampler& sampler, const TType& retType, const TSourceLoc& loc)
9397 {
9398     // Seed the output with an invalid index.  We will set it to a valid one if we can.
9399     sampler.structReturnIndex = TSampler::noReturnStruct;
9400
9401     // Arrays aren't supported.
9402     if (retType.isArray()) {
9403         error(loc, "Arrays not supported in texture template types", "", "");
9404         return false;
9405     }
9406
9407     // If return type is a vector, remember the vector size in the sampler, and return.
9408     if (retType.isVector() || retType.isScalar()) {
9409         sampler.vectorSize = retType.getVectorSize();
9410         return true;
9411     }
9412
9413     // If it wasn't a vector, it must be a struct meeting certain requirements.  The requirements
9414     // are checked below: just check for struct-ness here.
9415     if (!retType.isStruct()) {
9416         error(loc, "Invalid texture template type", "", "");
9417         return false;
9418     }
9419
9420     // TODO: Subpass doesn't handle struct returns, due to some oddities with fn overloading.
9421     if (sampler.isSubpass()) {
9422         error(loc, "Unimplemented: structure template type in subpass input", "", "");
9423         return false;
9424     }
9425
9426     TTypeList* members = retType.getWritableStruct();
9427
9428     // Check for too many or not enough structure members.
9429     if (members->size() > 4 || members->size() == 0) {
9430         error(loc, "Invalid member count in texture template structure", "", "");
9431         return false;
9432     }
9433
9434     // Error checking: We must have <= 4 total components, all of the same basic type.
9435     unsigned totalComponents = 0;
9436     for (unsigned m = 0; m < members->size(); ++m) {
9437         // Check for bad member types
9438         if (!(*members)[m].type->isScalar() && !(*members)[m].type->isVector()) {
9439             error(loc, "Invalid texture template struct member type", "", "");
9440             return false;
9441         }
9442
9443         const unsigned memberVectorSize = (*members)[m].type->getVectorSize();
9444         totalComponents += memberVectorSize;
9445
9446         // too many total member components
9447         if (totalComponents > 4) {
9448             error(loc, "Too many components in texture template structure type", "", "");
9449             return false;
9450         }
9451
9452         // All members must be of a common basic type
9453         if ((*members)[m].type->getBasicType() != (*members)[0].type->getBasicType()) {
9454             error(loc, "Texture template structure members must same basic type", "", "");
9455             return false;
9456         }
9457     }
9458
9459     // If the structure in the return type already exists in the table, we'll use it.  Otherwise, we'll make
9460     // a new entry.  This is a linear search, but it hardly ever happens, and the list cannot be very large.
9461     for (unsigned int idx = 0; idx < textureReturnStruct.size(); ++idx) {
9462         if (textureReturnStruct[idx] == members) {
9463             sampler.structReturnIndex = idx;
9464             return true;
9465         }
9466     }
9467
9468     // It wasn't found as an existing entry.  See if we have room for a new one.
9469     if (textureReturnStruct.size() >= TSampler::structReturnSlots) {
9470         error(loc, "Texture template struct return slots exceeded", "", "");
9471         return false;
9472     }
9473
9474     // Insert it in the vector that tracks struct return types.
9475     sampler.structReturnIndex = unsigned(textureReturnStruct.size());
9476     textureReturnStruct.push_back(members);
9477     
9478     // Success!
9479     return true;
9480 }
9481
9482 // Return the sampler return type in retType.
9483 void HlslParseContext::getTextureReturnType(const TSampler& sampler, TType& retType) const
9484 {
9485     if (sampler.hasReturnStruct()) {
9486         assert(textureReturnStruct.size() >= sampler.structReturnIndex);
9487
9488         // We land here if the texture return is a structure.
9489         TTypeList* blockStruct = textureReturnStruct[sampler.structReturnIndex];
9490
9491         const TType resultType(blockStruct, "");
9492         retType.shallowCopy(resultType);
9493     } else {
9494         // We land here if the texture return is a vector or scalar.
9495         const TType resultType(sampler.type, EvqTemporary, sampler.getVectorSize());
9496         retType.shallowCopy(resultType);
9497     }
9498 }
9499
9500
9501 // Return a symbol for the tessellation linkage variable of the given TBuiltInVariable type
9502 TIntermSymbol* HlslParseContext::findTessLinkageSymbol(TBuiltInVariable biType) const
9503 {
9504     const auto it = builtInTessLinkageSymbols.find(biType);
9505     if (it == builtInTessLinkageSymbols.end())  // if it wasn't declared by the user, return nullptr
9506         return nullptr;
9507
9508     return intermediate.addSymbol(*it->second->getAsVariable());
9509 }
9510
9511 // Find the patch constant function (issues error, returns nullptr if not found)
9512 const TFunction* HlslParseContext::findPatchConstantFunction(const TSourceLoc& loc)
9513 {
9514     if (symbolTable.isFunctionNameVariable(patchConstantFunctionName)) {
9515         error(loc, "can't use variable in patch constant function", patchConstantFunctionName.c_str(), "");
9516         return nullptr;
9517     }
9518
9519     const TString mangledName = patchConstantFunctionName + "(";
9520
9521     // create list of PCF candidates
9522     TVector<const TFunction*> candidateList;
9523     bool builtIn;
9524     symbolTable.findFunctionNameList(mangledName, candidateList, builtIn);
9525     
9526     // We have to have one and only one, or we don't know which to pick: the patchconstantfunc does not
9527     // allow any disambiguation of overloads.
9528     if (candidateList.empty()) {
9529         error(loc, "patch constant function not found", patchConstantFunctionName.c_str(), "");
9530         return nullptr;
9531     }
9532
9533     // Based on directed experiments, it appears that if there are overloaded patchconstantfunctions,
9534     // HLSL picks the last one in shader source order.  Since that isn't yet implemented here, error
9535     // out if there is more than one candidate.
9536     if (candidateList.size() > 1) {
9537         error(loc, "ambiguous patch constant function", patchConstantFunctionName.c_str(), "");
9538         return nullptr;
9539     }
9540
9541     return candidateList[0];
9542 }
9543
9544 // Finalization step: Add patch constant function invocation
9545 void HlslParseContext::addPatchConstantInvocation()
9546 {
9547     TSourceLoc loc;
9548     loc.init();
9549
9550     // If there's no patch constant function, or we're not a HS, do nothing.
9551     if (patchConstantFunctionName.empty() || language != EShLangTessControl)
9552         return;
9553
9554     // Look for built-in variables in a function's parameter list.
9555     const auto findBuiltIns = [&](const TFunction& function, std::set<tInterstageIoData>& builtIns) {
9556         for (int p=0; p<function.getParamCount(); ++p) {
9557             TStorageQualifier storage = function[p].type->getQualifier().storage;
9558
9559             if (storage == EvqConstReadOnly) // treated identically to input
9560                 storage = EvqIn;
9561
9562             if (function[p].getDeclaredBuiltIn() != EbvNone)
9563                 builtIns.insert(HlslParseContext::tInterstageIoData(function[p].getDeclaredBuiltIn(), storage));
9564             else
9565                 builtIns.insert(HlslParseContext::tInterstageIoData(function[p].type->getQualifier().builtIn, storage));
9566         }
9567     };
9568
9569     // If we synthesize a built-in interface variable, we must add it to the linkage.
9570     const auto addToLinkage = [&](const TType& type, const TString* name, TIntermSymbol** symbolNode) {
9571         if (name == nullptr) {
9572             error(loc, "unable to locate patch function parameter name", "", "");
9573             return;
9574         } else {
9575             TVariable& variable = *new TVariable(name, type);
9576             if (! symbolTable.insert(variable)) {
9577                 error(loc, "unable to declare patch constant function interface variable", name->c_str(), "");
9578                 return;
9579             }
9580
9581             globalQualifierFix(loc, variable.getWritableType().getQualifier());
9582
9583             if (symbolNode != nullptr)
9584                 *symbolNode = intermediate.addSymbol(variable);
9585
9586             trackLinkage(variable);
9587         }
9588     };
9589
9590     const auto isOutputPatch = [](TFunction& patchConstantFunction, int param) {
9591         const TType& type = *patchConstantFunction[param].type;
9592         const TBuiltInVariable biType = patchConstantFunction[param].getDeclaredBuiltIn();
9593
9594         return type.isSizedArray() && biType == EbvOutputPatch;
9595     };
9596     
9597     // We will perform these steps.  Each is in a scoped block for separation: they could
9598     // become separate functions to make addPatchConstantInvocation shorter.
9599     // 
9600     // 1. Union the interfaces, and create built-ins for anything present in the PCF and
9601     //    declared as a built-in variable that isn't present in the entry point's signature.
9602     //
9603     // 2. Synthesizes a call to the patchconstfunction using built-in variables from either main,
9604     //    or the ones we created.  Matching is based on built-in type.  We may use synthesized
9605     //    variables from (1) above.
9606     // 
9607     // 2B: Synthesize per control point invocations of wrapped entry point if the PCF requires them.
9608     //
9609     // 3. Create a return sequence: copy the return value (if any) from the PCF to a
9610     //    (non-sanitized) output variable.  In case this may involve multiple copies, such as for
9611     //    an arrayed variable, a temporary copy of the PCF output is created to avoid multiple
9612     //    indirections into a complex R-value coming from the call to the PCF.
9613     // 
9614     // 4. Create a barrier.
9615     // 
9616     // 5/5B. Call the PCF inside an if test for (invocation id == 0).
9617
9618     TFunction* patchConstantFunctionPtr = const_cast<TFunction*>(findPatchConstantFunction(loc));
9619
9620     if (patchConstantFunctionPtr == nullptr)
9621         return;
9622
9623     TFunction& patchConstantFunction = *patchConstantFunctionPtr;
9624
9625     const int pcfParamCount = patchConstantFunction.getParamCount();
9626     TIntermSymbol* invocationIdSym = findTessLinkageSymbol(EbvInvocationId);
9627     TIntermSequence& epBodySeq = entryPointFunctionBody->getAsAggregate()->getSequence();
9628
9629     int outPatchParam = -1; // -1 means there isn't one.
9630
9631     // ================ Step 1A: Union Interfaces ================
9632     // Our patch constant function.
9633     {
9634         std::set<tInterstageIoData> pcfBuiltIns;  // patch constant function built-ins
9635         std::set<tInterstageIoData> epfBuiltIns;  // entry point function built-ins
9636
9637         assert(entryPointFunction);
9638         assert(entryPointFunctionBody);
9639
9640         findBuiltIns(patchConstantFunction, pcfBuiltIns);
9641         findBuiltIns(*entryPointFunction,   epfBuiltIns);
9642
9643         // Find the set of built-ins in the PCF that are not present in the entry point.
9644         std::set<tInterstageIoData> notInEntryPoint;
9645
9646         notInEntryPoint = pcfBuiltIns;
9647
9648         // std::set_difference not usable on unordered containers
9649         for (auto bi = epfBuiltIns.begin(); bi != epfBuiltIns.end(); ++bi)
9650             notInEntryPoint.erase(*bi);
9651
9652         // Now we'll add those to the entry and to the linkage.
9653         for (int p=0; p<pcfParamCount; ++p) {
9654             const TBuiltInVariable biType   = patchConstantFunction[p].getDeclaredBuiltIn();
9655             TStorageQualifier storage = patchConstantFunction[p].type->getQualifier().storage;
9656
9657             // Track whether there is an output patch param
9658             if (isOutputPatch(patchConstantFunction, p)) {
9659                 if (outPatchParam >= 0) {
9660                     // Presently we only support one per ctrl pt input.
9661                     error(loc, "unimplemented: multiple output patches in patch constant function", "", "");
9662                     return;
9663                 }
9664                 outPatchParam = p;
9665             }
9666
9667             if (biType != EbvNone) {
9668                 TType* paramType = patchConstantFunction[p].type->clone();
9669
9670                 if (storage == EvqConstReadOnly) // treated identically to input
9671                     storage = EvqIn;
9672
9673                 // Presently, the only non-built-in we support is InputPatch, which is treated as
9674                 // a pseudo-built-in.
9675                 if (biType == EbvInputPatch) {
9676                     builtInTessLinkageSymbols[biType] = inputPatch;
9677                 } else if (biType == EbvOutputPatch) {
9678                     // Nothing...
9679                 } else {
9680                     // Use the original declaration type for the linkage
9681                     paramType->getQualifier().builtIn = biType;
9682
9683                     if (notInEntryPoint.count(tInterstageIoData(biType, storage)) == 1)
9684                         addToLinkage(*paramType, patchConstantFunction[p].name, nullptr);
9685                 }
9686             }
9687         }
9688
9689         // If we didn't find it because the shader made one, add our own.
9690         if (invocationIdSym == nullptr) {
9691             TType invocationIdType(EbtUint, EvqIn, 1);
9692             TString* invocationIdName = NewPoolTString("InvocationId");
9693             invocationIdType.getQualifier().builtIn = EbvInvocationId;
9694             addToLinkage(invocationIdType, invocationIdName, &invocationIdSym);
9695         }
9696
9697         assert(invocationIdSym);
9698     }
9699
9700     TIntermTyped* pcfArguments = nullptr;
9701     TVariable* perCtrlPtVar = nullptr;
9702
9703     // ================ Step 1B: Argument synthesis ================
9704     // Create pcfArguments for synthesis of patchconstantfunction invocation
9705     {
9706         for (int p=0; p<pcfParamCount; ++p) {
9707             TIntermTyped* inputArg = nullptr;
9708
9709             if (p == outPatchParam) {
9710                 if (perCtrlPtVar == nullptr) {
9711                     perCtrlPtVar = makeInternalVariable(*patchConstantFunction[outPatchParam].name,
9712                                                         *patchConstantFunction[outPatchParam].type);
9713
9714                     perCtrlPtVar->getWritableType().getQualifier().makeTemporary();
9715                 }
9716                 inputArg = intermediate.addSymbol(*perCtrlPtVar, loc);
9717             } else {
9718                 // find which built-in it is
9719                 const TBuiltInVariable biType = patchConstantFunction[p].getDeclaredBuiltIn();
9720                 
9721                 if (biType == EbvInputPatch && inputPatch == nullptr) {
9722                     error(loc, "unimplemented: PCF input patch without entry point input patch parameter", "", "");
9723                     return;
9724                 }
9725
9726                 inputArg = findTessLinkageSymbol(biType);
9727
9728                 if (inputArg == nullptr) {
9729                     error(loc, "unable to find patch constant function built-in variable", "", "");
9730                     return;
9731                 }
9732             }
9733
9734             if (pcfParamCount == 1)
9735                 pcfArguments = inputArg;
9736             else
9737                 pcfArguments = intermediate.growAggregate(pcfArguments, inputArg);
9738         }
9739     }
9740
9741     // ================ Step 2: Synthesize call to PCF ================
9742     TIntermAggregate* pcfCallSequence = nullptr;
9743     TIntermTyped* pcfCall = nullptr;
9744
9745     {
9746         // Create a function call to the patchconstantfunction
9747         if (pcfArguments)
9748             addInputArgumentConversions(patchConstantFunction, pcfArguments);
9749
9750         // Synthetic call.
9751         pcfCall = intermediate.setAggregateOperator(pcfArguments, EOpFunctionCall, patchConstantFunction.getType(), loc);
9752         pcfCall->getAsAggregate()->setUserDefined();
9753         pcfCall->getAsAggregate()->setName(patchConstantFunction.getMangledName());
9754         intermediate.addToCallGraph(infoSink, intermediate.getEntryPointMangledName().c_str(),
9755                                     patchConstantFunction.getMangledName());
9756
9757         if (pcfCall->getAsAggregate()) {
9758             TQualifierList& qualifierList = pcfCall->getAsAggregate()->getQualifierList();
9759             for (int i = 0; i < patchConstantFunction.getParamCount(); ++i) {
9760                 TStorageQualifier qual = patchConstantFunction[i].type->getQualifier().storage;
9761                 qualifierList.push_back(qual);
9762             }
9763             pcfCall = addOutputArgumentConversions(patchConstantFunction, *pcfCall->getAsOperator());
9764         }
9765     }
9766
9767     // ================ Step 2B: Per Control Point synthesis ================
9768     // If there is per control point data, we must either emulate that with multiple
9769     // invocations of the entry point to build up an array, or (TODO:) use a yet
9770     // unavailable extension to look across the SIMD lanes.  This is the former
9771     // as a placeholder for the latter.
9772     if (outPatchParam >= 0) {
9773         // We must introduce a local temp variable of the type wanted by the PCF input.
9774         const int arraySize = patchConstantFunction[outPatchParam].type->getOuterArraySize();
9775
9776         if (entryPointFunction->getType().getBasicType() == EbtVoid) {
9777             error(loc, "entry point must return a value for use with patch constant function", "", "");
9778             return;
9779         }
9780
9781         // Create calls to wrapped main to fill in the array.  We will substitute fixed values
9782         // of invocation ID when calling the wrapped main.
9783
9784         // This is the type of the each member of the per ctrl point array.
9785         const TType derefType(perCtrlPtVar->getType(), 0);
9786
9787         for (int cpt = 0; cpt < arraySize; ++cpt) {
9788             // TODO: improve.  substr(1) here is to avoid the '@' that was grafted on but isn't in the symtab
9789             // for this function.
9790             const TString origName = entryPointFunction->getName().substr(1);
9791             TFunction callee(&origName, TType(EbtVoid));
9792             TIntermTyped* callingArgs = nullptr;
9793
9794             for (int i = 0; i < entryPointFunction->getParamCount(); i++) {
9795                 TParameter& param = (*entryPointFunction)[i];
9796                 TType& paramType = *param.type;
9797
9798                 if (paramType.getQualifier().isParamOutput()) {
9799                     error(loc, "unimplemented: entry point outputs in patch constant function invocation", "", "");
9800                     return;
9801                 }
9802
9803                 if (paramType.getQualifier().isParamInput())  {
9804                     TIntermTyped* arg = nullptr;
9805                     if ((*entryPointFunction)[i].getDeclaredBuiltIn() == EbvInvocationId) {
9806                         // substitute invocation ID with the array element ID
9807                         arg = intermediate.addConstantUnion(cpt, loc);
9808                     } else {
9809                         TVariable* argVar = makeInternalVariable(*param.name, *param.type);
9810                         argVar->getWritableType().getQualifier().makeTemporary();
9811                         arg = intermediate.addSymbol(*argVar);
9812                     }
9813
9814                     handleFunctionArgument(&callee, callingArgs, arg);
9815                 }
9816             }
9817
9818             // Call and assign to per ctrl point variable
9819             currentCaller = intermediate.getEntryPointMangledName().c_str();
9820             TIntermTyped* callReturn = handleFunctionCall(loc, &callee, callingArgs);
9821             TIntermTyped* index = intermediate.addConstantUnion(cpt, loc);
9822             TIntermSymbol* perCtrlPtSym = intermediate.addSymbol(*perCtrlPtVar, loc);
9823             TIntermTyped* element = intermediate.addIndex(EOpIndexDirect, perCtrlPtSym, index, loc);
9824             element->setType(derefType);
9825             element->setLoc(loc);
9826
9827             pcfCallSequence = intermediate.growAggregate(pcfCallSequence, 
9828                                                          handleAssign(loc, EOpAssign, element, callReturn));
9829         }
9830     }
9831
9832     // ================ Step 3: Create return Sequence ================
9833     // Return sequence: copy PCF result to a temporary, then to shader output variable.
9834     if (pcfCall->getBasicType() != EbtVoid) {
9835         const TType* retType = &patchConstantFunction.getType();  // return type from the PCF
9836         TType outType; // output type that goes with the return type.
9837         outType.shallowCopy(*retType);
9838
9839         // substitute the output type
9840         const auto newLists = ioTypeMap.find(retType->getStruct());
9841         if (newLists != ioTypeMap.end())
9842             outType.setStruct(newLists->second.output);
9843
9844         // Substitute the top level type's built-in type
9845         if (patchConstantFunction.getDeclaredBuiltInType() != EbvNone)
9846             outType.getQualifier().builtIn = patchConstantFunction.getDeclaredBuiltInType();
9847
9848         outType.getQualifier().patch = true; // make it a per-patch variable
9849
9850         TVariable* pcfOutput = makeInternalVariable("@patchConstantOutput", outType);
9851         pcfOutput->getWritableType().getQualifier().storage = EvqVaryingOut;
9852
9853         if (pcfOutput->getType().containsBuiltIn())
9854             split(*pcfOutput);
9855
9856         assignToInterface(*pcfOutput);
9857
9858         TIntermSymbol* pcfOutputSym = intermediate.addSymbol(*pcfOutput, loc);
9859
9860         // The call to the PCF is a complex R-value: we want to store it in a temp to avoid
9861         // repeated calls to the PCF:
9862         TVariable* pcfCallResult = makeInternalVariable("@patchConstantResult", *retType);
9863         pcfCallResult->getWritableType().getQualifier().makeTemporary();
9864
9865         TIntermSymbol* pcfResultVar = intermediate.addSymbol(*pcfCallResult, loc);
9866         TIntermNode* pcfResultAssign = handleAssign(loc, EOpAssign, pcfResultVar, pcfCall);
9867         TIntermNode* pcfResultToOut = handleAssign(loc, EOpAssign, pcfOutputSym,
9868                                                    intermediate.addSymbol(*pcfCallResult, loc));
9869
9870         pcfCallSequence = intermediate.growAggregate(pcfCallSequence, pcfResultAssign);
9871         pcfCallSequence = intermediate.growAggregate(pcfCallSequence, pcfResultToOut);
9872     } else {
9873         pcfCallSequence = intermediate.growAggregate(pcfCallSequence, pcfCall);
9874     }
9875
9876     // ================ Step 4: Barrier ================    
9877     TIntermTyped* barrier = new TIntermAggregate(EOpBarrier);
9878     barrier->setLoc(loc);
9879     barrier->setType(TType(EbtVoid));
9880     epBodySeq.insert(epBodySeq.end(), barrier);
9881
9882     // ================ Step 5: Test on invocation ID ================
9883     TIntermTyped* zero = intermediate.addConstantUnion(0, loc, true);
9884     TIntermTyped* cmp =  intermediate.addBinaryNode(EOpEqual, invocationIdSym, zero, loc, TType(EbtBool));
9885
9886
9887     // ================ Step 5B: Create if statement on Invocation ID == 0 ================
9888     intermediate.setAggregateOperator(pcfCallSequence, EOpSequence, TType(EbtVoid), loc);
9889     TIntermTyped* invocationIdTest = new TIntermSelection(cmp, pcfCallSequence, nullptr);
9890     invocationIdTest->setLoc(loc);
9891
9892     // add our test sequence before the return.
9893     epBodySeq.insert(epBodySeq.end(), invocationIdTest);
9894 }
9895
9896 // Finalization step: remove unused buffer blocks from linkage (we don't know until the
9897 // shader is entirely compiled).
9898 // Preserve order of remaining symbols.
9899 void HlslParseContext::removeUnusedStructBufferCounters()
9900 {
9901     const auto endIt = std::remove_if(linkageSymbols.begin(), linkageSymbols.end(),
9902                                       [this](const TSymbol* sym) {
9903                                           const auto sbcIt = structBufferCounter.find(sym->getName());
9904                                           return sbcIt != structBufferCounter.end() && !sbcIt->second;
9905                                       });
9906
9907     linkageSymbols.erase(endIt, linkageSymbols.end());
9908 }
9909
9910 // Finalization step: patch texture shadow modes to match samplers they were combined with
9911 void HlslParseContext::fixTextureShadowModes()
9912 {
9913     for (auto symbol = linkageSymbols.begin(); symbol != linkageSymbols.end(); ++symbol) {
9914         TSampler& sampler = (*symbol)->getWritableType().getSampler();
9915
9916         if (sampler.isTexture()) {
9917             const auto shadowMode = textureShadowVariant.find((*symbol)->getUniqueId());
9918             if (shadowMode != textureShadowVariant.end()) {
9919
9920                 if (shadowMode->second->overloaded())
9921                     // Texture needs legalization if it's been seen with both shadow and non-shadow modes.
9922                     intermediate.setNeedsLegalization();
9923
9924                 sampler.shadow = shadowMode->second->isShadowId((*symbol)->getUniqueId());
9925             }
9926         }
9927     }
9928 }
9929
9930 // Finalization step: patch append methods to use proper stream output, which isn't known until
9931 // main is parsed, which could happen after the append method is parsed.
9932 void HlslParseContext::finalizeAppendMethods()
9933 {
9934     TSourceLoc loc;
9935     loc.init();
9936
9937     // Nothing to do: bypass test for valid stream output.
9938     if (gsAppends.empty())
9939         return;
9940
9941     if (gsStreamOutput == nullptr) {
9942         error(loc, "unable to find output symbol for Append()", "", "");
9943         return;
9944     }
9945
9946     // Patch append sequences, now that we know the stream output symbol.
9947     for (auto append = gsAppends.begin(); append != gsAppends.end(); ++append) {
9948         append->node->getSequence()[0] = 
9949             handleAssign(append->loc, EOpAssign,
9950                          intermediate.addSymbol(*gsStreamOutput, append->loc),
9951                          append->node->getSequence()[0]->getAsTyped());
9952     }
9953 }
9954
9955 // post-processing
9956 void HlslParseContext::finish()
9957 {
9958     // Error check: There was a dangling .mips operator.  These are not nested constructs in the grammar, so
9959     // cannot be detected there.  This is not strictly needed in a non-validating parser; it's just helpful.
9960     if (! mipsOperatorMipArg.empty()) {
9961         error(mipsOperatorMipArg.back().loc, "unterminated mips operator:", "", "");
9962     }
9963
9964     removeUnusedStructBufferCounters();
9965     addPatchConstantInvocation();
9966     fixTextureShadowModes();
9967     finalizeAppendMethods();
9968
9969     // Communicate out (esp. for command line) that we formed AST that will make
9970     // illegal AST SPIR-V and it needs transforms to legalize it.
9971     if (intermediate.needsLegalization() && (messages & EShMsgHlslLegalization))
9972         infoSink.info << "WARNING: AST will form illegal SPIR-V; need to transform to legalize";
9973
9974     TParseContextBase::finish();
9975 }
9976
9977 } // end namespace glslang