2 // Copyright (C) 2017-2018 Google, Inc.
3 // Copyright (C) 2017 LunarG, Inc.
5 // All rights reserved.
7 // Redistribution and use in source and binary forms, with or without
8 // modification, are permitted provided that the following conditions
11 // Redistributions of source code must retain the above copyright
12 // notice, this list of conditions and the following disclaimer.
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.
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.
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.
37 #include "hlslParseHelper.h"
38 #include "hlslScanContext.h"
39 #include "hlslGrammar.h"
40 #include "hlslAttributes.h"
42 #include "../glslang/Include/Common.h"
43 #include "../glslang/MachineIndependent/Scan.h"
44 #include "../glslang/MachineIndependent/preprocessor/PpContext.h"
46 #include "../glslang/OSDependent/osinclude.h"
56 HlslParseContext::HlslParseContext(TSymbolTable& symbolTable, TIntermediate& interm, bool parsingBuiltins,
57 int version, EProfile profile, const SpvVersion& spvVersion, EShLanguage language,
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),
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)
74 globalUniformDefaults.clear();
75 globalUniformDefaults.layoutMatrix = ElmRowMajor;
76 globalUniformDefaults.layoutPacking = ElpStd140;
78 globalBufferDefaults.clear();
79 globalBufferDefaults.layoutMatrix = ElmRowMajor;
80 globalBufferDefaults.layoutPacking = ElpStd430;
82 globalInputDefaults.clear();
83 globalOutputDefaults.clear();
85 clipSemanticNSizeIn.fill(0);
86 cullSemanticNSizeIn.fill(0);
87 clipSemanticNSizeOut.fill(0);
88 cullSemanticNSizeOut.fill(0);
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;
99 if (language == EShLangGeometry)
100 globalOutputDefaults.layoutStream = 0;
103 HlslParseContext::~HlslParseContext()
107 void HlslParseContext::initializeExtensionBehavior()
109 TParseContextBase::initializeExtensionBehavior();
111 // HLSL allows #line by default.
112 extensionBehavior[E_GL_GOOGLE_cpp_style_line_directive] = EBhEnable;
115 void HlslParseContext::setLimits(const TBuiltInResource& r)
118 intermediate.setLimits(resources);
122 // Parse an array of strings using the parser in HlslRules.
124 // Returns true for successful acceptance of the shader, false if any errors.
126 bool HlslParseContext::parseShaderStrings(TPpContext& ppContext, TInputScanner& input, bool versionWillBeError)
128 currentScanner = &input;
129 ppContext.setInput(input, versionWillBeError);
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";
145 return numErrors == 0;
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.
152 bool HlslParseContext::shouldConvertLValue(const TIntermNode* node) const
154 if (node == nullptr || node->getAsTyped() == nullptr)
157 const TIntermAggregate* lhsAsAggregate = node->getAsAggregate();
158 const TIntermBinary* lhsAsBinary = node->getAsBinaryNode();
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)
170 void HlslParseContext::growGlobalUniformBlock(const TSourceLoc& loc, TType& memberType, const TString& memberName,
171 TTypeList* newTypeList)
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;
180 TParseContextBase::growGlobalUniformBlock(loc, memberType, memberName, newTypeList);
184 // Return a TLayoutFormat corresponding to the given texture type.
186 TLayoutFormat HlslParseContext::getLayoutFromTxType(const TSourceLoc& loc, const TType& txType)
188 if (txType.isStruct()) {
190 error(loc, "unimplemented: structure type in image or buffer", "", "");
194 const int components = txType.getVectorSize();
195 const TBasicType txBasicType = txType.getBasicType();
197 const auto selectFormat = [this,&components](TLayoutFormat v1, TLayoutFormat v2, TLayoutFormat v4) -> TLayoutFormat {
198 if (intermediate.getNoStorageFormat())
201 return components == 1 ? v1 :
202 components == 2 ? v2 : v4;
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);
210 error(loc, "unknown basic type in image format", "", "");
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.
219 // Returns true if there was an error.
221 bool HlslParseContext::lValueErrorCheck(const TSourceLoc& loc, const char* op, TIntermTyped* node)
223 if (shouldConvertLValue(node)) {
224 // if we're writing to a texture, it must be an RW form.
226 TIntermAggregate* lhsAsAggregate = node->getAsAggregate();
227 TIntermTyped* object = lhsAsAggregate->getSequence()[0]->getAsTyped();
229 if (!object->getType().getSampler().isImage()) {
230 error(loc, "operator[] on a non-RW texture must be an r-value", "", "");
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();
242 // Let the base class check errors
243 return TParseContextBase::lValueErrorCheck(loc, op, node);
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.
252 // Most things are passed through unmodified, except for error checking.
254 TIntermTyped* HlslParseContext::handleLvalue(const TSourceLoc& loc, const char* op, TIntermTyped*& node)
259 TIntermBinary* nodeAsBinary = node->getAsBinaryNode();
260 TIntermUnary* nodeAsUnary = node->getAsUnaryNode();
261 TIntermAggregate* sequence = nullptr;
263 TIntermTyped* lhs = nodeAsUnary ? nodeAsUnary->getOperand() :
264 nodeAsBinary ? nodeAsBinary->getLeft() :
267 // Early bail out if there is no conversion to apply
268 if (!shouldConvertLValue(lhs)) {
270 if (lValueErrorCheck(loc, op, lhs))
275 // *** If we get here, we're going to apply some conversion to an l-value.
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);
281 loadOp->getSequence().push_back(object);
282 loadOp->getSequence().push_back(intermediate.addSymbol(*coord->getAsSymbolNode()));
283 loadOp->setType(derefType);
285 sequence = intermediate.growAggregate(sequence,
286 intermediate.addAssign(EOpAssign, rhsTmp, loadOp, loc),
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));
299 sequence = intermediate.growAggregate(sequence, storeOp);
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()),
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);
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,
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
333 // Track which components are being set.
334 std::array<bool, 4> compIsSet;
335 compIsSet.fill(false);
337 const TIntermConstantUnion* asConst = swizzle->getRight()->getAsConstantUnion();
338 const TIntermAggregate* asAggregate = swizzle->getRight()->getAsAggregate();
340 // This could be either a direct index, or a swizzle.
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;
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; } );
356 // Create swizzle matching input swizzle
357 const auto addSwizzle = [&](TIntermSymbol* var, TIntermBinary* swizzle) -> TIntermTyped* {
359 return intermediate.addBinaryNode(swizzle->getOp(), var, swizzle->getRight(), loc, swizzle->getType());
364 TIntermBinary* lhsAsBinary = lhs->getAsBinaryNode();
365 TIntermAggregate* lhsAsAggregate = lhs->getAsAggregate();
366 bool lhsIsSwizzle = false;
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();
374 TIntermTyped* object = lhsAsAggregate->getSequence()[0]->getAsTyped();
375 TIntermTyped* coord = lhsAsAggregate->getSequence()[1]->getAsTyped();
377 const TSampler& texSampler = object->getType().getSampler();
380 getTextureReturnType(texSampler, objDerefType);
383 TIntermTyped* rhs = nodeAsBinary->getRight();
384 const TOperator assignOp = nodeAsBinary->getOp();
386 bool isModifyOp = false;
392 case EOpVectorTimesMatrixAssign:
393 case EOpVectorTimesScalarAssign:
394 case EOpMatrixTimesScalarAssign:
395 case EOpMatrixTimesMatrixAssign:
399 case EOpInclusiveOrAssign:
400 case EOpExclusiveOrAssign:
401 case EOpLeftShiftAssign:
402 case EOpRightShiftAssign:
407 // Since this is an lvalue, we'll convert an image load to a sequence like this
408 // (to still provide the value):
410 // OpImageStore(object, lhs, 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:
416 // OpImageStore(object, coord, rhsTmp)
418 // If this is a read-modify-write op, like +=, we issue:
420 // coordtmp = load's param1
421 // rhsTmp = OpImageLoad(object, coordTmp)
423 // OpImageStore(object, coordTmp, rhsTmp)
426 // If the lvalue is swizzled, we apply that when writing the temp variable, like so:
428 // rhsTmp.some_swizzle = ...
429 // For partial writes, an error is generated.
431 TIntermSymbol* rhsTmp = rhs->getAsSymbolNode();
432 TIntermTyped* coordTmp = coord;
434 if (rhsTmp == nullptr || isModifyOp || lhsIsSwizzle) {
435 rhsTmp = makeInternalVariableNode(loc, "storeTemp", objDerefType);
437 // Partial updates not yet supported
438 if (!writesAllComponents(rhsTmp, lhsAsBinary)) {
439 error(loc, "unimplemented: partial image updates", "", "");
442 // Assign storeTemp = rhs
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)
451 makeBinary(assignOp, addSwizzle(intermediate.addSymbol(*rhsTmp), lhsAsBinary), rhs);
454 makeStore(object, coordTmp, rhsTmp); // add a store
455 return finishSequence(rhsTmp, objDerefType); // return rhsTmp from sequence
464 const TOperator assignOp = nodeAsUnary->getOp();
467 case EOpPreIncrement:
468 case EOpPreDecrement:
470 // We turn this into:
472 // coordtmp = load's param1
473 // rhsTmp = OpImageLoad(object, coordTmp)
475 // OpImageStore(object, coordTmp, rhsTmp)
478 TIntermSymbol* rhsTmp = makeInternalVariableNode(loc, "storeTemp", objDerefType);
479 TIntermTyped* coordTmp = makeInternalVariableNode(loc, "coordTemp", coord->getType());
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
488 case EOpPostIncrement:
489 case EOpPostDecrement:
491 // We turn this into:
493 // coordtmp = load's param1
494 // rhsTmp1 = OpImageLoad(object, coordTmp)
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());
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
517 if (lValueErrorCheck(loc, op, lhs))
523 void HlslParseContext::handlePragma(const TSourceLoc& loc, const TVector<TString>& tokens)
526 pragmaCallback(loc.line, tokens);
528 if (tokens.size() == 0)
531 // These pragmas are case insensitive in HLSL, so we'll compare in lower case.
532 TVector<TString> lowerTokens = tokens;
534 for (auto it = lowerTokens.begin(); it != lowerTokens.end(); ++it)
535 std::transform(it->begin(), it->end(), it->begin(), ::tolower);
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.
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;
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;
555 if (lowerTokens[0] == "once") {
556 warn(loc, "not implemented", "#pragma once", "");
562 // Look at a '.' matrix selector string and change it into components
563 // for a matrix. There are two types:
565 // _21 second row, first column (one based)
566 // _m21 third row, second column (zero based)
568 // Returns true if there is no error.
570 bool HlslParseContext::parseMatrixSwizzleSelector(const TSourceLoc& loc, const TString& fields, int cols, int rows,
571 TSwizzleSelectors<TMatrixSelector>& components)
573 int startPos[MaxSwizzleSelectors];
575 TString compString = fields;
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(), "");
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(), "");
590 startPos[numComps++] = (int)c + 1;
594 // Process each component
595 for (int i = 0; i < numComps; ++i) {
596 int pos = startPos[i];
598 if (compString[pos] == 'm' || compString[pos] == 'M') {
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(), "");
609 if (comp.coord2 < 0 || comp.coord2 >= rows) {
610 error(loc, "matrix column component out of range", compString.c_str(), "");
613 components.push_back(comp);
619 // If the 'comps' express a column of a matrix,
620 // return the column. Column means the first coords all match.
622 // Otherwise, return -1.
624 int HlslParseContext::getMatrixComponentsColumn(int rows, const TSwizzleSelectors<TMatrixSelector>& selector)
628 // right number of comps?
629 if (selector.size() != rows)
632 // all comps in the same column?
634 col = selector[0].coord1;
635 for (int i = 0; i < rows; ++i) {
636 if (col != selector[i].coord1)
638 if (i != selector[i].coord2)
646 // Handle seeing a variable identifier in the grammar.
648 TIntermTyped* HlslParseContext::handleVariable(const TSourceLoc& loc, const TString* string)
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(), "");
657 // Error check for requiring specific extensions present.
658 if (symbol && symbol->getNumExtensions())
659 requireExtensions(loc, symbol->getNumExtensions(), symbol->getExtensions(), symbol->getName().c_str());
661 const TVariable* variable = nullptr;
662 const TAnonMember* anon = symbol ? symbol->getAsAnonMember() : nullptr;
663 TIntermTyped* node = nullptr;
665 // It was a member of an anonymous container, which could be a 'this' structure.
667 // Create a subtree for its dereference.
669 variable = getImplicitThis(thisDepth);
670 if (variable == nullptr)
671 error(loc, "cannot access member variables (static member function?)", "this", "");
673 if (variable == nullptr)
674 variable = anon->getAnonContainer().getAsVariable();
676 TIntermTyped* container = intermediate.addSymbol(*variable, loc);
677 TIntermTyped* constNode = intermediate.addConstantUnion(anon->getMemberNumber(), loc);
678 node = intermediate.addIndex(EOpIndexDirectStruct, container, constNode, loc);
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(), "");
684 // Not a member of an anonymous container.
686 // The symbol table search was done in the lexical phase.
687 // See if it was a variable.
688 variable = symbol ? symbol->getAsVariable() : nullptr;
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(), "");
697 error(loc, "variable name expected", string->c_str(), "");
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));
706 if (variable->getType().getQualifier().isFrontEndConstant())
707 node = intermediate.addConstantUnion(variable->getConstArray(), variable->getType(), loc);
709 node = intermediate.addSymbol(*variable, loc);
712 if (variable->getType().getQualifier().isIo())
713 intermediate.addIoAccessed(*string);
719 // Handle operator[] on any objects it applies to. Currently:
723 TIntermTyped* HlslParseContext::handleBracketOperator(const TSourceLoc& loc, TIntermTyped* base, TIntermTyped* index)
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.
734 TIntermAggregate* load = new TIntermAggregate(sampler.isImage() ? EOpImageLoad : EOpTextureFetch);
736 TType sampReturnType;
737 getTextureReturnType(sampler, sampReturnType);
739 load->setType(sampReturnType);
741 load->getSequence().push_back(base);
742 load->getSequence().push_back(index);
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();
750 load->getSequence().push_back(intermediate.addConstantUnion(0, loc, true));
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)
766 // Now we'll apply the [] index to that array
767 const TOperator idxOp = (index->getQualifier().storage == EvqConst) ? EOpIndexDirect : EOpIndexIndirect;
769 TIntermTyped* element = intermediate.addIndex(idxOp, sbArray, index, loc);
770 const TType derefType(sbArray->getType(), 0);
771 element->setType(derefType);
779 // Cast index value to a uint if it isn't already (for operator[], load indexes, etc)
780 TIntermTyped* HlslParseContext::makeIntegerIndex(TIntermTyped* index)
782 const TBasicType indexBasicType = index->getType().getBasicType();
783 const int vecSize = index->getType().getVectorSize();
785 // We can use int types directly as the index
786 if (indexBasicType == EbtInt || indexBasicType == EbtUint ||
787 indexBasicType == EbtInt64 || indexBasicType == EbtUint64)
790 // Cast index to unsigned integer if it isn't one.
791 return intermediate.addConversion(EOpConstructUint, TType(EbtUint, EvqTemporary, vecSize), index);
795 // Handle seeing a base[index] dereference in the grammar.
797 TIntermTyped* HlslParseContext::handleBracketDereference(const TSourceLoc& loc, TIntermTyped* base, TIntermTyped* index)
799 index = makeIntegerIndex(index);
801 if (index == nullptr) {
802 error(loc, " unknown index type ", "", "");
806 TIntermTyped* result = handleBracketOperator(loc, base, index);
808 if (result != nullptr)
809 return result; // it was handled as an operator[]
811 bool flattened = false;
813 if (index->getQualifier().isFrontEndConstant())
814 indexValue = index->getAsConstantUnion()->getConstArray()[0].getIConst();
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(), "");
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);
828 // at least one of base and index is variable...
830 if (index->getQualifier().isFrontEndConstant())
831 checkIndex(loc, base->getType(), indexValue);
833 if (base->getType().isScalarOrVec1())
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(), "");
839 result = flattenAccess(base, indexValue);
840 flattened = (result != base);
842 if (index->getQualifier().isFrontEndConstant()) {
843 if (base->getType().isUnsizedArray())
844 base->getWritableType().updateImplicitArraySize(indexValue + 1);
846 checkIndex(loc, base->getType(), indexValue);
847 result = intermediate.addIndex(EOpIndexDirect, base, index, loc);
849 result = intermediate.addIndex(EOpIndexIndirect, base, index, loc);
853 if (result == nullptr) {
854 // Insert dummy error-recovery result
855 result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
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.
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;
866 newType.getQualifier().storage = EvqTemporary;
867 result->setType(newType);
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)
878 TIntermTyped* result = intermediate.addBinaryMath(op, left, right, loc);
879 if (result == nullptr)
880 binaryOpError(loc, str, left->getCompleteString(), right->getCompleteString());
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)
889 TIntermTyped* result = intermediate.addUnaryMath(op, childNode, loc);
894 unaryOpError(loc, str, childNode->getCompleteString());
899 // Return true if the name is a struct buffer method
901 bool HlslParseContext::isStructBufferMethod(const TString& name) const
904 name == "GetDimensions" ||
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" ||
929 // Handle seeing a base.field dereference in the grammar, where 'field' is a
930 // swizzle or member variable.
932 TIntermTyped* HlslParseContext::handleDotDereference(const TSourceLoc& loc, TIntermTyped* base, const TString& field)
936 if (base->isArray()) {
937 error(loc, "cannot apply to an array:", ".", field.c_str());
941 TIntermTyped* result = base;
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.
952 error(loc, "unexpected texture type for .mips[][] operator:",
953 base->getType().getCompleteString().c_str(), "");
955 error(loc, "unexpected operator on texture type:", field.c_str(),
956 base->getType().getCompleteString().c_str());
958 } else if (base->isVector() || base->isScalar()) {
959 TSwizzleSelectors<TVectorSelector> selectors;
960 parseSwizzleSelector(loc, field, base->getVectorSize(), selectors);
962 if (base->isScalar()) {
963 if (selectors.size() == 1)
966 TType type(base->getBasicType(), EvqTemporary, selectors.size());
967 return addConstructor(loc, base, type);
970 if (base->getVectorSize() == 1) {
971 TType scalarType(base->getBasicType(), EvqTemporary, 1);
972 if (selectors.size() == 1)
973 return addConstructor(loc, base, scalarType);
975 TType vectorType(base->getBasicType(), EvqTemporary, selectors.size());
976 return addConstructor(loc, addConstructor(loc, base, scalarType), vectorType);
980 if (base->getType().getQualifier().isFrontEndConstant())
981 result = intermediate.foldSwizzle(base, selectors, loc);
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));
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,
994 } else if (base->isMatrix()) {
995 TSwizzleSelectors<TMatrixSelector> selectors;
996 if (! parseMatrixSwizzleSelector(loc, field, base->getMatrixCols(), base->getMatrixRows(), selectors))
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);
1005 result = intermediate.addIndex(EOpIndexDirect, base,
1006 intermediate.addConstantUnion(selectors[0].coord1, loc),
1008 TType dereferencedCol(base->getType(), 0);
1009 result->setType(dereferencedCol);
1010 result = intermediate.addIndex(EOpIndexDirect, result,
1011 intermediate.addConstantUnion(selectors[0].coord2, loc),
1013 TType dereferenced(dereferencedCol, 0);
1014 result->setType(dereferenced);
1017 int column = getMatrixComponentsColumn(base->getMatrixRows(), selectors);
1019 // Representable by m[c]
1020 if (base->getType().getQualifier().isFrontEndConstant())
1021 result = intermediate.foldDereference(base, column, loc);
1023 result = intermediate.addIndex(EOpIndexDirect, base, intermediate.addConstantUnion(column, loc),
1025 TType dereferenced(base->getType(), 0);
1026 result->setType(dereferenced);
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,
1036 } else if (base->getBasicType() == EbtStruct || base->getBasicType() == EbtBlock) {
1037 const TTypeList* fields = base->getType().getStruct();
1038 bool fieldFound = false;
1040 for (member = 0; member < (int)fields->size(); ++member) {
1041 if ((*fields)[member].type->getFieldName() == field) {
1047 if (base->getAsSymbolNode() && wasFlattened(base)) {
1048 result = flattenAccess(base, member);
1050 if (base->getType().getQualifier().storage == EvqConst)
1051 result = intermediate.foldDereference(base, member, loc);
1053 TIntermTyped* index = intermediate.addConstantUnion(member, loc);
1054 result = intermediate.addIndex(EOpIndexDirectStruct, base, index, loc);
1055 result->setType(*(*fields)[member].type);
1059 error(loc, "no such field in structure", field.c_str(), "");
1061 error(loc, "does not apply to this type:", field.c_str(), base->getType().getCompleteString().c_str());
1067 // Return true if the field should be treated as a built-in method.
1068 // Return false otherwise.
1070 bool HlslParseContext::isBuiltInMethod(const TSourceLoc&, TIntermTyped* base, const TString& field)
1072 if (base == nullptr)
1075 variableCheck(base);
1077 if (base->getType().getBasicType() == EbtSampler) {
1079 } else if (isStructBufferType(base->getType()) && isStructBufferMethod(field)) {
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.
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)
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
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())
1105 TVariable* ioVar = makeInternalVariable(baseName + "." + memberType.getFieldName(), memberType);
1107 if (arraySizes != nullptr && !memberType.isArray())
1108 ioVar->getWritableType().copyArraySizes(*arraySizes);
1110 splitBuiltIns[tInterstageIoData(memberType.getQualifier().builtIn, outerQualifier.storage)] = ioVar;
1111 if (!isClipOrCullDistance(ioVar->getType()))
1112 trackLinkage(*ioVar);
1114 // Merge qualifier from the user structure
1115 mergeQualifiers(ioVar->getWritableType().getQualifier(), outerQualifier);
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());
1122 // But, not location, we're losing that
1123 ioVar->getWritableType().getQualifier().layoutLocation = TQualifier::layoutLocationEnd;
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)
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);
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)
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);
1149 split(*ioType->type, name + "." + ioType->type->getFieldName(), outerQualifier);
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
1164 switch (qualifier) {
1167 return type.isStruct() || type.isArray();
1169 return (type.isArray() && intermediate.getFlattenUniformArrays() && topLevel) ||
1170 (type.isStruct() && type.containsOpaque());
1176 // Top level variable flattening: construct data
1177 void HlslParseContext::flatten(const TVariable& variable, bool linkage)
1179 const TType& type = variable.getType();
1181 // If it's a standalone built-in, there is nothing to flatten
1182 if (type.isBuiltIn() && !type.isStruct())
1185 auto entry = flattenMap.insert(std::make_pair(variable.getUniqueId(),
1186 TFlattenData(type.getQualifier().layoutBinding,
1187 type.getQualifier().layoutLocation)));
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);
1193 // Recursively flatten the given variable at the provided type, building the flattenData as we go.
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.
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.
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:
1209 // struct { float2 a[2]; int b; float4 c[3] };
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}
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
1218 // so the 4th flattened member in traversal order is ours.
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)
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.
1228 return flattenArray(variable, type, flattenData, name, linkage, outerQualifier);
1229 else if (type.isStruct())
1230 return flattenStruct(variable, type, flattenData, name, linkage, outerQualifier, builtInArraySizes);
1232 assert(0); // should never happen
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)
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());
1249 if (flattenData.nextBinding != TQualifier::layoutBindingEnd)
1250 memberVariable->getWritableType().getQualifier().layoutBinding = flattenData.nextBinding++;
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;
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);
1264 flattenData.offsets.push_back(static_cast<int>(flattenData.members.size()));
1265 flattenData.members.push_back(memberVariable);
1268 trackLinkage(*memberVariable);
1270 return static_cast<int>(flattenData.offsets.size()) - 1; // location of the member reference
1272 // Further recursion required
1273 return flatten(variable, type, flattenData, memberName, linkage, outerQualifier, builtInArraySizes);
1277 // Figure out the mapping between an aggregate's top members and an
1278 // equivalent set of individual variables.
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)
1286 assert(type.isStruct());
1288 auto members = *type.getStruct();
1290 // Reserve space for this tree level.
1291 int start = static_cast<int>(flattenData.offsets.size());
1293 flattenData.offsets.resize(int(pos + members.size()), -1);
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);
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;
1313 // Figure out mapping between an array's members and an
1314 // equivalent set of individual variables.
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)
1321 assert(type.isSizedArray());
1323 const int size = type.getOuterArraySize();
1324 const TType dereferencedType(type, 0);
1327 name = variable.getName();
1329 // Reserve space for this tree level.
1330 int start = static_cast<int>(flattenData.offsets.size());
1332 flattenData.offsets.resize(int(pos + size), -1);
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());
1341 flattenData.offsets[pos++] = mpos;
1347 // Return true if we have flattened this node.
1348 bool HlslParseContext::wasFlattened(const TIntermTyped* node) const
1350 return node != nullptr && node->getAsSymbolNode() != nullptr &&
1351 wasFlattened(node->getAsSymbolNode()->getId());
1354 // Return true if we have split this structure
1355 bool HlslParseContext::wasSplit(const TIntermTyped* node) const
1357 return node != nullptr && node->getAsSymbolNode() != nullptr &&
1358 wasSplit(node->getAsSymbolNode()->getId());
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)
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());
1371 return flattened ? flattened : base;
1373 TIntermTyped* HlslParseContext::flattenAccess(int uniqueId, int member, TStorageQualifier outerStorage,
1374 const TType& dereferencedType, int subset)
1376 const auto flattenData = flattenMap.find(uniqueId);
1378 if (flattenData == flattenMap.end())
1381 // Calculate new cumulative offset from the packed tree
1382 int newSubset = flattenData->second.offsets[subset >= 0 ? subset + member : member];
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);
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);
1399 return subsetSymbol;
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.
1406 // Returns the offset into the first leaf of the subset.
1407 int HlslParseContext::findSubtreeOffset(const TIntermNode& node) const
1409 const TIntermSymbol* sym = node.getAsSymbolNode();
1412 if (!sym->isArray() && !sym->isStruct())
1414 int subset = sym->getFlattenSubset();
1418 // Getting this far means a partial aggregate is identified by the flatten subset.
1419 // Find the first leaf of the subset.
1421 const auto flattenData = flattenMap.find(sym->getId());
1422 if (flattenData == flattenMap.end())
1425 return findSubtreeOffset(sym->getType(), subset, flattenData->second.offsets);
1428 subset = flattenData->second.offsets[subset];
1431 // Recursively do the desent
1432 int HlslParseContext::findSubtreeOffset(const TType& type, int subset, const TVector<int>& offsets) const
1434 if (!type.isArray() && !type.isStruct())
1435 return offsets[subset];
1436 TType derefType(type, 0);
1437 return findSubtreeOffset(derefType, offsets[subset], offsets);
1440 // Find and return the split IO TVariable for id, or nullptr if none.
1441 TVariable* HlslParseContext::getSplitNonIoVar(int id) const
1443 const auto splitNonIoVar = splitNonIoVars.find(id);
1444 if (splitNonIoVar == splitNonIoVars.end())
1447 return splitNonIoVar->second;
1450 // Pass through to base class after remembering built-in mappings.
1451 void HlslParseContext::trackLinkage(TSymbol& symbol)
1453 TBuiltInVariable biType = symbol.getType().getQualifier().builtIn;
1455 if (biType != EbvNone)
1456 builtInTessLinkageSymbols[biType] = symbol.clone();
1458 TParseContextBase::trackLinkage(symbol);
1462 // Returns true if the built-in is a clip or cull distance variable.
1463 bool HlslParseContext::isClipOrCullDistance(TBuiltInVariable builtIn)
1465 return builtIn == EbvClipDistance || builtIn == EbvCullDistance;
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)
1475 int requiredArraySize = 0;
1476 int requiredVectorSize = 0;
1478 switch (type.getQualifier().builtIn) {
1479 case EbvTessLevelOuter: requiredArraySize = 4; break;
1480 case EbvTessLevelInner: requiredArraySize = 2; break;
1484 // Promote scalar to array of size 1. Leave existing arrays alone.
1485 if (!type.isArray())
1486 requiredArraySize = 1;
1490 case EbvWorkGroupId: requiredVectorSize = 3; break;
1491 case EbvGlobalInvocationId: requiredVectorSize = 3; break;
1492 case EbvLocalInvocationId: requiredVectorSize = 3; break;
1493 case EbvTessCoord: requiredVectorSize = 3; break;
1496 if (isClipOrCullDistance(type)) {
1497 const int loc = type.getQualifier().layoutLocation;
1499 if (type.getQualifier().builtIn == EbvClipDistance) {
1500 if (type.getQualifier().storage == EvqVaryingIn)
1501 clipSemanticNSizeIn[loc] = type.getVectorSize();
1503 clipSemanticNSizeOut[loc] = type.getVectorSize();
1505 if (type.getQualifier().storage == EvqVaryingIn)
1506 cullSemanticNSizeIn[loc] = type.getVectorSize();
1508 cullSemanticNSizeOut[loc] = type.getVectorSize();
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();
1520 type.shallowCopy(newType);
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);
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)
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.
1548 if (type.isArray() && qualifier.isArrayedIo(language)) {
1549 TType elementType(type, 0);
1550 size = intermediate.computeTypeLocationSize(elementType, language);
1552 size = intermediate.computeTypeLocationSize(type, language);
1554 if (qualifier.storage == EvqVaryingIn) {
1555 variable.getWritableType().getQualifier().layoutLocation = nextInLocation;
1556 nextInLocation += size;
1558 variable.getWritableType().getQualifier().layoutLocation = nextOutLocation;
1559 nextOutLocation += size;
1562 trackLinkage(variable);
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);
1575 assignLocation(variable);
1580 // Handle seeing a function declarator in the grammar. This is the precursor
1581 // to recognizing a function prototype or function definition.
1583 void HlslParseContext::handleFunctionDeclarator(const TSourceLoc& loc, TFunction& function, bool prototype)
1586 // Multiple declarations of the same function name are allowed.
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).
1592 TSymbol* symbol = symbolTable.find(function.getMangledName(), &builtIn);
1593 const TFunction* prevDec = symbol ? symbol->getAsFunction() : 0;
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();
1601 if (prevDec && ! builtIn)
1602 symbol->getAsFunction()->setPrototyped(); // need a writable one, but like having prevDec as a const
1603 function.setPrototyped();
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(), "");
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)
1619 if (! hasStructBuffCounter(*param.type))
1622 const TString counterBlockName(intermediate.addCounterBufferName(*param.name));
1625 counterBufferType(loc, counterType);
1626 TVariable *variable = makeInternalVariable(counterBlockName, counterType);
1628 if (! symbolTable.insert(*variable))
1629 error(loc, "redefinition", variable->getName().c_str(), "");
1631 paramNodes = intermediate.growAggregate(paramNodes,
1632 intermediate.addSymbol(*variable, loc),
1637 // Handle seeing the function prototype in front of a function definition in the grammar.
1638 // The body is handled after this function returns.
1640 // Returns an aggregate of parameter-symbol nodes.
1642 TIntermAggregate* HlslParseContext::handleFunctionDefinition(const TSourceLoc& loc, TFunction& function,
1643 const TAttributes& attributes,
1644 TIntermNode*& entryPointTree)
1646 currentCaller = function.getMangledName();
1647 TSymbol* symbol = symbolTable.find(function.getMangledName());
1648 TFunction* prevDec = symbol ? symbol->getAsFunction() : nullptr;
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.
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(), "");
1660 if (prevDec && ! prevDec->isDefined()) {
1661 prevDec->setDefined();
1663 // Remember the return type for later checking for RETURN statements.
1664 currentFunctionType = &(prevDec->getType());
1666 currentFunctionType = new TType(EbtVoid);
1667 functionReturnsValue = false;
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);
1674 // New symbol table scope for body of function plus its arguments
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).
1683 // Also, accumulate the list of parameters into the AST, so lower level code
1684 // knows where to find parameters.
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);
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);
1699 // Insert the parameters with name in the symbol table.
1700 if (! symbolTable.insert(*variable))
1701 error(loc, "redefinition", variable->getName().c_str(), "");
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),
1717 // Add the parameter to the AST
1718 paramNodes = intermediate.growAggregate(paramNodes,
1719 intermediate.addSymbol(*variable, loc),
1723 // Add hidden AST parameter for struct buffer counters, if needed.
1724 addStructBufferHiddenCounterParam(loc, param, paramNodes);
1726 paramNodes = intermediate.growAggregate(paramNodes, intermediate.addSymbol(*param.type, loc), loc);
1728 if (function.hasIllegalImplicitThis())
1729 pushImplicitThis(nullptr);
1731 intermediate.setAggregateOperator(paramNodes, EOpParameters, TType(EbtVoid), loc);
1732 loopNestingLevel = 0;
1733 controlFlowNestingLevel = 0;
1734 postEntryPointReturn = false;
1739 // Handle all [attrib] attribute for the shader entry point
1740 void HlslParseContext::handleEntryPointAttributes(const TSourceLoc& loc, const TAttributes& attributes)
1742 for (auto it = attributes.begin(); it != attributes.end(); ++it) {
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());
1751 case EatMaxVertexCount:
1755 if (! it->getInt(maxVertexCount)) {
1756 error(loc, "invalid maxvertexcount", "", "");
1758 if (! intermediate.setVertices(maxVertexCount))
1759 error(loc, "cannot change previously set maxvertexcount attribute", "", "");
1763 case EatPatchConstantFunc:
1766 if (! it->getString(pcfName, 0, false)) {
1767 error(loc, "invalid patch constant function", "", "");
1769 patchConstantFunctionName = pcfName;
1775 // Handle [domain("...")]
1777 if (! it->getString(domainStr)) {
1778 error(loc, "invalid domain", "", "");
1780 TLayoutGeometry domain = ElgNone;
1782 if (domainStr == "tri") {
1783 domain = ElgTriangles;
1784 } else if (domainStr == "quad") {
1786 } else if (domainStr == "isoline") {
1787 domain = ElgIsolines;
1789 error(loc, "unsupported domain type", domainStr.c_str(), "");
1792 if (language == EShLangTessEvaluation) {
1793 if (! intermediate.setInputPrimitive(domain))
1794 error(loc, "cannot change previously set domain", TQualifier::getGeometryString(domain), "");
1796 if (! intermediate.setOutputPrimitive(domain))
1797 error(loc, "cannot change previously set domain", TQualifier::getGeometryString(domain), "");
1802 case EatOutputTopology:
1804 // Handle [outputtopology("...")]
1805 TString topologyStr;
1806 if (! it->getString(topologyStr)) {
1807 error(loc, "invalid outputtopology", "", "");
1809 TVertexOrder vertexOrder = EvoNone;
1810 TLayoutGeometry primitive = ElgNone;
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;
1823 error(loc, "unsupported outputtopology type", topologyStr.c_str(), "");
1826 if (vertexOrder != EvoNone) {
1827 if (! intermediate.setVertexOrder(vertexOrder)) {
1828 error(loc, "cannot change previously set outputtopology",
1829 TQualifier::getVertexOrderString(vertexOrder), "");
1832 if (primitive != ElgNone)
1833 intermediate.setOutputPrimitive(primitive);
1837 case EatPartitioning:
1839 // Handle [partitioning("...")]
1840 TString partitionStr;
1841 if (! it->getString(partitionStr)) {
1842 error(loc, "invalid partitioning", "", "");
1844 TVertexSpacing partitioning = EvsNone;
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.
1854 error(loc, "unsupported partitioning type", partitionStr.c_str(), "");
1857 if (! intermediate.setVertexSpacing(partitioning))
1858 error(loc, "cannot change previously set partitioning",
1859 TQualifier::getVertexSpacingString(partitioning), "");
1863 case EatOutputControlPoints:
1865 // Handle [outputcontrolpoints("...")]
1867 if (! it->getInt(ctrlPoints)) {
1868 error(loc, "invalid outputcontrolpoints", "", "");
1870 if (! intermediate.setVertices(ctrlPoints)) {
1871 error(loc, "cannot change previously set outputcontrolpoints attribute", "", "");
1878 // tolerate these because of dual use of entrypoint and type attributes
1881 warn(loc, "attribute does not apply to entry point", "", "");
1887 // Update the given type with any type-like attribute information in the
1889 void HlslParseContext::transferTypeAttributes(const TSourceLoc& loc, const TAttributes& attributes, TType& type,
1892 if (attributes.size() == 0)
1896 TString builtInString;
1897 for (auto it = attributes.begin(); it != attributes.end(); ++it) {
1901 if (it->getInt(value))
1902 type.getQualifier().layoutLocation = value;
1906 if (it->getInt(value)) {
1907 type.getQualifier().layoutBinding = value;
1908 type.getQualifier().layoutSet = 0;
1911 if (it->getInt(value, 1))
1912 type.getQualifier().layoutSet = value;
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;
1922 case EatInputAttachment:
1924 if (it->getInt(value))
1925 type.getQualifier().layoutAttachment = value;
1928 // PointSize built-in
1929 if (it->getString(builtInString, 0, false)) {
1930 if (builtInString == "PointSize")
1931 type.getQualifier().builtIn = EbvPointSize;
1934 case EatPushConstant:
1936 type.getQualifier().layoutPushConstant = true;
1939 // specialization constant
1940 if (it->getInt(value)) {
1943 setSpecConstantId(loc, type.getQualifier(), value);
1948 warn(loc, "attribute does not apply to a type", "", "");
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.
1960 // retType shaderEntryPoint(args...) // shader declared entry point
1966 // in iargs<that are input>...;
1967 // out oargs<that are output> ...;
1969 // void shaderEntryPoint() // synthesized, but official, entry point
1971 // args<that are input> = iargs...;
1972 // ret = @shaderEntryPoint(args...);
1973 // oargs = args<that are output>...;
1975 // retType @shaderEntryPoint(args...)
1978 // The symbol table will still map the original entry point name to the
1979 // the modified function and its new name:
1981 // symbol table: shaderEntryPoint -> @shaderEntryPoint
1983 // Returns nullptr if no entry-point tree was built, otherwise, returns
1984 // a subtree that creates the entry point.
1986 TIntermNode* HlslParseContext::transformEntryPoint(const TSourceLoc& loc, TFunction& userFunction,
1987 const TAttributes& attributes)
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;
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);
2004 entryPointFunction = &userFunction; // needed in finish()
2006 // Handle entry point attributes
2007 handleEntryPointAttributes(loc, attributes);
2009 // entry point logic...
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);
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())
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() */);
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
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);
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));
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));
2055 // Synthesize the call
2057 pushScope(); // matches the one in handleFunctionBody()
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
2068 // change original name
2069 userFunction.addPrefix("@"); // change the name in the function, but not in the symbol table
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;
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();
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();
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)));
2096 currentCaller = synthEntryPoint.getMangledName();
2097 TIntermTyped* callReturn = handleFunctionCall(loc, &callee, callingArgs);
2098 currentCaller = userFunction.getMangledName();
2101 if (entryPointOutput) {
2102 TIntermTyped* returnAssign;
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);
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;
2116 TVariable* variable = makeInternalVariable(*invocationIdName, invocationIdType);
2118 globalQualifierFix(loc, variable->getWritableType().getQualifier());
2119 trackLinkage(*variable);
2121 invocationIdSym = intermediate.addSymbol(*variable);
2124 TIntermTyped* element = intermediate.addIndex(EOpIndexIndirect, intermediate.addSymbol(*entryPointOutput),
2125 invocationIdSym, loc);
2127 // Set the type of the array element being dereferenced
2128 const TType derefElementType(entryPointOutput->getType(), 0);
2129 element->setType(derefElementType);
2131 returnAssign = handleAssign(loc, EOpAssign, element, callReturn);
2133 returnAssign = handleAssign(loc, EOpAssign, intermediate.addSymbol(*entryPointOutput), callReturn);
2135 intermediate.growAggregate(synthBody, returnAssign);
2137 intermediate.growAggregate(synthBody, callReturn);
2140 auto outputIt = outputs.begin();
2141 for (int i = 0; i < userFunction.getParamCount(); i++) {
2142 TParameter& param = userFunction[i];
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;
2152 intermediate.growAggregate(synthBody, handleAssign(loc, EOpAssign,
2153 intermediate.addSymbol(**outputIt),
2154 intermediate.addSymbol(*argVars[i])));
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);
2167 entryPointFunctionBody = synthBody;
2169 return synthFunctionDef;
2172 void HlslParseContext::handleFunctionBody(const TSourceLoc& loc, TFunction& function, TIntermNode* functionBody,
2175 node = intermediate.growAggregate(node, functionBody);
2176 intermediate.setAggregateOperator(node, EOpFunction, function.getType(), loc);
2177 node->getAsAggregate()->setName(function.getMangledName().c_str());
2180 if (function.hasImplicitThis())
2183 if (function.getType().getBasicType() != EbtVoid && ! functionReturnsValue)
2184 error(loc, "function does not return a value:", "", function.getName().c_str());
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)
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);
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);
2221 // install the new input type
2222 if (it == ioTypeMap.end()) {
2223 tIoKinds newLists = { list, nullptr, nullptr };
2224 ioTypeMap[type.getStruct()] = newLists;
2226 it->second.input = list;
2229 finalList = it->second.input;
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;
2238 type.getQualifier().clearInterpolation();
2239 type.getQualifier().flat = true;
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);
2258 if (storage == EvqVaryingIn) {
2259 correctInput(ioVariable->getWritableType().getQualifier());
2260 if (language == EShLangTessEvaluation)
2261 if (!ioVariable->getType().isArray())
2262 ioVariable->getWritableType().getQualifier().patch = true;
2264 correctOutput(ioVariable->getWritableType().getQualifier());
2266 ioVariable->getWritableType().getQualifier().storage = storage;
2268 fixBuiltInIoType(ioVariable->getWritableType());
2273 // return value is actually a shader-scoped output (out)
2274 if (function.getType().getBasicType() == EbtVoid) {
2275 returnValue = nullptr;
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.
2281 returnValue = makeIoVariable("@entryPointOutput", function.getWritableType(), EvqVaryingOut);
2284 outputType.shallowCopy(function.getType());
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);
2291 clearUniformInputOutput(function.getWritableType().getQualifier());
2292 returnValue = makeIoVariable("@entryPointOutput", outputType, EvqVaryingOut);
2294 returnValue = makeIoVariable("@entryPointOutput", function.getWritableType(), EvqVaryingOut);
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);
2306 if (paramType.getQualifier().isParamOutput()) {
2307 TVariable* argAsGlobal = makeIoVariable(function[i].name->c_str(), paramType, EvqVaryingOut);
2308 outputs.push_back(argAsGlobal);
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)
2318 if (function.getType().getBasicType() != EbtVoid)
2319 clearUniformInputOutput(function.getWritableType().getQualifier());
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());
2328 // Handle function returns, including type conversions to the function return type
2330 TIntermNode* HlslParseContext::handleReturnValue(const TSourceLoc& loc, TIntermTyped* value)
2332 functionReturnsValue = true;
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", "");
2347 return intermediate.addBranch(EOpReturn, value, loc);
2350 void HlslParseContext::handleFunctionArgument(TFunction* function,
2351 TIntermTyped*& arguments, TIntermTyped* newArg)
2353 TParameter param = { 0, new TType, nullptr };
2354 param.type->shallowCopy(newArg->getType());
2356 function->addParameter(param);
2358 arguments = intermediate.growAggregate(arguments, newArg);
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)
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);
2373 // If we get here, we should invert Y.
2374 TIntermAggregate* assignList = nullptr;
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();
2382 TIntermTyped* rhsTempSym = intermediate.addSymbol(*rhsTempVar, loc);
2383 assignList = intermediate.growAggregate(assignList,
2384 intermediate.addAssign(EOpAssign, rhsTempSym, right, loc), loc);
2391 TIntermTyped* tempSymL = intermediate.addSymbol(*rhsTempVar, loc);
2392 TIntermTyped* tempSymR = intermediate.addSymbol(*rhsTempVar, loc);
2393 TIntermTyped* index = intermediate.addConstantUnion(Y, loc);
2395 TIntermTyped* lhsElement = intermediate.addIndex(EOpIndexDirect, tempSymL, index, loc);
2396 TIntermTyped* rhsElement = intermediate.addIndex(EOpIndexDirect, tempSymR, index, loc);
2398 const TType derefType(right->getType(), 0);
2400 lhsElement->setType(derefType);
2401 rhsElement->setType(derefType);
2403 TIntermTyped* yNeg = intermediate.addUnaryMath(EOpNegative, rhsElement, loc);
2405 assignList = intermediate.growAggregate(assignList, intermediate.addAssign(EOpAssign, lhsElement, yNeg, loc));
2408 // Assign the rhs temp (now with Y inversion) to the final output
2410 TIntermTyped* rhsTempSym = intermediate.addSymbol(*rhsTempVar, loc);
2411 assignList = intermediate.growAggregate(assignList, intermediate.addAssign(op, left, rhsTempSym, loc));
2414 assert(assignList != nullptr);
2415 assignList->setOperator(EOpSequence);
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.
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)
2431 case EShLangFragment:
2433 case EShLangGeometry:
2436 error(loc, "unimplemented: clip/cull not currently implemented for this stage", "", "");
2440 TVariable** clipCullVar = nullptr;
2442 // Figure out if we are assigning to, or from, clip or cull distance.
2443 const bool isOutput = isClipOrCullDistance(left->getType());
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;
2450 const TBuiltInVariable builtInType = clipCullNode->getQualifier().builtIn;
2452 decltype(clipSemanticNSizeIn)* semanticNSize = nullptr;
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;
2460 case EbvCullDistance:
2461 clipCullVar = isOutput ? &cullDistanceOutput : &cullDistanceInput;
2462 semanticNSize = isOutput ? &cullSemanticNSizeOut : &cullSemanticNSizeIn;
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;
2470 // This is the offset in the destination array of a given semantic's data
2471 std::array<int, maxClipCullRegs> semanticOffset;
2473 // Calculate offset of variable of semantic N in destination array
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
2484 semanticOffset[x] = arrayLoc;
2485 vecItems += (*semanticNSize)[x];
2486 arrayLoc += (*semanticNSize)[x];
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;
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);
2499 // The created type may be an array of arrays, e.g, for geometry shader inputs.
2500 const bool isImplicitlyArrayed = (language == EShLangGeometry && !isOutput);
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:
2511 // Of those, semantic ID and array size cannot appear simultaneously.
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.
2517 const bool useInnerSize = internalArrayDims > 1 || !isImplicitlyArrayed;
2519 const int requiredInnerArraySize = arrayLoc * (useInnerSize ? internalInnerArraySize : 1);
2520 const int requiredOuterArraySize = (internalArrayDims > 0) ? internalArraySizes->getDimSize(0) : 1;
2522 TType clipCullType(EbtFloat, clipCullNode->getType().getQualifier().storage, 1);
2523 clipCullType.getQualifier() = clipCullNode->getType().getQualifier();
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);
2532 // Obtain symbol name: we'll use that for the symbol we introduce.
2533 TIntermSymbol* sym = clipCullNode->getAsSymbolNode();
2534 assert(sym != nullptr);
2536 // We are moving the semantic ID from the layout location, so it is no longer needed or
2538 clipCullType.getQualifier().layoutLocation = TQualifier::layoutLocationEnd;
2540 // Create variable and track its linkage
2541 *clipCullVar = makeInternalVariable(sym->getName().c_str(), clipCullType);
2543 trackLinkage(**clipCullVar);
2546 // Create symbol for the clip or cull variable.
2547 TIntermSymbol* clipCullSym = intermediate.addSymbol(**clipCullVar);
2550 const int clipCullVectorSize = clipCullSym->getType().getVectorSize();
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);
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);
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;
2567 // Holds individual component assignments as we make them.
2568 TIntermTyped* clipCullAssign = nullptr;
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) {
2578 clipCullAssign = intermediate.addAssign(op, clipCullSym, internalNode, loc);
2580 clipCullAssign = intermediate.addAssign(op, internalNode, clipCullSym, loc);
2582 assignList = intermediate.growAggregate(assignList, clipCullAssign);
2583 assignList->setOperator(EOpSequence);
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;
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);
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;
2609 // If implicitly arrayed, there is an outer array dimension involved
2610 if (isImplicitlyArrayed)
2611 clipCullMember = addIndex(clipCullMember, clipCullOuterArrayPos);
2613 // Index into proper array position for clip cull member
2614 clipCullMember = addIndex(clipCullMember, clipCullInnerArrayPos++);
2616 // if needed, start over with next outer array slice.
2617 if (isImplicitlyArrayed && clipCullInnerArrayPos >= clipCullInnerArraySize) {
2618 clipCullInnerArrayPos = semanticOffset[semanticId];
2619 ++clipCullOuterArrayPos;
2622 // internal member to read from / write to:
2623 TIntermTyped* internalMember = internalNode;
2625 // If internal node has outer array dimension, index appropriately.
2626 if (internalArrayDims > 1)
2627 internalMember = addIndex(internalMember, internalOuterArrayPos);
2629 // If internal node has inner array dimension, index appropriately.
2630 if (internalArrayDims > 0)
2631 internalMember = addIndex(internalMember, internalInnerArrayPos);
2633 // If internal node is a vector, extract the component of interest.
2634 if (internalNode->getType().isVector())
2635 internalMember = addIndex(internalMember, internalComponent);
2637 // Create an assignment: output from internal to clip cull, or input from clip cull to internal.
2639 clipCullAssign = intermediate.addAssign(op, clipCullMember, internalMember, loc);
2641 clipCullAssign = intermediate.addAssign(op, internalMember, clipCullMember, loc);
2643 // Track assignment in the sequence.
2644 assignList = intermediate.growAggregate(assignList, clipCullAssign);
2649 assert(assignList != nullptr);
2650 assignList->setOperator(EOpSequence);
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().
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)
2664 if (left == nullptr || right == nullptr)
2667 // writing to opaques will require fixing transforms
2668 if (left->getType().containsOpaque())
2669 intermediate.setNeedsLegalization();
2671 if (left->getAsOperator() && left->getAsOperator()->getOp() == EOpMatrixSwizzle)
2672 return handleAssignToMatrixSwizzle(loc, op, left, right);
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();
2678 if (binaryNode == nullptr)
2681 return (binaryNode->getOp() == EOpIndexDirect || binaryNode->getOp() == EOpIndexIndirect) &&
2682 wasSplit(binaryNode->getLeft());
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);
2691 const bool isSplitLeft = wasSplit(left) || indexesSplit(left);
2692 const bool isSplitRight = wasSplit(right) || indexesSplit(right);
2694 const bool isFlattenLeft = wasFlattened(left);
2695 const bool isFlattenRight = wasFlattened(right);
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());
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.
2720 return intermediate.addAssign(op, left, right, loc);
2723 TIntermAggregate* assignList = nullptr;
2724 const TVector<TVariable*>* leftVariables = nullptr;
2725 const TVector<TVariable*>* rightVariables = nullptr;
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;
2731 // If the RHS is a simple symbol node, we'll copy it for each member.
2732 TIntermSymbol* cloneSymNode = nullptr;
2734 int memberCount = 0;
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();
2743 leftVariables = &flattenMap.find(left->getAsSymbolNode()->getId())->second.members;
2745 if (isFlattenRight) {
2746 rightVariables = &flattenMap.find(right->getAsSymbolNode()->getId())->second.members;
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.
2753 if (memberCount <= 1) {
2754 // case 1: we'll use the symbol directly below. Nothing to do.
2756 if (right->getAsSymbolNode() != nullptr) {
2757 // case 2: we'll copy the symbol per iteration below.
2758 cloneSymNode = right->getAsSymbolNode();
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);
2765 // Add this to the aggregate being built.
2766 assignList = intermediate.growAggregate(assignList,
2767 intermediate.addAssign(op, noFlattenRHS, right, loc), loc);
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;
2777 TStorageQualifier leftStorage = left->getType().getQualifier().storage;
2778 TStorageQualifier rightStorage = right->getType().getQualifier().storage;
2780 int leftOffset = findSubtreeOffset(*left);
2781 int rightOffset = findSubtreeOffset(*right);
2783 const auto getMember = [&](bool isLeft, const TType& type, int member, TIntermTyped* splitNode, int splitMember,
2786 const bool split = isLeft ? isSplitLeft : isSplitRight;
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;
2798 if (builtInVar != nullptr) {
2799 // copy from interstage IO built-in if needed
2800 subTree = intermediate.addSymbol(*builtInVar);
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.
2814 const TType splitDerefType(subTree->getType(), 0);
2815 subTree = intermediate.addIndex(splitNode->getAsOperator()->getOp(), subTree,
2816 splitNode->getAsBinaryNode()->getRight(), loc);
2817 subTree->setType(splitDerefType);
2820 } else if (flattened && !shouldFlatten(derefType, isLeft ? leftStorage : rightStorage, false)) {
2822 subTree = intermediate.addSymbol(*(*leftVariables)[leftOffset++]);
2824 subTree = intermediate.addSymbol(*(*rightVariables)[rightOffset++]);
2826 // Index operator if it's an aggregate, else EOpNull
2827 const TOperator accessOp = type.isArray() ? EOpIndexDirect
2828 : type.isStruct() ? EOpIndexDirectStruct
2830 if (accessOp == EOpNull) {
2831 subTree = splitNode;
2833 subTree = intermediate.addIndex(accessOp, splitNode, intermediate.addConstantUnion(splitMember, loc),
2835 const TType splitDerefType(splitNode->getType(), splitMember);
2836 subTree->setType(splitDerefType);
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) :
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,
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:
2858 bool shouldFlattenSubsetLeft = isFlattenLeft && shouldFlatten(left->getType(), leftStorage, topLevel);
2859 bool shouldFlattenSubsetRight = isFlattenRight && shouldFlatten(right->getType(), rightStorage, topLevel);
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;
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);
2872 for (int element = 0; element < elementsToCopy; ++element) {
2873 arrayElement.push_back(element);
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);
2881 TIntermTyped* subSplitLeft = isSplitLeft ? getMember(true, left->getType(), element, splitLeft,
2882 element, shouldFlattenSubsetLeft)
2884 TIntermTyped* subSplitRight = isSplitRight ? getMember(false, right->getType(), element, splitRight,
2885 element, shouldFlattenSubsetRight)
2888 traverse(subLeft, subRight, subSplitLeft, subSplitRight, false);
2890 arrayElement.pop_back();
2892 } else if (left->getType().isStruct() && (shouldFlattenSubsetLeft || isSplitLeft ||
2893 shouldFlattenSubsetRight || isSplitRight)) {
2895 const auto& membersL = *left->getType().getStruct();
2896 const auto& membersR = *right->getType().getStruct();
2898 // These track the members in the split structures corresponding to the same in the unsplit structures,
2899 // which we traverse in parallel.
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);
2907 for (int member = 0; member < int(membersL.size()); ++member) {
2908 const TType& typeL = *membersL[member].type;
2909 const TType& typeR = *membersR[member].type;
2911 TIntermTyped* subLeft = getMember(true, left->getType(), member, left, member,
2912 shouldFlattenSubsetLeft);
2913 TIntermTyped* subRight = getMember(false, right->getType(), member, right, member,
2914 shouldFlattenSubsetRight);
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)
2920 TIntermTyped* subSplitRight = isSplitRight ? getMember(false, right->getType(), member, splitRight,
2921 memberR, shouldFlattenSubsetRight)
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;
2928 const bool isOutput = isClipOrCullDistance(subSplitLeft->getType());
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;
2935 TIntermAggregate* clipCullAssign = assignClipCullDistance(loc, op, semanticId,
2936 subSplitLeft, subSplitRight);
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.
2953 assignList = intermediate.growAggregate(assignList,
2954 intermediate.addAssign(op, subSplitLeft, subSplitRight, loc),
2957 traverse(subLeft, subRight, subSplitLeft, subSplitRight, false);
2960 memberL += (typeL.isBuiltIn() ? 0 : 1);
2961 memberR += (typeR.isBuiltIn() ? 0 : 1);
2965 assignList = intermediate.growAggregate(assignList, intermediate.addAssign(op, left, right, loc), loc);
2970 TIntermTyped* splitLeft = left;
2971 TIntermTyped* splitRight = right;
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)
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();
2981 TIntermTyped* splitLeftNonIo = intermediate.addSymbol(*getSplitNonIoVar(symNode->getId()), loc);
2983 splitLeft = intermediate.addIndex(left->getAsBinaryNode()->getOp(), splitLeftNonIo,
2984 left->getAsBinaryNode()->getRight(), loc);
2986 const TType derefType(splitLeftNonIo->getType(), 0);
2987 splitLeft->setType(derefType);
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);
2996 splitRight = intermediate.addSymbol(*getSplitNonIoVar(right->getAsSymbolNode()->getId()), loc);
2998 // This makes the whole assignment, recursing through subtypes as needed.
2999 traverse(left, right, splitLeft, splitRight, true);
3001 assert(assignList != nullptr);
3002 assignList->setOperator(EOpSequence);
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
3010 TIntermTyped* HlslParseContext::handleAssignToMatrixSwizzle(const TSourceLoc& loc, TOperator op, TIntermTyped* left,
3011 TIntermTyped* right)
3013 assert(left->getAsOperator() && left->getAsOperator()->getOp() == EOpMatrixSwizzle);
3015 if (op != EOpAssign)
3016 error(loc, "only simple assignment to non-simple matrix swizzle is supported", "assign", "");
3018 // isolate the matrix and swizzle nodes
3019 TIntermTyped* matrix = left->getAsBinaryNode()->getLeft()->getAsTyped();
3020 const TIntermSequence& swizzle = left->getAsBinaryNode()->getRight()->getAsAggregate()->getSequence();
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);
3030 // assign the right to the new vector
3031 vectorAssign = handleAssign(loc, op, vector, right);
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);
3046 // the left component, double index into the LHS matrix
3047 TIntermTyped* leftComp = intermediate.addIndex(EOpIndexDirect, matrix,
3048 intermediate.addConstantUnion(swizzle[i]->getAsConstantUnion()->getConstArray(),
3051 leftComp->setType(columnType);
3052 leftComp = intermediate.addIndex(EOpIndexDirect, leftComp,
3053 intermediate.addConstantUnion(swizzle[i+1]->getAsConstantUnion()->getConstArray(),
3056 leftComp->setType(componentType);
3058 // Add the assignment to the aggregate
3059 result = intermediate.growAggregate(result, intermediate.addAssign(op, leftComp, rightComp, loc));
3062 result->setOp(EOpSequence);
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.
3072 TOperator HlslParseContext::mapAtomicOp(const TSourceLoc& loc, TOperator op, bool isImage)
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: ...
3085 error(loc, "unknown atomic operation", "unknown op", "");
3091 // Create a combined sampler/texture from separate sampler and texture.
3093 TIntermAggregate* HlslParseContext::handleSamplerTextureCombine(const TSourceLoc& loc, TIntermTyped* argTex,
3094 TIntermTyped* argSampler)
3096 TIntermAggregate* txcombine = new TIntermAggregate(EOpConstructTextureSampler);
3098 txcombine->getSequence().push_back(argTex);
3099 txcombine->getSequence().push_back(argSampler);
3101 TSampler samplerType = argTex->getType().getSampler();
3102 samplerType.combined = true;
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.
3108 const bool shadowMode = argSampler->getType().getSampler().shadow;
3110 TIntermSymbol* texSymbol = argTex->getAsSymbolNode();
3112 if (texSymbol == nullptr)
3113 texSymbol = argTex->getAsBinaryNode()->getLeft()->getAsSymbolNode();
3115 if (texSymbol == nullptr) {
3116 error(loc, "unable to find texture symbol", "", "");
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();
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());
3130 if (textureShadowEntry != textureShadowVariant.end())
3131 newId = textureShadowEntry->second->get(shadowMode);
3133 textureShadowVariant[texSymbol->getId()] = NewPoolObject(tShadowTextureSymbols(), 1);
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).
3139 texType.shallowCopy(argTex->getType());
3140 texType.getSampler().shadow = shadowMode; // set appropriate shadow mode.
3141 globalQualifierFix(loc, texType.getQualifier());
3143 TVariable* newTexture = makeInternalVariable(texSymbol->getName(), texType);
3145 trackLinkage(*newTexture);
3147 newId = newTexture->getUniqueId();
3150 assert(newId != -1);
3152 if (textureShadowVariant.find(newId) == textureShadowVariant.end())
3153 textureShadowVariant[newId] = textureShadowVariant[texSymbol->getId()];
3155 textureShadowVariant[newId]->set(shadowMode, newId);
3157 // Remember this shadow mode in the texture and the merged type.
3158 argTex->getWritableType().getSampler().shadow = shadowMode;
3159 samplerType.shadow = shadowMode;
3161 texSymbol->switchId(newId);
3164 txcombine->setType(TType(samplerType, EvqTemporary));
3165 txcombine->setLoc(loc);
3170 // Return true if this a buffer type that has an associated counter buffer.
3171 bool HlslParseContext::hasStructBuffCounter(const TType& type) const
3173 switch (type.getQualifier().declaredBuiltIn) {
3174 case EbvAppendConsume: // fall through...
3175 case EbvRWStructuredBuffer: // ...
3178 return false; // the other structuredbuffer types do not have a counter.
3182 void HlslParseContext::counterBufferType(const TSourceLoc& loc, TType& type)
3185 TType* counterType = new TType(EbtUint, EvqBuffer);
3186 counterType->setFieldName(intermediate.implicitCounterName);
3188 TTypeList* blockStruct = new TTypeList;
3189 TTypeLoc member = { counterType, loc };
3190 blockStruct->push_back(member);
3192 TType blockType(blockStruct, "", counterType->getQualifier());
3193 blockType.getQualifier().storage = EvqBuffer;
3195 type.shallowCopy(blockType);
3196 shareStructBufferType(type);
3199 // declare counter for a structured buffer type
3200 void HlslParseContext::declareStructBufferCounter(const TSourceLoc& loc, const TType& bufferType, const TString& name)
3202 // Bail out if not a struct buffer
3203 if (! isStructBufferType(bufferType))
3206 if (! hasStructBuffCounter(bufferType))
3210 counterBufferType(loc, blockType);
3212 TString* blockName = NewPoolTString(intermediate.addCounterBufferName(name).c_str());
3214 // Counter buffer is not yet in use
3215 structBufferCounter[*blockName] = false;
3217 shareStructBufferType(blockType);
3218 declareBlock(loc, blockType, blockName);
3221 // return the counter that goes with a given structuredbuffer
3222 TIntermTyped* HlslParseContext::getStructBufferCounter(const TSourceLoc& loc, TIntermTyped* buffer)
3224 // Bail out if not a struct buffer
3225 if (buffer == nullptr || ! isStructBufferType(buffer->getType()))
3228 const TString counterBlockName(intermediate.addCounterBufferName(buffer->getAsSymbolNode()->getName()));
3230 // Mark the counter as being used
3231 structBufferCounter[counterBlockName] = true;
3233 TIntermTyped* counterVar = handleVariable(loc, &counterBlockName); // find the block structure
3234 TIntermTyped* index = intermediate.addConstantUnion(0, loc); // index to counter inside block struct
3236 TIntermTyped* counterMember = intermediate.addIndex(EOpIndexDirectStruct, counterVar, index, loc);
3237 counterMember->setType(TType(EbtUint));
3238 return counterMember;
3242 // Decompose structure buffer methods into AST
3244 void HlslParseContext::decomposeStructBufferMethods(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
3246 if (node == nullptr || node->getAsOperator() == nullptr || arguments == nullptr)
3249 const TOperator op = node->getAsOperator()->getOp();
3250 TIntermAggregate* argAggregate = arguments->getAsAggregate();
3252 // Buffer is the object upon which method is called, so always arg 0
3253 TIntermTyped* bufferObj = nullptr;
3255 // The parameters can be an aggregate, or just a the object as a symbol if there are no fn params.
3257 if (argAggregate->getSequence().empty())
3259 if (argAggregate->getSequence()[0])
3260 bufferObj = argAggregate->getSequence()[0]->getAsTyped();
3262 bufferObj = arguments->getAsSymbolNode();
3265 if (bufferObj == nullptr || bufferObj->getAsSymbolNode() == nullptr)
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
3274 if (counter == nullptr)
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);
3283 return counterIncrement;
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.
3294 TIntermTyped* argIndex = makeIntegerIndex(argAggregate->getSequence()[1]->getAsTyped()); // index
3296 const TType& bufferType = bufferObj->getType();
3298 const TBuiltInVariable builtInType = bufferType.getQualifier().declaredBuiltIn;
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);
3306 if (isByteAddressBuffer)
3307 argIndex = intermediate.addBinaryNode(EOpRightShift, argIndex,
3308 intermediate.addConstantUnion(2, loc, true),
3309 loc, TType(EbtInt));
3311 // Index into the array to find the item being loaded.
3312 const TOperator idxOp = (argIndex->getQualifier().storage == EvqConst) ? EOpIndexDirect : EOpIndexIndirect;
3314 node = intermediate.addIndex(idxOp, argArray, argIndex, loc);
3316 const TType derefType(argArray->getType(), 0);
3317 node->setType(derefType);
3322 case EOpMethodLoad2:
3323 case EOpMethodLoad3:
3324 case EOpMethodLoad4:
3326 TIntermTyped* argIndex = makeIntegerIndex(argAggregate->getSequence()[1]->getAsTyped()); // index
3328 TOperator constructOp = EOpNull;
3332 case EOpMethodLoad2: size = 2; constructOp = EOpConstructVec2; break;
3333 case EOpMethodLoad3: size = 3; constructOp = EOpConstructVec3; break;
3334 case EOpMethodLoad4: size = 4; constructOp = EOpConstructVec4; break;
3338 TIntermTyped* body = nullptr;
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));
3346 TVariable* byteAddrSym = makeInternalVariable("byteAddrTemp", TType(EbtInt, EvqTemporary));
3347 TIntermTyped* byteAddrIdxVar = intermediate.addSymbol(*byteAddrSym, loc);
3349 body = intermediate.growAggregate(body, intermediate.addAssign(EOpAssign, byteAddrIdxVar, byteAddrIdx, loc));
3351 TIntermTyped* vec = nullptr;
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;
3360 offsetIdx = intermediate.addBinaryNode(EOpAdd, offsetIdx,
3361 intermediate.addConstantUnion(idx, loc, true),
3362 loc, TType(EbtInt));
3364 const TOperator idxOp = (offsetIdx->getQualifier().storage == EvqConst) ? EOpIndexDirect
3367 TIntermTyped* indexVal = intermediate.addIndex(idxOp, argArray, offsetIdx, loc);
3369 TType derefType(argArray->getType(), 0);
3370 derefType.getQualifier().makeTemporary();
3371 indexVal->setType(derefType);
3373 vec = intermediate.growAggregate(vec, indexVal);
3376 vec->setType(TType(argArray->getBasicType(), EvqTemporary, size));
3377 vec->getAsAggregate()->setOperator(constructOp);
3379 body = intermediate.growAggregate(body, vec);
3380 body->setType(vec->getType());
3381 body->getAsAggregate()->setOperator(EOpSequence);
3388 case EOpMethodStore:
3389 case EOpMethodStore2:
3390 case EOpMethodStore3:
3391 case EOpMethodStore4:
3393 TIntermTyped* argIndex = makeIntegerIndex(argAggregate->getSequence()[1]->getAsTyped()); // index
3394 TIntermTyped* argValue = argAggregate->getSequence()[2]->getAsTyped(); // value
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).
3403 case EOpMethodStore: size = 1; break;
3404 case EOpMethodStore2: size = 2; break;
3405 case EOpMethodStore3: size = 3; break;
3406 case EOpMethodStore4: size = 4; break;
3410 TIntermAggregate* body = nullptr;
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));
3417 TVariable* byteAddrSym = makeInternalVariable("byteAddrTemp", TType(EbtInt, EvqTemporary));
3418 TIntermTyped* byteAddrIdxVar = intermediate.addSymbol(*byteAddrSym, loc);
3420 body = intermediate.growAggregate(body, intermediate.addAssign(EOpAssign, byteAddrIdxVar, byteAddrIdx, loc));
3422 for (int idx=0; idx<size; ++idx) {
3423 TIntermTyped* offsetIdx = byteAddrIdxVar;
3424 TIntermTyped* idxConst = intermediate.addConstantUnion(idx, loc, true);
3428 offsetIdx = intermediate.addBinaryNode(EOpAdd, offsetIdx, idxConst, loc, TType(EbtInt));
3430 const TOperator idxOp = (offsetIdx->getQualifier().storage == EvqConst) ? EOpIndexDirect
3433 TIntermTyped* lValue = intermediate.addIndex(idxOp, argArray, offsetIdx, loc);
3434 const TType derefType(argArray->getType(), 0);
3435 lValue->setType(derefType);
3437 TIntermTyped* rValue;
3441 rValue = intermediate.addIndex(EOpIndexDirect, argValue, idxConst, loc);
3442 const TType indexType(argValue->getType(), 0);
3443 rValue->setType(indexType);
3446 TIntermTyped* assign = intermediate.addAssign(EOpAssign, lValue, rValue, loc);
3448 body = intermediate.growAggregate(body, assign);
3451 body->setOperator(EOpSequence);
3457 case EOpMethodGetDimensions:
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
3463 TIntermAggregate* body = nullptr;
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);
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);
3479 if (argStride != nullptr) {
3482 intermediate.getMemberAlignment(argArray->getType(), size, stride, argArray->getType().getQualifier().layoutPacking,
3483 argArray->getType().getQualifier().layoutMatrix == ElmRowMajor);
3485 TIntermTyped* assign = intermediate.addAssign(EOpAssign, argStride,
3486 intermediate.addConstantUnion(stride, loc, true), loc);
3488 body = intermediate.growAggregate(body, assign);
3491 body->setOperator(EOpSequence);
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:
3507 // We'll replace the first argument with the block dereference, and let
3508 // downstream decomposition handle the rest.
3510 TIntermSequence& sequence = argAggregate->getSequence();
3512 TIntermTyped* argIndex = makeIntegerIndex(sequence[1]->getAsTyped()); // index
3513 argIndex = intermediate.addBinaryNode(EOpRightShift, argIndex, intermediate.addConstantUnion(2, loc, true),
3514 loc, TType(EbtInt));
3516 const TOperator idxOp = (argIndex->getQualifier().storage == EvqConst) ? EOpIndexDirect : EOpIndexIndirect;
3517 TIntermTyped* element = intermediate.addIndex(idxOp, argArray, argIndex, loc);
3519 const TType derefType(argArray->getType(), 0);
3520 element->setType(derefType);
3522 // Replace the numeric byte offset parameter with array reference.
3523 sequence[1] = element;
3524 sequence.erase(sequence.begin(), sequence.begin()+1);
3528 case EOpMethodIncrementCounter:
3530 node = incDecCounter(1);
3534 case EOpMethodDecrementCounter:
3536 TIntermTyped* preIncValue = incDecCounter(-1); // result is original value
3537 node = intermediate.addBinaryNode(EOpAdd, preIncValue, intermediate.addConstantUnion(-1, loc, true), loc,
3538 preIncValue->getType());
3542 case EOpMethodAppend:
3544 TIntermTyped* oldCounter = incDecCounter(1);
3546 TIntermTyped* lValue = intermediate.addIndex(EOpIndexIndirect, argArray, oldCounter, loc);
3547 TIntermTyped* rValue = argAggregate->getSequence()[1]->getAsTyped();
3549 const TType derefType(argArray->getType(), 0);
3550 lValue->setType(derefType);
3552 node = intermediate.addAssign(EOpAssign, lValue, rValue, loc);
3557 case EOpMethodConsume:
3559 TIntermTyped* oldCounter = incDecCounter(-1);
3561 TIntermTyped* newCounter = intermediate.addBinaryNode(EOpAdd, oldCounter,
3562 intermediate.addConstantUnion(-1, loc, true), loc,
3563 oldCounter->getType());
3565 node = intermediate.addIndex(EOpIndexIndirect, argArray, newCounter, loc);
3567 const TType derefType(argArray->getType(), 0);
3568 node->setType(derefType);
3574 break; // most pass through unchanged
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)
3582 struct tSamplePos { float x, y; };
3584 static const tSamplePos pos1[] = {
3585 { 0.0/16.0, 0.0/16.0 },
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 },
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 },
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 },
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 },
3609 const tSamplePos* sampleLoc = nullptr;
3610 int numSamples = 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;
3622 TConstUnionArray* values = new TConstUnionArray(numSamples*2);
3624 for (int pos=0; pos<count; ++pos) {
3626 x.setDConst(sampleLoc[pos].x);
3627 y.setDConst(sampleLoc[pos].y);
3629 (*values)[pos*2+0] = x;
3630 (*values)[pos*2+1] = y;
3633 TType retType(EbtFloat, EvqConst, 2);
3635 if (numSamples != 1) {
3636 TArraySizes* arraySizes = new TArraySizes;
3637 arraySizes->addInnerSize(numSamples);
3638 retType.transferArraySizes(arraySizes);
3641 return new TIntermConstantUnion(*values, retType);
3645 // Decompose DX9 and DX10 sample intrinsics & object methods into AST
3647 void HlslParseContext::decomposeSampleMethods(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
3649 if (node == nullptr || !node->getAsOperator())
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()));
3656 TIntermTyped* convertedResult = nullptr;
3659 getTextureReturnType(sampler, retType);
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;
3666 // Convert vector output to return structure. We will need a temp symbol to copy the results to.
3667 TVariable* structVar = makeInternalVariable("@sampleStructTemp", retType);
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());
3673 // Initial copy from texture to our sample result shadow.
3674 TIntermTyped* shadowCopy = intermediate.addAssign(EOpAssign, intermediate.addSymbol(*sampleShadow, loc),
3677 conversionAggregate->getSequence().push_back(shadowCopy);
3679 unsigned vec4Pos = 0;
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.
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", "", "");
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);
3697 structMember->setType(memberType);
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));
3706 TIntermTyped* memberAssign = nullptr;
3708 if (memberType.isVector()) {
3709 // Vector member: we need to create an access chain to the vector component.
3711 TIntermTyped* structVecComponent = intermediate.addIndex(EOpIndexDirect, structMember,
3712 intermediate.addConstantUnion(component, loc), loc);
3714 memberAssign = intermediate.addAssign(EOpAssign, structVecComponent, vec4Member, loc);
3716 // Scalar member: we can assign to it directly.
3717 memberAssign = intermediate.addAssign(EOpAssign, structMember, vec4Member, loc);
3721 conversionAggregate->getSequence().push_back(memberAssign);
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));
3728 // Make it a sequence.
3729 intermediate.setAggregateOperator(conversionAggregate, EOpSequence, retType, loc);
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);
3736 convertedResult = constructBuiltIn(retType, op, result, loc, false);
3738 // Enough components. Use directly.
3739 convertedResult = result;
3743 convertedResult->setLoc(loc);
3744 return convertedResult;
3747 const TOperator op = node->getAsOperator()->getOp();
3748 const TIntermAggregate* argAggregate = arguments ? arguments->getAsAggregate() : nullptr;
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)
3759 if (argAggregate->getSequence().size() == 0 ||
3760 argAggregate->getSequence()[0] == nullptr ||
3761 argAggregate->getSequence()[0]->getAsTyped()->getBasicType() != EbtSampler)
3767 // **** DX9 intrinsics: ****
3770 // Texture with ddx & ddy is really gradient form in HLSL
3771 if (argAggregate->getSequence().size() == 4)
3772 node->getAsAggregate()->setOperator(EOpTextureGrad);
3776 case EOpTextureLod: //is almost EOpTextureBias (only args & operations are different)
3778 TIntermTyped *argSamp = argAggregate->getSequence()[0]->getAsTyped(); // sampler
3779 TIntermTyped *argCoord = argAggregate->getSequence()[1]->getAsTyped(); // coord
3781 assert(argCoord->getVectorSize() == 4);
3782 TIntermTyped *w = intermediate.addConstantUnion(3, loc, true);
3783 TIntermTyped *argLod = intermediate.addIndex(EOpIndexDirect, argCoord, w, loc);
3785 TOperator constructOp = EOpNull;
3786 const TSampler &sampler = argSamp->getType().getSampler();
3789 switch (sampler.dim)
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
3799 TIntermAggregate *constructCoord = new TIntermAggregate(constructOp);
3800 constructCoord->getSequence().push_back(argCoord);
3801 constructCoord->setLoc(loc);
3802 constructCoord->setType(TType(argCoord->getBasicType(), EvqTemporary, coordSize));
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
3809 node = convertReturn(tex, sampler);
3814 case EOpTextureBias:
3816 TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped(); // sampler
3817 TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped(); // coord
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);
3824 TOperator constructOp = EOpNull;
3825 const TSampler& sampler = arg0->getType().getSampler();
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
3835 TIntermAggregate* constructCoord = new TIntermAggregate(constructOp);
3836 constructCoord->getSequence().push_back(arg1);
3837 constructCoord->setLoc(loc);
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)));
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
3848 node = convertReturn(tex, sampler);
3853 // **** DX10 methods: ****
3854 case EOpMethodSample: // fall through
3855 case EOpMethodSampleBias: // ...
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();
3866 if (op == EOpMethodSampleBias) // SampleBias has a bias arg
3867 argBias = argAggregate->getSequence()[nextArg++]->getAsTyped();
3869 TOperator textureOp = EOpTexture;
3871 if ((int)argAggregate->getSequence().size() == (nextArg+1)) { // last parameter is offset form
3872 textureOp = EOpTextureOffset;
3873 argOffset = argAggregate->getSequence()[nextArg++]->getAsTyped();
3876 TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
3878 TIntermAggregate* txsample = new TIntermAggregate(textureOp);
3879 txsample->getSequence().push_back(txcombine);
3880 txsample->getSequence().push_back(argCoord);
3882 if (argBias != nullptr)
3883 txsample->getSequence().push_back(argBias);
3885 if (argOffset != nullptr)
3886 txsample->getSequence().push_back(argOffset);
3888 node = convertReturn(txsample, sampler);
3893 case EOpMethodSampleGrad: // ...
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();
3903 TOperator textureOp = EOpTextureGrad;
3905 if (argAggregate->getSequence().size() == 6) { // last parameter is offset form
3906 textureOp = EOpTextureGradOffset;
3907 argOffset = argAggregate->getSequence()[5]->getAsTyped();
3910 TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
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);
3918 if (argOffset != nullptr)
3919 txsample->getSequence().push_back(argOffset);
3921 node = convertReturn(txsample, sampler);
3926 case EOpMethodGetDimensions:
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;
3935 TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
3936 const TType& texType = argTex->getType();
3938 assert(texType.getBasicType() == EbtSampler);
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();
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)
3956 assert(0 && "unhandled texture dimension");
3959 // Arrayed adds another dimension for the number of array elements
3960 if (sampler.isArrayed())
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)));
3967 // Establish whether we must use the LOD form of query (even if the method did not supply a mip level to query).
3969 // 1. 1D/2D/3D/Cube AND multisample==0 AND NOT image (those can be sent to the non-LOD query)
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...
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);
3980 // If we're building an LOD query, add the LOD.
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);
3988 sizeQuery->setType(TType(EbtUint, EvqTemporary, numDims));
3989 sizeQuery->setLoc(loc);
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),
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;
4003 for (int compNum = 0; compNum < numDims; ++compNum) {
4004 TIntermTyped* indexedOut = nullptr;
4005 TIntermSymbol* sizeQueryReturn = intermediate.addSymbol(*tempArg, loc);
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);
4013 indexedOut = sizeQueryReturn;
4016 TIntermTyped* outParam = argAggregate->getSequence()[outParamBase + compNum]->getAsTyped();
4017 TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, outParam, indexedOut, loc);
4019 compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
4022 // handle mip level parameter
4024 TIntermTyped* outParam = argAggregate->getSequence()[outParamBase + numDims]->getAsTyped();
4026 TIntermAggregate* levelsQuery = new TIntermAggregate(EOpTextureQueryLevels);
4027 levelsQuery->getSequence().push_back(argTex);
4028 levelsQuery->setType(TType(EbtUint, EvqTemporary, 1));
4029 levelsQuery->setLoc(loc);
4031 TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, outParam, levelsQuery, loc);
4032 compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
4035 // 2DMS formats query # samples, which needs a different query op
4036 if (sampler.isMultiSample()) {
4037 TIntermTyped* outParam = argAggregate->getSequence()[outParamBase + numDims]->getAsTyped();
4039 TIntermAggregate* samplesQuery = new TIntermAggregate(EOpImageQuerySamples);
4040 samplesQuery->getSequence().push_back(argTex);
4041 samplesQuery->setType(TType(EbtUint, EvqTemporary, 1));
4042 samplesQuery->setLoc(loc);
4044 TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, outParam, samplesQuery, loc);
4045 compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
4048 compoundStatement->setOperator(EOpSequence);
4049 compoundStatement->setLoc(loc);
4050 compoundStatement->setType(TType(EbtVoid));
4052 node = compoundStatement;
4057 case EOpMethodSampleCmp: // fall through...
4058 case EOpMethodSampleCmpLevelZero:
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;
4066 // Sampler argument should be a sampler.
4067 if (argSamp->getType().getBasicType() != EbtSampler) {
4068 error(loc, "expected: sampler type", "", "");
4072 // Sampler should be a SamplerComparisonState
4073 if (! argSamp->getType().getSampler().isShadow()) {
4074 error(loc, "expected: SamplerComparisonState", "", "");
4078 // optional offset value
4079 if (argAggregate->getSequence().size() > 4)
4080 argOffset = argAggregate->getSequence()[4]->getAsTyped();
4082 const int coordDimWithCmpVal = argCoord->getType().getVectorSize() + 1; // +1 for cmp
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;
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)));
4102 TOperator textureOp = (op == EOpMethodSampleCmpLevelZero ? EOpTextureLod : EOpTexture);
4103 if (argOffset != nullptr)
4104 textureOp = (op == EOpMethodSampleCmpLevelZero ? EOpTextureLodOffset : EOpTextureOffset);
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);
4112 if (coordDimWithCmpVal == 5) // cube array shadow is special: cmp val follows coord.
4113 txsample->getSequence().push_back(argCmpVal);
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));
4119 // Add offset if present
4120 if (argOffset != nullptr)
4121 txsample->getSequence().push_back(argOffset);
4123 txsample->setType(node->getType());
4124 txsample->setLoc(loc);
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;
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();
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;
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()));
4159 TIntermTyped* lodIdx = intermediate.addConstantUnion(coordFields.size(), loc, true);
4160 lodComponent = intermediate.addIndex(EOpIndexDirect, argCoord, lodIdx, loc);
4161 lodComponent->setType(TType(coordBaseType, EvqTemporary, 1));
4164 const int numArgs = (int)argAggregate->getSequence().size();
4165 const bool hasOffset = ((!isMS && numArgs == 3) || (isMS && numArgs == 4));
4167 // Create texel fetch
4168 const TOperator fetchOp = (isImage ? EOpImageLoad :
4169 hasOffset ? EOpTextureFetchOffset :
4171 TIntermAggregate* txfetch = new TIntermAggregate(fetchOp);
4173 // Build up the fetch
4174 txfetch->getSequence().push_back(argTex);
4175 txfetch->getSequence().push_back(coordSwizzle);
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.
4186 // 2DMS and buffer have no LOD, but everything else does.
4187 txfetch->getSequence().push_back(lodComponent);
4190 // Obtain offset arg, if there is one.
4192 const int offsetPos = (isMS ? 3 : 2);
4193 argOffset = argAggregate->getSequence()[offsetPos]->getAsTyped();
4194 txfetch->getSequence().push_back(argOffset);
4197 node = convertReturn(txfetch, sampler);
4202 case EOpMethodSampleLevel:
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();
4211 const int numArgs = (int)argAggregate->getSequence().size();
4213 if (numArgs == 5) // offset, if present
4214 argOffset = argAggregate->getSequence()[4]->getAsTyped();
4216 const TOperator textureOp = (argOffset == nullptr ? EOpTextureLod : EOpTextureLodOffset);
4217 TIntermAggregate* txsample = new TIntermAggregate(textureOp);
4219 TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
4221 txsample->getSequence().push_back(txcombine);
4222 txsample->getSequence().push_back(argCoord);
4223 txsample->getSequence().push_back(argLod);
4225 if (argOffset != nullptr)
4226 txsample->getSequence().push_back(argOffset);
4228 node = convertReturn(txsample, sampler);
4233 case EOpMethodGather:
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;
4240 // Offset is optional
4241 if (argAggregate->getSequence().size() > 3)
4242 argOffset = argAggregate->getSequence()[3]->getAsTyped();
4244 const TOperator textureOp = (argOffset == nullptr ? EOpTextureGather : EOpTextureGatherOffset);
4245 TIntermAggregate* txgather = new TIntermAggregate(textureOp);
4247 TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
4249 txgather->getSequence().push_back(txcombine);
4250 txgather->getSequence().push_back(argCoord);
4251 // Offset if not given is implicitly channel 0 (red)
4253 if (argOffset != nullptr)
4254 txgather->getSequence().push_back(argOffset);
4256 txgather->setType(node->getType());
4257 txgather->setLoc(loc);
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: // ...
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)
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;
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", "", "");
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;
4308 const TSamplerDim dim = argTex->getType().getSampler().dim;
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;
4315 // Sampler argument should be a sampler.
4316 if (argSamp->getType().getBasicType() != EbtSampler) {
4317 error(loc, "expected: sampler type", "", "");
4321 // Cmp forms require SamplerComparisonState
4322 if (cmpValues > 0 && ! argSamp->getType().getSampler().isShadow()) {
4323 error(loc, "expected: SamplerComparisonState", "", "");
4327 // Only 2D forms can have offsets. Discover if we have 0, 1 or 4 offsets.
4329 hasOffset1 = (argSize == (4+cmpValues) || argSize == (5+cmpValues));
4330 hasOffset4 = (argSize == (7+cmpValues) || argSize == (8+cmpValues));
4333 assert(!(hasOffset1 && hasOffset4));
4335 TOperator textureOp = EOpTextureGather;
4337 // Compare forms have compare value
4339 argCmp = argOffset = argAggregate->getSequence()[arg++]->getAsTyped();
4341 // Some forms have single offset
4343 textureOp = EOpTextureGatherOffset; // single offset form
4344 argOffset = argAggregate->getSequence()[arg++]->getAsTyped();
4347 // Some forms have 4 gather offsets
4349 textureOp = EOpTextureGatherOffsets; // note plural, for 4 offset form
4350 for (int offsetNum = 0; offsetNum < 4; ++offsetNum)
4351 argOffsets[offsetNum] = argAggregate->getSequence()[arg++]->getAsTyped();
4356 // argStatus = argAggregate->getSequence()[arg++]->getAsTyped();
4357 error(loc, "unimplemented: residency status", "", "");
4361 TIntermAggregate* txgather = new TIntermAggregate(textureOp);
4362 TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
4364 TIntermTyped* argChannel = intermediate.addConstantUnion(channel, loc, true);
4366 txgather->getSequence().push_back(txcombine);
4367 txgather->getSequence().push_back(argCoord);
4369 // AST wants an array of 4 offsets, where HLSL has separate args. Here
4370 // we construct an array from the separate args.
4372 TType arrayType(EbtInt, EvqTemporary, 2);
4373 TArraySizes* arraySizes = new TArraySizes;
4374 arraySizes->addInnerSize(4);
4375 arrayType.transferArraySizes(arraySizes);
4377 TIntermAggregate* initList = new TIntermAggregate(EOpNull);
4379 for (int offsetNum = 0; offsetNum < 4; ++offsetNum)
4380 initList->getSequence().push_back(argOffsets[offsetNum]);
4382 argOffset = addConstructor(loc, initList, arrayType);
4385 // Add comparison value if we have one
4386 if (argCmp != nullptr)
4387 txgather->getSequence().push_back(argCmp);
4389 // Add offset (either 1, or an array of 4) if we have one
4390 if (argOffset != nullptr)
4391 txgather->getSequence().push_back(argOffset);
4393 // Add channel value if the sampler is not shadow
4394 if (! argSamp->getType().getSampler().isShadow())
4395 txgather->getSequence().push_back(argChannel);
4397 txgather->setType(node->getType());
4398 txgather->setLoc(loc);
4404 case EOpMethodCalculateLevelOfDetail:
4405 case EOpMethodCalculateLevelOfDetailUnclamped:
4407 TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
4408 TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
4409 TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
4411 TIntermAggregate* txquerylod = new TIntermAggregate(EOpTextureQueryLod);
4413 TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
4414 txquerylod->getSequence().push_back(txcombine);
4415 txquerylod->getSequence().push_back(argCoord);
4417 TIntermTyped* lodComponent = intermediate.addConstantUnion(
4418 op == EOpMethodCalculateLevelOfDetail ? 0 : 1,
4420 TIntermTyped* lodComponentIdx = intermediate.addIndex(EOpIndexDirect, txquerylod, lodComponent, loc);
4421 lodComponentIdx->setType(TType(EbtFloat, EvqTemporary, 1));
4422 node = lodComponentIdx;
4427 case EOpMethodGetSamplePosition:
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. ***
4434 TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
4435 TIntermTyped* argSampIdx = argAggregate->getSequence()[1]->getAsTyped();
4437 TIntermAggregate* samplesQuery = new TIntermAggregate(EOpImageQuerySamples);
4438 samplesQuery->getSequence().push_back(argTex);
4439 samplesQuery->setType(TType(EbtUint, EvqTemporary, 1));
4440 samplesQuery->setLoc(loc);
4442 TIntermAggregate* compoundStatement = nullptr;
4444 TVariable* outSampleCount = makeInternalVariable("@sampleCount", TType(EbtUint));
4445 outSampleCount->getWritableType().getQualifier().makeTemporary();
4446 TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, intermediate.addSymbol(*outSampleCount, loc),
4448 compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
4450 TIntermTyped* idxtest[4];
4452 // Create tests against 2, 4, 8, and 16 sample values
4454 for (int val = 2; val <= 16; val *= 2)
4456 intermediate.addBinaryNode(EOpEqual,
4457 intermediate.addSymbol(*outSampleCount, loc),
4458 intermediate.addConstantUnion(val, loc),
4459 loc, TType(EbtBool));
4461 const TOperator idxOp = (argSampIdx->getQualifier().storage == EvqConst) ? EOpIndexDirect : EOpIndexIndirect;
4463 // Create index ops into position arrays given sample index.
4464 // TODO: should it be clamped?
4465 TIntermTyped* index[4];
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));
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);
4484 compoundStatement = intermediate.growAggregate(compoundStatement, test);
4485 compoundStatement->setOperator(EOpSequence);
4486 compoundStatement->setLoc(loc);
4487 compoundStatement->setType(TType(EbtFloat, EvqTemporary, 2));
4489 node = compoundStatement;
4494 case EOpSubpassLoad:
4496 const TIntermTyped* argSubpass =
4497 argAggregate ? argAggregate->getSequence()[0]->getAsTyped() :
4498 arguments->getAsTyped();
4500 const TSampler& sampler = argSubpass->getType().getSampler();
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);
4507 node = convertReturn(node, sampler);
4514 break; // most pass through unchanged
4519 // Decompose geometry shader methods
4521 void HlslParseContext::decomposeGeometryMethods(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
4523 if (node == nullptr || !node->getAsOperator())
4526 const TOperator op = node->getAsOperator()->getOp();
4527 const TIntermAggregate* argAggregate = arguments ? arguments->getAsAggregate() : nullptr;
4530 case EOpMethodAppend:
4532 // Don't emit these for non-GS stage, since we won't have the gsStreamOutput symbol.
4533 if (language != EShLangGeometry) {
4538 TIntermAggregate* sequence = nullptr;
4539 TIntermAggregate* emit = new TIntermAggregate(EOpEmitVertex);
4542 emit->setType(TType(EbtVoid));
4544 TIntermTyped* data = argAggregate->getSequence()[1]->getAsTyped();
4546 // This will be patched in finalization during finalizeAppendMethods()
4547 sequence = intermediate.growAggregate(sequence, data, loc);
4548 sequence = intermediate.growAggregate(sequence, emit);
4550 sequence->setOperator(EOpSequence);
4551 sequence->setLoc(loc);
4552 sequence->setType(TType(EbtVoid));
4554 gsAppends.push_back({sequence, loc});
4560 case EOpMethodRestartStrip:
4562 // Don't emit these for non-GS stage, since we won't have the gsStreamOutput symbol.
4563 if (language != EShLangGeometry) {
4568 TIntermAggregate* cut = new TIntermAggregate(EOpEndPrimitive);
4570 cut->setType(TType(EbtVoid));
4576 break; // most pass through unchanged
4581 // Optionally decompose intrinsics to AST opcodes.
4583 void HlslParseContext::decomposeIntrinsic(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
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", "", "");
4596 atomic->getSequence().push_back(loadOp->getSequence()[0]);
4597 atomic->getSequence().push_back(loadOp->getSequence()[1]);
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;
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;
4611 TVariable* variable = new TVariable(new TString(name), type);
4613 symbolTable.insert(*variable);
4615 symbol = symbolTable.find(name);
4616 assert(symbol && "Inserted symbol could not be found!");
4619 return intermediate.addSymbol(*(symbol->getAsVariable()), loc);
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;
4626 if (!decomposeHlslIntrinsics || !node || !node->getAsOperator())
4629 const TIntermAggregate* argAggregate = arguments ? arguments->getAsAggregate() : nullptr;
4630 TIntermUnary* fnUnary = node->getAsUnaryNode();
4631 const TOperator op = node->getAsOperator()->getOp();
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();
4642 if (arg0->isVector() && arg1->isVector()) { // vec * vec
4643 node->getAsAggregate()->setOperator(EOpDot);
4645 node = handleBinaryMath(loc, "mul", EOpMul, arg0, arg1);
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);
4662 case EOpAny: // fall through
4665 TIntermTyped* typedArg = arguments->getAsTyped();
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());
4677 typedArg = intermediate.addConversion(EOpConstructBool, boolType, typedArg);
4678 node->getAsUnaryNode()->setOperand(typedArg);
4686 // saturate(a) -> clamp(a,0,1)
4687 TIntermTyped* arg0 = fnUnary->getOperand();
4688 TBasicType type0 = arg0->getBasicType();
4689 TIntermAggregate* clamp = new TIntermAggregate(EOpClamp);
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));
4695 clamp->setType(node->getType());
4696 clamp->getWritableType().getQualifier().makeTemporary();
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();
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);
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));
4720 node = compoundStatement;
4727 // clip(a) -> if (any(a<0)) discard;
4728 TIntermTyped* arg0 = fnUnary->getOperand();
4729 TBasicType type0 = arg0->getBasicType();
4730 TIntermTyped* compareNode = nullptr;
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);
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()));
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);
4753 if (arg0->getType().isIntegerDomain())
4756 zero.setDConst(0.0);
4757 TConstUnionArray zeros(constComponentCount, zero);
4759 less->getSequence().push_back(intermediate.addConstantUnion(zeros, arg0->getType(), loc, true));
4761 compareNode = intermediate.addBuiltInFunctionCall(loc, EOpAny, true, less, TType(EbtBool));
4764 if (arg0->getType().isIntegerDomain())
4765 zero = intermediate.addConstantUnion(0, loc, true);
4767 zero = intermediate.addConstantUnion(0.0, type0, loc, true);
4768 compareNode = handleBinaryMath(loc, "clip", EOpLessThan, arg0, zero);
4771 TIntermBranch* killNode = intermediate.addBranch(EOpKill, loc);
4773 node = new TIntermSelection(compareNode, killNode, nullptr);
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);
4786 node = handleBinaryMath(loc, "mul", EOpMul, log2, base);
4794 // dest.y = src0.y * src1.y;
4798 TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
4799 TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
4801 TIntermTyped* y = intermediate.addConstantUnion(1, loc, true);
4802 TIntermTyped* z = intermediate.addConstantUnion(2, loc, true);
4803 TIntermTyped* w = intermediate.addConstantUnion(3, loc, true);
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);
4810 TIntermAggregate* dst = new TIntermAggregate(EOpConstructVec4);
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));
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
4831 TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped(); // dest
4832 TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped(); // value
4833 TIntermTyped* arg2 = nullptr;
4835 if (argAggregate->getSequence().size() > 2)
4836 arg2 = argAggregate->getSequence()[2]->getAsTyped();
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);
4846 // orig_value = imageAtomicOp(image, loc, data)
4847 imageAtomicParams(atomic, arg0);
4848 atomic->getSequence().push_back(arg1);
4850 if (argAggregate->getSequence().size() > 2) {
4851 node = intermediate.addAssign(EOpAssign, arg2, atomic, loc);
4853 node = atomic; // no assignment needed, as there was no out var.
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);
4863 node = intermediate.addAssign(EOpAssign, arg2, atomic, loc);
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());
4874 case EOpInterlockedCompareExchange:
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
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();
4888 imageAtomicParams(atomic, arg0);
4890 atomic->getSequence().push_back(arg0);
4893 atomic->getSequence().push_back(arg1);
4894 atomic->getSequence().push_back(arg2);
4895 node = intermediate.addAssign(EOpAssign, arg3, atomic, loc);
4900 case EOpEvaluateAttributeSnapped:
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
4909 TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped(); // value
4910 TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped(); // offset
4912 TIntermTyped* i28 = intermediate.addConstantUnion(28, loc, true);
4913 TIntermTyped* iU = handleBinaryMath(loc, ">>", EOpRightShift,
4914 handleBinaryMath(loc, "<<", EOpLeftShift, arg1, i28),
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),
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();
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();
4941 TIntermAggregate* dst = new TIntermAggregate(EOpConstructVec4);
4944 dst->getSequence().push_back(intermediate.addConstantUnion(1.0, EbtFloat, loc, true));
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);
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));
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
4965 dst->getSequence().push_back(intermediate.addSelection(compare, zero, n_dot_h_m, loc));
4968 dst->getSequence().push_back(intermediate.addConstantUnion(1.0, EbtFloat, loc, true));
4971 dst->setType(TType(EbtFloat, EvqTemporary, 4));
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();
4983 if (arg0->getType().isVector()) { // TODO: ...
4984 error(loc, "double2 conversion not implemented", "asdouble", "");
4988 TIntermAggregate* uint64 = new TIntermAggregate(EOpConstructUVec2);
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);
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));
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();
5012 TOperator constructOp = EOpNull;
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;
5021 // For scalar case, we don't need to construct another type.
5022 TIntermAggregate* result = (vecSize > 1) ? new TIntermAggregate(constructOp) : nullptr;
5025 result->setType(TType(EbtFloat, EvqTemporary, vecSize));
5026 result->setLoc(loc);
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;
5034 if (component != argValue)
5035 component->setType(TType(argValue->getBasicType(), EvqTemporary));
5037 TIntermTyped* unpackOp = new TIntermUnary(EOpUnpackHalf2x16);
5038 unpackOp->setType(TType(EbtFloat, EvqTemporary, 2));
5039 unpackOp->getAsUnaryNode()->setOperand(component);
5040 unpackOp->setLoc(loc);
5042 TIntermTyped* lowOrder = intermediate.addIndex(EOpIndexDirect, unpackOp, zero, loc);
5044 if (result != nullptr) {
5045 result->getSequence().push_back(lowOrder);
5057 // input floatN converted to 16 bit float in low order bits of each component of uintN
5058 TIntermTyped* argValue = node->getAsUnaryNode()->getOperand();
5060 TIntermTyped* zero = intermediate.addConstantUnion(0.0, EbtFloat, loc, true);
5061 const int vecSize = argValue->getType().getVectorSize();
5063 TOperator constructOp = EOpNull;
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;
5072 // For scalar case, we don't need to construct another type.
5073 TIntermAggregate* result = (vecSize > 1) ? new TIntermAggregate(constructOp) : nullptr;
5076 result->setType(TType(EbtUint, EvqTemporary, vecSize));
5077 result->setLoc(loc);
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;
5085 if (component != argValue)
5086 component->setType(TType(argValue->getBasicType(), EvqTemporary));
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);
5094 TIntermTyped* packOp = new TIntermUnary(EOpPackHalf2x16);
5095 packOp->getAsUnaryNode()->setOperand(vec2ComponentAndZero);
5096 packOp->setLoc(loc);
5097 packOp->setType(TType(EbtUint, EvqTemporary));
5099 if (result != nullptr) {
5100 result->getSequence().push_back(packOp);
5110 case EOpD3DCOLORtoUBYTE4:
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();
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();
5129 node = intermediate.addConversion(EOpConstructInt, TType(EbtInt, EvqTemporary, 4), rangeConverted);
5131 node->setType(TType(EbtInt, EvqTemporary, 4));
5137 // Since OPIsFinite in SPIR-V is only supported with the Kernel capability, we translate
5138 // it to !isnan && !isinf
5140 TIntermTyped* arg0 = node->getAsUnaryNode()->getOperand();
5142 // We'll make a temporary in case the RHS is cmoplex
5143 TVariable* tempArg = makeInternalVariable("@finitetmp", arg0->getType());
5144 tempArg->getWritableType().getQualifier().makeTemporary();
5146 TIntermTyped* tmpArgAssign = intermediate.addAssign(EOpAssign,
5147 intermediate.addSymbol(*tempArg, loc),
5150 TIntermAggregate* compoundStatement = intermediate.makeAggregate(tmpArgAssign, loc);
5152 const TType boolType(EbtBool, EvqTemporary, arg0->getVectorSize(), arg0->getMatrixCols(),
5153 arg0->getMatrixRows());
5155 TIntermTyped* isnan = handleUnaryMath(loc, "isnan", EOpIsNan, intermediate.addSymbol(*tempArg, loc));
5156 isnan->setType(boolType);
5158 TIntermTyped* notnan = handleUnaryMath(loc, "!", EOpLogicalNot, isnan);
5159 notnan->setType(boolType);
5161 TIntermTyped* isinf = handleUnaryMath(loc, "isinf", EOpIsInf, intermediate.addSymbol(*tempArg, loc));
5162 isinf->setType(boolType);
5164 TIntermTyped* notinf = handleUnaryMath(loc, "!", EOpLogicalNot, isinf);
5165 notinf->setType(boolType);
5167 TIntermTyped* andNode = handleBinaryMath(loc, "and", EOpLogicalAnd, notnan, notinf);
5168 andNode->setType(boolType);
5170 compoundStatement = intermediate.growAggregate(compoundStatement, andNode);
5171 compoundStatement->setOperator(EOpSequence);
5172 compoundStatement->setLoc(loc);
5173 compoundStatement->setType(boolType);
5175 node = compoundStatement;
5179 case EOpWaveGetLaneCount:
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);
5188 case EOpWaveGetLaneIndex:
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
5194 TType type(EbtUint, EvqVaryingIn);
5195 node = lookupBuiltinVariable("@gl_SubgroupInvocationID", EbvSubgroupInvocation2, type);
5198 case EOpWaveActiveCountBits:
5200 // Mapped to subgroupBallotBitCount(subgroupBallot()) builtin
5203 TType uvec4Type(EbtUint, EvqTemporary, 4);
5205 // Get the uvec4 return from subgroupBallot().
5206 TIntermTyped* res = intermediate.addBuiltInFunctionCall(loc,
5207 EOpSubgroupBallot, true, arguments, uvec4Type);
5210 TType uintType(EbtUint, EvqTemporary);
5212 node = intermediate.addBuiltInFunctionCall(loc,
5213 EOpSubgroupBallotBitCount, true, res, uintType);
5217 case EOpWavePrefixCountBits:
5219 // Mapped to subgroupBallotInclusiveBitCount(subgroupBallot())
5223 TType uvec4Type(EbtUint, EvqTemporary, 4);
5225 // Get the uvec4 return from subgroupBallot().
5226 TIntermTyped* res = intermediate.addBuiltInFunctionCall(loc,
5227 EOpSubgroupBallot, true, arguments, uvec4Type);
5230 TType uintType(EbtUint, EvqTemporary);
5232 node = intermediate.addBuiltInFunctionCall(loc,
5233 EOpSubgroupBallotInclusiveBitCount, true, res, uintType);
5239 break; // most pass through unchanged
5244 // Handle seeing function call syntax in the grammar, which could be any of
5245 // - .length() method
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)
5250 // - subroutine call (not implemented yet)
5252 TIntermTyped* HlslParseContext::handleFunctionCall(const TSourceLoc& loc, TFunction* function, TIntermTyped* arguments)
5254 TIntermTyped* result = nullptr;
5256 TOperator op = function->getBuiltInOp();
5257 if (op != EOpNull) {
5259 // Then this should be a constructor.
5260 // Don't go through the symbol table for constructors.
5261 // Their parameters will be verified algorithmically.
5263 TType type(EbtVoid); // use this to get the type back
5264 if (! constructorError(loc, arguments, *function, op, type)) {
5266 // It's a constructor, of type 'type'.
5268 result = handleConstructor(loc, arguments, type);
5269 if (result == nullptr) {
5270 error(loc, "cannot construct with these arguments", type.getCompleteString().c_str(), "");
5276 // Find it in the symbol table.
5278 const TFunction* fnCandidate = nullptr;
5279 bool builtIn = false;
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);
5288 TIntermAggregate* aggregate = arguments ? arguments->getAsAggregate() : nullptr;
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.
5294 // Check if first argument is struct buffer type. It may be an aggregate or a symbol, so we
5295 // look for either case.
5297 TIntermTyped* arg0 = nullptr;
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();
5304 if (arg0 != nullptr && isStructBufferType(arg0->getType())) {
5305 static const int methodPrefixSize = sizeof(BUILTIN_PREFIX)-1;
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);
5313 fnCandidate = symbol->getAsFunction();
5318 if (fnCandidate == nullptr)
5319 fnCandidate = findFunction(loc, *function, builtIn, thisDepth, arguments);
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.
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());
5332 // turn an implicit member-function resolution into an explicit call
5335 callerName = fnCandidate->getMangledName();
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);
5344 // Convert 'in' arguments, so that types match.
5345 // However, skip those that need expansion, that is covered next.
5347 addInputArgumentConversions(*fnCandidate, arguments);
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);
5354 // Expansion may have changed the form of arguments
5355 aggregate = arguments ? arguments->getAsAggregate() : nullptr;
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());
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);
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
5380 call->setUserDefined();
5381 intermediate.addToCallGraph(infoSink, currentCaller, callerName);
5385 // for decompositions, since we want to operate on the function node, not the aggregate holding
5386 // output conversions.
5387 const TIntermTyped* fnNode = result;
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
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,
5407 // add structure member expansion
5408 for (int memb = 0; memb < (int)(*fnCandidate)[i].type->getStruct()->size(); ++memb)
5409 qualifierList.push_back(qual);
5412 qualifierList.push_back(qual);
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());
5427 // generic error recovery
5428 // TODO: simplification: localize all the error recoveries that look like this, and taking type into account to
5430 if (result == nullptr)
5431 result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
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)
5441 if (arguments == nullptr)
5443 else if (arguments->getAsAggregate() != nullptr)
5444 arguments->getAsAggregate()->getSequence().insert(arguments->getAsAggregate()->getSequence().begin(), front);
5446 arguments = intermediate.growAggregate(front, arguments);
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.
5454 void HlslParseContext::addGenMulArgumentConversion(const TSourceLoc& loc, TFunction& call, TIntermTyped*& args)
5456 TIntermAggregate* argAggregate = args ? args->getAsAggregate() : nullptr;
5458 if (argAggregate == nullptr || argAggregate->getSequence().size() != 2) {
5459 // It really ought to have two arguments.
5460 error(loc, "expected: mul arguments", "", "");
5464 TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
5465 TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
5467 if (arg0->isVector() && arg1->isVector()) {
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);
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);
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);
5510 // It's something with scalars: we'll just leave it alone. Function selection will handle it
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", "", "");
5518 // Put arguments back. (They might be unchanged, in which case this is harmless).
5519 argAggregate->getSequence()[0] = arg0;
5520 argAggregate->getSequence()[1] = arg1;
5522 call[0].type = &arg0->getWritableType();
5523 call[1].type = &arg1->getWritableType();
5527 // Add any needed implicit conversions for function-call arguments to input parameters.
5529 void HlslParseContext::addInputArgumentConversions(const TFunction& function, TIntermTyped*& arguments)
5531 TIntermAggregate* aggregate = arguments->getAsAggregate();
5533 // Replace a single argument with a single argument.
5534 const auto setArg = [&](int paramNum, TIntermTyped* arg) {
5535 if (function.getParamCount() == 1)
5538 if (aggregate == nullptr)
5541 aggregate->getSequence()[paramNum] = arg;
5545 // Process each argument's conversion
5546 for (int param = 0; param < function.getParamCount(); ++param) {
5547 if (! function[param].type->getQualifier().isParamInput())
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()
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);
5567 error(arg->getLoc(), "cannot convert input argument, argument", "", "%d", param);
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
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();
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);
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).
5602 void HlslParseContext::expandArguments(const TSourceLoc& loc, const TFunction& function, TIntermTyped*& arguments)
5604 TIntermAggregate* aggregate = arguments->getAsAggregate();
5605 int functionParamNumberOffset = 0;
5607 // Replace a single argument with a single argument.
5608 const auto setArg = [&](int paramNum, TIntermTyped* arg) {
5609 if (function.getParamCount() + functionParamNumberOffset == 1)
5612 if (aggregate == nullptr)
5615 aggregate->getSequence()[paramNum] = arg;
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);
5631 auto it = aggregate->getSequence().erase(aggregate->getSequence().begin() + paramNum);
5632 aggregate->getSequence().insert(it, args.begin(), args.end());
5634 functionParamNumberOffset += (int)(args.size() - 1);
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()
5646 aggregate->getSequence()[param + functionParamNumberOffset]->getAsTyped() :
5647 arguments->getAsTyped());
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);
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.
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.
5665 addStructBuffArguments(loc, aggregate);
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.
5673 // Returns a node of a subtree that evaluates to the return value of the function.
5675 TIntermTyped* HlslParseContext::addOutputArgumentConversions(const TFunction& function, TIntermOperator& intermNode)
5677 assert (intermNode.getAsAggregate() != nullptr || intermNode.getAsUnaryNode() != nullptr);
5679 const TSourceLoc& loc = intermNode.getLoc();
5681 TIntermSequence argSequence; // temp sequence for unary node args
5683 if (intermNode.getAsUnaryNode())
5684 argSequence.push_back(intermNode.getAsUnaryNode()->getOperand());
5686 TIntermSequence& arguments = argSequence.empty() ? intermNode.getAsAggregate()->getSequence() : argSequence;
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()));
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;
5704 if (! outputConversions)
5707 // Setup for the new tree, if needed:
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);
5723 conversionTree = &intermNode;
5725 conversionTree = intermediate.makeAggregate(conversionTree);
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.
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);
5738 // This makes the deepest level, the member-wise copy
5739 TIntermTyped* tempAssign = handleAssign(arguments[i]->getLoc(), EOpAssign, arguments[i]->getAsTyped(),
5741 tempAssign = handleLvalue(arguments[i]->getLoc(), "assign", tempAssign);
5742 conversionTree = intermediate.growAggregate(conversionTree, tempAssign, arguments[i]->getLoc());
5744 // replace the argument with another node for the same tempArg variable
5745 arguments[i] = intermediate.addSymbol(*tempArg, loc);
5749 // Finalize the tree topology (see bigger comment above).
5751 // do the "..., tempRet" bit from above
5752 TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, loc);
5753 conversionTree = intermediate.growAggregate(conversionTree, tempRetNode, loc);
5756 conversionTree = intermediate.setAggregateOperator(conversionTree, EOpComma, intermNode.getType(), loc);
5758 return conversionTree;
5762 // Add any needed "hidden" counter buffer arguments for function calls.
5764 // Modifies the 'aggregate' argument if needed. Otherwise, is no-op.
5766 void HlslParseContext::addStructBuffArguments(const TSourceLoc& loc, TIntermAggregate*& aggregate)
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());
5776 // Nothing to do, if we didn't find one.
5777 if (! hasStructBuffArg)
5780 TIntermSequence argsWithCounterBuffers;
5782 for (int param = 0; param < int(aggregate->getSequence().size()); ++param) {
5783 argsWithCounterBuffers.push_back(aggregate->getSequence()[param]);
5785 if (hasStructBuffCounter(aggregate->getSequence()[param]->getAsTyped()->getType())) {
5786 const TIntermSymbol* blockSym = aggregate->getSequence()[param]->getAsSymbolNode();
5787 if (blockSym != nullptr) {
5789 counterBufferType(loc, counterType);
5791 const TString counterBlockName(intermediate.addCounterBufferName(blockSym->getName()));
5793 TVariable* variable = makeInternalVariable(counterBlockName, counterType);
5795 // Mark this buffer's counter block as being in use
5796 structBufferCounter[counterBlockName] = true;
5798 TIntermSymbol* sym = intermediate.addSymbol(*variable, loc);
5799 argsWithCounterBuffers.push_back(sym);
5804 // Swap with the temp list we've built up.
5805 aggregate->getSequence().swap(argsWithCounterBuffers);
5810 // Do additional checking of built-in function calls that is not caught
5811 // by normal semantic checks on argument type, extension tagging, etc.
5813 // Assumes there has been a semantically correct match to a built-in function prototype.
5815 void HlslParseContext::builtInOpCheck(const TSourceLoc& loc, const TFunction& fnCandidate, TIntermOperator& callNode)
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();
5828 assert(callNode.getAsUnaryNode());
5829 unaryArg = callNode.getAsUnaryNode()->getOperand();
5832 const TIntermSequence& aggArgs = *argp; // only valid when unaryArg is nullptr
5834 switch (callNode.getOp()) {
5835 case EOpTextureGather:
5836 case EOpTextureGatherOffset:
5837 case EOpTextureGatherOffsets:
5839 // Figure out which variants are allowed by what extensions,
5840 // and what arguments must be constant for which situations.
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)
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)
5860 case EOpTextureGatherOffsets:
5861 if (! fnCandidate[0].type->getSampler().shadow)
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");
5874 error(loc, "must be a compile-time constant:", feature, "component argument");
5880 case EOpTextureOffset:
5881 case EOpTextureFetchOffset:
5882 case EOpTextureProjOffset:
5883 case EOpTextureLodOffset:
5884 case EOpTextureProjLodOffset:
5885 case EOpTextureGradOffset:
5886 case EOpTextureProjGradOffset:
5888 // Handle texture-offset limits checking
5889 // Pick which argument has to hold constant offsets
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;
5905 if (aggArgs[arg]->getAsConstantUnion() == nullptr)
5906 error(loc, "argument must be compile-time constant", "texel offset", "");
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]");
5921 case EOpTextureQuerySamples:
5922 case EOpImageQuerySamples:
5925 case EOpImageAtomicAdd:
5926 case EOpImageAtomicMin:
5927 case EOpImageAtomicMax:
5928 case EOpImageAtomicAnd:
5929 case EOpImageAtomicOr:
5930 case EOpImageAtomicXor:
5931 case EOpImageAtomicExchange:
5932 case EOpImageAtomicCompSwap:
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.
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.
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(), "");
5960 // Handle seeing something in a grammar production that can be done by calling
5963 // The constructor still must be "handled" by handleFunctionCall(), which will
5964 // then call handleConstructor().
5966 TFunction* HlslParseContext::makeConstructorCall(const TSourceLoc& loc, const TType& type)
5968 TOperator op = intermediate.mapTypeToConstructorOp(type);
5970 if (op == EOpNull) {
5971 error(loc, "cannot construct this type", type.getBasicString(), "");
5977 return new TFunction(&empty, type, op);
5981 // Handle seeing a "COLON semantic" at the end of a type declaration,
5982 // by updating the type according to the semantic.
5984 void HlslParseContext::handleSemantic(TSourceLoc loc, TQualifier& qualifier, TBuiltInVariable builtIn,
5985 const TString& upperCase)
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)
5996 unsigned int semanticNum = (unsigned int)atoi(semantic.c_str() + pos + 1);
5998 if (limit != 0 && semanticNum >= limit) {
5999 error(loc, errorMsg, semantic.c_str(), "");
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");
6022 // adjust for stage in/out
6023 if (language == EShLangFragment)
6024 builtIn = EbvFragCoord;
6026 case EbvFragStencilRef:
6027 error(loc, "unimplemented; need ARB_shader_stencil_export", "SV_STENCILREF", "");
6029 case EbvTessLevelInner:
6030 case EbvTessLevelOuter:
6031 qualifier.patch = true;
6037 if (qualifier.builtIn == EbvNone)
6038 qualifier.builtIn = builtIn;
6039 qualifier.semanticName = intermediate.addSemanticName(upperCase);
6043 // Handle seeing something like "PACKOFFSET LEFT_PAREN c[Subcomponent][.component] RIGHT_PAREN"
6045 // 'location' has the "c[Subcomponent]" part.
6046 // 'component' points to the "component" part, or nullptr if not present.
6048 void HlslParseContext::handlePackOffset(const TSourceLoc& loc, TQualifier& qualifier, const glslang::TString& location,
6049 const glslang::TString* component)
6051 if (location.size() == 0 || location[0] != 'c') {
6052 error(loc, "expected 'c'", "packoffset", "");
6055 if (location.size() == 1)
6057 if (! isdigit(location[1])) {
6058 error(loc, "expected number after 'c'", "packoffset", "");
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;
6071 componentOffset = -1;
6074 if (componentOffset < 0 || component->size() > 1) {
6075 error(loc, "expected {x, y, z, w} for component", "packoffset", "");
6078 qualifier.layoutOffset += componentOffset;
6083 // Handle seeing something like "REGISTER LEFT_PAREN [shader_profile,] Type# RIGHT_PAREN"
6085 // 'profile' points to the shader_profile part, or nullptr if not present.
6086 // 'desc' is the type# part.
6088 void HlslParseContext::handleRegister(const TSourceLoc& loc, TQualifier& qualifier, const glslang::TString* profile,
6089 const glslang::TString& desc, int subComponent, const glslang::TString* spaceDesc)
6091 if (profile != nullptr)
6092 warn(loc, "ignoring shader_profile", "register", "");
6094 if (desc.size() < 1) {
6095 error(loc, "expected register type", "register", "");
6100 if (desc.size() > 1) {
6101 if (isdigit(desc[1]))
6102 regNumber = atoi(desc.substr(1, desc.size()).c_str());
6104 error(loc, "expected register number after register type", "register", "");
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])) {
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;
6118 // const buffer register slot
6120 // textrues and structured buffers
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;
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;
6145 warn(loc, "ignoring unrecognized register type", "register", "%c", desc[0]);
6150 unsigned int setNumber;
6151 const auto crackSpace = [&]() -> bool {
6152 const int spaceLen = 5;
6153 if (spaceDesc->size() < spaceLen + 1)
6155 if (spaceDesc->compare(0, spaceLen, "space") != 0)
6157 if (! isdigit((*spaceDesc)[spaceLen]))
6159 setNumber = atoi(spaceDesc->substr(spaceLen, spaceDesc->size()).c_str());
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", "");
6170 qualifier.layoutSet = setNumber;
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,
6179 if (mustBeScalar && !condition->getType().isScalarOrVec1()) {
6180 error(loc, "requires a scalar", "conditional expression", "");
6184 return intermediate.addConversion(EOpConstructBool, TType(EbtBool, EvqTemporary, condition->getVectorSize()),
6189 // Same error message for all places assignments don't work.
6191 void HlslParseContext::assignError(const TSourceLoc& loc, const char* op, TString left, TString right)
6193 error(loc, "", op, "cannot convert from '%s' to '%s'",
6194 right.c_str(), left.c_str());
6198 // Same error message for all places unary operations don't work.
6200 void HlslParseContext::unaryOpError(const TSourceLoc& loc, const char* op, TString operand)
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());
6208 // Same error message for all binary operations don't work.
6210 void HlslParseContext::binaryOpError(const TSourceLoc& loc, const char* op, TString left, TString right)
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());
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.
6223 void HlslParseContext::variableCheck(TIntermTyped*& nodePtr)
6225 TIntermSymbol* symbol = nodePtr->getAsSymbolNode();
6229 if (symbol->getType().getBasicType() == EbtVoid) {
6230 error(symbol->getLoc(), "undeclared identifier", symbol->getName().c_str(), "");
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);
6237 // substitute a symbol node for this new variable
6238 nodePtr = intermediate.addSymbol(*fakeVariable, symbol->getLoc());
6244 // Both test, and if necessary spit out an error, to see if the node is really
6247 void HlslParseContext::constantValueCheck(TIntermTyped* node, const char* token)
6249 if (node->getQualifier().storage != EvqConst)
6250 error(node->getLoc(), "constant expression required", token, "");
6254 // Both test, and if necessary spit out an error, to see if the node is really
6257 void HlslParseContext::integerCheck(const TIntermTyped* node, const char* token)
6259 if ((node->getBasicType() == EbtInt || node->getBasicType() == EbtUint) && node->isScalar())
6262 error(node->getLoc(), "scalar integer expression required", token, "");
6266 // Both test, and if necessary spit out an error, to see if we are currently
6269 void HlslParseContext::globalCheck(const TSourceLoc& loc, const char* token)
6271 if (! symbolTable.atGlobalLevel())
6272 error(loc, "not allowed in nested scope", token, "");
6275 bool HlslParseContext::builtInName(const TString& /*identifier*/)
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.
6285 // Returns true if there was an error in construction.
6287 bool HlslParseContext::constructorError(const TSourceLoc& loc, TIntermNode* node, TFunction& function,
6288 TOperator op, TType& type)
6290 type.shallowCopy(function.getType());
6292 bool constructingMatrix = false;
6294 case EOpConstructTextureSampler:
6295 error(loc, "unhandled texture constructor", "constructor", "");
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;
6349 // Walk the arguments for first-pass checks and collection of information.
6353 bool constType = true;
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", "");
6367 if (constructingMatrix && function[arg].type->isMatrix())
6368 matrixInMatrix = true;
6370 // 'full' will go to true when enough args have been seen. If we loop
6371 // again, there is an extra argument.
6373 // For vectors and matrices, it's okay to have too many components
6374 // available, but not okay to have unused arguments.
6378 size += function[arg].type->computeNumComponents();
6379 if (op != EOpConstructStruct && ! type.isArray() && size >= type.computeNumComponents())
6382 if (function[arg].type->getQualifier().storage != EvqConst)
6387 type.getQualifier().storage = EvqConst;
6389 if (type.isArray()) {
6390 if (function.getParamCount() == 0) {
6391 error(loc, "array constructor must have at least one argument", "constructor", "");
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", "");
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();
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", "");
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));
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)
6434 if (arrayArg && op != EOpConstructStruct && ! type.isArrayOfArrays()) {
6435 error(loc, "constructing non-array constituent from array argument", "constructor", "");
6439 if (matrixInMatrix && ! type.isArray()) {
6444 error(loc, "too many arguments", "constructor", "");
6448 if (op == EOpConstructStruct && ! type.isArray()) {
6449 if (isScalarConstructor(node))
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)
6456 if ((int)type.getStruct()->size() != function.getParamCount()) {
6457 error(loc, "Number of constructor parameters does not match the number of structure fields", "constructor", "");
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", "");
6471 // See if 'node', in the context of constructing aggregates, is a scalar argument
6472 // to a constructor.
6474 bool HlslParseContext::isScalarConstructor(const TIntermNode* node)
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,
6483 return node->getAsTyped() != nullptr &&
6484 node->getAsTyped()->isScalar() &&
6485 (node->getAsAggregate() == nullptr || node->getAsAggregate()->getOp() != EOpNull);
6488 // Checks to see if a void variable has been declared and raise an error message for such a case
6490 // returns true in case of an error
6492 bool HlslParseContext::voidErrorCheck(const TSourceLoc& loc, const TString& identifier, const TBasicType basicType)
6494 if (basicType == EbtVoid) {
6495 error(loc, "illegal use of type 'void'", identifier.c_str(), "");
6503 // Fix just a full qualifier (no variables or types yet, but qualifier is complete) at global level.
6505 void HlslParseContext::globalQualifierFix(const TSourceLoc&, TQualifier& qualifier)
6507 // move from parameter/unknown qualifiers to pipeline in/out qualifiers
6508 switch (qualifier.storage) {
6510 qualifier.storage = EvqVaryingIn;
6513 qualifier.storage = EvqVaryingOut;
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.
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.
6529 void HlslParseContext::mergeQualifiers(TQualifier& dst, const TQualifier& src)
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;
6541 // Layout qualifiers
6542 mergeObjectLayoutQualifiers(dst, src, false);
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);
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)
6568 int arrayIndex = sampler.arrayed ? 1 : 0;
6569 int shadowIndex = sampler.shadow ? 1 : 0;
6570 int externalIndex = sampler.external ? 1 : 0;
6573 (EbtNumTypes * (2 * (2 * arrayIndex + shadowIndex) + externalIndex) + sampler.type) + sampler.dim;
6577 // Do size checking for an array type's size.
6579 void HlslParseContext::arraySizeCheck(const TSourceLoc& loc, TIntermTyped* expr, TArraySize& sizePair)
6581 bool isConst = false;
6583 sizePair.node = nullptr;
6585 TIntermConstantUnion* constant = expr->getAsConstantUnion();
6587 // handle true (non-specialization) constant
6588 sizePair.size = constant->getConstArray()[0].getIConst();
6591 // see if it's a specialization constant instead
6592 if (expr->getQualifier().isSpecConstant()) {
6594 sizePair.node = expr;
6595 TIntermSymbol* symbol = expr->getAsSymbolNode();
6596 if (symbol && symbol->getConstArray().size() > 0)
6597 sizePair.size = symbol->getConstArray()[0].getIConst();
6601 if (! isConst || (expr->getBasicType() != EbtInt && expr->getBasicType() != EbtUint)) {
6602 error(loc, "array size must be a constant integer expression", "", "");
6606 if (sizePair.size <= 0) {
6607 error(loc, "array size must be a positive integer", "", "");
6613 // Require array to be completely sized
6615 void HlslParseContext::arraySizeRequiredCheck(const TSourceLoc& loc, const TArraySizes& arraySizes)
6617 if (arraySizes.hasUnsized())
6618 error(loc, "array size required", "", "");
6621 void HlslParseContext::structArrayCheck(const TSourceLoc& /*loc*/, const TType& type)
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());
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.
6635 void HlslParseContext::declareArray(const TSourceLoc& loc, const TString& identifier, const TType& type,
6636 TSymbol*& symbol, bool track)
6638 if (symbol == nullptr) {
6640 symbol = symbolTable.find(identifier, nullptr, ¤tScope);
6642 if (symbol && builtInName(identifier) && ! symbolTable.atBuiltInLevel()) {
6643 // bad shader (errors already reported) trying to redeclare a built-in name as an array
6646 if (symbol == nullptr || ! currentScope) {
6648 // Successfully process a new definition.
6649 // (Redeclarations have to take place at the same scope; otherwise they are hiding declarations)
6651 symbol = new TVariable(&identifier, type);
6652 symbolTable.insert(*symbol);
6653 if (track && symbolTable.atGlobalLevel())
6654 trackLinkage(*symbol);
6658 if (symbol->getAsAnonMember()) {
6659 error(loc, "cannot redeclare a user-block member array", identifier.c_str(), "");
6666 // Process a redeclaration.
6669 if (symbol == nullptr) {
6670 error(loc, "array variable name expected", identifier.c_str(), "");
6674 // redeclareBuiltinVariable() should have already done the copyUp()
6675 TType& existingType = symbol->getWritableType();
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
6683 existingType.updateArraySizes(type);
6687 // Enforce non-initializer type/qualifier rules.
6689 void HlslParseContext::fixConstInit(const TSourceLoc& loc, const TString& identifier, TType& type,
6690 TIntermTyped*& initializer)
6693 // Make the qualifier make sense, given that there is an initializer.
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(), "");
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.
6709 // Returns nullptr if no redeclaration took place; meaning a normal declaration still
6710 // needs to occur for it, not necessarily an error.
6712 // Returns a redeclared and type-modified variable if a redeclared occurred.
6714 TSymbol* HlslParseContext::redeclareBuiltinVariable(const TSourceLoc& /*loc*/, const TString& identifier,
6715 const TQualifier& /*qualifier*/,
6716 const TShaderQualifiers& /*publicType*/)
6718 if (! builtInName(identifier) || symbolTable.atBuiltInLevel() || ! symbolTable.atGlobalLevel())
6725 // Generate index to the array element in a structure buffer (SSBO)
6727 TIntermTyped* HlslParseContext::indexStructBufferContent(const TSourceLoc& loc, TIntermTyped* buffer) const
6729 // Bail out if not a struct buffer
6730 if (buffer == nullptr || ! isStructBufferType(buffer->getType()))
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);
6737 TIntermTyped* argArray = intermediate.addIndex(EOpIndexDirectStruct, buffer, arrayPosition, loc);
6738 argArray->setType(*(*bufferStruct)[bufferStruct->size()-1].type);
6744 // IFF type is a structuredbuffer/byteaddressbuffer type, return the content
6745 // (template) type. E.g, StructuredBuffer<MyType> -> MyType. Else return nullptr.
6747 TType* HlslParseContext::getStructBufferContentType(const TType& type) const
6749 if (type.getBasicType() != EbtBlock || type.getQualifier().storage != EvqBuffer)
6752 const int memberCount = (int)type.getStruct()->size();
6753 assert(memberCount > 0);
6755 TType* contentType = (*type.getStruct())[memberCount-1].type;
6757 return contentType->isUnsizedArray() ? contentType : nullptr;
6761 // If an existing struct buffer has a sharable type, then share it.
6763 void HlslParseContext::shareStructBufferType(TType& type)
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)
6772 if (lhs.isStruct() != rhs.isStruct())
6775 if (lhs.isStruct() && rhs.isStruct()) {
6776 if (lhs.getStruct()->size() != rhs.getStruct()->size())
6779 for (int i = 0; i < int(lhs.getStruct()->size()); ++i)
6780 if (!compareQualifiers(*(*lhs.getStruct())[i].type, *(*rhs.getStruct())[i].type))
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)
6792 // If both are structures, recursively look for packOffset equality
6793 // as well as type equality.
6794 return compareQualifiers(lhs, rhs) && lhs == rhs;
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]);
6807 // Otherwise, remember it:
6808 TType* typeCopy = new TType;
6809 typeCopy->shallowCopy(type);
6810 structBufferTypes.push_back(typeCopy);
6813 void HlslParseContext::paramFix(TType& type)
6815 switch (type.getQualifier().storage) {
6817 type.getQualifier().storage = EvqConstReadOnly;
6822 type.getQualifier().storage = EvqIn;
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;
6842 void HlslParseContext::specializationCheck(const TSourceLoc& loc, const TType& type, const char* op)
6844 if (type.containsSpecializationSize())
6845 error(loc, "can't use with types containing arrays sized with a specialization constant", op, "");
6849 // Layout qualifier stuff.
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)
6856 std::transform(id.begin(), id.end(), id.begin(), ::tolower);
6858 if (id == TQualifier::getLayoutMatrixString(ElmColumnMajor)) {
6859 qualifier.layoutMatrix = ElmRowMajor;
6862 if (id == TQualifier::getLayoutMatrixString(ElmRowMajor)) {
6863 qualifier.layoutMatrix = ElmColumnMajor;
6866 if (id == "push_constant") {
6867 requireVulkan(loc, "push_constant");
6868 qualifier.layoutPushConstant = true;
6871 if (language == EShLangGeometry || language == EShLangTessEvaluation) {
6872 if (id == TQualifier::getGeometryString(ElgTriangles)) {
6873 // publicType.shaderQualifiers.geometry = ElgTriangles;
6874 warn(loc, "ignored", id.c_str(), "");
6877 if (language == EShLangGeometry) {
6878 if (id == TQualifier::getGeometryString(ElgPoints)) {
6879 // publicType.shaderQualifiers.geometry = ElgPoints;
6880 warn(loc, "ignored", id.c_str(), "");
6883 if (id == TQualifier::getGeometryString(ElgLineStrip)) {
6884 // publicType.shaderQualifiers.geometry = ElgLineStrip;
6885 warn(loc, "ignored", id.c_str(), "");
6888 if (id == TQualifier::getGeometryString(ElgLines)) {
6889 // publicType.shaderQualifiers.geometry = ElgLines;
6890 warn(loc, "ignored", id.c_str(), "");
6893 if (id == TQualifier::getGeometryString(ElgLinesAdjacency)) {
6894 // publicType.shaderQualifiers.geometry = ElgLinesAdjacency;
6895 warn(loc, "ignored", id.c_str(), "");
6898 if (id == TQualifier::getGeometryString(ElgTrianglesAdjacency)) {
6899 // publicType.shaderQualifiers.geometry = ElgTrianglesAdjacency;
6900 warn(loc, "ignored", id.c_str(), "");
6903 if (id == TQualifier::getGeometryString(ElgTriangleStrip)) {
6904 // publicType.shaderQualifiers.geometry = ElgTriangleStrip;
6905 warn(loc, "ignored", id.c_str(), "");
6909 assert(language == EShLangTessEvaluation);
6912 if (id == TQualifier::getGeometryString(ElgTriangles)) {
6913 // publicType.shaderQualifiers.geometry = ElgTriangles;
6914 warn(loc, "ignored", id.c_str(), "");
6917 if (id == TQualifier::getGeometryString(ElgQuads)) {
6918 // publicType.shaderQualifiers.geometry = ElgQuads;
6919 warn(loc, "ignored", id.c_str(), "");
6922 if (id == TQualifier::getGeometryString(ElgIsolines)) {
6923 // publicType.shaderQualifiers.geometry = ElgIsolines;
6924 warn(loc, "ignored", id.c_str(), "");
6929 if (id == TQualifier::getVertexSpacingString(EvsEqual)) {
6930 // publicType.shaderQualifiers.spacing = EvsEqual;
6931 warn(loc, "ignored", id.c_str(), "");
6934 if (id == TQualifier::getVertexSpacingString(EvsFractionalEven)) {
6935 // publicType.shaderQualifiers.spacing = EvsFractionalEven;
6936 warn(loc, "ignored", id.c_str(), "");
6939 if (id == TQualifier::getVertexSpacingString(EvsFractionalOdd)) {
6940 // publicType.shaderQualifiers.spacing = EvsFractionalOdd;
6941 warn(loc, "ignored", id.c_str(), "");
6946 if (id == TQualifier::getVertexOrderString(EvoCw)) {
6947 // publicType.shaderQualifiers.order = EvoCw;
6948 warn(loc, "ignored", id.c_str(), "");
6951 if (id == TQualifier::getVertexOrderString(EvoCcw)) {
6952 // publicType.shaderQualifiers.order = EvoCcw;
6953 warn(loc, "ignored", id.c_str(), "");
6958 if (id == "point_mode") {
6959 // publicType.shaderQualifiers.pointMode = true;
6960 warn(loc, "ignored", id.c_str(), "");
6965 if (language == EShLangFragment) {
6966 if (id == "origin_upper_left") {
6967 // publicType.shaderQualifiers.originUpperLeft = true;
6968 warn(loc, "ignored", id.c_str(), "");
6971 if (id == "pixel_center_integer") {
6972 // publicType.shaderQualifiers.pixelCenterInteger = true;
6973 warn(loc, "ignored", id.c_str(), "");
6976 if (id == "early_fragment_tests") {
6977 // publicType.shaderQualifiers.earlyFragmentTests = true;
6978 warn(loc, "ignored", id.c_str(), "");
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(), "");
6988 if (id.compare(0, 13, "blend_support") == 0) {
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(), "");
7001 error(loc, "unknown blend equation", "blend_support", "");
7005 error(loc, "unrecognized layout identifier, or qualifier requires assignment (e.g., binding = 4)", id.c_str(), "");
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)
7013 const char* feature = "layout-id value";
7014 // const char* nonLiteralFeature = "non-literal layout-id value";
7016 integerCheck(node, feature);
7017 const TIntermConstantUnion* constUnion = node->getAsConstantUnion();
7020 value = constUnion->getConstArray()[0].getIConst();
7023 std::transform(id.begin(), id.end(), id.begin(), ::tolower);
7025 if (id == "offset") {
7026 qualifier.layoutOffset = value;
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", "");
7033 qualifier.layoutAlign = value;
7035 } else if (id == "location") {
7036 if ((unsigned int)value >= TQualifier::layoutLocationEnd)
7037 error(loc, "location is too large", id.c_str(), "");
7039 qualifier.layoutLocation = value;
7041 } else if (id == "set") {
7042 if ((unsigned int)value >= TQualifier::layoutSetEnd)
7043 error(loc, "set is too large", id.c_str(), "");
7045 qualifier.layoutSet = value;
7047 } else if (id == "binding") {
7048 if ((unsigned int)value >= TQualifier::layoutBindingEnd)
7049 error(loc, "binding is too large", id.c_str(), "");
7051 qualifier.layoutBinding = value;
7053 } else if (id == "component") {
7054 if ((unsigned)value >= TQualifier::layoutComponentEnd)
7055 error(loc, "component is too large", id.c_str(), "");
7057 qualifier.layoutComponent = value;
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
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);
7074 qualifier.layoutXfbBuffer = value;
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);
7080 qualifier.layoutXfbOffset = value;
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;
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(), "");
7101 qualifier.layoutAttachment = value;
7104 if (id == "constant_id") {
7105 setSpecConstantId(loc, qualifier, value);
7113 case EShLangTessControl:
7114 if (id == "vertices") {
7116 error(loc, "must be greater than 0", "vertices", "");
7118 // publicType.shaderQualifiers.vertices = value;
7119 warn(loc, "ignored", id.c_str(), "");
7124 case EShLangTessEvaluation:
7127 case EShLangGeometry:
7128 if (id == "invocations") {
7130 error(loc, "must be at least 1", "invocations", "");
7132 // publicType.shaderQualifiers.invocations = value;
7133 warn(loc, "ignored", id.c_str(), "");
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", "");
7143 if (id == "stream") {
7144 qualifier.layoutStream = value;
7149 case EShLangFragment:
7150 if (id == "index") {
7151 qualifier.layoutIndex = value;
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(), "");
7163 if (id == "local_size_y") {
7164 // publicType.shaderQualifiers.localSize[1] = value;
7165 warn(loc, "ignored", id.c_str(), "");
7168 if (id == "local_size_z") {
7169 // publicType.shaderQualifiers.localSize[2] = value;
7170 warn(loc, "ignored", id.c_str(), "");
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(), "");
7179 if (id == "local_size_y_id") {
7180 // publicType.shaderQualifiers.localSizeSpecId[1] = value;
7181 warn(loc, "ignored", id.c_str(), "");
7184 if (id == "local_size_z_id") {
7185 // publicType.shaderQualifiers.localSizeSpecId[2] = value;
7186 warn(loc, "ignored", id.c_str(), "");
7197 error(loc, "there is no such layout identifier for this stage taking an assigned value", id.c_str(), "");
7200 void HlslParseContext::setSpecConstantId(const TSourceLoc& loc, TQualifier& qualifier, int value)
7202 if (value >= (int)TQualifier::layoutSpecConstantIdEnd) {
7203 error(loc, "specialization-constant id is too large", "constant_id", "");
7205 qualifier.layoutSpecConstantId = value;
7206 qualifier.specConstant = true;
7207 if (! intermediate.addUsedConstantId(value))
7208 error(loc, "specialization-constant id already used", "constant_id", "");
7213 // Merge any layout qualifier information from src into dst, leaving everything else in dst alone
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."
7228 void HlslParseContext::mergeObjectLayoutQualifiers(TQualifier& dst, const TQualifier& src, bool inheritOnly)
7230 if (src.hasMatrix())
7231 dst.layoutMatrix = src.layoutMatrix;
7232 if (src.hasPacking())
7233 dst.layoutPacking = src.layoutPacking;
7235 if (src.hasStream())
7236 dst.layoutStream = src.layoutStream;
7238 if (src.hasFormat())
7239 dst.layoutFormat = src.layoutFormat;
7241 if (src.hasXfbBuffer())
7242 dst.layoutXfbBuffer = src.layoutXfbBuffer;
7245 dst.layoutAlign = src.layoutAlign;
7247 if (! inheritOnly) {
7248 if (src.hasLocation())
7249 dst.layoutLocation = src.layoutLocation;
7250 if (src.hasComponent())
7251 dst.layoutComponent = src.layoutComponent;
7253 dst.layoutIndex = src.layoutIndex;
7255 if (src.hasOffset())
7256 dst.layoutOffset = src.layoutOffset;
7259 dst.layoutSet = src.layoutSet;
7260 if (src.layoutBinding != TQualifier::layoutBindingEnd)
7261 dst.layoutBinding = src.layoutBinding;
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;
7272 if (src.layoutPushConstant)
7273 dst.layoutPushConstant = true;
7279 // Look up a function name in the symbol table, and make sure it is a function.
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.
7285 // Return the function symbol if found, otherwise nullptr.
7287 const TFunction* HlslParseContext::findFunction(const TSourceLoc& loc, TFunction& call, bool& builtIn, int& thisDepth,
7288 TIntermTyped*& args)
7290 if (symbolTable.isFunctionNameVariable(call.getName())) {
7291 error(loc, "can't use function syntax on variable", call.getName().c_str(), "");
7295 // first, look for an exact match
7297 TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn, &dummyScope, &thisDepth);
7299 return symbol->getAsFunction();
7301 // no exact match, use the generic selector, parameterized by the GLSL rules
7303 // create list of candidates to send
7304 TVector<const TFunction*> candidateList;
7305 symbolTable.findFunctionNameList(call.getMangledName(), candidateList, builtIn);
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];
7318 bool allowOnlyUpConversions = true;
7320 // can 'from' convert to 'to'?
7321 const auto convertible = [&](const TType& from, const TType& to, TOperator op, int arg) -> bool {
7325 // no aggregate conversions
7326 if (from.isArray() || to.isArray() ||
7327 from.isStruct() || to.isStruct())
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.
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.
7350 case EOpMethodSample:
7351 case EOpMethodSampleBias:
7352 case EOpMethodSampleCmp:
7353 case EOpMethodSampleCmpLevelZero:
7354 case EOpMethodSampleGrad:
7355 case EOpMethodSampleLevel:
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?)
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;
7386 // basic types have to be convertible
7387 if (allowOnlyUpConversions)
7388 if (! intermediate.canImplicitlyPromote(from.getBasicType(), to.getBasicType(), EOpFunctionCall))
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()))
7398 // TODO: what are the matrix rules? they go here
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
7413 // shape changes are always worse
7414 if (from.isScalar() || from.isVector()) {
7415 if (from.getVectorSize() == to2.getVectorSize() &&
7416 from.getVectorSize() != to1.getVectorSize())
7418 if (from.getVectorSize() == to1.getVectorSize() &&
7419 from.getVectorSize() != to2.getVectorSize())
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();
7431 to1Sampler.vectorSize = to2Sampler.vectorSize = from.getSampler().vectorSize;
7433 if (from.getSampler() == to2Sampler)
7434 return from.getSampler() != to1Sampler;
7435 if (from.getSampler() == to1Sampler)
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.
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;
7462 return abs(linearize(to2.getBasicType()) - linearize(from.getBasicType())) <
7463 abs(linearize(to1.getBasicType()) - linearize(from.getBasicType()));
7466 // for ambiguity reporting
7469 // send to the generic selector
7470 const TFunction* bestMatch = selectFunction(candidateList, call, convertible, better, tie);
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);
7480 if (bestMatch == nullptr) {
7481 error(loc, "no matching overloaded function found", call.getName().c_str(), "");
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.
7491 // Step 1: If there's an exact match, use it.
7492 if (call.getMangledName() == bestMatch->getMangledName())
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;
7502 if (call.getParamCount() == 1) {
7503 promote = new TIntermUnary(bestMatch->getBuiltInOp());
7504 promote->getAsUnaryNode()->setOperand(args->getAsTyped());
7506 promote = new TIntermAggregate(bestMatch->getBuiltInOp());
7507 promote->getAsAggregate()->getSequence().swap(args->getAsAggregate()->getSequence());
7510 if (! intermediate.promote(promote))
7513 // Obtain the promoted arg list.
7514 if (call.getParamCount() == 1) {
7515 args = promote->getAsUnaryNode()->getOperand();
7517 promote->getAsAggregate()->getSequence().swap(args->getAsAggregate()->getSequence());
7521 // Step 2b: reconstruct the TFunction based on the new arg types
7522 TFunction convertedCall(&call.getName(), call.getType(), call.getBuiltInOp());
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);
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);
7543 assert(0); // unknown argument list.
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);
7551 // At this point, there should be no tie.
7555 error(loc, "ambiguous best function under implicit type conversion", call.getName().c_str(), "");
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);
7568 // Do everything necessary to handle a typedef declaration, for a single symbol.
7570 // 'parseType' is the type part of the declaration (to the left)
7571 // 'arraySizes' is the arrayness tagged on the identifier (to the right)
7573 void HlslParseContext::declareTypedef(const TSourceLoc& loc, const TString& identifier, const TType& parseType)
7575 TVariable* typeSymbol = new TVariable(&identifier, parseType, true);
7576 if (! symbolTable.insert(*typeSymbol))
7577 error(loc, "name already defined", "typedef", identifier.c_str());
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)
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)
7591 TVariable* userTypeDef = new TVariable(&structName, type, true);
7592 if (! symbolTable.insert(*userTypeDef)) {
7593 error(loc, "redefinition", structName.c_str(), "struct");
7597 // See if we need IO aliases for the structure typeList
7599 const auto condAlloc = [](bool pred, TTypeList*& list) {
7600 if (pred && list == nullptr)
7601 list = new TTypeList;
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);
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);
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());
7628 // We have IO involved.
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) {
7634 ioMember.type = new TType;
7635 ioMember.type->shallowCopy(*member->type);
7636 ioMember.type->setStruct(s);
7639 const auto newMember = [&](TTypeLoc& m) {
7640 if (m.type == nullptr) {
7642 m.type->shallowCopy(*member->type);
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);
7658 if (newLists.uniform) {
7659 newMember(newUniformMember);
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;
7665 correctUniform(newUniformMember.type->getQualifier());
7666 newLists.uniform->push_back(newUniformMember);
7668 if (newLists.input) {
7669 newMember(newInputMember);
7670 correctInput(newInputMember.type->getQualifier());
7671 newLists.input->push_back(newInputMember);
7673 if (newLists.output) {
7674 newMember(newOutputMember);
7675 correctOutput(newOutputMember.type->getQualifier());
7676 newLists.output->push_back(newOutputMember);
7679 // make original pure
7680 clearUniformInputOutput(member->type->getQualifier());
7682 ioTypeMap[type.getStruct()] = newLists;
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)
7690 TSymbol* symbol = symbolTable.find(typeName);
7691 if (symbol && symbol->getAsVariable() && symbol->getAsVariable()->isUserType()) {
7692 type.shallowCopy(symbol->getType());
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.
7703 // Returns a subtree node that computes an initializer, if needed.
7704 // Returns nullptr if there is no code to execute for initialization.
7706 // 'parseType' is the type part of the declaration (to the left)
7707 // 'arraySizes' is the arrayness tagged on the identifier (to the right)
7709 TIntermNode* HlslParseContext::declareVariable(const TSourceLoc& loc, const TString& identifier, TType& type,
7710 TIntermTyped* initializer)
7712 if (voidErrorCheck(loc, identifier, type.getBasicType()))
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.
7723 const bool nonConstInitializer = (initializer != nullptr && initializer->getQualifier().storage != EvqConst);
7725 if (type.getQualifier().storage == EvqConst && symbolTable.atGlobalLevel() && nonConstInitializer) {
7727 type.getQualifier().storage = EvqGlobal;
7730 // make const and initialization consistent
7731 fixConstInit(loc, identifier, type, initializer);
7733 // Check for redeclaration of built-ins and/or attempting to declare a reserved name
7734 TSymbol* symbol = nullptr;
7736 inheritGlobalDefaults(type.getQualifier());
7738 const bool flattenVar = shouldFlatten(type, type.getQualifier().storage, true);
7740 // correct IO in the type
7741 switch (type.getQualifier().storage) {
7744 clearUniformInputOutput(type.getQualifier());
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);
7760 // Declare the variable
7761 if (type.isArray()) {
7763 declareArray(loc, identifier, type, symbol, !flattenVar);
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());
7772 if (symbol == nullptr)
7776 flatten(*symbol->getAsVariable(), symbolTable.atGlobalLevel());
7778 if (initializer == nullptr)
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(), "");
7787 return executeInitializer(loc, initializer, variable);
7790 // Pick up global defaults from the provide global defaults into dst.
7791 void HlslParseContext::inheritGlobalDefaults(TQualifier& dst) const
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;
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.
7807 TVariable* HlslParseContext::makeInternalVariable(const char* name, const TType& type) const
7809 TString* nameString = NewPoolTString(name);
7810 TVariable* variable = new TVariable(nameString, type);
7811 symbolTable.makeInternalVariable(*variable);
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
7820 TVariable* tmpVar = makeInternalVariable(name, type);
7821 tmpVar->getWritableType().getQualifier().makeTemporary();
7823 return intermediate.addSymbol(*tmpVar, loc);
7827 // Declare a non-array variable, the main point being there is no redeclaration
7828 // for resizing allowed.
7830 // Return the successfully declared variable.
7832 TVariable* HlslParseContext::declareNonArray(const TSourceLoc& loc, const TString& identifier, const TType& type,
7835 // make a new variable
7836 TVariable* variable = new TVariable(&identifier, type);
7838 // add variable to symbol table
7839 if (symbolTable.insert(*variable)) {
7840 if (track && symbolTable.atGlobalLevel())
7841 trackLinkage(*variable);
7845 error(loc, "redefinition", variable->getName().c_str(), "");
7850 // Handle all types of initializers from the grammar.
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.
7855 // Returns a subtree that accomplished the initialization.
7857 TIntermNode* HlslParseContext::executeInitializer(const TSourceLoc& loc, TIntermTyped* initializer, TVariable* variable)
7860 // Identifier must be of type constant, a global, or a temporary, and
7861 // starting at version 120, desktop allows uniforms to have initializers.
7863 TStorageQualifier qualifier = variable->getType().getQualifier().storage;
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.
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.
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;
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());
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));
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;
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;
7919 if (qualifier == EvqConst || qualifier == EvqUniform) {
7920 // Compile-time tagging of the variable with its constant value...
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;
7933 variable->setConstArray(initializer->getAsConstantUnion()->getConstArray());
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());
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
7954 // Returns a node representing an expression for the initializer list expressed
7955 // as the correct type.
7957 // Returns nullptr if there is an error.
7959 TIntermTyped* HlslParseContext::convertInitializerList(const TSourceLoc& loc, const TType& type,
7960 TIntermTyped* initializer, TIntermTyped* scalarInit)
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.
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())
7975 initList = intermediate.makeAggregate(initializer);
7978 // Of the initializer-list set of nodes, need to process bottom up,
7979 // so recurse deep, then process on the way up.
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.
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
7989 // edit array sizes to fill in unsized dimensions
7990 if (type.isUnsizedArray())
7991 arrayType.changeOuterArraySize((int)initList->getSequence().size());
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));
8005 // lengthen list to be long enough
8006 lengthenList(loc, initList->getSequence(), arrayType.getOuterArraySize(), scalarInit);
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)
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", "");
8027 // lengthen list to be long enough
8028 lengthenList(loc, initList->getSequence(), static_cast<int>(type.getStruct()->size()), scalarInit);
8030 if (type.getStruct()->size() != initList->getSequence().size()) {
8031 error(loc, "wrong number of structure members", "initializer list", "");
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)
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.
8046 // lengthen list to be long enough
8047 lengthenList(loc, initList->getSequence(), type.getMatrixCols(), scalarInit);
8049 if (type.getMatrixCols() != (int)initList->getSequence().size()) {
8050 error(loc, "wrong number of matrix columns:", "initializer list", type.getCompleteString().c_str());
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)
8061 } else if (type.isVector()) {
8062 // lengthen list to be long enough
8063 lengthenList(loc, initList->getSequence(), type.getVectorSize(), scalarInit);
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());
8071 } else if (type.isScalar()) {
8072 // lengthen list to be long enough
8073 lengthenList(loc, initList->getSequence(), 1, scalarInit);
8075 if ((int)initList->getSequence().size() != 1) {
8076 error(loc, "scalar expected one element:", "initializer list", type.getCompleteString().c_str());
8080 error(loc, "unexpected initializer-list type:", "initializer list", type.getCompleteString().c_str());
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();
8090 emulatedConstructorArguments = initList;
8092 return addConstructor(loc, emulatedConstructorArguments, type);
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.
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'.
8103 // 'scalarInit' must be safe to use each time this is called (no side effects replication).
8105 void HlslParseContext::lengthenList(const TSourceLoc& loc, TIntermSequence& list, int size, TIntermTyped* scalarInit)
8107 for (int c = (int)list.size(); c < size; ++c) {
8108 if (scalarInit == nullptr)
8109 list.push_back(intermediate.addConstantUnion(0, loc));
8111 list.push_back(scalarInit);
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.
8119 // Returns nullptr for an error or the constructed node (aggregate or typed) for no error.
8121 TIntermTyped* HlslParseContext::handleConstructor(const TSourceLoc& loc, TIntermTyped* node, const TType& type)
8123 if (node == nullptr)
8126 // Construct identical type
8127 if (type == node->getType())
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);
8145 return convertInitializerList(loc, type, intermediate.makeAggregate(loc), node);
8148 return addConstructor(loc, node, type);
8151 // Add a constructor, either from the grammar, or other programmatic reasons.
8153 // 'node' is what to construct from.
8154 // 'type' is what type to construct.
8156 // Returns the constructed object.
8157 // Return nullptr if it can't be done.
8159 TIntermTyped* HlslParseContext::addConstructor(const TSourceLoc& loc, TIntermTyped* node, const TType& type)
8161 TIntermAggregate* aggrNode = node->getAsAggregate();
8162 TOperator op = intermediate.mapTypeToConstructorOp(type);
8164 if (op == EOpConstructTextureSampler)
8165 return intermediate.setAggregateOperator(aggrNode, op, type, loc);
8167 TTypeList::const_iterator memberTypes;
8168 if (op == EOpConstructStruct)
8169 memberTypes = type.getStruct()->begin();
8172 if (type.isArray()) {
8173 TType dereferenced(type, 0);
8174 elementType.shallowCopy(dereferenced);
8176 elementType.shallowCopy(type);
8179 if (aggrNode != nullptr) {
8180 if (aggrNode->getOp() != EOpNull)
8187 TIntermTyped *newNode;
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);
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());
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);
8208 newNode = constructBuiltIn(type, op, node, node->getLoc(), false);
8211 if (newNode && (type.isArray() || op == EOpConstructStruct))
8212 newNode = intermediate.setAggregateOperator(newNode, EOpConstructStruct, type, loc);
8218 // Handle list of arguments.
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
8224 int paramCount = 0; // keeps a track of the constructor parameter number being checked
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.
8230 for (TIntermSequence::iterator p = sequenceVector.begin();
8231 p != sequenceVector.end(); p++, paramCount++) {
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());
8237 newNode = constructBuiltIn(type, op, (*p)->getAsTyped(), node->getLoc(), true);
8245 TIntermTyped* constructor = intermediate.setAggregateOperator(aggrNode, op, type, loc);
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.
8255 // Returns nullptr for an error or the constructed node.
8257 TIntermTyped* HlslParseContext::constructBuiltIn(const TType& type, TOperator op, TIntermTyped* node,
8258 const TSourceLoc& loc, bool subset)
8260 TIntermTyped* newNode;
8264 // First, convert types as needed.
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;
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;
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;
8315 case EOpConstructI16Vec2:
8316 case EOpConstructI16Vec3:
8317 case EOpConstructI16Vec4:
8318 case EOpConstructInt16:
8319 basicOp = EOpConstructInt16;
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;
8338 case EOpConstructU16Vec2:
8339 case EOpConstructU16Vec3:
8340 case EOpConstructU16Vec4:
8341 case EOpConstructUint16:
8342 basicOp = EOpConstructUint16;
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;
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;
8378 error(loc, "unsupported construction", "", "");
8382 newNode = intermediate.addUnaryMath(basicOp, node, node->getLoc());
8383 if (newNode == nullptr) {
8384 error(loc, "can't convert", "constructor", "");
8389 // Now, if there still isn't an operation to do the construction, and we need one, add one.
8392 // Otherwise, skip out early.
8393 if (subset || (newNode != node && newNode->getType() == type))
8396 // setAggregateOperator will insert a new node for the constructor, as needed.
8397 return intermediate.setAggregateOperator(newNode, op, type, loc);
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)
8405 assert(node->isArray() && type.isArray());
8406 if (node->getType().computeNumComponents() < type.computeNumComponents())
8409 // TODO: write an argument replicator, for the case the argument should not be
8410 // executed multiple times, yet multiple copies are needed.
8412 TIntermTyped* constructee = node->getAsTyped();
8413 // track where we are in consuming the argument
8414 int constructeeElement = 0;
8415 int constructeeComponent = 0;
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;
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()));
8449 // mismatched element shapes
8450 if (type.getVectorSize() == 1)
8451 elementArg = getNextComponent();
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);
8460 // convert basic types
8461 elementArg = intermediate.addConversion(componentOp, derefType, elementArg);
8462 if (elementArg == nullptr)
8464 // combine with top-level constructor
8465 constructor = intermediate.growAggregate(constructor, elementArg);
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.
8474 // Returns nullptr for an error or the input node itself if the expected and the given parameter types match.
8476 TIntermTyped* HlslParseContext::constructAggregate(TIntermNode* node, const TType& type, int paramCount,
8477 const TSourceLoc& loc)
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());
8492 // Do everything needed to add an interface block.
8494 void HlslParseContext::declareBlock(const TSourceLoc& loc, TType& type, const TString* instanceName)
8496 assert(type.getWritableStruct() != nullptr);
8498 // Clean up top-level decorations that don't belong.
8499 switch (type.getQualifier().storage) {
8502 correctUniform(type.getQualifier());
8505 correctInput(type.getQualifier());
8508 correctOutput(type.getQualifier());
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;
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) {
8529 correctUniform(type.getQualifier());
8530 if (it != ioTypeMap.end() && it->second.uniform)
8531 memberType.setStruct(it->second.uniform);
8534 correctInput(type.getQualifier());
8535 if (it != ioTypeMap.end() && it->second.input)
8536 memberType.setStruct(it->second.input);
8539 correctOutput(type.getQualifier());
8540 if (it != ioTypeMap.end() && it->second.output)
8541 memberType.setStruct(it->second.output);
8549 // Make default block qualification, and adjust the member qualifications
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;
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;
8565 // fix and check for member layout qualifiers
8567 mergeObjectLayoutQualifiers(defaultQualification, type.getQualifier(), true);
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", "");
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", "");
8588 if (memberQualifier.hasLocation()) {
8589 switch (type.getQualifier().storage) {
8592 memberWithLocation = true;
8598 memberWithoutLocation = true;
8600 TQualifier newMemberQualification = defaultQualification;
8601 mergeQualifiers(newMemberQualification, memberQualifier);
8602 memberQualifier = newMemberQualification;
8605 // Process the members
8606 fixBlockLocations(loc, type.getQualifier(), typeList, memberWithLocation, memberWithoutLocation);
8607 fixXfbOffsets(type.getQualifier(), typeList);
8608 fixBlockUniformOffsets(type.getQualifier(), typeList);
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);
8615 // Build and add the interface block as a new type named 'blockName'
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();
8621 TType blockType(&typeList, interfaceName, type.getQualifier());
8623 blockType.transferArraySizes(type.getArraySizes());
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("");
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() */, "");
8636 error(loc, "block instance name redefinition", variable.getName().c_str(), "");
8641 // Save it in the AST for linker use.
8642 if (symbolTable.atGlobalLevel())
8643 trackLinkage(variable);
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)
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", "");
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", "");
8670 if (qualifier.hasIndex()) {
8671 error(loc, "cannot apply to a block", "index", "");
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;
8683 nextLocation = memberQualifier.layoutLocation +
8684 intermediate.computeTypeLocationSize(*typeList[member].type, language);
8690 void HlslParseContext::fixXfbOffsets(TQualifier& qualifier, TTypeList& typeList)
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
8697 if (! qualifier.hasXfbBuffer() || ! qualifier.hasXfbOffset())
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;
8712 nextOffset = memberQualifier.layoutXfbOffset;
8713 nextOffset += memberSize;
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;
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.
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.
8727 void HlslParseContext::fixBlockUniformOffsets(const TQualifier& qualifier, TTypeList& typeList)
8729 if (! qualifier.isUniformOrBuffer())
8731 if (qualifier.layoutPacking != ElpStd140 && qualifier.layoutPacking != ElpStd430 && qualifier.layoutPacking != ElpScalar)
8736 for (unsigned int member = 0; member < typeList.size(); ++member) {
8737 TQualifier& memberQualifier = typeList[member].type->getQualifier();
8738 const TSourceLoc& memberLoc = typeList[member].loc;
8740 // "When align is applied to an array, it effects only the start of the array, not the array's internal stride."
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;
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", "");
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);
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);
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;
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)
8780 TSymbol* symbol = symbolTable.find(identifier);
8781 if (symbol == nullptr) {
8782 error(loc, "identifier not previously declared", identifier.c_str(), "");
8785 if (symbol->getAsFunction()) {
8786 error(loc, "cannot re-qualify a function name", identifier.c_str(), "");
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(), "");
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);
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;
8818 warn(loc, "unknown requalification", "", "");
8821 void HlslParseContext::addQualifierToExisting(const TSourceLoc& loc, TQualifier qualifier, TIdentifierList& identifiers)
8823 for (unsigned int i = 0; i < identifiers.size(); ++i)
8824 addQualifierToExisting(loc, qualifier, *identifiers[i]);
8828 // Update the intermediate for the given input geometry
8830 bool HlslParseContext::handleInputGeometry(const TSourceLoc& loc, const TLayoutGeometry& 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), "");
8845 error(loc, "cannot apply to 'in'", TQualifier::getGeometryString(geometry), "");
8853 // Update the intermediate for the given output geometry
8855 bool HlslParseContext::handleOutputGeometry(const TSourceLoc& loc, const TLayoutGeometry& geometry)
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)
8865 case ElgTriangleStrip:
8866 if (! intermediate.setOutputPrimitive(geometry)) {
8867 error(loc, "output primitive geometry redefinition", TQualifier::getGeometryString(geometry), "");
8872 error(loc, "cannot apply to 'out'", TQualifier::getGeometryString(geometry), "");
8880 // Selection attributes
8882 void HlslParseContext::handleSelectionAttributes(const TSourceLoc& loc, TIntermSelection* selection,
8883 const TAttributes& attributes)
8885 if (selection == nullptr)
8888 for (auto it = attributes.begin(); it != attributes.end(); ++it) {
8891 selection->setFlatten();
8894 selection->setDontFlatten();
8897 warn(loc, "attribute does not apply to a selection", "", "");
8904 // Switch attributes
8906 void HlslParseContext::handleSwitchAttributes(const TSourceLoc& loc, TIntermSwitch* selection,
8907 const TAttributes& attributes)
8909 if (selection == nullptr)
8912 for (auto it = attributes.begin(); it != attributes.end(); ++it) {
8915 selection->setFlatten();
8918 selection->setDontFlatten();
8921 warn(loc, "attribute does not apply to a switch", "", "");
8930 void HlslParseContext::handleLoopAttributes(const TSourceLoc& loc, TIntermLoop* loop,
8931 const TAttributes& attributes)
8933 if (loop == nullptr)
8936 for (auto it = attributes.begin(); it != attributes.end(); ++it) {
8942 loop->setDontUnroll();
8945 warn(loc, "attribute does not apply to a loop", "", "");
8952 // Updating default qualifier for the case of a declaration with just a qualifier,
8953 // no type, block, or identifier.
8955 void HlslParseContext::updateStandaloneQualifierDefaults(const TSourceLoc& loc, const TPublicType& publicType)
8957 if (publicType.shaderQualifiers.vertices != TQualifier::layoutNotSet) {
8958 assert(language == EShLangTessControl || language == EShLangGeometry);
8959 // const char* id = (language == EShLangTessControl) ? "vertices" : "max_vertices";
8961 if (publicType.shaderQualifiers.invocations != TQualifier::layoutNotSet) {
8962 if (! intermediate.setInvocations(publicType.shaderQualifiers.invocations))
8963 error(loc, "cannot change previously set layout value", "invocations", "");
8965 if (publicType.shaderQualifiers.geometry != ElgNone) {
8966 if (publicType.qualifier.storage == EvqVaryingIn) {
8967 switch (publicType.shaderQualifiers.geometry) {
8970 case ElgLinesAdjacency:
8972 case ElgTrianglesAdjacency:
8977 error(loc, "cannot apply to input", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry),
8980 } else if (publicType.qualifier.storage == EvqVaryingOut) {
8981 handleOutputGeometry(loc, publicType.shaderQualifiers.geometry);
8983 error(loc, "cannot apply to:", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry),
8984 GetStorageQualifierString(publicType.qualifier.storage));
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) {
8996 case 0: max = resources.maxComputeWorkGroupSizeX; break;
8997 case 1: max = resources.maxComputeWorkGroupSizeY; break;
8998 case 2: max = resources.maxComputeWorkGroupSizeZ; break;
9001 if (intermediate.getLocalSize(i) > (unsigned int)max)
9002 error(loc, "too large; see gl_MaxComputeWorkGroupSize", "local_size", "");
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));
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;
9015 if (publicType.shaderQualifiers.earlyFragmentTests)
9016 intermediate.setEarlyFragmentTests();
9018 const TQualifier& qualifier = publicType.qualifier;
9020 switch (qualifier.storage) {
9022 if (qualifier.hasMatrix())
9023 globalUniformDefaults.layoutMatrix = qualifier.layoutMatrix;
9024 if (qualifier.hasPacking())
9025 globalUniformDefaults.layoutPacking = qualifier.layoutPacking;
9028 if (qualifier.hasMatrix())
9029 globalBufferDefaults.layoutMatrix = qualifier.layoutMatrix;
9030 if (qualifier.hasPacking())
9031 globalBufferDefaults.layoutPacking = qualifier.layoutPacking;
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);
9047 error(loc, "default qualifier requires 'uniform', 'buffer', 'in', or 'out' storage qualification", "", "");
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
9058 void HlslParseContext::wrapupSwitchSubsequence(TIntermAggregate* statements, TIntermNode* branchNode)
9060 TIntermSequence* switchSequence = switchSequenceStack.back();
9063 statements->setOperator(EOpSequence);
9064 switchSequence->push_back(statements);
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();
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", "");
9084 switchSequence->push_back(branchNode);
9089 // Turn the top-level node sequence built up of wrapupSwitchSubsequence
9090 // into a switch node.
9092 TIntermNode* HlslParseContext::addSwitch(const TSourceLoc& loc, TIntermTyped* expression,
9093 TIntermAggregate* lastStatements, const TAttributes& attributes)
9095 wrapupSwitchSubsequence(lastStatements, nullptr);
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", "");
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)
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);
9114 TIntermAggregate* body = new TIntermAggregate(EOpSequence);
9115 body->getSequence() = *switchSequenceStack.back();
9118 TIntermSwitch* switchNode = new TIntermSwitch(expression, body);
9119 switchNode->setLoc(loc);
9120 handleSwitchAttributes(loc, switchNode, attributes);
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)
9131 TVariable& thisVariable = *new TVariable(NewPoolTString(""), thisStruct);
9132 symbolTable.pushThis(thisVariable);
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);
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
9152 // The string is empty when at normal global level.
9154 void HlslParseContext::pushNamespace(const TString& typeName)
9156 // make new type prefix
9158 if (currentTypePrefix.size() > 0)
9159 newPrefix = currentTypePrefix.back();
9160 newPrefix.append(typeName);
9161 newPrefix.append(scopeMangler);
9162 currentTypePrefix.push_back(newPrefix);
9165 // Opposite of pushNamespace(), see above
9166 void HlslParseContext::popNamespace()
9168 currentTypePrefix.pop_back();
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
9175 if (currentTypePrefix.size() == 0)
9178 TString* fullName = NewPoolTString(currentTypePrefix.back().c_str());
9179 fullName->append(*name);
9183 // Helper function to add the namespace scope mangling syntax to a string.
9184 void HlslParseContext::addScopeMangler(TString& name)
9186 name.append(scopeMangler);
9189 // Return true if this has uniform-interface like decorations.
9190 bool HlslParseContext::hasUniform(const TQualifier& qualifier) const
9192 return qualifier.hasUniformLayout() ||
9193 qualifier.layoutPushConstant;
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)
9201 qualifier.clearUniformLayout();
9202 qualifier.layoutPushConstant = false;
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
9208 switch (qualifier.builtIn) {
9211 return language != EShLangVertex && language != EShLangCompute && language != EShLangFragment;
9212 case EbvClipDistance:
9213 case EbvCullDistance:
9214 return language != EShLangVertex && language != EShLangCompute;
9217 case EbvHelperInvocation:
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;
9237 case EbvInstanceIndex:
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;
9247 return language == EShLangTessEvaluation;
9253 // Return true if there are decorations to preserve for input-like storage.
9254 bool HlslParseContext::hasInput(const TQualifier& qualifier) const
9256 if (qualifier.hasAnyLocation())
9259 if (language == EShLangFragment && (qualifier.isInterpolation() || qualifier.centroid || qualifier.sample))
9262 if (language == EShLangTessEvaluation && qualifier.patch)
9265 if (isInputBuiltIn(qualifier))
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
9274 switch (qualifier.builtIn) {
9278 case EbvClipDistance:
9279 case EbvCullDistance:
9280 return language != EShLangFragment && language != EShLangCompute;
9282 case EbvFragDepthGreater:
9283 case EbvFragDepthLesser:
9285 return language == EShLangFragment;
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;
9299 // Return true if there are decorations to preserve for output-like storage.
9300 bool HlslParseContext::hasOutput(const TQualifier& qualifier) const
9302 if (qualifier.hasAnyLocation())
9305 if (language != EShLangFragment && language != EShLangCompute && qualifier.hasXfb())
9308 if (language == EShLangTessControl && qualifier.patch)
9311 if (language == EShLangGeometry && qualifier.hasStream())
9314 if (isOutputBuiltIn(qualifier))
9320 // Make the IO decorations etc. be appropriate only for an input interface.
9321 void HlslParseContext::correctInput(TQualifier& qualifier)
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;
9333 qualifier.clearStreamLayout();
9334 qualifier.clearXfbLayout();
9336 if (! isInputBuiltIn(qualifier))
9337 qualifier.builtIn = EbvNone;
9340 // Make the IO decorations etc. be appropriate only for an output interface.
9341 void HlslParseContext::correctOutput(TQualifier& qualifier)
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;
9353 switch (qualifier.builtIn) {
9355 intermediate.setDepthReplacing();
9356 intermediate.setDepth(EldAny);
9358 case EbvFragDepthGreater:
9359 intermediate.setDepthReplacing();
9360 intermediate.setDepth(EldGreater);
9361 qualifier.builtIn = EbvFragDepth;
9363 case EbvFragDepthLesser:
9364 intermediate.setDepthReplacing();
9365 intermediate.setDepth(EldLess);
9366 qualifier.builtIn = EbvFragDepth;
9372 if (! isOutputBuiltIn(qualifier))
9373 qualifier.builtIn = EbvNone;
9376 // Make the IO decorations etc. be appropriate only for uniform type interfaces.
9377 void HlslParseContext::correctUniform(TQualifier& qualifier)
9379 if (qualifier.declaredBuiltIn == EbvNone)
9380 qualifier.declaredBuiltIn = qualifier.builtIn;
9382 qualifier.builtIn = EbvNone;
9383 qualifier.clearInterstage();
9384 qualifier.clearInterstageLayout();
9387 // Clear out all IO/Uniform stuff, so this has nothing to do with being an IO interface.
9388 void HlslParseContext::clearUniformInputOutput(TQualifier& qualifier)
9390 clearUniform(qualifier);
9391 correctUniform(qualifier);
9395 // Set texture return type. Returns success (not all types are valid).
9396 bool HlslParseContext::setTextureReturnType(TSampler& sampler, const TType& retType, const TSourceLoc& loc)
9398 // Seed the output with an invalid index. We will set it to a valid one if we can.
9399 sampler.structReturnIndex = TSampler::noReturnStruct;
9401 // Arrays aren't supported.
9402 if (retType.isArray()) {
9403 error(loc, "Arrays not supported in texture template types", "", "");
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();
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", "", "");
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", "", "");
9426 TTypeList* members = retType.getWritableStruct();
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", "", "");
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", "", "");
9443 const unsigned memberVectorSize = (*members)[m].type->getVectorSize();
9444 totalComponents += memberVectorSize;
9446 // too many total member components
9447 if (totalComponents > 4) {
9448 error(loc, "Too many components in texture template structure type", "", "");
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", "", "");
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;
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", "", "");
9474 // Insert it in the vector that tracks struct return types.
9475 sampler.structReturnIndex = unsigned(textureReturnStruct.size());
9476 textureReturnStruct.push_back(members);
9482 // Return the sampler return type in retType.
9483 void HlslParseContext::getTextureReturnType(const TSampler& sampler, TType& retType) const
9485 if (sampler.hasReturnStruct()) {
9486 assert(textureReturnStruct.size() >= sampler.structReturnIndex);
9488 // We land here if the texture return is a structure.
9489 TTypeList* blockStruct = textureReturnStruct[sampler.structReturnIndex];
9491 const TType resultType(blockStruct, "");
9492 retType.shallowCopy(resultType);
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);
9501 // Return a symbol for the tessellation linkage variable of the given TBuiltInVariable type
9502 TIntermSymbol* HlslParseContext::findTessLinkageSymbol(TBuiltInVariable biType) const
9504 const auto it = builtInTessLinkageSymbols.find(biType);
9505 if (it == builtInTessLinkageSymbols.end()) // if it wasn't declared by the user, return nullptr
9508 return intermediate.addSymbol(*it->second->getAsVariable());
9511 // Find the patch constant function (issues error, returns nullptr if not found)
9512 const TFunction* HlslParseContext::findPatchConstantFunction(const TSourceLoc& loc)
9514 if (symbolTable.isFunctionNameVariable(patchConstantFunctionName)) {
9515 error(loc, "can't use variable in patch constant function", patchConstantFunctionName.c_str(), "");
9519 const TString mangledName = patchConstantFunctionName + "(";
9521 // create list of PCF candidates
9522 TVector<const TFunction*> candidateList;
9524 symbolTable.findFunctionNameList(mangledName, candidateList, builtIn);
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(), "");
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(), "");
9541 return candidateList[0];
9544 // Finalization step: Add patch constant function invocation
9545 void HlslParseContext::addPatchConstantInvocation()
9550 // If there's no patch constant function, or we're not a HS, do nothing.
9551 if (patchConstantFunctionName.empty() || language != EShLangTessControl)
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;
9559 if (storage == EvqConstReadOnly) // treated identically to input
9562 if (function[p].getDeclaredBuiltIn() != EbvNone)
9563 builtIns.insert(HlslParseContext::tInterstageIoData(function[p].getDeclaredBuiltIn(), storage));
9565 builtIns.insert(HlslParseContext::tInterstageIoData(function[p].type->getQualifier().builtIn, storage));
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", "", "");
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(), "");
9581 globalQualifierFix(loc, variable.getWritableType().getQualifier());
9583 if (symbolNode != nullptr)
9584 *symbolNode = intermediate.addSymbol(variable);
9586 trackLinkage(variable);
9590 const auto isOutputPatch = [](TFunction& patchConstantFunction, int param) {
9591 const TType& type = *patchConstantFunction[param].type;
9592 const TBuiltInVariable biType = patchConstantFunction[param].getDeclaredBuiltIn();
9594 return type.isSizedArray() && biType == EbvOutputPatch;
9597 // We will perform these steps. Each is in a scoped block for separation: they could
9598 // become separate functions to make addPatchConstantInvocation shorter.
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.
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.
9607 // 2B: Synthesize per control point invocations of wrapped entry point if the PCF requires them.
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.
9614 // 4. Create a barrier.
9616 // 5/5B. Call the PCF inside an if test for (invocation id == 0).
9618 TFunction* patchConstantFunctionPtr = const_cast<TFunction*>(findPatchConstantFunction(loc));
9620 if (patchConstantFunctionPtr == nullptr)
9623 TFunction& patchConstantFunction = *patchConstantFunctionPtr;
9625 const int pcfParamCount = patchConstantFunction.getParamCount();
9626 TIntermSymbol* invocationIdSym = findTessLinkageSymbol(EbvInvocationId);
9627 TIntermSequence& epBodySeq = entryPointFunctionBody->getAsAggregate()->getSequence();
9629 int outPatchParam = -1; // -1 means there isn't one.
9631 // ================ Step 1A: Union Interfaces ================
9632 // Our patch constant function.
9634 std::set<tInterstageIoData> pcfBuiltIns; // patch constant function built-ins
9635 std::set<tInterstageIoData> epfBuiltIns; // entry point function built-ins
9637 assert(entryPointFunction);
9638 assert(entryPointFunctionBody);
9640 findBuiltIns(patchConstantFunction, pcfBuiltIns);
9641 findBuiltIns(*entryPointFunction, epfBuiltIns);
9643 // Find the set of built-ins in the PCF that are not present in the entry point.
9644 std::set<tInterstageIoData> notInEntryPoint;
9646 notInEntryPoint = pcfBuiltIns;
9648 // std::set_difference not usable on unordered containers
9649 for (auto bi = epfBuiltIns.begin(); bi != epfBuiltIns.end(); ++bi)
9650 notInEntryPoint.erase(*bi);
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;
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", "", "");
9667 if (biType != EbvNone) {
9668 TType* paramType = patchConstantFunction[p].type->clone();
9670 if (storage == EvqConstReadOnly) // treated identically to input
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) {
9680 // Use the original declaration type for the linkage
9681 paramType->getQualifier().builtIn = biType;
9683 if (notInEntryPoint.count(tInterstageIoData(biType, storage)) == 1)
9684 addToLinkage(*paramType, patchConstantFunction[p].name, nullptr);
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);
9697 assert(invocationIdSym);
9700 TIntermTyped* pcfArguments = nullptr;
9701 TVariable* perCtrlPtVar = nullptr;
9703 // ================ Step 1B: Argument synthesis ================
9704 // Create pcfArguments for synthesis of patchconstantfunction invocation
9706 for (int p=0; p<pcfParamCount; ++p) {
9707 TIntermTyped* inputArg = nullptr;
9709 if (p == outPatchParam) {
9710 if (perCtrlPtVar == nullptr) {
9711 perCtrlPtVar = makeInternalVariable(*patchConstantFunction[outPatchParam].name,
9712 *patchConstantFunction[outPatchParam].type);
9714 perCtrlPtVar->getWritableType().getQualifier().makeTemporary();
9716 inputArg = intermediate.addSymbol(*perCtrlPtVar, loc);
9718 // find which built-in it is
9719 const TBuiltInVariable biType = patchConstantFunction[p].getDeclaredBuiltIn();
9721 if (biType == EbvInputPatch && inputPatch == nullptr) {
9722 error(loc, "unimplemented: PCF input patch without entry point input patch parameter", "", "");
9726 inputArg = findTessLinkageSymbol(biType);
9728 if (inputArg == nullptr) {
9729 error(loc, "unable to find patch constant function built-in variable", "", "");
9734 if (pcfParamCount == 1)
9735 pcfArguments = inputArg;
9737 pcfArguments = intermediate.growAggregate(pcfArguments, inputArg);
9741 // ================ Step 2: Synthesize call to PCF ================
9742 TIntermAggregate* pcfCallSequence = nullptr;
9743 TIntermTyped* pcfCall = nullptr;
9746 // Create a function call to the patchconstantfunction
9748 addInputArgumentConversions(patchConstantFunction, pcfArguments);
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());
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);
9763 pcfCall = addOutputArgumentConversions(patchConstantFunction, *pcfCall->getAsOperator());
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();
9776 if (entryPointFunction->getType().getBasicType() == EbtVoid) {
9777 error(loc, "entry point must return a value for use with patch constant function", "", "");
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.
9784 // This is the type of the each member of the per ctrl point array.
9785 const TType derefType(perCtrlPtVar->getType(), 0);
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;
9794 for (int i = 0; i < entryPointFunction->getParamCount(); i++) {
9795 TParameter& param = (*entryPointFunction)[i];
9796 TType& paramType = *param.type;
9798 if (paramType.getQualifier().isParamOutput()) {
9799 error(loc, "unimplemented: entry point outputs in patch constant function invocation", "", "");
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);
9809 TVariable* argVar = makeInternalVariable(*param.name, *param.type);
9810 argVar->getWritableType().getQualifier().makeTemporary();
9811 arg = intermediate.addSymbol(*argVar);
9814 handleFunctionArgument(&callee, callingArgs, arg);
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);
9827 pcfCallSequence = intermediate.growAggregate(pcfCallSequence,
9828 handleAssign(loc, EOpAssign, element, callReturn));
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);
9839 // substitute the output type
9840 const auto newLists = ioTypeMap.find(retType->getStruct());
9841 if (newLists != ioTypeMap.end())
9842 outType.setStruct(newLists->second.output);
9844 // Substitute the top level type's built-in type
9845 if (patchConstantFunction.getDeclaredBuiltInType() != EbvNone)
9846 outType.getQualifier().builtIn = patchConstantFunction.getDeclaredBuiltInType();
9848 outType.getQualifier().patch = true; // make it a per-patch variable
9850 TVariable* pcfOutput = makeInternalVariable("@patchConstantOutput", outType);
9851 pcfOutput->getWritableType().getQualifier().storage = EvqVaryingOut;
9853 if (pcfOutput->getType().containsBuiltIn())
9856 assignToInterface(*pcfOutput);
9858 TIntermSymbol* pcfOutputSym = intermediate.addSymbol(*pcfOutput, loc);
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();
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));
9870 pcfCallSequence = intermediate.growAggregate(pcfCallSequence, pcfResultAssign);
9871 pcfCallSequence = intermediate.growAggregate(pcfCallSequence, pcfResultToOut);
9873 pcfCallSequence = intermediate.growAggregate(pcfCallSequence, pcfCall);
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);
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));
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);
9892 // add our test sequence before the return.
9893 epBodySeq.insert(epBodySeq.end(), invocationIdTest);
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()
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;
9907 linkageSymbols.erase(endIt, linkageSymbols.end());
9910 // Finalization step: patch texture shadow modes to match samplers they were combined with
9911 void HlslParseContext::fixTextureShadowModes()
9913 for (auto symbol = linkageSymbols.begin(); symbol != linkageSymbols.end(); ++symbol) {
9914 TSampler& sampler = (*symbol)->getWritableType().getSampler();
9916 if (sampler.isTexture()) {
9917 const auto shadowMode = textureShadowVariant.find((*symbol)->getUniqueId());
9918 if (shadowMode != textureShadowVariant.end()) {
9920 if (shadowMode->second->overloaded())
9921 // Texture needs legalization if it's been seen with both shadow and non-shadow modes.
9922 intermediate.setNeedsLegalization();
9924 sampler.shadow = shadowMode->second->isShadowId((*symbol)->getUniqueId());
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()
9937 // Nothing to do: bypass test for valid stream output.
9938 if (gsAppends.empty())
9941 if (gsStreamOutput == nullptr) {
9942 error(loc, "unable to find output symbol for Append()", "", "");
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());
9956 void HlslParseContext::finish()
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:", "", "");
9964 removeUnusedStructBufferCounters();
9965 addPatchConstantInvocation();
9966 fixTextureShadowModes();
9967 finalizeAppendMethods();
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";
9974 TParseContextBase::finish();
9977 } // end namespace glslang