2 // Copyright (C) 2017 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/MachineIndependent/Scan.h"
43 #include "../glslang/MachineIndependent/preprocessor/PpContext.h"
45 #include "../glslang/OSDependent/osinclude.h"
55 HlslParseContext::HlslParseContext(TSymbolTable& symbolTable, TIntermediate& interm, bool parsingBuiltins,
56 int version, EProfile profile, const SpvVersion& spvVersion, EShLanguage language,
58 const TString sourceEntryPointName,
59 bool forwardCompatible, EShMessages messages) :
60 TParseContextBase(symbolTable, interm, parsingBuiltins, version, profile, spvVersion, language, infoSink,
61 forwardCompatible, messages, &sourceEntryPointName),
62 annotationNestingLevel(0),
64 nextInLocation(0), nextOutLocation(0),
65 entryPointFunction(nullptr),
66 entryPointFunctionBody(nullptr),
67 gsStreamOutput(nullptr),
68 clipDistanceOutput(nullptr),
69 cullDistanceOutput(nullptr),
70 clipDistanceInput(nullptr),
71 cullDistanceInput(nullptr)
73 globalUniformDefaults.clear();
74 globalUniformDefaults.layoutMatrix = ElmRowMajor;
75 globalUniformDefaults.layoutPacking = ElpStd140;
77 globalBufferDefaults.clear();
78 globalBufferDefaults.layoutMatrix = ElmRowMajor;
79 globalBufferDefaults.layoutPacking = ElpStd430;
81 globalInputDefaults.clear();
82 globalOutputDefaults.clear();
84 clipSemanticNSizeIn.fill(0);
85 cullSemanticNSizeIn.fill(0);
86 clipSemanticNSizeOut.fill(0);
87 cullSemanticNSizeOut.fill(0);
89 // "Shaders in the transform
90 // feedback capturing mode have an initial global default of
91 // layout(xfb_buffer = 0) out;"
92 if (language == EShLangVertex ||
93 language == EShLangTessControl ||
94 language == EShLangTessEvaluation ||
95 language == EShLangGeometry)
96 globalOutputDefaults.layoutXfbBuffer = 0;
98 if (language == EShLangGeometry)
99 globalOutputDefaults.layoutStream = 0;
101 if (spvVersion.spv == 0 || spvVersion.vulkan == 0)
102 infoSink.info << "ERROR: HLSL currently only supported when requesting SPIR-V for Vulkan.\n";
105 HlslParseContext::~HlslParseContext()
109 void HlslParseContext::initializeExtensionBehavior()
111 TParseContextBase::initializeExtensionBehavior();
113 // HLSL allows #line by default.
114 extensionBehavior[E_GL_GOOGLE_cpp_style_line_directive] = EBhEnable;
117 void HlslParseContext::setLimits(const TBuiltInResource& r)
120 intermediate.setLimits(resources);
124 // Parse an array of strings using the parser in HlslRules.
126 // Returns true for successful acceptance of the shader, false if any errors.
128 bool HlslParseContext::parseShaderStrings(TPpContext& ppContext, TInputScanner& input, bool versionWillBeError)
130 currentScanner = &input;
131 ppContext.setInput(input, versionWillBeError);
133 HlslScanContext scanContext(*this, ppContext);
134 HlslGrammar grammar(scanContext, *this);
135 if (!grammar.parse()) {
136 // Print a message formated such that if you click on the message it will take you right to
137 // the line through most UIs.
138 const glslang::TSourceLoc& sourceLoc = input.getSourceLoc();
139 infoSink.info << sourceLoc.name << "(" << sourceLoc.line << "): error at column " << sourceLoc.column
140 << ", HLSL parsing failed.\n";
147 return numErrors == 0;
151 // Return true if this l-value node should be converted in some manner.
152 // For instance: turning a load aggregate into a store in an l-value.
154 bool HlslParseContext::shouldConvertLValue(const TIntermNode* node) const
156 if (node == nullptr || node->getAsTyped() == nullptr)
159 const TIntermAggregate* lhsAsAggregate = node->getAsAggregate();
160 const TIntermBinary* lhsAsBinary = node->getAsBinaryNode();
162 // If it's a swizzled/indexed aggregate, look at the left node instead.
163 if (lhsAsBinary != nullptr &&
164 (lhsAsBinary->getOp() == EOpVectorSwizzle || lhsAsBinary->getOp() == EOpIndexDirect))
165 lhsAsAggregate = lhsAsBinary->getLeft()->getAsAggregate();
166 if (lhsAsAggregate != nullptr && lhsAsAggregate->getOp() == EOpImageLoad)
172 void HlslParseContext::growGlobalUniformBlock(const TSourceLoc& loc, TType& memberType, const TString& memberName,
173 TTypeList* newTypeList)
175 newTypeList = nullptr;
176 correctUniform(memberType.getQualifier());
177 if (memberType.isStruct()) {
178 auto it = ioTypeMap.find(memberType.getStruct());
179 if (it != ioTypeMap.end() && it->second.uniform)
180 newTypeList = it->second.uniform;
182 TParseContextBase::growGlobalUniformBlock(loc, memberType, memberName, newTypeList);
186 // Return a TLayoutFormat corresponding to the given texture type.
188 TLayoutFormat HlslParseContext::getLayoutFromTxType(const TSourceLoc& loc, const TType& txType)
190 if (txType.isStruct()) {
192 error(loc, "unimplemented: structure type in image or buffer", "", "");
196 const int components = txType.getVectorSize();
197 const TBasicType txBasicType = txType.getBasicType();
199 const auto selectFormat = [this,&components](TLayoutFormat v1, TLayoutFormat v2, TLayoutFormat v4) -> TLayoutFormat {
200 if (intermediate.getNoStorageFormat())
203 return components == 1 ? v1 :
204 components == 2 ? v2 : v4;
207 switch (txBasicType) {
208 case EbtFloat: return selectFormat(ElfR32f, ElfRg32f, ElfRgba32f);
209 case EbtInt: return selectFormat(ElfR32i, ElfRg32i, ElfRgba32i);
210 case EbtUint: return selectFormat(ElfR32ui, ElfRg32ui, ElfRgba32ui);
212 error(loc, "unknown basic type in image format", "", "");
218 // Both test and if necessary, spit out an error, to see if the node is really
219 // an l-value that can be operated on this way.
221 // Returns true if there was an error.
223 bool HlslParseContext::lValueErrorCheck(const TSourceLoc& loc, const char* op, TIntermTyped* node)
225 if (shouldConvertLValue(node)) {
226 // if we're writing to a texture, it must be an RW form.
228 TIntermAggregate* lhsAsAggregate = node->getAsAggregate();
229 TIntermTyped* object = lhsAsAggregate->getSequence()[0]->getAsTyped();
231 if (!object->getType().getSampler().isImage()) {
232 error(loc, "operator[] on a non-RW texture must be an r-value", "", "");
237 // We tolerate samplers as l-values, even though they are nominally
238 // illegal, because we expect a later optimization to eliminate them.
239 if (node->getType().getBasicType() == EbtSampler) {
240 intermediate.setNeedsLegalization();
244 // Let the base class check errors
245 return TParseContextBase::lValueErrorCheck(loc, op, node);
249 // This function handles l-value conversions and verifications. It uses, but is not synonymous
250 // with lValueErrorCheck. That function accepts an l-value directly, while this one must be
251 // given the surrounding tree - e.g, with an assignment, so we can convert the assign into a
252 // series of other image operations.
254 // Most things are passed through unmodified, except for error checking.
256 TIntermTyped* HlslParseContext::handleLvalue(const TSourceLoc& loc, const char* op, TIntermTyped*& node)
261 TIntermBinary* nodeAsBinary = node->getAsBinaryNode();
262 TIntermUnary* nodeAsUnary = node->getAsUnaryNode();
263 TIntermAggregate* sequence = nullptr;
265 TIntermTyped* lhs = nodeAsUnary ? nodeAsUnary->getOperand() :
266 nodeAsBinary ? nodeAsBinary->getLeft() :
269 // Early bail out if there is no conversion to apply
270 if (!shouldConvertLValue(lhs)) {
272 if (lValueErrorCheck(loc, op, lhs))
277 // *** If we get here, we're going to apply some conversion to an l-value.
279 // Helper to create a load.
280 const auto makeLoad = [&](TIntermSymbol* rhsTmp, TIntermTyped* object, TIntermTyped* coord, const TType& derefType) {
281 TIntermAggregate* loadOp = new TIntermAggregate(EOpImageLoad);
283 loadOp->getSequence().push_back(object);
284 loadOp->getSequence().push_back(intermediate.addSymbol(*coord->getAsSymbolNode()));
285 loadOp->setType(derefType);
287 sequence = intermediate.growAggregate(sequence,
288 intermediate.addAssign(EOpAssign, rhsTmp, loadOp, loc),
292 // Helper to create a store.
293 const auto makeStore = [&](TIntermTyped* object, TIntermTyped* coord, TIntermSymbol* rhsTmp) {
294 TIntermAggregate* storeOp = new TIntermAggregate(EOpImageStore);
295 storeOp->getSequence().push_back(object);
296 storeOp->getSequence().push_back(coord);
297 storeOp->getSequence().push_back(intermediate.addSymbol(*rhsTmp));
298 storeOp->setLoc(loc);
299 storeOp->setType(TType(EbtVoid));
301 sequence = intermediate.growAggregate(sequence, storeOp);
304 // Helper to create an assign.
305 const auto makeBinary = [&](TOperator op, TIntermTyped* lhs, TIntermTyped* rhs) {
306 sequence = intermediate.growAggregate(sequence,
307 intermediate.addBinaryNode(op, lhs, rhs, loc, lhs->getType()),
311 // Helper to complete sequence by adding trailing variable, so we evaluate to the right value.
312 const auto finishSequence = [&](TIntermSymbol* rhsTmp, const TType& derefType) -> TIntermAggregate* {
313 // Add a trailing use of the temp, so the sequence returns the proper value.
314 sequence = intermediate.growAggregate(sequence, intermediate.addSymbol(*rhsTmp));
315 sequence->setOperator(EOpSequence);
316 sequence->setLoc(loc);
317 sequence->setType(derefType);
322 // Helper to add unary op
323 const auto makeUnary = [&](TOperator op, TIntermSymbol* rhsTmp) {
324 sequence = intermediate.growAggregate(sequence,
325 intermediate.addUnaryNode(op, intermediate.addSymbol(*rhsTmp), loc,
330 // Return true if swizzle or index writes all components of the given variable.
331 const auto writesAllComponents = [&](TIntermSymbol* var, TIntermBinary* swizzle) -> bool {
332 if (swizzle == nullptr) // not a swizzle or index
335 // Track which components are being set.
336 std::array<bool, 4> compIsSet;
337 compIsSet.fill(false);
339 const TIntermConstantUnion* asConst = swizzle->getRight()->getAsConstantUnion();
340 const TIntermAggregate* asAggregate = swizzle->getRight()->getAsAggregate();
342 // This could be either a direct index, or a swizzle.
344 compIsSet[asConst->getConstArray()[0].getIConst()] = true;
345 } else if (asAggregate) {
346 const TIntermSequence& seq = asAggregate->getSequence();
347 for (int comp=0; comp<int(seq.size()); ++comp)
348 compIsSet[seq[comp]->getAsConstantUnion()->getConstArray()[0].getIConst()] = true;
353 // Return true if all components are being set by the index or swizzle
354 return std::all_of(compIsSet.begin(), compIsSet.begin() + var->getType().getVectorSize(),
355 [](bool isSet) { return isSet; } );
358 // Create swizzle matching input swizzle
359 const auto addSwizzle = [&](TIntermSymbol* var, TIntermBinary* swizzle) -> TIntermTyped* {
361 return intermediate.addBinaryNode(swizzle->getOp(), var, swizzle->getRight(), loc, swizzle->getType());
366 TIntermBinary* lhsAsBinary = lhs->getAsBinaryNode();
367 TIntermAggregate* lhsAsAggregate = lhs->getAsAggregate();
368 bool lhsIsSwizzle = false;
370 // If it's a swizzled L-value, remember the swizzle, and use the LHS.
371 if (lhsAsBinary != nullptr && (lhsAsBinary->getOp() == EOpVectorSwizzle || lhsAsBinary->getOp() == EOpIndexDirect)) {
372 lhsAsAggregate = lhsAsBinary->getLeft()->getAsAggregate();
376 TIntermTyped* object = lhsAsAggregate->getSequence()[0]->getAsTyped();
377 TIntermTyped* coord = lhsAsAggregate->getSequence()[1]->getAsTyped();
379 const TSampler& texSampler = object->getType().getSampler();
382 getTextureReturnType(texSampler, objDerefType);
385 TIntermTyped* rhs = nodeAsBinary->getRight();
386 const TOperator assignOp = nodeAsBinary->getOp();
388 bool isModifyOp = false;
394 case EOpVectorTimesMatrixAssign:
395 case EOpVectorTimesScalarAssign:
396 case EOpMatrixTimesScalarAssign:
397 case EOpMatrixTimesMatrixAssign:
401 case EOpInclusiveOrAssign:
402 case EOpExclusiveOrAssign:
403 case EOpLeftShiftAssign:
404 case EOpRightShiftAssign:
409 // Since this is an lvalue, we'll convert an image load to a sequence like this
410 // (to still provide the value):
412 // OpImageStore(object, lhs, rhs)
414 // But if it's not a simple symbol RHS (say, a fn call), we don't want to duplicate the RHS,
415 // so we'll convert instead to this:
418 // OpImageStore(object, coord, rhsTmp)
420 // If this is a read-modify-write op, like +=, we issue:
422 // coordtmp = load's param1
423 // rhsTmp = OpImageLoad(object, coordTmp)
425 // OpImageStore(object, coordTmp, rhsTmp)
428 // If the lvalue is swizzled, we apply that when writing the temp variable, like so:
430 // rhsTmp.some_swizzle = ...
431 // For partial writes, an error is generated.
433 TIntermSymbol* rhsTmp = rhs->getAsSymbolNode();
434 TIntermTyped* coordTmp = coord;
436 if (rhsTmp == nullptr || isModifyOp || lhsIsSwizzle) {
437 rhsTmp = makeInternalVariableNode(loc, "storeTemp", objDerefType);
439 // Partial updates not yet supported
440 if (!writesAllComponents(rhsTmp, lhsAsBinary)) {
441 error(loc, "unimplemented: partial image updates", "", "");
444 // Assign storeTemp = rhs
446 // We have to make a temp var for the coordinate, to avoid evaluating it twice.
447 coordTmp = makeInternalVariableNode(loc, "coordTemp", coord->getType());
448 makeBinary(EOpAssign, coordTmp, coord); // coordtmp = load[param1]
449 makeLoad(rhsTmp, object, coordTmp, objDerefType); // rhsTmp = OpImageLoad(object, coordTmp)
453 makeBinary(assignOp, addSwizzle(intermediate.addSymbol(*rhsTmp), lhsAsBinary), rhs);
456 makeStore(object, coordTmp, rhsTmp); // add a store
457 return finishSequence(rhsTmp, objDerefType); // return rhsTmp from sequence
466 const TOperator assignOp = nodeAsUnary->getOp();
469 case EOpPreIncrement:
470 case EOpPreDecrement:
472 // We turn this into:
474 // coordtmp = load's param1
475 // rhsTmp = OpImageLoad(object, coordTmp)
477 // OpImageStore(object, coordTmp, rhsTmp)
480 TIntermSymbol* rhsTmp = makeInternalVariableNode(loc, "storeTemp", objDerefType);
481 TIntermTyped* coordTmp = makeInternalVariableNode(loc, "coordTemp", coord->getType());
483 makeBinary(EOpAssign, coordTmp, coord); // coordtmp = load[param1]
484 makeLoad(rhsTmp, object, coordTmp, objDerefType); // rhsTmp = OpImageLoad(object, coordTmp)
485 makeUnary(assignOp, rhsTmp); // op rhsTmp
486 makeStore(object, coordTmp, rhsTmp); // OpImageStore(object, coordTmp, rhsTmp)
487 return finishSequence(rhsTmp, objDerefType); // return rhsTmp from sequence
490 case EOpPostIncrement:
491 case EOpPostDecrement:
493 // We turn this into:
495 // coordtmp = load's param1
496 // rhsTmp1 = OpImageLoad(object, coordTmp)
499 // OpImageStore(object, coordTmp, rhsTmp2)
500 // rhsTmp1 (pre-op value)
501 TIntermSymbol* rhsTmp1 = makeInternalVariableNode(loc, "storeTempPre", objDerefType);
502 TIntermSymbol* rhsTmp2 = makeInternalVariableNode(loc, "storeTempPost", objDerefType);
503 TIntermTyped* coordTmp = makeInternalVariableNode(loc, "coordTemp", coord->getType());
505 makeBinary(EOpAssign, coordTmp, coord); // coordtmp = load[param1]
506 makeLoad(rhsTmp1, object, coordTmp, objDerefType); // rhsTmp1 = OpImageLoad(object, coordTmp)
507 makeBinary(EOpAssign, rhsTmp2, rhsTmp1); // rhsTmp2 = rhsTmp1
508 makeUnary(assignOp, rhsTmp2); // rhsTmp op
509 makeStore(object, coordTmp, rhsTmp2); // OpImageStore(object, coordTmp, rhsTmp2)
510 return finishSequence(rhsTmp1, objDerefType); // return rhsTmp from sequence
519 if (lValueErrorCheck(loc, op, lhs))
525 void HlslParseContext::handlePragma(const TSourceLoc& loc, const TVector<TString>& tokens)
528 pragmaCallback(loc.line, tokens);
530 if (tokens.size() == 0)
533 // These pragmas are case insensitive in HLSL, so we'll compare in lower case.
534 TVector<TString> lowerTokens = tokens;
536 for (auto it = lowerTokens.begin(); it != lowerTokens.end(); ++it)
537 std::transform(it->begin(), it->end(), it->begin(), ::tolower);
539 // Handle pack_matrix
540 if (tokens.size() == 4 && lowerTokens[0] == "pack_matrix" && tokens[1] == "(" && tokens[3] == ")") {
541 // Note that HLSL semantic order is Mrc, not Mcr like SPIR-V, so we reverse the sense.
542 // Row major becomes column major and vice versa.
544 if (lowerTokens[2] == "row_major") {
545 globalUniformDefaults.layoutMatrix = globalBufferDefaults.layoutMatrix = ElmColumnMajor;
546 } else if (lowerTokens[2] == "column_major") {
547 globalUniformDefaults.layoutMatrix = globalBufferDefaults.layoutMatrix = ElmRowMajor;
549 // unknown majorness strings are treated as (HLSL column major)==(SPIR-V row major)
550 warn(loc, "unknown pack_matrix pragma value", tokens[2].c_str(), "");
551 globalUniformDefaults.layoutMatrix = globalBufferDefaults.layoutMatrix = ElmRowMajor;
557 if (lowerTokens[0] == "once") {
558 warn(loc, "not implemented", "#pragma once", "");
564 // Look at a '.' matrix selector string and change it into components
565 // for a matrix. There are two types:
567 // _21 second row, first column (one based)
568 // _m21 third row, second column (zero based)
570 // Returns true if there is no error.
572 bool HlslParseContext::parseMatrixSwizzleSelector(const TSourceLoc& loc, const TString& fields, int cols, int rows,
573 TSwizzleSelectors<TMatrixSelector>& components)
575 int startPos[MaxSwizzleSelectors];
577 TString compString = fields;
579 // Find where each component starts,
580 // recording the first character position after the '_'.
581 for (size_t c = 0; c < compString.size(); ++c) {
582 if (compString[c] == '_') {
583 if (numComps >= MaxSwizzleSelectors) {
584 error(loc, "matrix component swizzle has too many components", compString.c_str(), "");
587 if (c > compString.size() - 3 ||
588 ((compString[c+1] == 'm' || compString[c+1] == 'M') && c > compString.size() - 4)) {
589 error(loc, "matrix component swizzle missing", compString.c_str(), "");
592 startPos[numComps++] = (int)c + 1;
596 // Process each component
597 for (int i = 0; i < numComps; ++i) {
598 int pos = startPos[i];
600 if (compString[pos] == 'm' || compString[pos] == 'M') {
604 TMatrixSelector comp;
605 comp.coord1 = compString[pos+0] - '0' + bias;
606 comp.coord2 = compString[pos+1] - '0' + bias;
607 if (comp.coord1 < 0 || comp.coord1 >= cols) {
608 error(loc, "matrix row component out of range", compString.c_str(), "");
611 if (comp.coord2 < 0 || comp.coord2 >= rows) {
612 error(loc, "matrix column component out of range", compString.c_str(), "");
615 components.push_back(comp);
621 // If the 'comps' express a column of a matrix,
622 // return the column. Column means the first coords all match.
624 // Otherwise, return -1.
626 int HlslParseContext::getMatrixComponentsColumn(int rows, const TSwizzleSelectors<TMatrixSelector>& selector)
630 // right number of comps?
631 if (selector.size() != rows)
634 // all comps in the same column?
636 col = selector[0].coord1;
637 for (int i = 0; i < rows; ++i) {
638 if (col != selector[i].coord1)
640 if (i != selector[i].coord2)
648 // Handle seeing a variable identifier in the grammar.
650 TIntermTyped* HlslParseContext::handleVariable(const TSourceLoc& loc, const TString* string)
653 TSymbol* symbol = symbolTable.find(*string, thisDepth);
654 if (symbol && symbol->getAsVariable() && symbol->getAsVariable()->isUserType()) {
655 error(loc, "expected symbol, not user-defined type", string->c_str(), "");
659 // Error check for requiring specific extensions present.
660 if (symbol && symbol->getNumExtensions())
661 requireExtensions(loc, symbol->getNumExtensions(), symbol->getExtensions(), symbol->getName().c_str());
663 const TVariable* variable = nullptr;
664 const TAnonMember* anon = symbol ? symbol->getAsAnonMember() : nullptr;
665 TIntermTyped* node = nullptr;
667 // It was a member of an anonymous container, which could be a 'this' structure.
669 // Create a subtree for its dereference.
671 variable = getImplicitThis(thisDepth);
672 if (variable == nullptr)
673 error(loc, "cannot access member variables (static member function?)", "this", "");
675 if (variable == nullptr)
676 variable = anon->getAnonContainer().getAsVariable();
678 TIntermTyped* container = intermediate.addSymbol(*variable, loc);
679 TIntermTyped* constNode = intermediate.addConstantUnion(anon->getMemberNumber(), loc);
680 node = intermediate.addIndex(EOpIndexDirectStruct, container, constNode, loc);
682 node->setType(*(*variable->getType().getStruct())[anon->getMemberNumber()].type);
683 if (node->getType().hiddenMember())
684 error(loc, "member of nameless block was not redeclared", string->c_str(), "");
686 // Not a member of an anonymous container.
688 // The symbol table search was done in the lexical phase.
689 // See if it was a variable.
690 variable = symbol ? symbol->getAsVariable() : nullptr;
692 if ((variable->getType().getBasicType() == EbtBlock ||
693 variable->getType().getBasicType() == EbtStruct) && variable->getType().getStruct() == nullptr) {
694 error(loc, "cannot be used (maybe an instance name is needed)", string->c_str(), "");
699 error(loc, "variable name expected", string->c_str(), "");
702 // Recovery, if it wasn't found or was not a variable.
703 if (variable == nullptr) {
704 error(loc, "unknown variable", string->c_str(), "");
705 variable = new TVariable(string, TType(EbtVoid));
708 if (variable->getType().getQualifier().isFrontEndConstant())
709 node = intermediate.addConstantUnion(variable->getConstArray(), variable->getType(), loc);
711 node = intermediate.addSymbol(*variable, loc);
714 if (variable->getType().getQualifier().isIo())
715 intermediate.addIoAccessed(*string);
721 // Handle operator[] on any objects it applies to. Currently:
725 TIntermTyped* HlslParseContext::handleBracketOperator(const TSourceLoc& loc, TIntermTyped* base, TIntermTyped* index)
727 // handle r-value operator[] on textures and images. l-values will be processed later.
728 if (base->getType().getBasicType() == EbtSampler && !base->isArray()) {
729 const TSampler& sampler = base->getType().getSampler();
730 if (sampler.isImage() || sampler.isTexture()) {
731 if (! mipsOperatorMipArg.empty() && mipsOperatorMipArg.back().mipLevel == nullptr) {
732 // The first operator[] to a .mips[] sequence is the mip level. We'll remember it.
733 mipsOperatorMipArg.back().mipLevel = index;
734 return base; // next [] index is to the same base.
736 TIntermAggregate* load = new TIntermAggregate(sampler.isImage() ? EOpImageLoad : EOpTextureFetch);
738 TType sampReturnType;
739 getTextureReturnType(sampler, sampReturnType);
741 load->setType(sampReturnType);
743 load->getSequence().push_back(base);
744 load->getSequence().push_back(index);
746 // Textures need a MIP. If we saw one go by, use it. Otherwise, use zero.
747 if (sampler.isTexture()) {
748 if (! mipsOperatorMipArg.empty()) {
749 load->getSequence().push_back(mipsOperatorMipArg.back().mipLevel);
750 mipsOperatorMipArg.pop_back();
752 load->getSequence().push_back(intermediate.addConstantUnion(0, loc, true));
761 // Handle operator[] on structured buffers: this indexes into the array element of the buffer.
762 // indexStructBufferContent returns nullptr if it isn't a structuredbuffer (SSBO).
763 TIntermTyped* sbArray = indexStructBufferContent(loc, base);
764 if (sbArray != nullptr) {
765 if (sbArray == nullptr)
768 // Now we'll apply the [] index to that array
769 const TOperator idxOp = (index->getQualifier().storage == EvqConst) ? EOpIndexDirect : EOpIndexIndirect;
771 TIntermTyped* element = intermediate.addIndex(idxOp, sbArray, index, loc);
772 const TType derefType(sbArray->getType(), 0);
773 element->setType(derefType);
781 // Cast index value to a uint if it isn't already (for operator[], load indexes, etc)
782 TIntermTyped* HlslParseContext::makeIntegerIndex(TIntermTyped* index)
784 const TBasicType indexBasicType = index->getType().getBasicType();
785 const int vecSize = index->getType().getVectorSize();
787 // We can use int types directly as the index
788 if (indexBasicType == EbtInt || indexBasicType == EbtUint ||
789 indexBasicType == EbtInt64 || indexBasicType == EbtUint64)
792 // Cast index to unsigned integer if it isn't one.
793 return intermediate.addConversion(EOpConstructUint, TType(EbtUint, EvqTemporary, vecSize), index);
797 // Handle seeing a base[index] dereference in the grammar.
799 TIntermTyped* HlslParseContext::handleBracketDereference(const TSourceLoc& loc, TIntermTyped* base, TIntermTyped* index)
801 index = makeIntegerIndex(index);
803 if (index == nullptr) {
804 error(loc, " unknown index type ", "", "");
808 TIntermTyped* result = handleBracketOperator(loc, base, index);
810 if (result != nullptr)
811 return result; // it was handled as an operator[]
813 bool flattened = false;
815 if (index->getQualifier().isFrontEndConstant())
816 indexValue = index->getAsConstantUnion()->getConstArray()[0].getIConst();
819 if (! base->isArray() && ! base->isMatrix() && ! base->isVector()) {
820 if (base->getAsSymbolNode())
821 error(loc, " left of '[' is not of type array, matrix, or vector ",
822 base->getAsSymbolNode()->getName().c_str(), "");
824 error(loc, " left of '[' is not of type array, matrix, or vector ", "expression", "");
825 } else if (base->getType().getQualifier().storage == EvqConst && index->getQualifier().storage == EvqConst) {
826 // both base and index are front-end constants
827 checkIndex(loc, base->getType(), indexValue);
828 return intermediate.foldDereference(base, indexValue, loc);
830 // at least one of base and index is variable...
832 if (index->getQualifier().isFrontEndConstant())
833 checkIndex(loc, base->getType(), indexValue);
835 if (base->getType().isScalarOrVec1())
837 else if (base->getAsSymbolNode() && wasFlattened(base)) {
838 if (index->getQualifier().storage != EvqConst)
839 error(loc, "Invalid variable index to flattened array", base->getAsSymbolNode()->getName().c_str(), "");
841 result = flattenAccess(base, indexValue);
842 flattened = (result != base);
844 if (index->getQualifier().isFrontEndConstant()) {
845 if (base->getType().isUnsizedArray())
846 base->getWritableType().updateImplicitArraySize(indexValue + 1);
848 checkIndex(loc, base->getType(), indexValue);
849 result = intermediate.addIndex(EOpIndexDirect, base, index, loc);
851 result = intermediate.addIndex(EOpIndexIndirect, base, index, loc);
855 if (result == nullptr) {
856 // Insert dummy error-recovery result
857 result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
859 // If the array reference was flattened, it has the correct type. E.g, if it was
860 // a uniform array, it was flattened INTO a set of scalar uniforms, not scalar temps.
861 // In that case, we preserve the qualifiers.
863 // Insert valid dereferenced result
864 TType newType(base->getType(), 0); // dereferenced type
865 if (base->getType().getQualifier().storage == EvqConst && index->getQualifier().storage == EvqConst)
866 newType.getQualifier().storage = EvqConst;
868 newType.getQualifier().storage = EvqTemporary;
869 result->setType(newType);
876 // Handle seeing a binary node with a math operation.
877 TIntermTyped* HlslParseContext::handleBinaryMath(const TSourceLoc& loc, const char* str, TOperator op,
878 TIntermTyped* left, TIntermTyped* right)
880 TIntermTyped* result = intermediate.addBinaryMath(op, left, right, loc);
881 if (result == nullptr)
882 binaryOpError(loc, str, left->getCompleteString(), right->getCompleteString());
887 // Handle seeing a unary node with a math operation.
888 TIntermTyped* HlslParseContext::handleUnaryMath(const TSourceLoc& loc, const char* str, TOperator op,
889 TIntermTyped* childNode)
891 TIntermTyped* result = intermediate.addUnaryMath(op, childNode, loc);
896 unaryOpError(loc, str, childNode->getCompleteString());
901 // Return true if the name is a struct buffer method
903 bool HlslParseContext::isStructBufferMethod(const TString& name) const
906 name == "GetDimensions" ||
915 name == "InterlockedAdd" ||
916 name == "InterlockedAnd" ||
917 name == "InterlockedCompareExchange" ||
918 name == "InterlockedCompareStore" ||
919 name == "InterlockedExchange" ||
920 name == "InterlockedMax" ||
921 name == "InterlockedMin" ||
922 name == "InterlockedOr" ||
923 name == "InterlockedXor" ||
924 name == "IncrementCounter" ||
925 name == "DecrementCounter" ||
931 // Handle seeing a base.field dereference in the grammar, where 'field' is a
932 // swizzle or member variable.
934 TIntermTyped* HlslParseContext::handleDotDereference(const TSourceLoc& loc, TIntermTyped* base, const TString& field)
938 if (base->isArray()) {
939 error(loc, "cannot apply to an array:", ".", field.c_str());
943 TIntermTyped* result = base;
945 if (base->getType().getBasicType() == EbtSampler) {
946 // Handle .mips[mipid][pos] operation on textures
947 const TSampler& sampler = base->getType().getSampler();
948 if (sampler.isTexture() && field == "mips") {
949 // Push a null to signify that we expect a mip level under operator[] next.
950 mipsOperatorMipArg.push_back(tMipsOperatorData(loc, nullptr));
951 // Keep 'result' pointing to 'base', since we expect an operator[] to go by next.
954 error(loc, "unexpected texture type for .mips[][] operator:",
955 base->getType().getCompleteString().c_str(), "");
957 error(loc, "unexpected operator on texture type:", field.c_str(),
958 base->getType().getCompleteString().c_str());
960 } else if (base->isVector() || base->isScalar()) {
961 TSwizzleSelectors<TVectorSelector> selectors;
962 parseSwizzleSelector(loc, field, base->getVectorSize(), selectors);
964 if (base->isScalar()) {
965 if (selectors.size() == 1)
968 TType type(base->getBasicType(), EvqTemporary, selectors.size());
969 return addConstructor(loc, base, type);
972 if (base->getVectorSize() == 1) {
973 TType scalarType(base->getBasicType(), EvqTemporary, 1);
974 if (selectors.size() == 1)
975 return addConstructor(loc, base, scalarType);
977 TType vectorType(base->getBasicType(), EvqTemporary, selectors.size());
978 return addConstructor(loc, addConstructor(loc, base, scalarType), vectorType);
982 if (base->getType().getQualifier().isFrontEndConstant())
983 result = intermediate.foldSwizzle(base, selectors, loc);
985 if (selectors.size() == 1) {
986 TIntermTyped* index = intermediate.addConstantUnion(selectors[0], loc);
987 result = intermediate.addIndex(EOpIndexDirect, base, index, loc);
988 result->setType(TType(base->getBasicType(), EvqTemporary));
990 TIntermTyped* index = intermediate.addSwizzle(selectors, loc);
991 result = intermediate.addIndex(EOpVectorSwizzle, base, index, loc);
992 result->setType(TType(base->getBasicType(), EvqTemporary, base->getType().getQualifier().precision,
996 } else if (base->isMatrix()) {
997 TSwizzleSelectors<TMatrixSelector> selectors;
998 if (! parseMatrixSwizzleSelector(loc, field, base->getMatrixCols(), base->getMatrixRows(), selectors))
1001 if (selectors.size() == 1) {
1002 // Representable by m[c][r]
1003 if (base->getType().getQualifier().isFrontEndConstant()) {
1004 result = intermediate.foldDereference(base, selectors[0].coord1, loc);
1005 result = intermediate.foldDereference(result, selectors[0].coord2, loc);
1007 result = intermediate.addIndex(EOpIndexDirect, base,
1008 intermediate.addConstantUnion(selectors[0].coord1, loc),
1010 TType dereferencedCol(base->getType(), 0);
1011 result->setType(dereferencedCol);
1012 result = intermediate.addIndex(EOpIndexDirect, result,
1013 intermediate.addConstantUnion(selectors[0].coord2, loc),
1015 TType dereferenced(dereferencedCol, 0);
1016 result->setType(dereferenced);
1019 int column = getMatrixComponentsColumn(base->getMatrixRows(), selectors);
1021 // Representable by m[c]
1022 if (base->getType().getQualifier().isFrontEndConstant())
1023 result = intermediate.foldDereference(base, column, loc);
1025 result = intermediate.addIndex(EOpIndexDirect, base, intermediate.addConstantUnion(column, loc),
1027 TType dereferenced(base->getType(), 0);
1028 result->setType(dereferenced);
1031 // general case, not a column, not a single component
1032 TIntermTyped* index = intermediate.addSwizzle(selectors, loc);
1033 result = intermediate.addIndex(EOpMatrixSwizzle, base, index, loc);
1034 result->setType(TType(base->getBasicType(), EvqTemporary, base->getType().getQualifier().precision,
1038 } else if (base->getBasicType() == EbtStruct || base->getBasicType() == EbtBlock) {
1039 const TTypeList* fields = base->getType().getStruct();
1040 bool fieldFound = false;
1042 for (member = 0; member < (int)fields->size(); ++member) {
1043 if ((*fields)[member].type->getFieldName() == field) {
1049 if (base->getAsSymbolNode() && wasFlattened(base)) {
1050 result = flattenAccess(base, member);
1052 if (base->getType().getQualifier().storage == EvqConst)
1053 result = intermediate.foldDereference(base, member, loc);
1055 TIntermTyped* index = intermediate.addConstantUnion(member, loc);
1056 result = intermediate.addIndex(EOpIndexDirectStruct, base, index, loc);
1057 result->setType(*(*fields)[member].type);
1061 error(loc, "no such field in structure", field.c_str(), "");
1063 error(loc, "does not apply to this type:", field.c_str(), base->getType().getCompleteString().c_str());
1069 // Return true if the field should be treated as a built-in method.
1070 // Return false otherwise.
1072 bool HlslParseContext::isBuiltInMethod(const TSourceLoc&, TIntermTyped* base, const TString& field)
1074 if (base == nullptr)
1077 variableCheck(base);
1079 if (base->getType().getBasicType() == EbtSampler) {
1081 } else if (isStructBufferType(base->getType()) && isStructBufferMethod(field)) {
1083 } else if (field == "Append" ||
1084 field == "RestartStrip") {
1085 // We cannot check the type here: it may be sanitized if we're not compiling a geometry shader, but
1086 // the code is around in the shader source.
1092 // Independently establish a built-in that is a member of a structure.
1093 // 'arraySizes' are what's desired for the independent built-in, whatever
1094 // the higher-level source/expression of them was.
1095 void HlslParseContext::splitBuiltIn(const TString& baseName, const TType& memberType, const TArraySizes* arraySizes,
1096 const TQualifier& outerQualifier)
1098 // Because of arrays of structs, we might be asked more than once,
1099 // but the arraySizes passed in should have captured the whole thing
1101 // However, clip/cull rely on multiple updates.
1102 if (!isClipOrCullDistance(memberType))
1103 if (splitBuiltIns.find(tInterstageIoData(memberType.getQualifier().builtIn, outerQualifier.storage)) !=
1104 splitBuiltIns.end())
1107 TVariable* ioVar = makeInternalVariable(baseName + "." + memberType.getFieldName(), memberType);
1109 if (arraySizes != nullptr && !memberType.isArray())
1110 ioVar->getWritableType().copyArraySizes(*arraySizes);
1112 splitBuiltIns[tInterstageIoData(memberType.getQualifier().builtIn, outerQualifier.storage)] = ioVar;
1113 if (!isClipOrCullDistance(ioVar->getType()))
1114 trackLinkage(*ioVar);
1116 // Merge qualifier from the user structure
1117 mergeQualifiers(ioVar->getWritableType().getQualifier(), outerQualifier);
1119 // Fix the builtin type if needed (e.g, some types require fixed array sizes, no matter how the
1120 // shader declared them). This is done after mergeQualifiers(), in case fixBuiltInIoType looks
1121 // at the qualifier to determine e.g, in or out qualifications.
1122 fixBuiltInIoType(ioVar->getWritableType());
1124 // But, not location, we're losing that
1125 ioVar->getWritableType().getQualifier().layoutLocation = TQualifier::layoutLocationEnd;
1128 // Split a type into
1129 // 1. a struct of non-I/O members
1130 // 2. a collection of independent I/O variables
1131 void HlslParseContext::split(const TVariable& variable)
1133 // Create a new variable:
1134 const TType& clonedType = *variable.getType().clone();
1135 const TType& splitType = split(clonedType, variable.getName(), clonedType.getQualifier());
1136 splitNonIoVars[variable.getUniqueId()] = makeInternalVariable(variable.getName(), splitType);
1139 // Recursive implementation of split().
1140 // Returns reference to the modified type.
1141 const TType& HlslParseContext::split(const TType& type, const TString& name, const TQualifier& outerQualifier)
1143 if (type.isStruct()) {
1144 TTypeList* userStructure = type.getWritableStruct();
1145 for (auto ioType = userStructure->begin(); ioType != userStructure->end(); ) {
1146 if (ioType->type->isBuiltIn()) {
1147 // move out the built-in
1148 splitBuiltIn(name, *ioType->type, type.getArraySizes(), outerQualifier);
1149 ioType = userStructure->erase(ioType);
1151 split(*ioType->type, name + "." + ioType->type->getFieldName(), outerQualifier);
1160 // Is this an aggregate that should be flattened?
1161 // Can be applied to intermediate levels of type in a hierarchy.
1162 // Some things like flattening uniform arrays are only about the top level
1163 // of the aggregate, triggered on 'topLevel'.
1164 bool HlslParseContext::shouldFlatten(const TType& type, TStorageQualifier qualifier, bool topLevel) const
1166 switch (qualifier) {
1169 return type.isStruct() || type.isArray();
1171 return (type.isArray() && intermediate.getFlattenUniformArrays() && topLevel) ||
1172 (type.isStruct() && type.containsOpaque());
1178 // Top level variable flattening: construct data
1179 void HlslParseContext::flatten(const TVariable& variable, bool linkage)
1181 const TType& type = variable.getType();
1183 // If it's a standalone built-in, there is nothing to flatten
1184 if (type.isBuiltIn() && !type.isStruct())
1187 auto entry = flattenMap.insert(std::make_pair(variable.getUniqueId(),
1188 TFlattenData(type.getQualifier().layoutBinding,
1189 type.getQualifier().layoutLocation)));
1191 // the item is a map pair, so first->second is the TFlattenData itself.
1192 flatten(variable, type, entry.first->second, variable.getName(), linkage, type.getQualifier(), nullptr);
1195 // Recursively flatten the given variable at the provided type, building the flattenData as we go.
1197 // This is mutually recursive with flattenStruct and flattenArray.
1198 // We are going to flatten an arbitrarily nested composite structure into a linear sequence of
1199 // members, and later on, we want to turn a path through the tree structure into a final
1200 // location in this linear sequence.
1202 // If the tree was N-ary, that can be directly calculated. However, we are dealing with
1203 // arbitrary numbers - perhaps a struct of 7 members containing an array of 3. Thus, we must
1204 // build a data structure to allow the sequence of bracket and dot operators on arrays and
1205 // structs to arrive at the proper member.
1207 // To avoid storing a tree with pointers, we are going to flatten the tree into a vector of integers.
1208 // The leaves are the indexes into the flattened member array.
1209 // Each level will have the next location for the Nth item stored sequentially, so for instance:
1211 // struct { float2 a[2]; int b; float4 c[3] };
1213 // This will produce the following flattened tree:
1214 // Pos: 0 1 2 3 4 5 6 7 8 9 10 11 12 13
1215 // (3, 7, 8, 5, 6, 0, 1, 2, 11, 12, 13, 3, 4, 5}
1217 // Given a reference to mystruct.c[1], the access chain is (2,1), so we traverse:
1218 // (0+2) = 8 --> (8+1) = 12 --> 12 = 4
1220 // so the 4th flattened member in traversal order is ours.
1222 int HlslParseContext::flatten(const TVariable& variable, const TType& type,
1223 TFlattenData& flattenData, TString name, bool linkage,
1224 const TQualifier& outerQualifier,
1225 const TArraySizes* builtInArraySizes)
1227 // If something is an arrayed struct, the array flattener will recursively call flatten()
1228 // to then flatten the struct, so this is an "if else": we don't do both.
1230 return flattenArray(variable, type, flattenData, name, linkage, outerQualifier);
1231 else if (type.isStruct())
1232 return flattenStruct(variable, type, flattenData, name, linkage, outerQualifier, builtInArraySizes);
1234 assert(0); // should never happen
1239 // Add a single flattened member to the flattened data being tracked for the composite
1240 // Returns true for the final flattening level.
1241 int HlslParseContext::addFlattenedMember(const TVariable& variable, const TType& type, TFlattenData& flattenData,
1242 const TString& memberName, bool linkage,
1243 const TQualifier& outerQualifier,
1244 const TArraySizes* builtInArraySizes)
1246 if (!shouldFlatten(type, outerQualifier.storage, false)) {
1247 // This is as far as we flatten. Insert the variable.
1248 TVariable* memberVariable = makeInternalVariable(memberName, type);
1249 mergeQualifiers(memberVariable->getWritableType().getQualifier(), variable.getType().getQualifier());
1251 if (flattenData.nextBinding != TQualifier::layoutBindingEnd)
1252 memberVariable->getWritableType().getQualifier().layoutBinding = flattenData.nextBinding++;
1254 if (memberVariable->getType().isBuiltIn()) {
1255 // inherited locations are nonsensical for built-ins (TODO: what if semantic had a number)
1256 memberVariable->getWritableType().getQualifier().layoutLocation = TQualifier::layoutLocationEnd;
1258 // inherited locations must be auto bumped, not replicated
1259 if (flattenData.nextLocation != TQualifier::layoutLocationEnd) {
1260 memberVariable->getWritableType().getQualifier().layoutLocation = flattenData.nextLocation;
1261 flattenData.nextLocation += intermediate.computeTypeLocationSize(memberVariable->getType(), language);
1262 nextOutLocation = std::max(nextOutLocation, flattenData.nextLocation);
1266 flattenData.offsets.push_back(static_cast<int>(flattenData.members.size()));
1267 flattenData.members.push_back(memberVariable);
1270 trackLinkage(*memberVariable);
1272 return static_cast<int>(flattenData.offsets.size()) - 1; // location of the member reference
1274 // Further recursion required
1275 return flatten(variable, type, flattenData, memberName, linkage, outerQualifier, builtInArraySizes);
1279 // Figure out the mapping between an aggregate's top members and an
1280 // equivalent set of individual variables.
1282 // Assumes shouldFlatten() or equivalent was called first.
1283 int HlslParseContext::flattenStruct(const TVariable& variable, const TType& type,
1284 TFlattenData& flattenData, TString name, bool linkage,
1285 const TQualifier& outerQualifier,
1286 const TArraySizes* builtInArraySizes)
1288 assert(type.isStruct());
1290 auto members = *type.getStruct();
1292 // Reserve space for this tree level.
1293 int start = static_cast<int>(flattenData.offsets.size());
1295 flattenData.offsets.resize(int(pos + members.size()), -1);
1297 for (int member = 0; member < (int)members.size(); ++member) {
1298 TType& dereferencedType = *members[member].type;
1299 if (dereferencedType.isBuiltIn())
1300 splitBuiltIn(variable.getName(), dereferencedType, builtInArraySizes, outerQualifier);
1302 const int mpos = addFlattenedMember(variable, dereferencedType, flattenData,
1303 name + "." + dereferencedType.getFieldName(),
1304 linkage, outerQualifier,
1305 builtInArraySizes == nullptr && dereferencedType.isArray()
1306 ? dereferencedType.getArraySizes()
1307 : builtInArraySizes);
1308 flattenData.offsets[pos++] = mpos;
1315 // Figure out mapping between an array's members and an
1316 // equivalent set of individual variables.
1318 // Assumes shouldFlatten() or equivalent was called first.
1319 int HlslParseContext::flattenArray(const TVariable& variable, const TType& type,
1320 TFlattenData& flattenData, TString name, bool linkage,
1321 const TQualifier& outerQualifier)
1323 assert(type.isSizedArray());
1325 const int size = type.getOuterArraySize();
1326 const TType dereferencedType(type, 0);
1329 name = variable.getName();
1331 // Reserve space for this tree level.
1332 int start = static_cast<int>(flattenData.offsets.size());
1334 flattenData.offsets.resize(int(pos + size), -1);
1336 for (int element=0; element < size; ++element) {
1337 char elementNumBuf[20]; // sufficient for MAXINT
1338 snprintf(elementNumBuf, sizeof(elementNumBuf)-1, "[%d]", element);
1339 const int mpos = addFlattenedMember(variable, dereferencedType, flattenData,
1340 name + elementNumBuf, linkage, outerQualifier,
1341 type.getArraySizes());
1343 flattenData.offsets[pos++] = mpos;
1349 // Return true if we have flattened this node.
1350 bool HlslParseContext::wasFlattened(const TIntermTyped* node) const
1352 return node != nullptr && node->getAsSymbolNode() != nullptr &&
1353 wasFlattened(node->getAsSymbolNode()->getId());
1356 // Return true if we have split this structure
1357 bool HlslParseContext::wasSplit(const TIntermTyped* node) const
1359 return node != nullptr && node->getAsSymbolNode() != nullptr &&
1360 wasSplit(node->getAsSymbolNode()->getId());
1363 // Turn an access into an aggregate that was flattened to instead be
1364 // an access to the individual variable the member was flattened to.
1365 // Assumes wasFlattened() or equivalent was called first.
1366 TIntermTyped* HlslParseContext::flattenAccess(TIntermTyped* base, int member)
1368 const TType dereferencedType(base->getType(), member); // dereferenced type
1369 const TIntermSymbol& symbolNode = *base->getAsSymbolNode();
1370 TIntermTyped* flattened = flattenAccess(symbolNode.getId(), member, base->getQualifier().storage,
1371 dereferencedType, symbolNode.getFlattenSubset());
1373 return flattened ? flattened : base;
1375 TIntermTyped* HlslParseContext::flattenAccess(int uniqueId, int member, TStorageQualifier outerStorage,
1376 const TType& dereferencedType, int subset)
1378 const auto flattenData = flattenMap.find(uniqueId);
1380 if (flattenData == flattenMap.end())
1383 // Calculate new cumulative offset from the packed tree
1384 int newSubset = flattenData->second.offsets[subset >= 0 ? subset + member : member];
1386 TIntermSymbol* subsetSymbol;
1387 if (!shouldFlatten(dereferencedType, outerStorage, false)) {
1388 // Finished flattening: create symbol for variable
1389 member = flattenData->second.offsets[newSubset];
1390 const TVariable* memberVariable = flattenData->second.members[member];
1391 subsetSymbol = intermediate.addSymbol(*memberVariable);
1392 subsetSymbol->setFlattenSubset(-1);
1395 // If this is not the final flattening, accumulate the position and return
1396 // an object of the partially dereferenced type.
1397 subsetSymbol = new TIntermSymbol(uniqueId, "flattenShadow", dereferencedType);
1398 subsetSymbol->setFlattenSubset(newSubset);
1401 return subsetSymbol;
1404 // For finding where the first leaf is in a subtree of a multi-level aggregate
1405 // that is just getting a subset assigned. Follows the same logic as flattenAccess,
1406 // but logically going down the "left-most" tree branch each step of the way.
1408 // Returns the offset into the first leaf of the subset.
1409 int HlslParseContext::findSubtreeOffset(const TIntermNode& node) const
1411 const TIntermSymbol* sym = node.getAsSymbolNode();
1414 if (!sym->isArray() && !sym->isStruct())
1416 int subset = sym->getFlattenSubset();
1420 // Getting this far means a partial aggregate is identified by the flatten subset.
1421 // Find the first leaf of the subset.
1423 const auto flattenData = flattenMap.find(sym->getId());
1424 if (flattenData == flattenMap.end())
1427 return findSubtreeOffset(sym->getType(), subset, flattenData->second.offsets);
1430 subset = flattenData->second.offsets[subset];
1433 // Recursively do the desent
1434 int HlslParseContext::findSubtreeOffset(const TType& type, int subset, const TVector<int>& offsets) const
1436 if (!type.isArray() && !type.isStruct())
1437 return offsets[subset];
1438 TType derefType(type, 0);
1439 return findSubtreeOffset(derefType, offsets[subset], offsets);
1442 // Find and return the split IO TVariable for id, or nullptr if none.
1443 TVariable* HlslParseContext::getSplitNonIoVar(int id) const
1445 const auto splitNonIoVar = splitNonIoVars.find(id);
1446 if (splitNonIoVar == splitNonIoVars.end())
1449 return splitNonIoVar->second;
1452 // Pass through to base class after remembering built-in mappings.
1453 void HlslParseContext::trackLinkage(TSymbol& symbol)
1455 TBuiltInVariable biType = symbol.getType().getQualifier().builtIn;
1457 if (biType != EbvNone)
1458 builtInTessLinkageSymbols[biType] = symbol.clone();
1460 TParseContextBase::trackLinkage(symbol);
1464 // Returns true if the built-in is a clip or cull distance variable.
1465 bool HlslParseContext::isClipOrCullDistance(TBuiltInVariable builtIn)
1467 return builtIn == EbvClipDistance || builtIn == EbvCullDistance;
1470 // Some types require fixed array sizes in SPIR-V, but can be scalars or
1471 // arrays of sizes SPIR-V doesn't allow. For example, tessellation factors.
1472 // This creates the right size. A conversion is performed when the internal
1473 // type is copied to or from the external type. This corrects the externally
1474 // facing input or output type to abide downstream semantics.
1475 void HlslParseContext::fixBuiltInIoType(TType& type)
1477 int requiredArraySize = 0;
1478 int requiredVectorSize = 0;
1480 switch (type.getQualifier().builtIn) {
1481 case EbvTessLevelOuter: requiredArraySize = 4; break;
1482 case EbvTessLevelInner: requiredArraySize = 2; break;
1486 // Promote scalar to array of size 1. Leave existing arrays alone.
1487 if (!type.isArray())
1488 requiredArraySize = 1;
1492 case EbvWorkGroupId: requiredVectorSize = 3; break;
1493 case EbvGlobalInvocationId: requiredVectorSize = 3; break;
1494 case EbvLocalInvocationId: requiredVectorSize = 3; break;
1495 case EbvTessCoord: requiredVectorSize = 3; break;
1498 if (isClipOrCullDistance(type)) {
1499 const int loc = type.getQualifier().layoutLocation;
1501 if (type.getQualifier().builtIn == EbvClipDistance) {
1502 if (type.getQualifier().storage == EvqVaryingIn)
1503 clipSemanticNSizeIn[loc] = type.getVectorSize();
1505 clipSemanticNSizeOut[loc] = type.getVectorSize();
1507 if (type.getQualifier().storage == EvqVaryingIn)
1508 cullSemanticNSizeIn[loc] = type.getVectorSize();
1510 cullSemanticNSizeOut[loc] = type.getVectorSize();
1517 // Alter or set vector size as needed.
1518 if (requiredVectorSize > 0) {
1519 TType newType(type.getBasicType(), type.getQualifier().storage, requiredVectorSize);
1520 newType.getQualifier() = type.getQualifier();
1522 type.shallowCopy(newType);
1525 // Alter or set array size as needed.
1526 if (requiredArraySize > 0) {
1527 if (!type.isArray() || type.getOuterArraySize() != requiredArraySize) {
1528 TArraySizes* arraySizes = new TArraySizes;
1529 arraySizes->addInnerSize(requiredArraySize);
1530 type.transferArraySizes(arraySizes);
1535 // Variables that correspond to the user-interface in and out of a stage
1536 // (not the built-in interface) are
1537 // - assigned locations
1538 // - registered as a linkage node (part of the stage's external interface).
1539 // Assumes it is called in the order in which locations should be assigned.
1540 void HlslParseContext::assignToInterface(TVariable& variable)
1542 const auto assignLocation = [&](TVariable& variable) {
1543 TType& type = variable.getWritableType();
1544 if (!type.isStruct() || type.getStruct()->size() > 0) {
1545 TQualifier& qualifier = type.getQualifier();
1546 if (qualifier.storage == EvqVaryingIn || qualifier.storage == EvqVaryingOut) {
1547 if (qualifier.builtIn == EbvNone && !qualifier.hasLocation()) {
1548 // Strip off the outer array dimension for those having an extra one.
1550 if (type.isArray() && qualifier.isArrayedIo(language)) {
1551 TType elementType(type, 0);
1552 size = intermediate.computeTypeLocationSize(elementType, language);
1554 size = intermediate.computeTypeLocationSize(type, language);
1556 if (qualifier.storage == EvqVaryingIn) {
1557 variable.getWritableType().getQualifier().layoutLocation = nextInLocation;
1558 nextInLocation += size;
1560 variable.getWritableType().getQualifier().layoutLocation = nextOutLocation;
1561 nextOutLocation += size;
1564 trackLinkage(variable);
1569 if (wasFlattened(variable.getUniqueId())) {
1570 auto& memberList = flattenMap[variable.getUniqueId()].members;
1571 for (auto member = memberList.begin(); member != memberList.end(); ++member)
1572 assignLocation(**member);
1573 } else if (wasSplit(variable.getUniqueId())) {
1574 TVariable* splitIoVar = getSplitNonIoVar(variable.getUniqueId());
1575 assignLocation(*splitIoVar);
1577 assignLocation(variable);
1582 // Handle seeing a function declarator in the grammar. This is the precursor
1583 // to recognizing a function prototype or function definition.
1585 void HlslParseContext::handleFunctionDeclarator(const TSourceLoc& loc, TFunction& function, bool prototype)
1588 // Multiple declarations of the same function name are allowed.
1590 // If this is a definition, the definition production code will check for redefinitions
1591 // (we don't know at this point if it's a definition or not).
1594 TSymbol* symbol = symbolTable.find(function.getMangledName(), &builtIn);
1595 const TFunction* prevDec = symbol ? symbol->getAsFunction() : 0;
1598 // All built-in functions are defined, even though they don't have a body.
1599 // Count their prototype as a definition instead.
1600 if (symbolTable.atBuiltInLevel())
1601 function.setDefined();
1603 if (prevDec && ! builtIn)
1604 symbol->getAsFunction()->setPrototyped(); // need a writable one, but like having prevDec as a const
1605 function.setPrototyped();
1609 // This insert won't actually insert it if it's a duplicate signature, but it will still check for
1610 // other forms of name collisions.
1611 if (! symbolTable.insert(function))
1612 error(loc, "function name is redeclaration of existing name", function.getName().c_str(), "");
1615 // For struct buffers with counters, we must pass the counter buffer as hidden parameter.
1616 // This adds the hidden parameter to the parameter list in 'paramNodes' if needed.
1617 // Otherwise, it's a no-op
1618 void HlslParseContext::addStructBufferHiddenCounterParam(const TSourceLoc& loc, TParameter& param,
1619 TIntermAggregate*& paramNodes)
1621 if (! hasStructBuffCounter(*param.type))
1624 const TString counterBlockName(intermediate.addCounterBufferName(*param.name));
1627 counterBufferType(loc, counterType);
1628 TVariable *variable = makeInternalVariable(counterBlockName, counterType);
1630 if (! symbolTable.insert(*variable))
1631 error(loc, "redefinition", variable->getName().c_str(), "");
1633 paramNodes = intermediate.growAggregate(paramNodes,
1634 intermediate.addSymbol(*variable, loc),
1639 // Handle seeing the function prototype in front of a function definition in the grammar.
1640 // The body is handled after this function returns.
1642 // Returns an aggregate of parameter-symbol nodes.
1644 TIntermAggregate* HlslParseContext::handleFunctionDefinition(const TSourceLoc& loc, TFunction& function,
1645 const TAttributes& attributes,
1646 TIntermNode*& entryPointTree)
1648 currentCaller = function.getMangledName();
1649 TSymbol* symbol = symbolTable.find(function.getMangledName());
1650 TFunction* prevDec = symbol ? symbol->getAsFunction() : nullptr;
1652 if (prevDec == nullptr)
1653 error(loc, "can't find function", function.getName().c_str(), "");
1654 // Note: 'prevDec' could be 'function' if this is the first time we've seen function
1655 // as it would have just been put in the symbol table. Otherwise, we're looking up
1656 // an earlier occurrence.
1658 if (prevDec && prevDec->isDefined()) {
1659 // Then this function already has a body.
1660 error(loc, "function already has a body", function.getName().c_str(), "");
1662 if (prevDec && ! prevDec->isDefined()) {
1663 prevDec->setDefined();
1665 // Remember the return type for later checking for RETURN statements.
1666 currentFunctionType = &(prevDec->getType());
1668 currentFunctionType = new TType(EbtVoid);
1669 functionReturnsValue = false;
1671 // Entry points need different I/O and other handling, transform it so the
1672 // rest of this function doesn't care.
1673 entryPointTree = transformEntryPoint(loc, function, attributes);
1676 // New symbol table scope for body of function plus its arguments
1681 // Insert parameters into the symbol table.
1682 // If the parameter has no name, it's not an error, just don't insert it
1683 // (could be used for unused args).
1685 // Also, accumulate the list of parameters into the AST, so lower level code
1686 // knows where to find parameters.
1688 TIntermAggregate* paramNodes = new TIntermAggregate;
1689 for (int i = 0; i < function.getParamCount(); i++) {
1690 TParameter& param = function[i];
1691 if (param.name != nullptr) {
1692 TVariable *variable = new TVariable(param.name, *param.type);
1694 if (i == 0 && function.hasImplicitThis()) {
1695 // Anonymous 'this' members are already in a symbol-table level,
1696 // and we need to know what function parameter to map them to.
1697 symbolTable.makeInternalVariable(*variable);
1698 pushImplicitThis(variable);
1701 // Insert the parameters with name in the symbol table.
1702 if (! symbolTable.insert(*variable))
1703 error(loc, "redefinition", variable->getName().c_str(), "");
1705 // Add parameters to the AST list.
1706 if (shouldFlatten(variable->getType(), variable->getType().getQualifier().storage, true)) {
1707 // Expand the AST parameter nodes (but not the name mangling or symbol table view)
1708 // for structures that need to be flattened.
1709 flatten(*variable, false);
1710 const TTypeList* structure = variable->getType().getStruct();
1711 for (int mem = 0; mem < (int)structure->size(); ++mem) {
1712 paramNodes = intermediate.growAggregate(paramNodes,
1713 flattenAccess(variable->getUniqueId(), mem,
1714 variable->getType().getQualifier().storage,
1715 *(*structure)[mem].type),
1719 // Add the parameter to the AST
1720 paramNodes = intermediate.growAggregate(paramNodes,
1721 intermediate.addSymbol(*variable, loc),
1725 // Add hidden AST parameter for struct buffer counters, if needed.
1726 addStructBufferHiddenCounterParam(loc, param, paramNodes);
1728 paramNodes = intermediate.growAggregate(paramNodes, intermediate.addSymbol(*param.type, loc), loc);
1730 if (function.hasIllegalImplicitThis())
1731 pushImplicitThis(nullptr);
1733 intermediate.setAggregateOperator(paramNodes, EOpParameters, TType(EbtVoid), loc);
1734 loopNestingLevel = 0;
1735 controlFlowNestingLevel = 0;
1736 postEntryPointReturn = false;
1741 // Handle all [attrib] attribute for the shader entry point
1742 void HlslParseContext::handleEntryPointAttributes(const TSourceLoc& loc, const TAttributes& attributes)
1744 for (auto it = attributes.begin(); it != attributes.end(); ++it) {
1748 const TIntermSequence& sequence = it->args->getSequence();
1749 for (int lid = 0; lid < int(sequence.size()); ++lid)
1750 intermediate.setLocalSize(lid, sequence[lid]->getAsConstantUnion()->getConstArray()[0].getIConst());
1753 case EatMaxVertexCount:
1757 if (! it->getInt(maxVertexCount)) {
1758 error(loc, "invalid maxvertexcount", "", "");
1760 if (! intermediate.setVertices(maxVertexCount))
1761 error(loc, "cannot change previously set maxvertexcount attribute", "", "");
1765 case EatPatchConstantFunc:
1768 if (! it->getString(pcfName, 0, false)) {
1769 error(loc, "invalid patch constant function", "", "");
1771 patchConstantFunctionName = pcfName;
1777 // Handle [domain("...")]
1779 if (! it->getString(domainStr)) {
1780 error(loc, "invalid domain", "", "");
1782 TLayoutGeometry domain = ElgNone;
1784 if (domainStr == "tri") {
1785 domain = ElgTriangles;
1786 } else if (domainStr == "quad") {
1788 } else if (domainStr == "isoline") {
1789 domain = ElgIsolines;
1791 error(loc, "unsupported domain type", domainStr.c_str(), "");
1794 if (language == EShLangTessEvaluation) {
1795 if (! intermediate.setInputPrimitive(domain))
1796 error(loc, "cannot change previously set domain", TQualifier::getGeometryString(domain), "");
1798 if (! intermediate.setOutputPrimitive(domain))
1799 error(loc, "cannot change previously set domain", TQualifier::getGeometryString(domain), "");
1804 case EatOutputTopology:
1806 // Handle [outputtopology("...")]
1807 TString topologyStr;
1808 if (! it->getString(topologyStr)) {
1809 error(loc, "invalid outputtopology", "", "");
1811 TVertexOrder vertexOrder = EvoNone;
1812 TLayoutGeometry primitive = ElgNone;
1814 if (topologyStr == "point") {
1815 intermediate.setPointMode();
1816 } else if (topologyStr == "line") {
1817 primitive = ElgIsolines;
1818 } else if (topologyStr == "triangle_cw") {
1819 vertexOrder = EvoCw;
1820 primitive = ElgTriangles;
1821 } else if (topologyStr == "triangle_ccw") {
1822 vertexOrder = EvoCcw;
1823 primitive = ElgTriangles;
1825 error(loc, "unsupported outputtopology type", topologyStr.c_str(), "");
1828 if (vertexOrder != EvoNone) {
1829 if (! intermediate.setVertexOrder(vertexOrder)) {
1830 error(loc, "cannot change previously set outputtopology",
1831 TQualifier::getVertexOrderString(vertexOrder), "");
1834 if (primitive != ElgNone)
1835 intermediate.setOutputPrimitive(primitive);
1839 case EatPartitioning:
1841 // Handle [partitioning("...")]
1842 TString partitionStr;
1843 if (! it->getString(partitionStr)) {
1844 error(loc, "invalid partitioning", "", "");
1846 TVertexSpacing partitioning = EvsNone;
1848 if (partitionStr == "integer") {
1849 partitioning = EvsEqual;
1850 } else if (partitionStr == "fractional_even") {
1851 partitioning = EvsFractionalEven;
1852 } else if (partitionStr == "fractional_odd") {
1853 partitioning = EvsFractionalOdd;
1854 //} else if (partition == "pow2") { // TODO: currently nothing to map this to.
1856 error(loc, "unsupported partitioning type", partitionStr.c_str(), "");
1859 if (! intermediate.setVertexSpacing(partitioning))
1860 error(loc, "cannot change previously set partitioning",
1861 TQualifier::getVertexSpacingString(partitioning), "");
1865 case EatOutputControlPoints:
1867 // Handle [outputcontrolpoints("...")]
1869 if (! it->getInt(ctrlPoints)) {
1870 error(loc, "invalid outputcontrolpoints", "", "");
1872 if (! intermediate.setVertices(ctrlPoints)) {
1873 error(loc, "cannot change previously set outputcontrolpoints attribute", "", "");
1880 // tolerate these because of dual use of entrypoint and type attributes
1883 warn(loc, "attribute does not apply to entry point", "", "");
1889 // Update the given type with any type-like attribute information in the
1891 void HlslParseContext::transferTypeAttributes(const TSourceLoc& loc, const TAttributes& attributes, TType& type,
1894 if (attributes.size() == 0)
1898 TString builtInString;
1899 for (auto it = attributes.begin(); it != attributes.end(); ++it) {
1903 if (it->getInt(value))
1904 type.getQualifier().layoutLocation = value;
1908 if (it->getInt(value)) {
1909 type.getQualifier().layoutBinding = value;
1910 type.getQualifier().layoutSet = 0;
1913 if (it->getInt(value, 1))
1914 type.getQualifier().layoutSet = value;
1916 case EatGlobalBinding:
1917 // global cbuffer binding
1918 if (it->getInt(value))
1919 globalUniformBinding = value;
1920 // global cbuffer binding
1921 if (it->getInt(value, 1))
1922 globalUniformSet = value;
1924 case EatInputAttachment:
1926 if (it->getInt(value))
1927 type.getQualifier().layoutAttachment = value;
1930 // PointSize built-in
1931 if (it->getString(builtInString, 0, false)) {
1932 if (builtInString == "PointSize")
1933 type.getQualifier().builtIn = EbvPointSize;
1936 case EatPushConstant:
1938 type.getQualifier().layoutPushConstant = true;
1941 // specialization constant
1942 if (it->getInt(value)) {
1945 setSpecConstantId(loc, type.getQualifier(), value);
1950 warn(loc, "attribute does not apply to a type", "", "");
1957 // Do all special handling for the entry point, including wrapping
1958 // the shader's entry point with the official entry point that will call it.
1962 // retType shaderEntryPoint(args...) // shader declared entry point
1968 // in iargs<that are input>...;
1969 // out oargs<that are output> ...;
1971 // void shaderEntryPoint() // synthesized, but official, entry point
1973 // args<that are input> = iargs...;
1974 // ret = @shaderEntryPoint(args...);
1975 // oargs = args<that are output>...;
1977 // retType @shaderEntryPoint(args...)
1980 // The symbol table will still map the original entry point name to the
1981 // the modified function and its new name:
1983 // symbol table: shaderEntryPoint -> @shaderEntryPoint
1985 // Returns nullptr if no entry-point tree was built, otherwise, returns
1986 // a subtree that creates the entry point.
1988 TIntermNode* HlslParseContext::transformEntryPoint(const TSourceLoc& loc, TFunction& userFunction,
1989 const TAttributes& attributes)
1991 // Return true if this is a tessellation patch constant function input to a domain shader.
1992 const auto isDsPcfInput = [this](const TType& type) {
1993 return language == EShLangTessEvaluation &&
1994 type.contains([](const TType* t) {
1995 return t->getQualifier().builtIn == EbvTessLevelOuter ||
1996 t->getQualifier().builtIn == EbvTessLevelInner;
2000 // if we aren't in the entry point, fix the IO as such and exit
2001 if (userFunction.getName().compare(intermediate.getEntryPointName().c_str()) != 0) {
2002 remapNonEntryPointIO(userFunction);
2006 entryPointFunction = &userFunction; // needed in finish()
2008 // Handle entry point attributes
2009 handleEntryPointAttributes(loc, attributes);
2011 // entry point logic...
2013 // Move parameters and return value to shader in/out
2014 TVariable* entryPointOutput; // gets created in remapEntryPointIO
2015 TVector<TVariable*> inputs;
2016 TVector<TVariable*> outputs;
2017 remapEntryPointIO(userFunction, entryPointOutput, inputs, outputs);
2019 // Further this return/in/out transform by flattening, splitting, and assigning locations
2020 const auto makeVariableInOut = [&](TVariable& variable) {
2021 if (variable.getType().isStruct()) {
2022 if (variable.getType().getQualifier().isArrayedIo(language)) {
2023 if (variable.getType().containsBuiltIn())
2025 } else if (shouldFlatten(variable.getType(), EvqVaryingIn /* not assigned yet, but close enough */, true))
2026 flatten(variable, false /* don't track linkage here, it will be tracked in assignToInterface() */);
2028 // TODO: flatten arrays too
2029 // TODO: flatten everything in I/O
2030 // TODO: replace all split with flatten, make all paths can create flattened I/O, then split code can be removed
2032 // For clip and cull distance, multiple output variables potentially get merged
2033 // into one in assignClipCullDistance. That code in assignClipCullDistance
2034 // handles the interface logic, so we avoid it here in that case.
2035 if (!isClipOrCullDistance(variable.getType()))
2036 assignToInterface(variable);
2038 if (entryPointOutput != nullptr)
2039 makeVariableInOut(*entryPointOutput);
2040 for (auto it = inputs.begin(); it != inputs.end(); ++it)
2041 if (!isDsPcfInput((*it)->getType())) // wait until the end for PCF input (see comment below)
2042 makeVariableInOut(*(*it));
2043 for (auto it = outputs.begin(); it != outputs.end(); ++it)
2044 makeVariableInOut(*(*it));
2046 // In the domain shader, PCF input must be at the end of the linkage. That's because in the
2047 // hull shader there is no ordering: the output comes from the separate PCF, which does not
2048 // participate in the argument list. That is always put at the end of the HS linkage, so the
2049 // input side of the DS must match. The argument may be in any position in the DS argument list
2050 // however, so this ensures the linkage is built in the correct order regardless of argument order.
2051 if (language == EShLangTessEvaluation) {
2052 for (auto it = inputs.begin(); it != inputs.end(); ++it)
2053 if (isDsPcfInput((*it)->getType()))
2054 makeVariableInOut(*(*it));
2057 // Synthesize the call
2059 pushScope(); // matches the one in handleFunctionBody()
2062 TType voidType(EbtVoid);
2063 TFunction synthEntryPoint(&userFunction.getName(), voidType);
2064 TIntermAggregate* synthParams = new TIntermAggregate();
2065 intermediate.setAggregateOperator(synthParams, EOpParameters, voidType, loc);
2066 intermediate.setEntryPointMangledName(synthEntryPoint.getMangledName().c_str());
2067 intermediate.incrementEntryPointCount();
2068 TFunction callee(&userFunction.getName(), voidType); // call based on old name, which is still in the symbol table
2070 // change original name
2071 userFunction.addPrefix("@"); // change the name in the function, but not in the symbol table
2073 // Copy inputs (shader-in -> calling arg), while building up the call node
2074 TVector<TVariable*> argVars;
2075 TIntermAggregate* synthBody = new TIntermAggregate();
2076 auto inputIt = inputs.begin();
2077 TIntermTyped* callingArgs = nullptr;
2079 for (int i = 0; i < userFunction.getParamCount(); i++) {
2080 TParameter& param = userFunction[i];
2081 argVars.push_back(makeInternalVariable(*param.name, *param.type));
2082 argVars.back()->getWritableType().getQualifier().makeTemporary();
2084 // Track the input patch, which is the only non-builtin supported by hull shader PCF.
2085 if (param.getDeclaredBuiltIn() == EbvInputPatch)
2086 inputPatch = argVars.back();
2088 TIntermSymbol* arg = intermediate.addSymbol(*argVars.back());
2089 handleFunctionArgument(&callee, callingArgs, arg);
2090 if (param.type->getQualifier().isParamInput()) {
2091 intermediate.growAggregate(synthBody, handleAssign(loc, EOpAssign, arg,
2092 intermediate.addSymbol(**inputIt)));
2098 currentCaller = synthEntryPoint.getMangledName();
2099 TIntermTyped* callReturn = handleFunctionCall(loc, &callee, callingArgs);
2100 currentCaller = userFunction.getMangledName();
2103 if (entryPointOutput) {
2104 TIntermTyped* returnAssign;
2106 // For hull shaders, the wrapped entry point return value is written to
2107 // an array element as indexed by invocation ID, which we might have to make up.
2108 // This is required to match SPIR-V semantics.
2109 if (language == EShLangTessControl) {
2110 TIntermSymbol* invocationIdSym = findTessLinkageSymbol(EbvInvocationId);
2112 // If there is no user declared invocation ID, we must make one.
2113 if (invocationIdSym == nullptr) {
2114 TType invocationIdType(EbtUint, EvqIn, 1);
2115 TString* invocationIdName = NewPoolTString("InvocationId");
2116 invocationIdType.getQualifier().builtIn = EbvInvocationId;
2118 TVariable* variable = makeInternalVariable(*invocationIdName, invocationIdType);
2120 globalQualifierFix(loc, variable->getWritableType().getQualifier());
2121 trackLinkage(*variable);
2123 invocationIdSym = intermediate.addSymbol(*variable);
2126 TIntermTyped* element = intermediate.addIndex(EOpIndexIndirect, intermediate.addSymbol(*entryPointOutput),
2127 invocationIdSym, loc);
2129 // Set the type of the array element being dereferenced
2130 const TType derefElementType(entryPointOutput->getType(), 0);
2131 element->setType(derefElementType);
2133 returnAssign = handleAssign(loc, EOpAssign, element, callReturn);
2135 returnAssign = handleAssign(loc, EOpAssign, intermediate.addSymbol(*entryPointOutput), callReturn);
2137 intermediate.growAggregate(synthBody, returnAssign);
2139 intermediate.growAggregate(synthBody, callReturn);
2142 auto outputIt = outputs.begin();
2143 for (int i = 0; i < userFunction.getParamCount(); i++) {
2144 TParameter& param = userFunction[i];
2146 // GS outputs are via emit, so we do not copy them here.
2147 if (param.type->getQualifier().isParamOutput()) {
2148 if (param.getDeclaredBuiltIn() == EbvGsOutputStream) {
2149 // GS output stream does not assign outputs here: it's the Append() method
2150 // which writes to the output, probably multiple times separated by Emit.
2151 // We merely remember the output to use, here.
2152 gsStreamOutput = *outputIt;
2154 intermediate.growAggregate(synthBody, handleAssign(loc, EOpAssign,
2155 intermediate.addSymbol(**outputIt),
2156 intermediate.addSymbol(*argVars[i])));
2163 // Put the pieces together to form a full function subtree
2164 // for the synthesized entry point.
2165 synthBody->setOperator(EOpSequence);
2166 TIntermNode* synthFunctionDef = synthParams;
2167 handleFunctionBody(loc, synthEntryPoint, synthBody, synthFunctionDef);
2169 entryPointFunctionBody = synthBody;
2171 return synthFunctionDef;
2174 void HlslParseContext::handleFunctionBody(const TSourceLoc& loc, TFunction& function, TIntermNode* functionBody,
2177 node = intermediate.growAggregate(node, functionBody);
2178 intermediate.setAggregateOperator(node, EOpFunction, function.getType(), loc);
2179 node->getAsAggregate()->setName(function.getMangledName().c_str());
2182 if (function.hasImplicitThis())
2185 if (function.getType().getBasicType() != EbtVoid && ! functionReturnsValue)
2186 error(loc, "function does not return a value:", "", function.getName().c_str());
2189 // AST I/O is done through shader globals declared in the 'in' or 'out'
2190 // storage class. An HLSL entry point has a return value, input parameters
2191 // and output parameters. These need to get remapped to the AST I/O.
2192 void HlslParseContext::remapEntryPointIO(TFunction& function, TVariable*& returnValue,
2193 TVector<TVariable*>& inputs, TVector<TVariable*>& outputs)
2195 // We might have in input structure type with no decorations that caused it
2196 // to look like an input type, yet it has (e.g.) interpolation types that
2197 // must be modified that turn it into an input type.
2198 // Hence, a missing ioTypeMap for 'input' might need to be synthesized.
2199 const auto synthesizeEditedInput = [this](TType& type) {
2200 // True if a type needs to be 'flat'
2201 const auto needsFlat = [](const TType& type) {
2202 return type.containsBasicType(EbtInt) ||
2203 type.containsBasicType(EbtUint) ||
2204 type.containsBasicType(EbtInt64) ||
2205 type.containsBasicType(EbtUint64) ||
2206 type.containsBasicType(EbtBool) ||
2207 type.containsBasicType(EbtDouble);
2210 if (language == EShLangFragment && needsFlat(type)) {
2211 if (type.isStruct()) {
2212 TTypeList* finalList = nullptr;
2213 auto it = ioTypeMap.find(type.getStruct());
2214 if (it == ioTypeMap.end() || it->second.input == nullptr) {
2215 // Getting here means we have no input struct, but we need one.
2216 auto list = new TTypeList;
2217 for (auto member = type.getStruct()->begin(); member != type.getStruct()->end(); ++member) {
2218 TType* newType = new TType;
2219 newType->shallowCopy(*member->type);
2220 TTypeLoc typeLoc = { newType, member->loc };
2221 list->push_back(typeLoc);
2223 // install the new input type
2224 if (it == ioTypeMap.end()) {
2225 tIoKinds newLists = { list, nullptr, nullptr };
2226 ioTypeMap[type.getStruct()] = newLists;
2228 it->second.input = list;
2231 finalList = it->second.input;
2233 for (auto member = finalList->begin(); member != finalList->end(); ++member) {
2234 if (needsFlat(*member->type)) {
2235 member->type->getQualifier().clearInterpolation();
2236 member->type->getQualifier().flat = true;
2240 type.getQualifier().clearInterpolation();
2241 type.getQualifier().flat = true;
2246 // Do the actual work to make a type be a shader input or output variable,
2247 // and clear the original to be non-IO (for use as a normal function parameter/return).
2248 const auto makeIoVariable = [this](const char* name, TType& type, TStorageQualifier storage) -> TVariable* {
2249 TVariable* ioVariable = makeInternalVariable(name, type);
2250 clearUniformInputOutput(type.getQualifier());
2251 if (type.isStruct()) {
2252 auto newLists = ioTypeMap.find(ioVariable->getType().getStruct());
2253 if (newLists != ioTypeMap.end()) {
2254 if (storage == EvqVaryingIn && newLists->second.input)
2255 ioVariable->getWritableType().setStruct(newLists->second.input);
2256 else if (storage == EvqVaryingOut && newLists->second.output)
2257 ioVariable->getWritableType().setStruct(newLists->second.output);
2260 if (storage == EvqVaryingIn) {
2261 correctInput(ioVariable->getWritableType().getQualifier());
2262 if (language == EShLangTessEvaluation)
2263 if (!ioVariable->getType().isArray())
2264 ioVariable->getWritableType().getQualifier().patch = true;
2266 correctOutput(ioVariable->getWritableType().getQualifier());
2268 ioVariable->getWritableType().getQualifier().storage = storage;
2270 fixBuiltInIoType(ioVariable->getWritableType());
2275 // return value is actually a shader-scoped output (out)
2276 if (function.getType().getBasicType() == EbtVoid) {
2277 returnValue = nullptr;
2279 if (language == EShLangTessControl) {
2280 // tessellation evaluation in HLSL writes a per-ctrl-pt value, but it needs to be an
2281 // array in SPIR-V semantics. We'll write to it indexed by invocation ID.
2283 returnValue = makeIoVariable("@entryPointOutput", function.getWritableType(), EvqVaryingOut);
2286 outputType.shallowCopy(function.getType());
2288 // vertices has necessarily already been set when handling entry point attributes.
2289 TArraySizes* arraySizes = new TArraySizes;
2290 arraySizes->addInnerSize(intermediate.getVertices());
2291 outputType.transferArraySizes(arraySizes);
2293 clearUniformInputOutput(function.getWritableType().getQualifier());
2294 returnValue = makeIoVariable("@entryPointOutput", outputType, EvqVaryingOut);
2296 returnValue = makeIoVariable("@entryPointOutput", function.getWritableType(), EvqVaryingOut);
2300 // parameters are actually shader-scoped inputs and outputs (in or out)
2301 for (int i = 0; i < function.getParamCount(); i++) {
2302 TType& paramType = *function[i].type;
2303 if (paramType.getQualifier().isParamInput()) {
2304 synthesizeEditedInput(paramType);
2305 TVariable* argAsGlobal = makeIoVariable(function[i].name->c_str(), paramType, EvqVaryingIn);
2306 inputs.push_back(argAsGlobal);
2308 if (paramType.getQualifier().isParamOutput()) {
2309 TVariable* argAsGlobal = makeIoVariable(function[i].name->c_str(), paramType, EvqVaryingOut);
2310 outputs.push_back(argAsGlobal);
2315 // An HLSL function that looks like an entry point, but is not,
2316 // declares entry point IO built-ins, but these have to be undone.
2317 void HlslParseContext::remapNonEntryPointIO(TFunction& function)
2320 if (function.getType().getBasicType() != EbtVoid)
2321 clearUniformInputOutput(function.getWritableType().getQualifier());
2324 // References to structuredbuffer types are left unmodified
2325 for (int i = 0; i < function.getParamCount(); i++)
2326 if (!isReference(*function[i].type))
2327 clearUniformInputOutput(function[i].type->getQualifier());
2330 // Handle function returns, including type conversions to the function return type
2332 TIntermNode* HlslParseContext::handleReturnValue(const TSourceLoc& loc, TIntermTyped* value)
2334 functionReturnsValue = true;
2336 if (currentFunctionType->getBasicType() == EbtVoid) {
2337 error(loc, "void function cannot return a value", "return", "");
2338 return intermediate.addBranch(EOpReturn, loc);
2339 } else if (*currentFunctionType != value->getType()) {
2340 value = intermediate.addConversion(EOpReturn, *currentFunctionType, value);
2341 if (value && *currentFunctionType != value->getType())
2342 value = intermediate.addUniShapeConversion(EOpReturn, *currentFunctionType, value);
2343 if (value == nullptr || *currentFunctionType != value->getType()) {
2344 error(loc, "type does not match, or is not convertible to, the function's return type", "return", "");
2349 return intermediate.addBranch(EOpReturn, value, loc);
2352 void HlslParseContext::handleFunctionArgument(TFunction* function,
2353 TIntermTyped*& arguments, TIntermTyped* newArg)
2355 TParameter param = { 0, new TType, nullptr };
2356 param.type->shallowCopy(newArg->getType());
2358 function->addParameter(param);
2360 arguments = intermediate.growAggregate(arguments, newArg);
2365 // Position may require special handling: we can optionally invert Y.
2366 // See: https://github.com/KhronosGroup/glslang/issues/1173
2367 // https://github.com/KhronosGroup/glslang/issues/494
2368 TIntermTyped* HlslParseContext::assignPosition(const TSourceLoc& loc, TOperator op,
2369 TIntermTyped* left, TIntermTyped* right)
2371 // If we are not asked for Y inversion, use a plain old assign.
2372 if (!intermediate.getInvertY())
2373 return intermediate.addAssign(op, left, right, loc);
2375 // If we get here, we should invert Y.
2376 TIntermAggregate* assignList = nullptr;
2378 // If this is a complex rvalue, we don't want to dereference it many times. Create a temporary.
2379 TVariable* rhsTempVar = nullptr;
2380 rhsTempVar = makeInternalVariable("@position", right->getType());
2381 rhsTempVar->getWritableType().getQualifier().makeTemporary();
2384 TIntermTyped* rhsTempSym = intermediate.addSymbol(*rhsTempVar, loc);
2385 assignList = intermediate.growAggregate(assignList,
2386 intermediate.addAssign(EOpAssign, rhsTempSym, right, loc), loc);
2393 TIntermTyped* tempSymL = intermediate.addSymbol(*rhsTempVar, loc);
2394 TIntermTyped* tempSymR = intermediate.addSymbol(*rhsTempVar, loc);
2395 TIntermTyped* index = intermediate.addConstantUnion(Y, loc);
2397 TIntermTyped* lhsElement = intermediate.addIndex(EOpIndexDirect, tempSymL, index, loc);
2398 TIntermTyped* rhsElement = intermediate.addIndex(EOpIndexDirect, tempSymR, index, loc);
2400 const TType derefType(right->getType(), 0);
2402 lhsElement->setType(derefType);
2403 rhsElement->setType(derefType);
2405 TIntermTyped* yNeg = intermediate.addUnaryMath(EOpNegative, rhsElement, loc);
2407 assignList = intermediate.growAggregate(assignList, intermediate.addAssign(EOpAssign, lhsElement, yNeg, loc));
2410 // Assign the rhs temp (now with Y inversion) to the final output
2412 TIntermTyped* rhsTempSym = intermediate.addSymbol(*rhsTempVar, loc);
2413 assignList = intermediate.growAggregate(assignList, intermediate.addAssign(op, left, rhsTempSym, loc));
2416 assert(assignList != nullptr);
2417 assignList->setOperator(EOpSequence);
2422 // Clip and cull distance require special handling due to a semantic mismatch. In HLSL,
2423 // these can be float scalar, float vector, or arrays of float scalar or float vector.
2424 // In SPIR-V, they are arrays of scalar floats in all cases. We must copy individual components
2425 // (e.g, both x and y components of a float2) out into the destination float array.
2427 // The values are assigned to sequential members of the output array. The inner dimension
2428 // is vector components. The outer dimension is array elements.
2429 TIntermAggregate* HlslParseContext::assignClipCullDistance(const TSourceLoc& loc, TOperator op, int semanticId,
2430 TIntermTyped* left, TIntermTyped* right)
2433 case EShLangFragment:
2435 case EShLangGeometry:
2438 error(loc, "unimplemented: clip/cull not currently implemented for this stage", "", "");
2442 TVariable** clipCullVar = nullptr;
2444 // Figure out if we are assigning to, or from, clip or cull distance.
2445 const bool isOutput = isClipOrCullDistance(left->getType());
2447 // This is the rvalue or lvalue holding the clip or cull distance.
2448 TIntermTyped* clipCullNode = isOutput ? left : right;
2449 // This is the value going into or out of the clip or cull distance.
2450 TIntermTyped* internalNode = isOutput ? right : left;
2452 const TBuiltInVariable builtInType = clipCullNode->getQualifier().builtIn;
2454 decltype(clipSemanticNSizeIn)* semanticNSize = nullptr;
2456 // Refer to either the clip or the cull distance, depending on semantic.
2457 switch (builtInType) {
2458 case EbvClipDistance:
2459 clipCullVar = isOutput ? &clipDistanceOutput : &clipDistanceInput;
2460 semanticNSize = isOutput ? &clipSemanticNSizeOut : &clipSemanticNSizeIn;
2462 case EbvCullDistance:
2463 clipCullVar = isOutput ? &cullDistanceOutput : &cullDistanceInput;
2464 semanticNSize = isOutput ? &cullSemanticNSizeOut : &cullSemanticNSizeIn;
2467 // called invalidly: we expected a clip or a cull distance.
2468 // static compile time problem: should not happen.
2469 default: assert(0); return nullptr;
2472 // This is the offset in the destination array of a given semantic's data
2473 std::array<int, maxClipCullRegs> semanticOffset;
2475 // Calculate offset of variable of semantic N in destination array
2479 for (int x = 0; x < maxClipCullRegs; ++x) {
2480 // See if we overflowed the vec4 packing
2481 if ((vecItems + (*semanticNSize)[x]) > 4) {
2482 arrayLoc = (arrayLoc + 3) & (~0x3); // round up to next multiple of 4
2486 semanticOffset[x] = arrayLoc;
2487 vecItems += (*semanticNSize)[x];
2488 arrayLoc += (*semanticNSize)[x];
2492 // It can have up to 2 array dimensions (in the case of geometry shader inputs)
2493 const TArraySizes* const internalArraySizes = internalNode->getType().getArraySizes();
2494 const int internalArrayDims = internalNode->getType().isArray() ? internalArraySizes->getNumDims() : 0;
2496 const int internalVectorSize = internalNode->getType().getVectorSize();
2497 // array sizes, or 1 if it's not an array:
2498 const int internalInnerArraySize = (internalArrayDims > 0 ? internalArraySizes->getDimSize(internalArrayDims-1) : 1);
2499 const int internalOuterArraySize = (internalArrayDims > 1 ? internalArraySizes->getDimSize(0) : 1);
2501 // The created type may be an array of arrays, e.g, for geometry shader inputs.
2502 const bool isImplicitlyArrayed = (language == EShLangGeometry && !isOutput);
2504 // If we haven't created the output already, create it now.
2505 if (*clipCullVar == nullptr) {
2506 // ClipDistance and CullDistance are handled specially in the entry point input/output copy
2507 // algorithm, because they may need to be unpacked from components of vectors (or a scalar)
2508 // into a float array, or vice versa. Here, we make the array the right size and type,
2509 // which depends on the incoming data, which has several potential dimensions:
2513 // Of those, semantic ID and array size cannot appear simultaneously.
2515 // Also to note: for implicitly arrayed forms (e.g, geometry shader inputs), we need to create two
2516 // array dimensions. The shader's declaration may have one or two array dimensions. One is always
2517 // the geometry's dimension.
2519 const bool useInnerSize = internalArrayDims > 1 || !isImplicitlyArrayed;
2521 const int requiredInnerArraySize = arrayLoc * (useInnerSize ? internalInnerArraySize : 1);
2522 const int requiredOuterArraySize = (internalArrayDims > 0) ? internalArraySizes->getDimSize(0) : 1;
2524 TType clipCullType(EbtFloat, clipCullNode->getType().getQualifier().storage, 1);
2525 clipCullType.getQualifier() = clipCullNode->getType().getQualifier();
2527 // Create required array dimension
2528 TArraySizes* arraySizes = new TArraySizes;
2529 if (isImplicitlyArrayed)
2530 arraySizes->addInnerSize(requiredOuterArraySize);
2531 arraySizes->addInnerSize(requiredInnerArraySize);
2532 clipCullType.transferArraySizes(arraySizes);
2534 // Obtain symbol name: we'll use that for the symbol we introduce.
2535 TIntermSymbol* sym = clipCullNode->getAsSymbolNode();
2536 assert(sym != nullptr);
2538 // We are moving the semantic ID from the layout location, so it is no longer needed or
2540 clipCullType.getQualifier().layoutLocation = TQualifier::layoutLocationEnd;
2542 // Create variable and track its linkage
2543 *clipCullVar = makeInternalVariable(sym->getName().c_str(), clipCullType);
2545 trackLinkage(**clipCullVar);
2548 // Create symbol for the clip or cull variable.
2549 TIntermSymbol* clipCullSym = intermediate.addSymbol(**clipCullVar);
2552 const int clipCullVectorSize = clipCullSym->getType().getVectorSize();
2554 // array sizes, or 1 if it's not an array:
2555 const TArraySizes* const clipCullArraySizes = clipCullSym->getType().getArraySizes();
2556 const int clipCullOuterArraySize = isImplicitlyArrayed ? clipCullArraySizes->getDimSize(0) : 1;
2557 const int clipCullInnerArraySize = clipCullArraySizes->getDimSize(isImplicitlyArrayed ? 1 : 0);
2559 // clipCullSym has got to be an array of scalar floats, per SPIR-V semantics.
2560 // fixBuiltInIoType() should have handled that upstream.
2561 assert(clipCullSym->getType().isArray());
2562 assert(clipCullSym->getType().getVectorSize() == 1);
2563 assert(clipCullSym->getType().getBasicType() == EbtFloat);
2565 // We may be creating multiple sub-assignments. This is an aggregate to hold them.
2566 // TODO: it would be possible to be clever sometimes and avoid the sequence node if not needed.
2567 TIntermAggregate* assignList = nullptr;
2569 // Holds individual component assignments as we make them.
2570 TIntermTyped* clipCullAssign = nullptr;
2572 // If the types are homomorphic, use a simple assign. No need to mess about with
2573 // individual components.
2574 if (clipCullSym->getType().isArray() == internalNode->getType().isArray() &&
2575 clipCullInnerArraySize == internalInnerArraySize &&
2576 clipCullOuterArraySize == internalOuterArraySize &&
2577 clipCullVectorSize == internalVectorSize) {
2580 clipCullAssign = intermediate.addAssign(op, clipCullSym, internalNode, loc);
2582 clipCullAssign = intermediate.addAssign(op, internalNode, clipCullSym, loc);
2584 assignList = intermediate.growAggregate(assignList, clipCullAssign);
2585 assignList->setOperator(EOpSequence);
2590 // We are going to copy each component of the internal (per array element if indicated) to sequential
2591 // array elements of the clipCullSym. This tracks the lhs element we're writing to as we go along.
2592 // We may be starting in the middle - e.g, for a non-zero semantic ID calculated above.
2593 int clipCullInnerArrayPos = semanticOffset[semanticId];
2594 int clipCullOuterArrayPos = 0;
2596 // Lambda to add an index to a node, set the type of the result, and return the new node.
2597 const auto addIndex = [this, &loc](TIntermTyped* node, int pos) -> TIntermTyped* {
2598 const TType derefType(node->getType(), 0);
2599 node = intermediate.addIndex(EOpIndexDirect, node, intermediate.addConstantUnion(pos, loc), loc);
2600 node->setType(derefType);
2604 // Loop through every component of every element of the internal, and copy to or from the matching external.
2605 for (int internalOuterArrayPos = 0; internalOuterArrayPos < internalOuterArraySize; ++internalOuterArrayPos) {
2606 for (int internalInnerArrayPos = 0; internalInnerArrayPos < internalInnerArraySize; ++internalInnerArrayPos) {
2607 for (int internalComponent = 0; internalComponent < internalVectorSize; ++internalComponent) {
2608 // clip/cull array member to read from / write to:
2609 TIntermTyped* clipCullMember = clipCullSym;
2611 // If implicitly arrayed, there is an outer array dimension involved
2612 if (isImplicitlyArrayed)
2613 clipCullMember = addIndex(clipCullMember, clipCullOuterArrayPos);
2615 // Index into proper array position for clip cull member
2616 clipCullMember = addIndex(clipCullMember, clipCullInnerArrayPos++);
2618 // if needed, start over with next outer array slice.
2619 if (isImplicitlyArrayed && clipCullInnerArrayPos >= clipCullInnerArraySize) {
2620 clipCullInnerArrayPos = semanticOffset[semanticId];
2621 ++clipCullOuterArrayPos;
2624 // internal member to read from / write to:
2625 TIntermTyped* internalMember = internalNode;
2627 // If internal node has outer array dimension, index appropriately.
2628 if (internalArrayDims > 1)
2629 internalMember = addIndex(internalMember, internalOuterArrayPos);
2631 // If internal node has inner array dimension, index appropriately.
2632 if (internalArrayDims > 0)
2633 internalMember = addIndex(internalMember, internalInnerArrayPos);
2635 // If internal node is a vector, extract the component of interest.
2636 if (internalNode->getType().isVector())
2637 internalMember = addIndex(internalMember, internalComponent);
2639 // Create an assignment: output from internal to clip cull, or input from clip cull to internal.
2641 clipCullAssign = intermediate.addAssign(op, clipCullMember, internalMember, loc);
2643 clipCullAssign = intermediate.addAssign(op, internalMember, clipCullMember, loc);
2645 // Track assignment in the sequence.
2646 assignList = intermediate.growAggregate(assignList, clipCullAssign);
2651 assert(assignList != nullptr);
2652 assignList->setOperator(EOpSequence);
2657 // Some simple source assignments need to be flattened to a sequence
2658 // of AST assignments. Catch these and flatten, otherwise, pass through
2659 // to intermediate.addAssign().
2661 // Also, assignment to matrix swizzles requires multiple component assignments,
2662 // intercept those as well.
2663 TIntermTyped* HlslParseContext::handleAssign(const TSourceLoc& loc, TOperator op, TIntermTyped* left,
2664 TIntermTyped* right)
2666 if (left == nullptr || right == nullptr)
2669 // writing to opaques will require fixing transforms
2670 if (left->getType().containsOpaque())
2671 intermediate.setNeedsLegalization();
2673 if (left->getAsOperator() && left->getAsOperator()->getOp() == EOpMatrixSwizzle)
2674 return handleAssignToMatrixSwizzle(loc, op, left, right);
2676 // Return true if the given node is an index operation into a split variable.
2677 const auto indexesSplit = [this](const TIntermTyped* node) -> bool {
2678 const TIntermBinary* binaryNode = node->getAsBinaryNode();
2680 if (binaryNode == nullptr)
2683 return (binaryNode->getOp() == EOpIndexDirect || binaryNode->getOp() == EOpIndexIndirect) &&
2684 wasSplit(binaryNode->getLeft());
2687 // Return true if this stage assigns clip position with potentially inverted Y
2688 const auto assignsClipPos = [this](const TIntermTyped* node) -> bool {
2689 return node->getType().getQualifier().builtIn == EbvPosition &&
2690 (language == EShLangVertex || language == EShLangGeometry || language == EShLangTessEvaluation);
2693 const bool isSplitLeft = wasSplit(left) || indexesSplit(left);
2694 const bool isSplitRight = wasSplit(right) || indexesSplit(right);
2696 const bool isFlattenLeft = wasFlattened(left);
2697 const bool isFlattenRight = wasFlattened(right);
2699 // OK to do a single assign if neither side is split or flattened. Otherwise,
2700 // fall through to a member-wise copy.
2701 if (!isFlattenLeft && !isFlattenRight && !isSplitLeft && !isSplitRight) {
2702 // Clip and cull distance requires more processing. See comment above assignClipCullDistance.
2703 if (isClipOrCullDistance(left->getType()) || isClipOrCullDistance(right->getType())) {
2704 const bool isOutput = isClipOrCullDistance(left->getType());
2706 const int semanticId = (isOutput ? left : right)->getType().getQualifier().layoutLocation;
2707 return assignClipCullDistance(loc, op, semanticId, left, right);
2708 } else if (assignsClipPos(left)) {
2709 // Position can require special handling: see comment above assignPosition
2710 return assignPosition(loc, op, left, right);
2711 } else if (left->getQualifier().builtIn == EbvSampleMask) {
2712 // Certain builtins are required to be arrayed outputs in SPIR-V, but may internally be scalars
2713 // in the shader. Copy the scalar RHS into the LHS array element zero, if that happens.
2714 if (left->isArray() && !right->isArray()) {
2715 const TType derefType(left->getType(), 0);
2716 left = intermediate.addIndex(EOpIndexDirect, left, intermediate.addConstantUnion(0, loc), loc);
2717 left->setType(derefType);
2718 // Fall through to add assign.
2722 return intermediate.addAssign(op, left, right, loc);
2725 TIntermAggregate* assignList = nullptr;
2726 const TVector<TVariable*>* leftVariables = nullptr;
2727 const TVector<TVariable*>* rightVariables = nullptr;
2729 // A temporary to store the right node's value, so we don't keep indirecting into it
2730 // if it's not a simple symbol.
2731 TVariable* rhsTempVar = nullptr;
2733 // If the RHS is a simple symbol node, we'll copy it for each member.
2734 TIntermSymbol* cloneSymNode = nullptr;
2736 int memberCount = 0;
2738 // Track how many items there are to copy.
2739 if (left->getType().isStruct())
2740 memberCount = (int)left->getType().getStruct()->size();
2741 if (left->getType().isArray())
2742 memberCount = left->getType().getCumulativeArraySize();
2745 leftVariables = &flattenMap.find(left->getAsSymbolNode()->getId())->second.members;
2747 if (isFlattenRight) {
2748 rightVariables = &flattenMap.find(right->getAsSymbolNode()->getId())->second.members;
2750 // The RHS is not flattened. There are several cases:
2751 // 1. 1 item to copy: Use the RHS directly.
2752 // 2. >1 item, simple symbol RHS: we'll create a new TIntermSymbol node for each, but no assign to temp.
2753 // 3. >1 item, complex RHS: assign it to a new temp variable, and create a TIntermSymbol for each member.
2755 if (memberCount <= 1) {
2756 // case 1: we'll use the symbol directly below. Nothing to do.
2758 if (right->getAsSymbolNode() != nullptr) {
2759 // case 2: we'll copy the symbol per iteration below.
2760 cloneSymNode = right->getAsSymbolNode();
2762 // case 3: assign to a temp, and indirect into that.
2763 rhsTempVar = makeInternalVariable("flattenTemp", right->getType());
2764 rhsTempVar->getWritableType().getQualifier().makeTemporary();
2765 TIntermTyped* noFlattenRHS = intermediate.addSymbol(*rhsTempVar, loc);
2767 // Add this to the aggregate being built.
2768 assignList = intermediate.growAggregate(assignList,
2769 intermediate.addAssign(op, noFlattenRHS, right, loc), loc);
2774 // When dealing with split arrayed structures of built-ins, the arrayness is moved to the extracted built-in
2775 // variables, which is awkward when copying between split and unsplit structures. This variable tracks
2776 // array indirections so they can be percolated from outer structs to inner variables.
2777 std::vector <int> arrayElement;
2779 TStorageQualifier leftStorage = left->getType().getQualifier().storage;
2780 TStorageQualifier rightStorage = right->getType().getQualifier().storage;
2782 int leftOffset = findSubtreeOffset(*left);
2783 int rightOffset = findSubtreeOffset(*right);
2785 const auto getMember = [&](bool isLeft, const TType& type, int member, TIntermTyped* splitNode, int splitMember,
2788 const bool split = isLeft ? isSplitLeft : isSplitRight;
2790 TIntermTyped* subTree;
2791 const TType derefType(type, member);
2792 const TVariable* builtInVar = nullptr;
2793 if ((flattened || split) && derefType.isBuiltIn()) {
2794 auto splitPair = splitBuiltIns.find(HlslParseContext::tInterstageIoData(
2795 derefType.getQualifier().builtIn,
2796 isLeft ? leftStorage : rightStorage));
2797 if (splitPair != splitBuiltIns.end())
2798 builtInVar = splitPair->second;
2800 if (builtInVar != nullptr) {
2801 // copy from interstage IO built-in if needed
2802 subTree = intermediate.addSymbol(*builtInVar);
2804 if (subTree->getType().isArray()) {
2805 // Arrayness of builtIn symbols isn't handled by the normal recursion:
2806 // it's been extracted and moved to the built-in.
2807 if (!arrayElement.empty()) {
2808 const TType splitDerefType(subTree->getType(), arrayElement.back());
2809 subTree = intermediate.addIndex(EOpIndexDirect, subTree,
2810 intermediate.addConstantUnion(arrayElement.back(), loc), loc);
2811 subTree->setType(splitDerefType);
2812 } else if (splitNode->getAsOperator() != nullptr && (splitNode->getAsOperator()->getOp() == EOpIndexIndirect)) {
2813 // This might also be a stage with arrayed outputs, in which case there's an index
2814 // operation we should transfer to the output builtin.
2816 const TType splitDerefType(subTree->getType(), 0);
2817 subTree = intermediate.addIndex(splitNode->getAsOperator()->getOp(), subTree,
2818 splitNode->getAsBinaryNode()->getRight(), loc);
2819 subTree->setType(splitDerefType);
2822 } else if (flattened && !shouldFlatten(derefType, isLeft ? leftStorage : rightStorage, false)) {
2824 subTree = intermediate.addSymbol(*(*leftVariables)[leftOffset++]);
2826 subTree = intermediate.addSymbol(*(*rightVariables)[rightOffset++]);
2828 // Index operator if it's an aggregate, else EOpNull
2829 const TOperator accessOp = type.isArray() ? EOpIndexDirect
2830 : type.isStruct() ? EOpIndexDirectStruct
2832 if (accessOp == EOpNull) {
2833 subTree = splitNode;
2835 subTree = intermediate.addIndex(accessOp, splitNode, intermediate.addConstantUnion(splitMember, loc),
2837 const TType splitDerefType(splitNode->getType(), splitMember);
2838 subTree->setType(splitDerefType);
2845 // Use the proper RHS node: a new symbol from a TVariable, copy
2846 // of an TIntermSymbol node, or sometimes the right node directly.
2847 right = rhsTempVar != nullptr ? intermediate.addSymbol(*rhsTempVar, loc) :
2848 cloneSymNode != nullptr ? intermediate.addSymbol(*cloneSymNode) :
2851 // Cannot use auto here, because this is recursive, and auto can't work out the type without seeing the
2852 // whole thing. So, we'll resort to an explicit type via std::function.
2853 const std::function<void(TIntermTyped* left, TIntermTyped* right, TIntermTyped* splitLeft, TIntermTyped* splitRight,
2855 traverse = [&](TIntermTyped* left, TIntermTyped* right, TIntermTyped* splitLeft, TIntermTyped* splitRight,
2856 bool topLevel) -> void {
2857 // If we get here, we are assigning to or from a whole array or struct that must be
2858 // flattened, so have to do member-by-member assignment:
2860 bool shouldFlattenSubsetLeft = isFlattenLeft && shouldFlatten(left->getType(), leftStorage, topLevel);
2861 bool shouldFlattenSubsetRight = isFlattenRight && shouldFlatten(right->getType(), rightStorage, topLevel);
2863 if ((left->getType().isArray() || right->getType().isArray()) &&
2864 (shouldFlattenSubsetLeft || isSplitLeft ||
2865 shouldFlattenSubsetRight || isSplitRight)) {
2866 const int elementsL = left->getType().isArray() ? left->getType().getOuterArraySize() : 1;
2867 const int elementsR = right->getType().isArray() ? right->getType().getOuterArraySize() : 1;
2869 // The arrays might not be the same size,
2870 // e.g., if the size has been forced for EbvTessLevelInner/Outer.
2871 const int elementsToCopy = std::min(elementsL, elementsR);
2874 for (int element = 0; element < elementsToCopy; ++element) {
2875 arrayElement.push_back(element);
2877 // Add a new AST symbol node if we have a temp variable holding a complex RHS.
2878 TIntermTyped* subLeft = getMember(true, left->getType(), element, left, element,
2879 shouldFlattenSubsetLeft);
2880 TIntermTyped* subRight = getMember(false, right->getType(), element, right, element,
2881 shouldFlattenSubsetRight);
2883 TIntermTyped* subSplitLeft = isSplitLeft ? getMember(true, left->getType(), element, splitLeft,
2884 element, shouldFlattenSubsetLeft)
2886 TIntermTyped* subSplitRight = isSplitRight ? getMember(false, right->getType(), element, splitRight,
2887 element, shouldFlattenSubsetRight)
2890 traverse(subLeft, subRight, subSplitLeft, subSplitRight, false);
2892 arrayElement.pop_back();
2894 } else if (left->getType().isStruct() && (shouldFlattenSubsetLeft || isSplitLeft ||
2895 shouldFlattenSubsetRight || isSplitRight)) {
2897 const auto& membersL = *left->getType().getStruct();
2898 const auto& membersR = *right->getType().getStruct();
2900 // These track the members in the split structures corresponding to the same in the unsplit structures,
2901 // which we traverse in parallel.
2905 // Handle empty structure assignment
2906 if (int(membersL.size()) == 0 && int(membersR.size()) == 0)
2907 assignList = intermediate.growAggregate(assignList, intermediate.addAssign(op, left, right, loc), loc);
2909 for (int member = 0; member < int(membersL.size()); ++member) {
2910 const TType& typeL = *membersL[member].type;
2911 const TType& typeR = *membersR[member].type;
2913 TIntermTyped* subLeft = getMember(true, left->getType(), member, left, member,
2914 shouldFlattenSubsetLeft);
2915 TIntermTyped* subRight = getMember(false, right->getType(), member, right, member,
2916 shouldFlattenSubsetRight);
2918 // If there is no splitting, use the same values to avoid inefficiency.
2919 TIntermTyped* subSplitLeft = isSplitLeft ? getMember(true, left->getType(), member, splitLeft,
2920 memberL, shouldFlattenSubsetLeft)
2922 TIntermTyped* subSplitRight = isSplitRight ? getMember(false, right->getType(), member, splitRight,
2923 memberR, shouldFlattenSubsetRight)
2926 if (isClipOrCullDistance(subSplitLeft->getType()) || isClipOrCullDistance(subSplitRight->getType())) {
2927 // Clip and cull distance built-in assignment is complex in its own right, and is handled in
2928 // a separate function dedicated to that task. See comment above assignClipCullDistance;
2930 const bool isOutput = isClipOrCullDistance(subSplitLeft->getType());
2932 // Since all clip/cull semantics boil down to the same built-in type, we need to get the
2933 // semantic ID from the dereferenced type's layout location, to avoid an N-1 mapping.
2934 const TType derefType((isOutput ? left : right)->getType(), member);
2935 const int semanticId = derefType.getQualifier().layoutLocation;
2937 TIntermAggregate* clipCullAssign = assignClipCullDistance(loc, op, semanticId,
2938 subSplitLeft, subSplitRight);
2940 assignList = intermediate.growAggregate(assignList, clipCullAssign, loc);
2941 } else if (assignsClipPos(subSplitLeft)) {
2942 // Position can require special handling: see comment above assignPosition
2943 TIntermTyped* positionAssign = assignPosition(loc, op, subSplitLeft, subSplitRight);
2944 assignList = intermediate.growAggregate(assignList, positionAssign, loc);
2945 } else if (!shouldFlattenSubsetLeft && !shouldFlattenSubsetRight &&
2946 !typeL.containsBuiltIn() && !typeR.containsBuiltIn()) {
2947 // If this is the final flattening (no nested types below to flatten)
2948 // we'll copy the member, else recurse into the type hierarchy.
2949 // However, if splitting the struct, that means we can copy a whole
2950 // subtree here IFF it does not itself contain any interstage built-in
2951 // IO variables, so we only have to recurse into it if there's something
2952 // for splitting to do. That can save a lot of AST verbosity for
2953 // a bunch of memberwise copies.
2955 assignList = intermediate.growAggregate(assignList,
2956 intermediate.addAssign(op, subSplitLeft, subSplitRight, loc),
2959 traverse(subLeft, subRight, subSplitLeft, subSplitRight, false);
2962 memberL += (typeL.isBuiltIn() ? 0 : 1);
2963 memberR += (typeR.isBuiltIn() ? 0 : 1);
2967 assignList = intermediate.growAggregate(assignList, intermediate.addAssign(op, left, right, loc), loc);
2972 TIntermTyped* splitLeft = left;
2973 TIntermTyped* splitRight = right;
2975 // If either left or right was a split structure, we must read or write it, but still have to
2976 // parallel-recurse through the unsplit structure to identify the built-in IO vars.
2977 // The left can be either a symbol, or an index into a symbol (e.g, array reference)
2979 if (indexesSplit(left)) {
2980 // Index case: Refer to the indexed symbol, if the left is an index operator.
2981 const TIntermSymbol* symNode = left->getAsBinaryNode()->getLeft()->getAsSymbolNode();
2983 TIntermTyped* splitLeftNonIo = intermediate.addSymbol(*getSplitNonIoVar(symNode->getId()), loc);
2985 splitLeft = intermediate.addIndex(left->getAsBinaryNode()->getOp(), splitLeftNonIo,
2986 left->getAsBinaryNode()->getRight(), loc);
2988 const TType derefType(splitLeftNonIo->getType(), 0);
2989 splitLeft->setType(derefType);
2991 // Symbol case: otherwise, if not indexed, we have the symbol directly.
2992 const TIntermSymbol* symNode = left->getAsSymbolNode();
2993 splitLeft = intermediate.addSymbol(*getSplitNonIoVar(symNode->getId()), loc);
2998 splitRight = intermediate.addSymbol(*getSplitNonIoVar(right->getAsSymbolNode()->getId()), loc);
3000 // This makes the whole assignment, recursing through subtypes as needed.
3001 traverse(left, right, splitLeft, splitRight, true);
3003 assert(assignList != nullptr);
3004 assignList->setOperator(EOpSequence);
3009 // An assignment to matrix swizzle must be decomposed into individual assignments.
3010 // These must be selected component-wise from the RHS and stored component-wise
3012 TIntermTyped* HlslParseContext::handleAssignToMatrixSwizzle(const TSourceLoc& loc, TOperator op, TIntermTyped* left,
3013 TIntermTyped* right)
3015 assert(left->getAsOperator() && left->getAsOperator()->getOp() == EOpMatrixSwizzle);
3017 if (op != EOpAssign)
3018 error(loc, "only simple assignment to non-simple matrix swizzle is supported", "assign", "");
3020 // isolate the matrix and swizzle nodes
3021 TIntermTyped* matrix = left->getAsBinaryNode()->getLeft()->getAsTyped();
3022 const TIntermSequence& swizzle = left->getAsBinaryNode()->getRight()->getAsAggregate()->getSequence();
3024 // if the RHS isn't already a simple vector, let's store into one
3025 TIntermSymbol* vector = right->getAsSymbolNode();
3026 TIntermTyped* vectorAssign = nullptr;
3027 if (vector == nullptr) {
3028 // create a new intermediate vector variable to assign to
3029 TType vectorType(matrix->getBasicType(), EvqTemporary, matrix->getQualifier().precision, (int)swizzle.size()/2);
3030 vector = intermediate.addSymbol(*makeInternalVariable("intermVec", vectorType), loc);
3032 // assign the right to the new vector
3033 vectorAssign = handleAssign(loc, op, vector, right);
3036 // Assign the vector components to the matrix components.
3037 // Store this as a sequence, so a single aggregate node represents this
3038 // entire operation.
3039 TIntermAggregate* result = intermediate.makeAggregate(vectorAssign);
3040 TType columnType(matrix->getType(), 0);
3041 TType componentType(columnType, 0);
3042 TType indexType(EbtInt);
3043 for (int i = 0; i < (int)swizzle.size(); i += 2) {
3044 // the right component, single index into the RHS vector
3045 TIntermTyped* rightComp = intermediate.addIndex(EOpIndexDirect, vector,
3046 intermediate.addConstantUnion(i/2, loc), loc);
3048 // the left component, double index into the LHS matrix
3049 TIntermTyped* leftComp = intermediate.addIndex(EOpIndexDirect, matrix,
3050 intermediate.addConstantUnion(swizzle[i]->getAsConstantUnion()->getConstArray(),
3053 leftComp->setType(columnType);
3054 leftComp = intermediate.addIndex(EOpIndexDirect, leftComp,
3055 intermediate.addConstantUnion(swizzle[i+1]->getAsConstantUnion()->getConstArray(),
3058 leftComp->setType(componentType);
3060 // Add the assignment to the aggregate
3061 result = intermediate.growAggregate(result, intermediate.addAssign(op, leftComp, rightComp, loc));
3064 result->setOp(EOpSequence);
3070 // HLSL atomic operations have slightly different arguments than
3071 // GLSL/AST/SPIRV. The semantics are converted below in decomposeIntrinsic.
3072 // This provides the post-decomposition equivalent opcode.
3074 TOperator HlslParseContext::mapAtomicOp(const TSourceLoc& loc, TOperator op, bool isImage)
3077 case EOpInterlockedAdd: return isImage ? EOpImageAtomicAdd : EOpAtomicAdd;
3078 case EOpInterlockedAnd: return isImage ? EOpImageAtomicAnd : EOpAtomicAnd;
3079 case EOpInterlockedCompareExchange: return isImage ? EOpImageAtomicCompSwap : EOpAtomicCompSwap;
3080 case EOpInterlockedMax: return isImage ? EOpImageAtomicMax : EOpAtomicMax;
3081 case EOpInterlockedMin: return isImage ? EOpImageAtomicMin : EOpAtomicMin;
3082 case EOpInterlockedOr: return isImage ? EOpImageAtomicOr : EOpAtomicOr;
3083 case EOpInterlockedXor: return isImage ? EOpImageAtomicXor : EOpAtomicXor;
3084 case EOpInterlockedExchange: return isImage ? EOpImageAtomicExchange : EOpAtomicExchange;
3085 case EOpInterlockedCompareStore: // TODO: ...
3087 error(loc, "unknown atomic operation", "unknown op", "");
3093 // Create a combined sampler/texture from separate sampler and texture.
3095 TIntermAggregate* HlslParseContext::handleSamplerTextureCombine(const TSourceLoc& loc, TIntermTyped* argTex,
3096 TIntermTyped* argSampler)
3098 TIntermAggregate* txcombine = new TIntermAggregate(EOpConstructTextureSampler);
3100 txcombine->getSequence().push_back(argTex);
3101 txcombine->getSequence().push_back(argSampler);
3103 TSampler samplerType = argTex->getType().getSampler();
3104 samplerType.combined = true;
3107 // This block exists until the spec no longer requires shadow modes on texture objects.
3108 // It can be deleted after that, along with the shadowTextureVariant member.
3110 const bool shadowMode = argSampler->getType().getSampler().shadow;
3112 TIntermSymbol* texSymbol = argTex->getAsSymbolNode();
3114 if (texSymbol == nullptr)
3115 texSymbol = argTex->getAsBinaryNode()->getLeft()->getAsSymbolNode();
3117 if (texSymbol == nullptr) {
3118 error(loc, "unable to find texture symbol", "", "");
3122 // This forces the texture's shadow state to be the sampler's
3123 // shadow state. This depends on downstream optimization to
3124 // DCE one variant in [shadow, nonshadow] if both are present,
3125 // or the SPIR-V module would be invalid.
3126 int newId = texSymbol->getId();
3128 // Check to see if this texture has been given a shadow mode already.
3129 // If so, look up the one we already have.
3130 const auto textureShadowEntry = textureShadowVariant.find(texSymbol->getId());
3132 if (textureShadowEntry != textureShadowVariant.end())
3133 newId = textureShadowEntry->second->get(shadowMode);
3135 textureShadowVariant[texSymbol->getId()] = new tShadowTextureSymbols;
3137 // Sometimes we have to create another symbol (if this texture has been seen before,
3138 // and we haven't created the form for this shadow mode).
3141 texType.shallowCopy(argTex->getType());
3142 texType.getSampler().shadow = shadowMode; // set appropriate shadow mode.
3143 globalQualifierFix(loc, texType.getQualifier());
3145 TVariable* newTexture = makeInternalVariable(texSymbol->getName(), texType);
3147 trackLinkage(*newTexture);
3149 newId = newTexture->getUniqueId();
3152 assert(newId != -1);
3154 if (textureShadowVariant.find(newId) == textureShadowVariant.end())
3155 textureShadowVariant[newId] = textureShadowVariant[texSymbol->getId()];
3157 textureShadowVariant[newId]->set(shadowMode, newId);
3159 // Remember this shadow mode in the texture and the merged type.
3160 argTex->getWritableType().getSampler().shadow = shadowMode;
3161 samplerType.shadow = shadowMode;
3163 texSymbol->switchId(newId);
3166 txcombine->setType(TType(samplerType, EvqTemporary));
3167 txcombine->setLoc(loc);
3172 // Return true if this a buffer type that has an associated counter buffer.
3173 bool HlslParseContext::hasStructBuffCounter(const TType& type) const
3175 switch (type.getQualifier().declaredBuiltIn) {
3176 case EbvAppendConsume: // fall through...
3177 case EbvRWStructuredBuffer: // ...
3180 return false; // the other structuredbuffer types do not have a counter.
3184 void HlslParseContext::counterBufferType(const TSourceLoc& loc, TType& type)
3187 TType* counterType = new TType(EbtUint, EvqBuffer);
3188 counterType->setFieldName(intermediate.implicitCounterName);
3190 TTypeList* blockStruct = new TTypeList;
3191 TTypeLoc member = { counterType, loc };
3192 blockStruct->push_back(member);
3194 TType blockType(blockStruct, "", counterType->getQualifier());
3195 blockType.getQualifier().storage = EvqBuffer;
3197 type.shallowCopy(blockType);
3198 shareStructBufferType(type);
3201 // declare counter for a structured buffer type
3202 void HlslParseContext::declareStructBufferCounter(const TSourceLoc& loc, const TType& bufferType, const TString& name)
3204 // Bail out if not a struct buffer
3205 if (! isStructBufferType(bufferType))
3208 if (! hasStructBuffCounter(bufferType))
3212 counterBufferType(loc, blockType);
3214 TString* blockName = new TString(intermediate.addCounterBufferName(name));
3216 // Counter buffer is not yet in use
3217 structBufferCounter[*blockName] = false;
3219 shareStructBufferType(blockType);
3220 declareBlock(loc, blockType, blockName);
3223 // return the counter that goes with a given structuredbuffer
3224 TIntermTyped* HlslParseContext::getStructBufferCounter(const TSourceLoc& loc, TIntermTyped* buffer)
3226 // Bail out if not a struct buffer
3227 if (buffer == nullptr || ! isStructBufferType(buffer->getType()))
3230 const TString counterBlockName(intermediate.addCounterBufferName(buffer->getAsSymbolNode()->getName()));
3232 // Mark the counter as being used
3233 structBufferCounter[counterBlockName] = true;
3235 TIntermTyped* counterVar = handleVariable(loc, &counterBlockName); // find the block structure
3236 TIntermTyped* index = intermediate.addConstantUnion(0, loc); // index to counter inside block struct
3238 TIntermTyped* counterMember = intermediate.addIndex(EOpIndexDirectStruct, counterVar, index, loc);
3239 counterMember->setType(TType(EbtUint));
3240 return counterMember;
3244 // Decompose structure buffer methods into AST
3246 void HlslParseContext::decomposeStructBufferMethods(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
3248 if (node == nullptr || node->getAsOperator() == nullptr || arguments == nullptr)
3251 const TOperator op = node->getAsOperator()->getOp();
3252 TIntermAggregate* argAggregate = arguments->getAsAggregate();
3254 // Buffer is the object upon which method is called, so always arg 0
3255 TIntermTyped* bufferObj = nullptr;
3257 // The parameters can be an aggregate, or just a the object as a symbol if there are no fn params.
3259 if (argAggregate->getSequence().empty())
3261 bufferObj = argAggregate->getSequence()[0]->getAsTyped();
3263 bufferObj = arguments->getAsSymbolNode();
3266 if (bufferObj == nullptr || bufferObj->getAsSymbolNode() == nullptr)
3269 // Some methods require a hidden internal counter, obtained via getStructBufferCounter().
3270 // This lambda adds something to it and returns the old value.
3271 const auto incDecCounter = [&](int incval) -> TIntermTyped* {
3272 TIntermTyped* incrementValue = intermediate.addConstantUnion(static_cast<unsigned int>(incval), loc, true);
3273 TIntermTyped* counter = getStructBufferCounter(loc, bufferObj); // obtain the counter member
3275 if (counter == nullptr)
3278 TIntermAggregate* counterIncrement = new TIntermAggregate(EOpAtomicAdd);
3279 counterIncrement->setType(TType(EbtUint, EvqTemporary));
3280 counterIncrement->setLoc(loc);
3281 counterIncrement->getSequence().push_back(counter);
3282 counterIncrement->getSequence().push_back(incrementValue);
3284 return counterIncrement;
3287 // Index to obtain the runtime sized array out of the buffer.
3288 TIntermTyped* argArray = indexStructBufferContent(loc, bufferObj);
3289 if (argArray == nullptr)
3290 return; // It might not be a struct buffer method.
3295 TIntermTyped* argIndex = makeIntegerIndex(argAggregate->getSequence()[1]->getAsTyped()); // index
3297 const TType& bufferType = bufferObj->getType();
3299 const TBuiltInVariable builtInType = bufferType.getQualifier().declaredBuiltIn;
3301 // Byte address buffers index in bytes (only multiples of 4 permitted... not so much a byte address
3302 // buffer then, but that's what it calls itself.
3303 const bool isByteAddressBuffer = (builtInType == EbvByteAddressBuffer ||
3304 builtInType == EbvRWByteAddressBuffer);
3307 if (isByteAddressBuffer)
3308 argIndex = intermediate.addBinaryNode(EOpRightShift, argIndex,
3309 intermediate.addConstantUnion(2, loc, true),
3310 loc, TType(EbtInt));
3312 // Index into the array to find the item being loaded.
3313 const TOperator idxOp = (argIndex->getQualifier().storage == EvqConst) ? EOpIndexDirect : EOpIndexIndirect;
3315 node = intermediate.addIndex(idxOp, argArray, argIndex, loc);
3317 const TType derefType(argArray->getType(), 0);
3318 node->setType(derefType);
3323 case EOpMethodLoad2:
3324 case EOpMethodLoad3:
3325 case EOpMethodLoad4:
3327 TIntermTyped* argIndex = makeIntegerIndex(argAggregate->getSequence()[1]->getAsTyped()); // index
3329 TOperator constructOp = EOpNull;
3333 case EOpMethodLoad2: size = 2; constructOp = EOpConstructVec2; break;
3334 case EOpMethodLoad3: size = 3; constructOp = EOpConstructVec3; break;
3335 case EOpMethodLoad4: size = 4; constructOp = EOpConstructVec4; break;
3339 TIntermTyped* body = nullptr;
3341 // First, we'll store the address in a variable to avoid multiple shifts
3342 // (we must convert the byte address to an item address)
3343 TIntermTyped* byteAddrIdx = intermediate.addBinaryNode(EOpRightShift, argIndex,
3344 intermediate.addConstantUnion(2, loc, true),
3345 loc, TType(EbtInt));
3347 TVariable* byteAddrSym = makeInternalVariable("byteAddrTemp", TType(EbtInt, EvqTemporary));
3348 TIntermTyped* byteAddrIdxVar = intermediate.addSymbol(*byteAddrSym, loc);
3350 body = intermediate.growAggregate(body, intermediate.addAssign(EOpAssign, byteAddrIdxVar, byteAddrIdx, loc));
3352 TIntermTyped* vec = nullptr;
3354 // These are only valid on (rw)byteaddressbuffers, so we can always perform the >>2
3355 // address conversion.
3356 for (int idx=0; idx<size; ++idx) {
3357 TIntermTyped* offsetIdx = byteAddrIdxVar;
3361 offsetIdx = intermediate.addBinaryNode(EOpAdd, offsetIdx,
3362 intermediate.addConstantUnion(idx, loc, true),
3363 loc, TType(EbtInt));
3365 const TOperator idxOp = (offsetIdx->getQualifier().storage == EvqConst) ? EOpIndexDirect
3368 TIntermTyped* indexVal = intermediate.addIndex(idxOp, argArray, offsetIdx, loc);
3370 TType derefType(argArray->getType(), 0);
3371 derefType.getQualifier().makeTemporary();
3372 indexVal->setType(derefType);
3374 vec = intermediate.growAggregate(vec, indexVal);
3377 vec->setType(TType(argArray->getBasicType(), EvqTemporary, size));
3378 vec->getAsAggregate()->setOperator(constructOp);
3380 body = intermediate.growAggregate(body, vec);
3381 body->setType(vec->getType());
3382 body->getAsAggregate()->setOperator(EOpSequence);
3389 case EOpMethodStore:
3390 case EOpMethodStore2:
3391 case EOpMethodStore3:
3392 case EOpMethodStore4:
3394 TIntermTyped* argIndex = makeIntegerIndex(argAggregate->getSequence()[1]->getAsTyped()); // index
3395 TIntermTyped* argValue = argAggregate->getSequence()[2]->getAsTyped(); // value
3397 // Index into the array to find the item being loaded.
3398 // Byte address buffers index in bytes (only multiples of 4 permitted... not so much a byte address
3399 // buffer then, but that's what it calls itself).
3404 case EOpMethodStore: size = 1; break;
3405 case EOpMethodStore2: size = 2; break;
3406 case EOpMethodStore3: size = 3; break;
3407 case EOpMethodStore4: size = 4; break;
3411 TIntermAggregate* body = nullptr;
3413 // First, we'll store the address in a variable to avoid multiple shifts
3414 // (we must convert the byte address to an item address)
3415 TIntermTyped* byteAddrIdx = intermediate.addBinaryNode(EOpRightShift, argIndex,
3416 intermediate.addConstantUnion(2, loc, true), loc, TType(EbtInt));
3418 TVariable* byteAddrSym = makeInternalVariable("byteAddrTemp", TType(EbtInt, EvqTemporary));
3419 TIntermTyped* byteAddrIdxVar = intermediate.addSymbol(*byteAddrSym, loc);
3421 body = intermediate.growAggregate(body, intermediate.addAssign(EOpAssign, byteAddrIdxVar, byteAddrIdx, loc));
3423 for (int idx=0; idx<size; ++idx) {
3424 TIntermTyped* offsetIdx = byteAddrIdxVar;
3425 TIntermTyped* idxConst = intermediate.addConstantUnion(idx, loc, true);
3429 offsetIdx = intermediate.addBinaryNode(EOpAdd, offsetIdx, idxConst, loc, TType(EbtInt));
3431 const TOperator idxOp = (offsetIdx->getQualifier().storage == EvqConst) ? EOpIndexDirect
3434 TIntermTyped* lValue = intermediate.addIndex(idxOp, argArray, offsetIdx, loc);
3435 const TType derefType(argArray->getType(), 0);
3436 lValue->setType(derefType);
3438 TIntermTyped* rValue;
3442 rValue = intermediate.addIndex(EOpIndexDirect, argValue, idxConst, loc);
3443 const TType indexType(argValue->getType(), 0);
3444 rValue->setType(indexType);
3447 TIntermTyped* assign = intermediate.addAssign(EOpAssign, lValue, rValue, loc);
3449 body = intermediate.growAggregate(body, assign);
3452 body->setOperator(EOpSequence);
3458 case EOpMethodGetDimensions:
3460 const int numArgs = (int)argAggregate->getSequence().size();
3461 TIntermTyped* argNumItems = argAggregate->getSequence()[1]->getAsTyped(); // out num items
3462 TIntermTyped* argStride = numArgs > 2 ? argAggregate->getSequence()[2]->getAsTyped() : nullptr; // out stride
3464 TIntermAggregate* body = nullptr;
3467 if (argArray->getType().isSizedArray()) {
3468 const int length = argArray->getType().getOuterArraySize();
3469 TIntermTyped* assign = intermediate.addAssign(EOpAssign, argNumItems,
3470 intermediate.addConstantUnion(length, loc, true), loc);
3471 body = intermediate.growAggregate(body, assign, loc);
3473 TIntermTyped* lengthCall = intermediate.addBuiltInFunctionCall(loc, EOpArrayLength, true, argArray,
3474 argNumItems->getType());
3475 TIntermTyped* assign = intermediate.addAssign(EOpAssign, argNumItems, lengthCall, loc);
3476 body = intermediate.growAggregate(body, assign, loc);
3480 if (argStride != nullptr) {
3483 intermediate.getBaseAlignment(argArray->getType(), size, stride, false,
3484 argArray->getType().getQualifier().layoutMatrix == ElmRowMajor);
3486 TIntermTyped* assign = intermediate.addAssign(EOpAssign, argStride,
3487 intermediate.addConstantUnion(stride, loc, true), loc);
3489 body = intermediate.growAggregate(body, assign);
3492 body->setOperator(EOpSequence);
3498 case EOpInterlockedAdd:
3499 case EOpInterlockedAnd:
3500 case EOpInterlockedExchange:
3501 case EOpInterlockedMax:
3502 case EOpInterlockedMin:
3503 case EOpInterlockedOr:
3504 case EOpInterlockedXor:
3505 case EOpInterlockedCompareExchange:
3506 case EOpInterlockedCompareStore:
3508 // We'll replace the first argument with the block dereference, and let
3509 // downstream decomposition handle the rest.
3511 TIntermSequence& sequence = argAggregate->getSequence();
3513 TIntermTyped* argIndex = makeIntegerIndex(sequence[1]->getAsTyped()); // index
3514 argIndex = intermediate.addBinaryNode(EOpRightShift, argIndex, intermediate.addConstantUnion(2, loc, true),
3515 loc, TType(EbtInt));
3517 const TOperator idxOp = (argIndex->getQualifier().storage == EvqConst) ? EOpIndexDirect : EOpIndexIndirect;
3518 TIntermTyped* element = intermediate.addIndex(idxOp, argArray, argIndex, loc);
3520 const TType derefType(argArray->getType(), 0);
3521 element->setType(derefType);
3523 // Replace the numeric byte offset parameter with array reference.
3524 sequence[1] = element;
3525 sequence.erase(sequence.begin(), sequence.begin()+1);
3529 case EOpMethodIncrementCounter:
3531 node = incDecCounter(1);
3535 case EOpMethodDecrementCounter:
3537 TIntermTyped* preIncValue = incDecCounter(-1); // result is original value
3538 node = intermediate.addBinaryNode(EOpAdd, preIncValue, intermediate.addConstantUnion(-1, loc, true), loc,
3539 preIncValue->getType());
3543 case EOpMethodAppend:
3545 TIntermTyped* oldCounter = incDecCounter(1);
3547 TIntermTyped* lValue = intermediate.addIndex(EOpIndexIndirect, argArray, oldCounter, loc);
3548 TIntermTyped* rValue = argAggregate->getSequence()[1]->getAsTyped();
3550 const TType derefType(argArray->getType(), 0);
3551 lValue->setType(derefType);
3553 node = intermediate.addAssign(EOpAssign, lValue, rValue, loc);
3558 case EOpMethodConsume:
3560 TIntermTyped* oldCounter = incDecCounter(-1);
3562 TIntermTyped* newCounter = intermediate.addBinaryNode(EOpAdd, oldCounter,
3563 intermediate.addConstantUnion(-1, loc, true), loc,
3564 oldCounter->getType());
3566 node = intermediate.addIndex(EOpIndexIndirect, argArray, newCounter, loc);
3568 const TType derefType(argArray->getType(), 0);
3569 node->setType(derefType);
3575 break; // most pass through unchanged
3579 // Create array of standard sample positions for given sample count.
3580 // TODO: remove when a real method to query sample pos exists in SPIR-V.
3581 TIntermConstantUnion* HlslParseContext::getSamplePosArray(int count)
3583 struct tSamplePos { float x, y; };
3585 static const tSamplePos pos1[] = {
3586 { 0.0/16.0, 0.0/16.0 },
3589 // standard sample positions for 2, 4, 8, and 16 samples.
3590 static const tSamplePos pos2[] = {
3591 { 4.0/16.0, 4.0/16.0 }, {-4.0/16.0, -4.0/16.0 },
3594 static const tSamplePos pos4[] = {
3595 {-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 },
3598 static const tSamplePos pos8[] = {
3599 { 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 },
3600 {-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 },
3603 static const tSamplePos pos16[] = {
3604 { 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 },
3605 {-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 },
3606 {-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 },
3607 {-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 },
3610 const tSamplePos* sampleLoc = nullptr;
3611 int numSamples = count;
3614 case 2: sampleLoc = pos2; break;
3615 case 4: sampleLoc = pos4; break;
3616 case 8: sampleLoc = pos8; break;
3617 case 16: sampleLoc = pos16; break;
3623 TConstUnionArray* values = new TConstUnionArray(numSamples*2);
3625 for (int pos=0; pos<count; ++pos) {
3627 x.setDConst(sampleLoc[pos].x);
3628 y.setDConst(sampleLoc[pos].y);
3630 (*values)[pos*2+0] = x;
3631 (*values)[pos*2+1] = y;
3634 TType retType(EbtFloat, EvqConst, 2);
3636 if (numSamples != 1) {
3637 TArraySizes* arraySizes = new TArraySizes;
3638 arraySizes->addInnerSize(numSamples);
3639 retType.transferArraySizes(arraySizes);
3642 return new TIntermConstantUnion(*values, retType);
3646 // Decompose DX9 and DX10 sample intrinsics & object methods into AST
3648 void HlslParseContext::decomposeSampleMethods(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
3650 if (node == nullptr || !node->getAsOperator())
3653 // Sampler return must always be a vec4, but we can construct a shorter vector or a structure from it.
3654 const auto convertReturn = [&loc, &node, this](TIntermTyped* result, const TSampler& sampler) -> TIntermTyped* {
3655 result->setType(TType(node->getType().getBasicType(), EvqTemporary, node->getVectorSize()));
3657 TIntermTyped* convertedResult = nullptr;
3660 getTextureReturnType(sampler, retType);
3662 if (retType.isStruct()) {
3663 // For type convenience, conversionAggregate points to the convertedResult (we know it's an aggregate here)
3664 TIntermAggregate* conversionAggregate = new TIntermAggregate;
3665 convertedResult = conversionAggregate;
3667 // Convert vector output to return structure. We will need a temp symbol to copy the results to.
3668 TVariable* structVar = makeInternalVariable("@sampleStructTemp", retType);
3670 // We also need a temp symbol to hold the result of the texture. We don't want to re-fetch the
3671 // sample each time we'll index into the result, so we'll copy to this, and index into the copy.
3672 TVariable* sampleShadow = makeInternalVariable("@sampleResultShadow", result->getType());
3674 // Initial copy from texture to our sample result shadow.
3675 TIntermTyped* shadowCopy = intermediate.addAssign(EOpAssign, intermediate.addSymbol(*sampleShadow, loc),
3678 conversionAggregate->getSequence().push_back(shadowCopy);
3680 unsigned vec4Pos = 0;
3682 for (unsigned m = 0; m < unsigned(retType.getStruct()->size()); ++m) {
3683 const TType memberType(retType, m); // dereferenced type of the member we're about to assign.
3685 // Check for bad struct members. This should have been caught upstream. Complain, because
3686 // wwe don't know what to do with it. This algorithm could be generalized to handle
3687 // other things, e.g, sub-structures, but HLSL doesn't allow them.
3688 if (!memberType.isVector() && !memberType.isScalar()) {
3689 error(loc, "expected: scalar or vector type in texture structure", "", "");
3693 // Index into the struct variable to find the member to assign.
3694 TIntermTyped* structMember = intermediate.addIndex(EOpIndexDirectStruct,
3695 intermediate.addSymbol(*structVar, loc),
3696 intermediate.addConstantUnion(m, loc), loc);
3698 structMember->setType(memberType);
3700 // Assign each component of (possible) vector in struct member.
3701 for (int component = 0; component < memberType.getVectorSize(); ++component) {
3702 TIntermTyped* vec4Member = intermediate.addIndex(EOpIndexDirect,
3703 intermediate.addSymbol(*sampleShadow, loc),
3704 intermediate.addConstantUnion(vec4Pos++, loc), loc);
3705 vec4Member->setType(TType(memberType.getBasicType(), EvqTemporary, 1));
3707 TIntermTyped* memberAssign = nullptr;
3709 if (memberType.isVector()) {
3710 // Vector member: we need to create an access chain to the vector component.
3712 TIntermTyped* structVecComponent = intermediate.addIndex(EOpIndexDirect, structMember,
3713 intermediate.addConstantUnion(component, loc), loc);
3715 memberAssign = intermediate.addAssign(EOpAssign, structVecComponent, vec4Member, loc);
3717 // Scalar member: we can assign to it directly.
3718 memberAssign = intermediate.addAssign(EOpAssign, structMember, vec4Member, loc);
3722 conversionAggregate->getSequence().push_back(memberAssign);
3726 // Add completed variable so the expression results in the whole struct value we just built.
3727 conversionAggregate->getSequence().push_back(intermediate.addSymbol(*structVar, loc));
3729 // Make it a sequence.
3730 intermediate.setAggregateOperator(conversionAggregate, EOpSequence, retType, loc);
3732 // vector clamp the output if template vector type is smaller than sample result.
3733 if (retType.getVectorSize() < node->getVectorSize()) {
3734 // Too many components. Construct shorter vector from it.
3735 const TOperator op = intermediate.mapTypeToConstructorOp(retType);
3737 convertedResult = constructBuiltIn(retType, op, result, loc, false);
3739 // Enough components. Use directly.
3740 convertedResult = result;
3744 convertedResult->setLoc(loc);
3745 return convertedResult;
3748 const TOperator op = node->getAsOperator()->getOp();
3749 const TIntermAggregate* argAggregate = arguments ? arguments->getAsAggregate() : nullptr;
3751 // Bail out if not a sampler method.
3752 // Note though this is odd to do before checking the op, because the op
3753 // could be something that takes the arguments, and the function in question
3754 // takes the result of the op. So, this is not the final word.
3755 if (arguments != nullptr) {
3756 if (argAggregate == nullptr) {
3757 if (arguments->getAsTyped()->getBasicType() != EbtSampler)
3760 if (argAggregate->getSequence().size() == 0 ||
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);
3777 case EOpTextureBias:
3779 TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped(); // sampler
3780 TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped(); // coord
3782 // HLSL puts bias in W component of coordinate. We extract it and add it to
3783 // the argument list, instead
3784 TIntermTyped* w = intermediate.addConstantUnion(3, loc, true);
3785 TIntermTyped* bias = intermediate.addIndex(EOpIndexDirect, arg1, w, loc);
3787 TOperator constructOp = EOpNull;
3788 const TSampler& sampler = arg0->getType().getSampler();
3790 switch (sampler.dim) {
3791 case Esd1D: constructOp = EOpConstructFloat; break; // 1D
3792 case Esd2D: constructOp = EOpConstructVec2; break; // 2D
3793 case Esd3D: constructOp = EOpConstructVec3; break; // 3D
3794 case EsdCube: constructOp = EOpConstructVec3; break; // also 3D
3798 TIntermAggregate* constructCoord = new TIntermAggregate(constructOp);
3799 constructCoord->getSequence().push_back(arg1);
3800 constructCoord->setLoc(loc);
3802 // The input vector should never be less than 2, since there's always a bias.
3803 // The max is for safety, and should be a no-op.
3804 constructCoord->setType(TType(arg1->getBasicType(), EvqTemporary, std::max(arg1->getVectorSize() - 1, 0)));
3806 TIntermAggregate* tex = new TIntermAggregate(EOpTexture);
3807 tex->getSequence().push_back(arg0); // sampler
3808 tex->getSequence().push_back(constructCoord); // coordinate
3809 tex->getSequence().push_back(bias); // bias
3811 node = convertReturn(tex, sampler);
3816 // **** DX10 methods: ****
3817 case EOpMethodSample: // fall through
3818 case EOpMethodSampleBias: // ...
3820 TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
3821 TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
3822 TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
3823 TIntermTyped* argBias = nullptr;
3824 TIntermTyped* argOffset = nullptr;
3825 const TSampler& sampler = argTex->getType().getSampler();
3829 if (op == EOpMethodSampleBias) // SampleBias has a bias arg
3830 argBias = argAggregate->getSequence()[nextArg++]->getAsTyped();
3832 TOperator textureOp = EOpTexture;
3834 if ((int)argAggregate->getSequence().size() == (nextArg+1)) { // last parameter is offset form
3835 textureOp = EOpTextureOffset;
3836 argOffset = argAggregate->getSequence()[nextArg++]->getAsTyped();
3839 TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
3841 TIntermAggregate* txsample = new TIntermAggregate(textureOp);
3842 txsample->getSequence().push_back(txcombine);
3843 txsample->getSequence().push_back(argCoord);
3845 if (argBias != nullptr)
3846 txsample->getSequence().push_back(argBias);
3848 if (argOffset != nullptr)
3849 txsample->getSequence().push_back(argOffset);
3851 node = convertReturn(txsample, sampler);
3856 case EOpMethodSampleGrad: // ...
3858 TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
3859 TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
3860 TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
3861 TIntermTyped* argDDX = argAggregate->getSequence()[3]->getAsTyped();
3862 TIntermTyped* argDDY = argAggregate->getSequence()[4]->getAsTyped();
3863 TIntermTyped* argOffset = nullptr;
3864 const TSampler& sampler = argTex->getType().getSampler();
3866 TOperator textureOp = EOpTextureGrad;
3868 if (argAggregate->getSequence().size() == 6) { // last parameter is offset form
3869 textureOp = EOpTextureGradOffset;
3870 argOffset = argAggregate->getSequence()[5]->getAsTyped();
3873 TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
3875 TIntermAggregate* txsample = new TIntermAggregate(textureOp);
3876 txsample->getSequence().push_back(txcombine);
3877 txsample->getSequence().push_back(argCoord);
3878 txsample->getSequence().push_back(argDDX);
3879 txsample->getSequence().push_back(argDDY);
3881 if (argOffset != nullptr)
3882 txsample->getSequence().push_back(argOffset);
3884 node = convertReturn(txsample, sampler);
3889 case EOpMethodGetDimensions:
3891 // AST returns a vector of results, which we break apart component-wise into
3892 // separate values to assign to the HLSL method's outputs, ala:
3893 // tx . GetDimensions(width, height);
3894 // float2 sizeQueryTemp = EOpTextureQuerySize
3895 // width = sizeQueryTemp.X;
3896 // height = sizeQueryTemp.Y;
3898 TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
3899 const TType& texType = argTex->getType();
3901 assert(texType.getBasicType() == EbtSampler);
3903 const TSampler& sampler = texType.getSampler();
3904 const TSamplerDim dim = sampler.dim;
3905 const bool isImage = sampler.isImage();
3906 const bool isMs = sampler.isMultiSample();
3907 const int numArgs = (int)argAggregate->getSequence().size();
3912 case Esd1D: numDims = 1; break; // W
3913 case Esd2D: numDims = 2; break; // W, H
3914 case Esd3D: numDims = 3; break; // W, H, D
3915 case EsdCube: numDims = 2; break; // W, H (cube)
3916 case EsdBuffer: numDims = 1; break; // W (buffers)
3917 case EsdRect: numDims = 2; break; // W, H (rect)
3919 assert(0 && "unhandled texture dimension");
3922 // Arrayed adds another dimension for the number of array elements
3923 if (sampler.isArrayed())
3926 // Establish whether the method itself is querying mip levels. This can be false even
3927 // if the underlying query requires a MIP level, due to the available HLSL method overloads.
3928 const bool mipQuery = (numArgs > (numDims + 1 + (isMs ? 1 : 0)));
3930 // Establish whether we must use the LOD form of query (even if the method did not supply a mip level to query).
3932 // 1. 1D/2D/3D/Cube AND multisample==0 AND NOT image (those can be sent to the non-LOD query)
3934 // 2. There is a LOD (because the non-LOD query cannot be used in that case, per spec)
3935 const bool mipRequired =
3936 ((dim == Esd1D || dim == Esd2D || dim == Esd3D || dim == EsdCube) && !isMs && !isImage) || // 1...
3939 // AST assumes integer return. Will be converted to float if required.
3940 TIntermAggregate* sizeQuery = new TIntermAggregate(isImage ? EOpImageQuerySize : EOpTextureQuerySize);
3941 sizeQuery->getSequence().push_back(argTex);
3943 // If we're building an LOD query, add the LOD.
3945 // If the base HLSL query had no MIP level given, use level 0.
3946 TIntermTyped* queryLod = mipQuery ? argAggregate->getSequence()[1]->getAsTyped() :
3947 intermediate.addConstantUnion(0, loc, true);
3948 sizeQuery->getSequence().push_back(queryLod);
3951 sizeQuery->setType(TType(EbtUint, EvqTemporary, numDims));
3952 sizeQuery->setLoc(loc);
3954 // Return value from size query
3955 TVariable* tempArg = makeInternalVariable("sizeQueryTemp", sizeQuery->getType());
3956 tempArg->getWritableType().getQualifier().makeTemporary();
3957 TIntermTyped* sizeQueryAssign = intermediate.addAssign(EOpAssign,
3958 intermediate.addSymbol(*tempArg, loc),
3961 // Compound statement for assigning outputs
3962 TIntermAggregate* compoundStatement = intermediate.makeAggregate(sizeQueryAssign, loc);
3963 // Index of first output parameter
3964 const int outParamBase = mipQuery ? 2 : 1;
3966 for (int compNum = 0; compNum < numDims; ++compNum) {
3967 TIntermTyped* indexedOut = nullptr;
3968 TIntermSymbol* sizeQueryReturn = intermediate.addSymbol(*tempArg, loc);
3971 TIntermTyped* component = intermediate.addConstantUnion(compNum, loc, true);
3972 indexedOut = intermediate.addIndex(EOpIndexDirect, sizeQueryReturn, component, loc);
3973 indexedOut->setType(TType(EbtUint, EvqTemporary, 1));
3974 indexedOut->setLoc(loc);
3976 indexedOut = sizeQueryReturn;
3979 TIntermTyped* outParam = argAggregate->getSequence()[outParamBase + compNum]->getAsTyped();
3980 TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, outParam, indexedOut, loc);
3982 compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
3985 // handle mip level parameter
3987 TIntermTyped* outParam = argAggregate->getSequence()[outParamBase + numDims]->getAsTyped();
3989 TIntermAggregate* levelsQuery = new TIntermAggregate(EOpTextureQueryLevels);
3990 levelsQuery->getSequence().push_back(argTex);
3991 levelsQuery->setType(TType(EbtUint, EvqTemporary, 1));
3992 levelsQuery->setLoc(loc);
3994 TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, outParam, levelsQuery, loc);
3995 compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
3998 // 2DMS formats query # samples, which needs a different query op
3999 if (sampler.isMultiSample()) {
4000 TIntermTyped* outParam = argAggregate->getSequence()[outParamBase + numDims]->getAsTyped();
4002 TIntermAggregate* samplesQuery = new TIntermAggregate(EOpImageQuerySamples);
4003 samplesQuery->getSequence().push_back(argTex);
4004 samplesQuery->setType(TType(EbtUint, EvqTemporary, 1));
4005 samplesQuery->setLoc(loc);
4007 TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, outParam, samplesQuery, loc);
4008 compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
4011 compoundStatement->setOperator(EOpSequence);
4012 compoundStatement->setLoc(loc);
4013 compoundStatement->setType(TType(EbtVoid));
4015 node = compoundStatement;
4020 case EOpMethodSampleCmp: // fall through...
4021 case EOpMethodSampleCmpLevelZero:
4023 TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
4024 TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
4025 TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
4026 TIntermTyped* argCmpVal = argAggregate->getSequence()[3]->getAsTyped();
4027 TIntermTyped* argOffset = nullptr;
4029 // Sampler argument should be a sampler.
4030 if (argSamp->getType().getBasicType() != EbtSampler) {
4031 error(loc, "expected: sampler type", "", "");
4035 // Sampler should be a SamplerComparisonState
4036 if (! argSamp->getType().getSampler().isShadow()) {
4037 error(loc, "expected: SamplerComparisonState", "", "");
4041 // optional offset value
4042 if (argAggregate->getSequence().size() > 4)
4043 argOffset = argAggregate->getSequence()[4]->getAsTyped();
4045 const int coordDimWithCmpVal = argCoord->getType().getVectorSize() + 1; // +1 for cmp
4047 // AST wants comparison value as one of the texture coordinates
4048 TOperator constructOp = EOpNull;
4049 switch (coordDimWithCmpVal) {
4050 // 1D can't happen: there's always at least 1 coordinate dimension + 1 cmp val
4051 case 2: constructOp = EOpConstructVec2; break;
4052 case 3: constructOp = EOpConstructVec3; break;
4053 case 4: constructOp = EOpConstructVec4; break;
4054 case 5: constructOp = EOpConstructVec4; break; // cubeArrayShadow, cmp value is separate arg.
4055 default: assert(0); break;
4058 TIntermAggregate* coordWithCmp = new TIntermAggregate(constructOp);
4059 coordWithCmp->getSequence().push_back(argCoord);
4060 if (coordDimWithCmpVal != 5) // cube array shadow is special.
4061 coordWithCmp->getSequence().push_back(argCmpVal);
4062 coordWithCmp->setLoc(loc);
4063 coordWithCmp->setType(TType(argCoord->getBasicType(), EvqTemporary, std::min(coordDimWithCmpVal, 4)));
4065 TOperator textureOp = (op == EOpMethodSampleCmpLevelZero ? EOpTextureLod : EOpTexture);
4066 if (argOffset != nullptr)
4067 textureOp = (op == EOpMethodSampleCmpLevelZero ? EOpTextureLodOffset : EOpTextureOffset);
4069 // Create combined sampler & texture op
4070 TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
4071 TIntermAggregate* txsample = new TIntermAggregate(textureOp);
4072 txsample->getSequence().push_back(txcombine);
4073 txsample->getSequence().push_back(coordWithCmp);
4075 if (coordDimWithCmpVal == 5) // cube array shadow is special: cmp val follows coord.
4076 txsample->getSequence().push_back(argCmpVal);
4078 // the LevelZero form uses 0 as an explicit LOD
4079 if (op == EOpMethodSampleCmpLevelZero)
4080 txsample->getSequence().push_back(intermediate.addConstantUnion(0.0, EbtFloat, loc, true));
4082 // Add offset if present
4083 if (argOffset != nullptr)
4084 txsample->getSequence().push_back(argOffset);
4086 txsample->setType(node->getType());
4087 txsample->setLoc(loc);
4095 TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
4096 TIntermTyped* argCoord = argAggregate->getSequence()[1]->getAsTyped();
4097 TIntermTyped* argOffset = nullptr;
4098 TIntermTyped* lodComponent = nullptr;
4099 TIntermTyped* coordSwizzle = nullptr;
4101 const TSampler& sampler = argTex->getType().getSampler();
4102 const bool isMS = sampler.isMultiSample();
4103 const bool isBuffer = sampler.dim == EsdBuffer;
4104 const bool isImage = sampler.isImage();
4105 const TBasicType coordBaseType = argCoord->getType().getBasicType();
4107 // Last component of coordinate is the mip level, for non-MS. we separate them here:
4108 if (isMS || isBuffer || isImage) {
4109 // MS, Buffer, and Image have no LOD
4110 coordSwizzle = argCoord;
4112 // Extract coordinate
4113 int swizzleSize = argCoord->getType().getVectorSize() - (isMS ? 0 : 1);
4114 TSwizzleSelectors<TVectorSelector> coordFields;
4115 for (int i = 0; i < swizzleSize; ++i)
4116 coordFields.push_back(i);
4117 TIntermTyped* coordIdx = intermediate.addSwizzle(coordFields, loc);
4118 coordSwizzle = intermediate.addIndex(EOpVectorSwizzle, argCoord, coordIdx, loc);
4119 coordSwizzle->setType(TType(coordBaseType, EvqTemporary, coordFields.size()));
4122 TIntermTyped* lodIdx = intermediate.addConstantUnion(coordFields.size(), loc, true);
4123 lodComponent = intermediate.addIndex(EOpIndexDirect, argCoord, lodIdx, loc);
4124 lodComponent->setType(TType(coordBaseType, EvqTemporary, 1));
4127 const int numArgs = (int)argAggregate->getSequence().size();
4128 const bool hasOffset = ((!isMS && numArgs == 3) || (isMS && numArgs == 4));
4130 // Create texel fetch
4131 const TOperator fetchOp = (isImage ? EOpImageLoad :
4132 hasOffset ? EOpTextureFetchOffset :
4134 TIntermAggregate* txfetch = new TIntermAggregate(fetchOp);
4136 // Build up the fetch
4137 txfetch->getSequence().push_back(argTex);
4138 txfetch->getSequence().push_back(coordSwizzle);
4141 // add 2DMS sample index
4142 TIntermTyped* argSampleIdx = argAggregate->getSequence()[2]->getAsTyped();
4143 txfetch->getSequence().push_back(argSampleIdx);
4144 } else if (isBuffer) {
4145 // Nothing else to do for buffers.
4146 } else if (isImage) {
4147 // Nothing else to do for images.
4149 // 2DMS and buffer have no LOD, but everything else does.
4150 txfetch->getSequence().push_back(lodComponent);
4153 // Obtain offset arg, if there is one.
4155 const int offsetPos = (isMS ? 3 : 2);
4156 argOffset = argAggregate->getSequence()[offsetPos]->getAsTyped();
4157 txfetch->getSequence().push_back(argOffset);
4160 node = convertReturn(txfetch, sampler);
4165 case EOpMethodSampleLevel:
4167 TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
4168 TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
4169 TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
4170 TIntermTyped* argLod = argAggregate->getSequence()[3]->getAsTyped();
4171 TIntermTyped* argOffset = nullptr;
4172 const TSampler& sampler = argTex->getType().getSampler();
4174 const int numArgs = (int)argAggregate->getSequence().size();
4176 if (numArgs == 5) // offset, if present
4177 argOffset = argAggregate->getSequence()[4]->getAsTyped();
4179 const TOperator textureOp = (argOffset == nullptr ? EOpTextureLod : EOpTextureLodOffset);
4180 TIntermAggregate* txsample = new TIntermAggregate(textureOp);
4182 TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
4184 txsample->getSequence().push_back(txcombine);
4185 txsample->getSequence().push_back(argCoord);
4186 txsample->getSequence().push_back(argLod);
4188 if (argOffset != nullptr)
4189 txsample->getSequence().push_back(argOffset);
4191 node = convertReturn(txsample, sampler);
4196 case EOpMethodGather:
4198 TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
4199 TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
4200 TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
4201 TIntermTyped* argOffset = nullptr;
4203 // Offset is optional
4204 if (argAggregate->getSequence().size() > 3)
4205 argOffset = argAggregate->getSequence()[3]->getAsTyped();
4207 const TOperator textureOp = (argOffset == nullptr ? EOpTextureGather : EOpTextureGatherOffset);
4208 TIntermAggregate* txgather = new TIntermAggregate(textureOp);
4210 TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
4212 txgather->getSequence().push_back(txcombine);
4213 txgather->getSequence().push_back(argCoord);
4214 // Offset if not given is implicitly channel 0 (red)
4216 if (argOffset != nullptr)
4217 txgather->getSequence().push_back(argOffset);
4219 txgather->setType(node->getType());
4220 txgather->setLoc(loc);
4226 case EOpMethodGatherRed: // fall through...
4227 case EOpMethodGatherGreen: // ...
4228 case EOpMethodGatherBlue: // ...
4229 case EOpMethodGatherAlpha: // ...
4230 case EOpMethodGatherCmpRed: // ...
4231 case EOpMethodGatherCmpGreen: // ...
4232 case EOpMethodGatherCmpBlue: // ...
4233 case EOpMethodGatherCmpAlpha: // ...
4235 int channel = 0; // the channel we are gathering
4236 int cmpValues = 0; // 1 if there is a compare value (handier than a bool below)
4239 case EOpMethodGatherCmpRed: cmpValues = 1; // fall through
4240 case EOpMethodGatherRed: channel = 0; break;
4241 case EOpMethodGatherCmpGreen: cmpValues = 1; // fall through
4242 case EOpMethodGatherGreen: channel = 1; break;
4243 case EOpMethodGatherCmpBlue: cmpValues = 1; // fall through
4244 case EOpMethodGatherBlue: channel = 2; break;
4245 case EOpMethodGatherCmpAlpha: cmpValues = 1; // fall through
4246 case EOpMethodGatherAlpha: channel = 3; break;
4247 default: assert(0); break;
4250 // For now, we have nothing to map the component-wise comparison forms
4251 // to, because neither GLSL nor SPIR-V has such an opcode. Issue an
4252 // unimplemented error instead. Most of the machinery is here if that
4253 // should ever become available. However, red can be passed through
4254 // to OpImageDrefGather. G/B/A cannot, because that opcode does not
4255 // accept a component.
4256 if (cmpValues != 0 && op != EOpMethodGatherCmpRed) {
4257 error(loc, "unimplemented: component-level gather compare", "", "");
4263 TIntermTyped* argTex = argAggregate->getSequence()[arg++]->getAsTyped();
4264 TIntermTyped* argSamp = argAggregate->getSequence()[arg++]->getAsTyped();
4265 TIntermTyped* argCoord = argAggregate->getSequence()[arg++]->getAsTyped();
4266 TIntermTyped* argOffset = nullptr;
4267 TIntermTyped* argOffsets[4] = { nullptr, nullptr, nullptr, nullptr };
4268 // TIntermTyped* argStatus = nullptr; // TODO: residency
4269 TIntermTyped* argCmp = nullptr;
4271 const TSamplerDim dim = argTex->getType().getSampler().dim;
4273 const int argSize = (int)argAggregate->getSequence().size();
4274 bool hasStatus = (argSize == (5+cmpValues) || argSize == (8+cmpValues));
4275 bool hasOffset1 = false;
4276 bool hasOffset4 = false;
4278 // Sampler argument should be a sampler.
4279 if (argSamp->getType().getBasicType() != EbtSampler) {
4280 error(loc, "expected: sampler type", "", "");
4284 // Cmp forms require SamplerComparisonState
4285 if (cmpValues > 0 && ! argSamp->getType().getSampler().isShadow()) {
4286 error(loc, "expected: SamplerComparisonState", "", "");
4290 // Only 2D forms can have offsets. Discover if we have 0, 1 or 4 offsets.
4292 hasOffset1 = (argSize == (4+cmpValues) || argSize == (5+cmpValues));
4293 hasOffset4 = (argSize == (7+cmpValues) || argSize == (8+cmpValues));
4296 assert(!(hasOffset1 && hasOffset4));
4298 TOperator textureOp = EOpTextureGather;
4300 // Compare forms have compare value
4302 argCmp = argOffset = argAggregate->getSequence()[arg++]->getAsTyped();
4304 // Some forms have single offset
4306 textureOp = EOpTextureGatherOffset; // single offset form
4307 argOffset = argAggregate->getSequence()[arg++]->getAsTyped();
4310 // Some forms have 4 gather offsets
4312 textureOp = EOpTextureGatherOffsets; // note plural, for 4 offset form
4313 for (int offsetNum = 0; offsetNum < 4; ++offsetNum)
4314 argOffsets[offsetNum] = argAggregate->getSequence()[arg++]->getAsTyped();
4319 // argStatus = argAggregate->getSequence()[arg++]->getAsTyped();
4320 error(loc, "unimplemented: residency status", "", "");
4324 TIntermAggregate* txgather = new TIntermAggregate(textureOp);
4325 TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
4327 TIntermTyped* argChannel = intermediate.addConstantUnion(channel, loc, true);
4329 txgather->getSequence().push_back(txcombine);
4330 txgather->getSequence().push_back(argCoord);
4332 // AST wants an array of 4 offsets, where HLSL has separate args. Here
4333 // we construct an array from the separate args.
4335 TType arrayType(EbtInt, EvqTemporary, 2);
4336 TArraySizes* arraySizes = new TArraySizes;
4337 arraySizes->addInnerSize(4);
4338 arrayType.transferArraySizes(arraySizes);
4340 TIntermAggregate* initList = new TIntermAggregate(EOpNull);
4342 for (int offsetNum = 0; offsetNum < 4; ++offsetNum)
4343 initList->getSequence().push_back(argOffsets[offsetNum]);
4345 argOffset = addConstructor(loc, initList, arrayType);
4348 // Add comparison value if we have one
4349 if (argCmp != nullptr)
4350 txgather->getSequence().push_back(argCmp);
4352 // Add offset (either 1, or an array of 4) if we have one
4353 if (argOffset != nullptr)
4354 txgather->getSequence().push_back(argOffset);
4356 // Add channel value if the sampler is not shadow
4357 if (! argSamp->getType().getSampler().isShadow())
4358 txgather->getSequence().push_back(argChannel);
4360 txgather->setType(node->getType());
4361 txgather->setLoc(loc);
4367 case EOpMethodCalculateLevelOfDetail:
4368 case EOpMethodCalculateLevelOfDetailUnclamped:
4370 TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
4371 TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
4372 TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
4374 TIntermAggregate* txquerylod = new TIntermAggregate(EOpTextureQueryLod);
4376 TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
4377 txquerylod->getSequence().push_back(txcombine);
4378 txquerylod->getSequence().push_back(argCoord);
4380 TIntermTyped* lodComponent = intermediate.addConstantUnion(
4381 op == EOpMethodCalculateLevelOfDetail ? 0 : 1,
4383 TIntermTyped* lodComponentIdx = intermediate.addIndex(EOpIndexDirect, txquerylod, lodComponent, loc);
4384 lodComponentIdx->setType(TType(EbtFloat, EvqTemporary, 1));
4385 node = lodComponentIdx;
4390 case EOpMethodGetSamplePosition:
4392 // TODO: this entire decomposition exists because there is not yet a way to query
4393 // the sample position directly through SPIR-V. Instead, we return fixed sample
4394 // positions for common cases. *** If the sample positions are set differently,
4395 // this will be wrong. ***
4397 TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
4398 TIntermTyped* argSampIdx = argAggregate->getSequence()[1]->getAsTyped();
4400 TIntermAggregate* samplesQuery = new TIntermAggregate(EOpImageQuerySamples);
4401 samplesQuery->getSequence().push_back(argTex);
4402 samplesQuery->setType(TType(EbtUint, EvqTemporary, 1));
4403 samplesQuery->setLoc(loc);
4405 TIntermAggregate* compoundStatement = nullptr;
4407 TVariable* outSampleCount = makeInternalVariable("@sampleCount", TType(EbtUint));
4408 outSampleCount->getWritableType().getQualifier().makeTemporary();
4409 TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, intermediate.addSymbol(*outSampleCount, loc),
4411 compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
4413 TIntermTyped* idxtest[4];
4415 // Create tests against 2, 4, 8, and 16 sample values
4417 for (int val = 2; val <= 16; val *= 2)
4419 intermediate.addBinaryNode(EOpEqual,
4420 intermediate.addSymbol(*outSampleCount, loc),
4421 intermediate.addConstantUnion(val, loc),
4422 loc, TType(EbtBool));
4424 const TOperator idxOp = (argSampIdx->getQualifier().storage == EvqConst) ? EOpIndexDirect : EOpIndexIndirect;
4426 // Create index ops into position arrays given sample index.
4427 // TODO: should it be clamped?
4428 TIntermTyped* index[4];
4430 for (int val = 2; val <= 16; val *= 2) {
4431 index[count] = intermediate.addIndex(idxOp, getSamplePosArray(val), argSampIdx, loc);
4432 index[count++]->setType(TType(EbtFloat, EvqTemporary, 2));
4435 // Create expression as:
4436 // (sampleCount == 2) ? pos2[idx] :
4437 // (sampleCount == 4) ? pos4[idx] :
4438 // (sampleCount == 8) ? pos8[idx] :
4439 // (sampleCount == 16) ? pos16[idx] : float2(0,0);
4440 TIntermTyped* test =
4441 intermediate.addSelection(idxtest[0], index[0],
4442 intermediate.addSelection(idxtest[1], index[1],
4443 intermediate.addSelection(idxtest[2], index[2],
4444 intermediate.addSelection(idxtest[3], index[3],
4445 getSamplePosArray(1), loc), loc), loc), loc);
4447 compoundStatement = intermediate.growAggregate(compoundStatement, test);
4448 compoundStatement->setOperator(EOpSequence);
4449 compoundStatement->setLoc(loc);
4450 compoundStatement->setType(TType(EbtFloat, EvqTemporary, 2));
4452 node = compoundStatement;
4457 case EOpSubpassLoad:
4459 const TIntermTyped* argSubpass =
4460 argAggregate ? argAggregate->getSequence()[0]->getAsTyped() :
4461 arguments->getAsTyped();
4463 const TSampler& sampler = argSubpass->getType().getSampler();
4465 // subpass load: the multisample form is overloaded. Here, we convert that to
4466 // the EOpSubpassLoadMS opcode.
4467 if (argAggregate != nullptr && argAggregate->getSequence().size() > 1)
4468 node->getAsOperator()->setOp(EOpSubpassLoadMS);
4470 node = convertReturn(node, sampler);
4477 break; // most pass through unchanged
4482 // Decompose geometry shader methods
4484 void HlslParseContext::decomposeGeometryMethods(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
4486 if (node == nullptr || !node->getAsOperator())
4489 const TOperator op = node->getAsOperator()->getOp();
4490 const TIntermAggregate* argAggregate = arguments ? arguments->getAsAggregate() : nullptr;
4493 case EOpMethodAppend:
4495 // Don't emit these for non-GS stage, since we won't have the gsStreamOutput symbol.
4496 if (language != EShLangGeometry) {
4501 TIntermAggregate* sequence = nullptr;
4502 TIntermAggregate* emit = new TIntermAggregate(EOpEmitVertex);
4505 emit->setType(TType(EbtVoid));
4507 TIntermTyped* data = argAggregate->getSequence()[1]->getAsTyped();
4509 // This will be patched in finalization during finalizeAppendMethods()
4510 sequence = intermediate.growAggregate(sequence, data, loc);
4511 sequence = intermediate.growAggregate(sequence, emit);
4513 sequence->setOperator(EOpSequence);
4514 sequence->setLoc(loc);
4515 sequence->setType(TType(EbtVoid));
4517 gsAppends.push_back({sequence, loc});
4523 case EOpMethodRestartStrip:
4525 // Don't emit these for non-GS stage, since we won't have the gsStreamOutput symbol.
4526 if (language != EShLangGeometry) {
4531 TIntermAggregate* cut = new TIntermAggregate(EOpEndPrimitive);
4533 cut->setType(TType(EbtVoid));
4539 break; // most pass through unchanged
4544 // Optionally decompose intrinsics to AST opcodes.
4546 void HlslParseContext::decomposeIntrinsic(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
4548 // Helper to find image data for image atomics:
4549 // OpImageLoad(image[idx])
4550 // We take the image load apart and add its params to the atomic op aggregate node
4551 const auto imageAtomicParams = [this, &loc, &node](TIntermAggregate* atomic, TIntermTyped* load) {
4552 TIntermAggregate* loadOp = load->getAsAggregate();
4553 if (loadOp == nullptr) {
4554 error(loc, "unknown image type in atomic operation", "", "");
4559 atomic->getSequence().push_back(loadOp->getSequence()[0]);
4560 atomic->getSequence().push_back(loadOp->getSequence()[1]);
4563 // Return true if this is an imageLoad, which we will change to an image atomic.
4564 const auto isImageParam = [](TIntermTyped* image) -> bool {
4565 TIntermAggregate* imageAggregate = image->getAsAggregate();
4566 return imageAggregate != nullptr && imageAggregate->getOp() == EOpImageLoad;
4569 const auto lookupBuiltinVariable = [&](const char* name, TBuiltInVariable builtin, TType& type) -> TIntermTyped* {
4570 TSymbol* symbol = symbolTable.find(name);
4571 if (nullptr == symbol) {
4572 type.getQualifier().builtIn = builtin;
4574 TVariable* variable = new TVariable(new TString(name), type);
4576 symbolTable.insert(*variable);
4578 symbol = symbolTable.find(name);
4579 assert(symbol && "Inserted symbol could not be found!");
4582 return intermediate.addSymbol(*(symbol->getAsVariable()), loc);
4585 // HLSL intrinsics can be pass through to native AST opcodes, or decomposed here to existing AST
4586 // opcodes for compatibility with existing software stacks.
4587 static const bool decomposeHlslIntrinsics = true;
4589 if (!decomposeHlslIntrinsics || !node || !node->getAsOperator())
4592 const TIntermAggregate* argAggregate = arguments ? arguments->getAsAggregate() : nullptr;
4593 TIntermUnary* fnUnary = node->getAsUnaryNode();
4594 const TOperator op = node->getAsOperator()->getOp();
4599 // mul(a,b) -> MatrixTimesMatrix, MatrixTimesVector, MatrixTimesScalar, VectorTimesScalar, Dot, Mul
4600 // Since we are treating HLSL rows like GLSL columns (the first matrix indirection),
4601 // we must reverse the operand order here. Hence, arg0 gets sequence[1], etc.
4602 TIntermTyped* arg0 = argAggregate->getSequence()[1]->getAsTyped();
4603 TIntermTyped* arg1 = argAggregate->getSequence()[0]->getAsTyped();
4605 if (arg0->isVector() && arg1->isVector()) { // vec * vec
4606 node->getAsAggregate()->setOperator(EOpDot);
4608 node = handleBinaryMath(loc, "mul", EOpMul, arg0, arg1);
4617 TIntermTyped* arg0 = fnUnary->getOperand();
4618 TBasicType type0 = arg0->getBasicType();
4619 TIntermTyped* one = intermediate.addConstantUnion(1, type0, loc, true);
4620 node = handleBinaryMath(loc, "rcp", EOpDiv, one, arg0);
4625 case EOpAny: // fall through
4628 TIntermTyped* typedArg = arguments->getAsTyped();
4630 // HLSL allows float/etc types here, and the SPIR-V opcode requires a bool.
4631 // We'll convert here. Note that for efficiency, we could add a smarter
4632 // decomposition for some type cases, e.g, maybe by decomposing a dot product.
4633 if (typedArg->getType().getBasicType() != EbtBool) {
4634 const TType boolType(EbtBool, EvqTemporary,
4635 typedArg->getVectorSize(),
4636 typedArg->getMatrixCols(),
4637 typedArg->getMatrixRows(),
4638 typedArg->isVector());
4640 typedArg = intermediate.addConversion(EOpConstructBool, boolType, typedArg);
4641 node->getAsUnaryNode()->setOperand(typedArg);
4649 // saturate(a) -> clamp(a,0,1)
4650 TIntermTyped* arg0 = fnUnary->getOperand();
4651 TBasicType type0 = arg0->getBasicType();
4652 TIntermAggregate* clamp = new TIntermAggregate(EOpClamp);
4654 clamp->getSequence().push_back(arg0);
4655 clamp->getSequence().push_back(intermediate.addConstantUnion(0, type0, loc, true));
4656 clamp->getSequence().push_back(intermediate.addConstantUnion(1, type0, loc, true));
4658 clamp->setType(node->getType());
4659 clamp->getWritableType().getQualifier().makeTemporary();
4667 // sincos(a,b,c) -> b = sin(a), c = cos(a)
4668 TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
4669 TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
4670 TIntermTyped* arg2 = argAggregate->getSequence()[2]->getAsTyped();
4672 TIntermTyped* sinStatement = handleUnaryMath(loc, "sin", EOpSin, arg0);
4673 TIntermTyped* cosStatement = handleUnaryMath(loc, "cos", EOpCos, arg0);
4674 TIntermTyped* sinAssign = intermediate.addAssign(EOpAssign, arg1, sinStatement, loc);
4675 TIntermTyped* cosAssign = intermediate.addAssign(EOpAssign, arg2, cosStatement, loc);
4677 TIntermAggregate* compoundStatement = intermediate.makeAggregate(sinAssign, loc);
4678 compoundStatement = intermediate.growAggregate(compoundStatement, cosAssign);
4679 compoundStatement->setOperator(EOpSequence);
4680 compoundStatement->setLoc(loc);
4681 compoundStatement->setType(TType(EbtVoid));
4683 node = compoundStatement;
4690 // clip(a) -> if (any(a<0)) discard;
4691 TIntermTyped* arg0 = fnUnary->getOperand();
4692 TBasicType type0 = arg0->getBasicType();
4693 TIntermTyped* compareNode = nullptr;
4695 // For non-scalars: per experiment with FXC compiler, discard if any component < 0.
4696 if (!arg0->isScalar()) {
4697 // component-wise compare: a < 0
4698 TIntermAggregate* less = new TIntermAggregate(EOpLessThan);
4699 less->getSequence().push_back(arg0);
4702 // make vec or mat of bool matching dimensions of input
4703 less->setType(TType(EbtBool, EvqTemporary,
4704 arg0->getType().getVectorSize(),
4705 arg0->getType().getMatrixCols(),
4706 arg0->getType().getMatrixRows(),
4707 arg0->getType().isVector()));
4709 // calculate # of components for comparison const
4710 const int constComponentCount =
4711 std::max(arg0->getType().getVectorSize(), 1) *
4712 std::max(arg0->getType().getMatrixCols(), 1) *
4713 std::max(arg0->getType().getMatrixRows(), 1);
4716 if (arg0->getType().isIntegerDomain())
4719 zero.setDConst(0.0);
4720 TConstUnionArray zeros(constComponentCount, zero);
4722 less->getSequence().push_back(intermediate.addConstantUnion(zeros, arg0->getType(), loc, true));
4724 compareNode = intermediate.addBuiltInFunctionCall(loc, EOpAny, true, less, TType(EbtBool));
4727 if (arg0->getType().isIntegerDomain())
4728 zero = intermediate.addConstantUnion(0, loc, true);
4730 zero = intermediate.addConstantUnion(0.0, type0, loc, true);
4731 compareNode = handleBinaryMath(loc, "clip", EOpLessThan, arg0, zero);
4734 TIntermBranch* killNode = intermediate.addBranch(EOpKill, loc);
4736 node = new TIntermSelection(compareNode, killNode, nullptr);
4744 // log10(a) -> log2(a) * 0.301029995663981 (== 1/log2(10))
4745 TIntermTyped* arg0 = fnUnary->getOperand();
4746 TIntermTyped* log2 = handleUnaryMath(loc, "log2", EOpLog2, arg0);
4747 TIntermTyped* base = intermediate.addConstantUnion(0.301029995663981f, EbtFloat, loc, true);
4749 node = handleBinaryMath(loc, "mul", EOpMul, log2, base);
4757 // dest.y = src0.y * src1.y;
4761 TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
4762 TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
4764 TIntermTyped* y = intermediate.addConstantUnion(1, loc, true);
4765 TIntermTyped* z = intermediate.addConstantUnion(2, loc, true);
4766 TIntermTyped* w = intermediate.addConstantUnion(3, loc, true);
4768 TIntermTyped* src0y = intermediate.addIndex(EOpIndexDirect, arg0, y, loc);
4769 TIntermTyped* src1y = intermediate.addIndex(EOpIndexDirect, arg1, y, loc);
4770 TIntermTyped* src0z = intermediate.addIndex(EOpIndexDirect, arg0, z, loc);
4771 TIntermTyped* src1w = intermediate.addIndex(EOpIndexDirect, arg1, w, loc);
4773 TIntermAggregate* dst = new TIntermAggregate(EOpConstructVec4);
4775 dst->getSequence().push_back(intermediate.addConstantUnion(1.0, EbtFloat, loc, true));
4776 dst->getSequence().push_back(handleBinaryMath(loc, "mul", EOpMul, src0y, src1y));
4777 dst->getSequence().push_back(src0z);
4778 dst->getSequence().push_back(src1w);
4779 dst->setType(TType(EbtFloat, EvqTemporary, 4));
4786 case EOpInterlockedAdd: // optional last argument (if present) is assigned from return value
4787 case EOpInterlockedMin: // ...
4788 case EOpInterlockedMax: // ...
4789 case EOpInterlockedAnd: // ...
4790 case EOpInterlockedOr: // ...
4791 case EOpInterlockedXor: // ...
4792 case EOpInterlockedExchange: // always has output arg
4794 TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped(); // dest
4795 TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped(); // value
4796 TIntermTyped* arg2 = nullptr;
4798 if (argAggregate->getSequence().size() > 2)
4799 arg2 = argAggregate->getSequence()[2]->getAsTyped();
4801 const bool isImage = isImageParam(arg0);
4802 const TOperator atomicOp = mapAtomicOp(loc, op, isImage);
4803 TIntermAggregate* atomic = new TIntermAggregate(atomicOp);
4804 atomic->setType(arg0->getType());
4805 atomic->getWritableType().getQualifier().makeTemporary();
4806 atomic->setLoc(loc);
4809 // orig_value = imageAtomicOp(image, loc, data)
4810 imageAtomicParams(atomic, arg0);
4811 atomic->getSequence().push_back(arg1);
4813 if (argAggregate->getSequence().size() > 2) {
4814 node = intermediate.addAssign(EOpAssign, arg2, atomic, loc);
4816 node = atomic; // no assignment needed, as there was no out var.
4819 // Normal memory variable:
4820 // arg0 = mem, arg1 = data, arg2(optional,out) = orig_value
4821 if (argAggregate->getSequence().size() > 2) {
4822 // optional output param is present. return value goes to arg2.
4823 atomic->getSequence().push_back(arg0);
4824 atomic->getSequence().push_back(arg1);
4826 node = intermediate.addAssign(EOpAssign, arg2, atomic, loc);
4828 // Set the matching operator. Since output is absent, this is all we need to do.
4829 node->getAsAggregate()->setOperator(atomicOp);
4830 node->setType(atomic->getType());
4837 case EOpInterlockedCompareExchange:
4839 TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped(); // dest
4840 TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped(); // cmp
4841 TIntermTyped* arg2 = argAggregate->getSequence()[2]->getAsTyped(); // value
4842 TIntermTyped* arg3 = argAggregate->getSequence()[3]->getAsTyped(); // orig
4844 const bool isImage = isImageParam(arg0);
4845 TIntermAggregate* atomic = new TIntermAggregate(mapAtomicOp(loc, op, isImage));
4846 atomic->setLoc(loc);
4847 atomic->setType(arg2->getType());
4848 atomic->getWritableType().getQualifier().makeTemporary();
4851 imageAtomicParams(atomic, arg0);
4853 atomic->getSequence().push_back(arg0);
4856 atomic->getSequence().push_back(arg1);
4857 atomic->getSequence().push_back(arg2);
4858 node = intermediate.addAssign(EOpAssign, arg3, atomic, loc);
4863 case EOpEvaluateAttributeSnapped:
4865 // SPIR-V InterpolateAtOffset uses float vec2 offset in pixels
4866 // HLSL uses int2 offset on a 16x16 grid in [-8..7] on x & y:
4867 // iU = (iU<<28)>>28
4868 // fU = ((float)iU)/16
4869 // Targets might handle this natively, in which case they can disable
4872 TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped(); // value
4873 TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped(); // offset
4875 TIntermTyped* i28 = intermediate.addConstantUnion(28, loc, true);
4876 TIntermTyped* iU = handleBinaryMath(loc, ">>", EOpRightShift,
4877 handleBinaryMath(loc, "<<", EOpLeftShift, arg1, i28),
4880 TIntermTyped* recip16 = intermediate.addConstantUnion((1.0/16.0), EbtFloat, loc, true);
4881 TIntermTyped* floatOffset = handleBinaryMath(loc, "mul", EOpMul,
4882 intermediate.addConversion(EOpConstructFloat,
4883 TType(EbtFloat, EvqTemporary, 2), iU),
4886 TIntermAggregate* interp = new TIntermAggregate(EOpInterpolateAtOffset);
4887 interp->getSequence().push_back(arg0);
4888 interp->getSequence().push_back(floatOffset);
4889 interp->setLoc(loc);
4890 interp->setType(arg0->getType());
4891 interp->getWritableType().getQualifier().makeTemporary();
4900 TIntermTyped* n_dot_l = argAggregate->getSequence()[0]->getAsTyped();
4901 TIntermTyped* n_dot_h = argAggregate->getSequence()[1]->getAsTyped();
4902 TIntermTyped* m = argAggregate->getSequence()[2]->getAsTyped();
4904 TIntermAggregate* dst = new TIntermAggregate(EOpConstructVec4);
4907 dst->getSequence().push_back(intermediate.addConstantUnion(1.0, EbtFloat, loc, true));
4910 TIntermTyped* zero = intermediate.addConstantUnion(0.0, EbtFloat, loc, true);
4911 TIntermAggregate* diffuse = new TIntermAggregate(EOpMax);
4912 diffuse->getSequence().push_back(n_dot_l);
4913 diffuse->getSequence().push_back(zero);
4914 diffuse->setLoc(loc);
4915 diffuse->setType(TType(EbtFloat));
4916 dst->getSequence().push_back(diffuse);
4919 TIntermAggregate* min_ndot = new TIntermAggregate(EOpMin);
4920 min_ndot->getSequence().push_back(n_dot_l);
4921 min_ndot->getSequence().push_back(n_dot_h);
4922 min_ndot->setLoc(loc);
4923 min_ndot->setType(TType(EbtFloat));
4925 TIntermTyped* compare = handleBinaryMath(loc, "<", EOpLessThan, min_ndot, zero);
4926 TIntermTyped* n_dot_h_m = handleBinaryMath(loc, "mul", EOpMul, n_dot_h, m); // n_dot_h * m
4928 dst->getSequence().push_back(intermediate.addSelection(compare, zero, n_dot_h_m, loc));
4931 dst->getSequence().push_back(intermediate.addConstantUnion(1.0, EbtFloat, loc, true));
4934 dst->setType(TType(EbtFloat, EvqTemporary, 4));
4941 // asdouble accepts two 32 bit ints. we can use EOpUint64BitsToDouble, but must
4942 // first construct a uint64.
4943 TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
4944 TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
4946 if (arg0->getType().isVector()) { // TODO: ...
4947 error(loc, "double2 conversion not implemented", "asdouble", "");
4951 TIntermAggregate* uint64 = new TIntermAggregate(EOpConstructUVec2);
4953 uint64->getSequence().push_back(arg0);
4954 uint64->getSequence().push_back(arg1);
4955 uint64->setType(TType(EbtUint, EvqTemporary, 2)); // convert 2 uints to a uint2
4956 uint64->setLoc(loc);
4958 // bitcast uint2 to a double
4959 TIntermTyped* convert = new TIntermUnary(EOpUint64BitsToDouble);
4960 convert->getAsUnaryNode()->setOperand(uint64);
4961 convert->setLoc(loc);
4962 convert->setType(TType(EbtDouble, EvqTemporary));
4970 // input uvecN with low 16 bits of each component holding a float16. convert to float32.
4971 TIntermTyped* argValue = node->getAsUnaryNode()->getOperand();
4972 TIntermTyped* zero = intermediate.addConstantUnion(0, loc, true);
4973 const int vecSize = argValue->getType().getVectorSize();
4975 TOperator constructOp = EOpNull;
4977 case 1: constructOp = EOpNull; break; // direct use, no construct needed
4978 case 2: constructOp = EOpConstructVec2; break;
4979 case 3: constructOp = EOpConstructVec3; break;
4980 case 4: constructOp = EOpConstructVec4; break;
4981 default: assert(0); break;
4984 // For scalar case, we don't need to construct another type.
4985 TIntermAggregate* result = (vecSize > 1) ? new TIntermAggregate(constructOp) : nullptr;
4988 result->setType(TType(EbtFloat, EvqTemporary, vecSize));
4989 result->setLoc(loc);
4992 for (int idx = 0; idx < vecSize; ++idx) {
4993 TIntermTyped* idxConst = intermediate.addConstantUnion(idx, loc, true);
4994 TIntermTyped* component = argValue->getType().isVector() ?
4995 intermediate.addIndex(EOpIndexDirect, argValue, idxConst, loc) : argValue;
4997 if (component != argValue)
4998 component->setType(TType(argValue->getBasicType(), EvqTemporary));
5000 TIntermTyped* unpackOp = new TIntermUnary(EOpUnpackHalf2x16);
5001 unpackOp->setType(TType(EbtFloat, EvqTemporary, 2));
5002 unpackOp->getAsUnaryNode()->setOperand(component);
5003 unpackOp->setLoc(loc);
5005 TIntermTyped* lowOrder = intermediate.addIndex(EOpIndexDirect, unpackOp, zero, loc);
5007 if (result != nullptr) {
5008 result->getSequence().push_back(lowOrder);
5020 // input floatN converted to 16 bit float in low order bits of each component of uintN
5021 TIntermTyped* argValue = node->getAsUnaryNode()->getOperand();
5023 TIntermTyped* zero = intermediate.addConstantUnion(0.0, EbtFloat, loc, true);
5024 const int vecSize = argValue->getType().getVectorSize();
5026 TOperator constructOp = EOpNull;
5028 case 1: constructOp = EOpNull; break; // direct use, no construct needed
5029 case 2: constructOp = EOpConstructUVec2; break;
5030 case 3: constructOp = EOpConstructUVec3; break;
5031 case 4: constructOp = EOpConstructUVec4; break;
5032 default: assert(0); break;
5035 // For scalar case, we don't need to construct another type.
5036 TIntermAggregate* result = (vecSize > 1) ? new TIntermAggregate(constructOp) : nullptr;
5039 result->setType(TType(EbtUint, EvqTemporary, vecSize));
5040 result->setLoc(loc);
5043 for (int idx = 0; idx < vecSize; ++idx) {
5044 TIntermTyped* idxConst = intermediate.addConstantUnion(idx, loc, true);
5045 TIntermTyped* component = argValue->getType().isVector() ?
5046 intermediate.addIndex(EOpIndexDirect, argValue, idxConst, loc) : argValue;
5048 if (component != argValue)
5049 component->setType(TType(argValue->getBasicType(), EvqTemporary));
5051 TIntermAggregate* vec2ComponentAndZero = new TIntermAggregate(EOpConstructVec2);
5052 vec2ComponentAndZero->getSequence().push_back(component);
5053 vec2ComponentAndZero->getSequence().push_back(zero);
5054 vec2ComponentAndZero->setType(TType(EbtFloat, EvqTemporary, 2));
5055 vec2ComponentAndZero->setLoc(loc);
5057 TIntermTyped* packOp = new TIntermUnary(EOpPackHalf2x16);
5058 packOp->getAsUnaryNode()->setOperand(vec2ComponentAndZero);
5059 packOp->setLoc(loc);
5060 packOp->setType(TType(EbtUint, EvqTemporary));
5062 if (result != nullptr) {
5063 result->getSequence().push_back(packOp);
5073 case EOpD3DCOLORtoUBYTE4:
5075 // ivec4 ( x.zyxw * 255.001953 );
5076 TIntermTyped* arg0 = node->getAsUnaryNode()->getOperand();
5077 TSwizzleSelectors<TVectorSelector> selectors;
5078 selectors.push_back(2);
5079 selectors.push_back(1);
5080 selectors.push_back(0);
5081 selectors.push_back(3);
5082 TIntermTyped* swizzleIdx = intermediate.addSwizzle(selectors, loc);
5083 TIntermTyped* swizzled = intermediate.addIndex(EOpVectorSwizzle, arg0, swizzleIdx, loc);
5084 swizzled->setType(arg0->getType());
5085 swizzled->getWritableType().getQualifier().makeTemporary();
5087 TIntermTyped* conversion = intermediate.addConstantUnion(255.001953f, EbtFloat, loc, true);
5088 TIntermTyped* rangeConverted = handleBinaryMath(loc, "mul", EOpMul, conversion, swizzled);
5089 rangeConverted->setType(arg0->getType());
5090 rangeConverted->getWritableType().getQualifier().makeTemporary();
5092 node = intermediate.addConversion(EOpConstructInt, TType(EbtInt, EvqTemporary, 4), rangeConverted);
5094 node->setType(TType(EbtInt, EvqTemporary, 4));
5100 // Since OPIsFinite in SPIR-V is only supported with the Kernel capability, we translate
5101 // it to !isnan && !isinf
5103 TIntermTyped* arg0 = node->getAsUnaryNode()->getOperand();
5105 // We'll make a temporary in case the RHS is cmoplex
5106 TVariable* tempArg = makeInternalVariable("@finitetmp", arg0->getType());
5107 tempArg->getWritableType().getQualifier().makeTemporary();
5109 TIntermTyped* tmpArgAssign = intermediate.addAssign(EOpAssign,
5110 intermediate.addSymbol(*tempArg, loc),
5113 TIntermAggregate* compoundStatement = intermediate.makeAggregate(tmpArgAssign, loc);
5115 const TType boolType(EbtBool, EvqTemporary, arg0->getVectorSize(), arg0->getMatrixCols(),
5116 arg0->getMatrixRows());
5118 TIntermTyped* isnan = handleUnaryMath(loc, "isnan", EOpIsNan, intermediate.addSymbol(*tempArg, loc));
5119 isnan->setType(boolType);
5121 TIntermTyped* notnan = handleUnaryMath(loc, "!", EOpLogicalNot, isnan);
5122 notnan->setType(boolType);
5124 TIntermTyped* isinf = handleUnaryMath(loc, "isinf", EOpIsInf, intermediate.addSymbol(*tempArg, loc));
5125 isinf->setType(boolType);
5127 TIntermTyped* notinf = handleUnaryMath(loc, "!", EOpLogicalNot, isinf);
5128 notinf->setType(boolType);
5130 TIntermTyped* andNode = handleBinaryMath(loc, "and", EOpLogicalAnd, notnan, notinf);
5131 andNode->setType(boolType);
5133 compoundStatement = intermediate.growAggregate(compoundStatement, andNode);
5134 compoundStatement->setOperator(EOpSequence);
5135 compoundStatement->setLoc(loc);
5136 compoundStatement->setType(boolType);
5138 node = compoundStatement;
5142 case EOpWaveGetLaneCount:
5144 // Mapped to gl_SubgroupSize builtin (We preprend @ to the symbol
5145 // so that it inhabits the symbol table, but has a user-invalid name
5146 // in-case some source HLSL defined the symbol also).
5147 TType type(EbtUint, EvqVaryingIn);
5148 node = lookupBuiltinVariable("@gl_SubgroupSize", EbvSubgroupSize2, type);
5151 case EOpWaveGetLaneIndex:
5153 // Mapped to gl_SubgroupInvocationID builtin (We preprend @ to the
5154 // symbol so that it inhabits the symbol table, but has a
5155 // user-invalid name in-case some source HLSL defined the symbol
5157 TType type(EbtUint, EvqVaryingIn);
5158 node = lookupBuiltinVariable("@gl_SubgroupInvocationID", EbvSubgroupInvocation2, type);
5161 case EOpWaveActiveCountBits:
5163 // Mapped to subgroupBallotBitCount(subgroupBallot()) builtin
5166 TType uvec4Type(EbtUint, EvqTemporary, 4);
5168 // Get the uvec4 return from subgroupBallot().
5169 TIntermTyped* res = intermediate.addBuiltInFunctionCall(loc,
5170 EOpSubgroupBallot, true, arguments, uvec4Type);
5173 TType uintType(EbtUint, EvqTemporary);
5175 node = intermediate.addBuiltInFunctionCall(loc,
5176 EOpSubgroupBallotBitCount, true, res, uintType);
5180 case EOpWavePrefixCountBits:
5182 // Mapped to subgroupBallotInclusiveBitCount(subgroupBallot())
5186 TType uvec4Type(EbtUint, EvqTemporary, 4);
5188 // Get the uvec4 return from subgroupBallot().
5189 TIntermTyped* res = intermediate.addBuiltInFunctionCall(loc,
5190 EOpSubgroupBallot, true, arguments, uvec4Type);
5193 TType uintType(EbtUint, EvqTemporary);
5195 node = intermediate.addBuiltInFunctionCall(loc,
5196 EOpSubgroupBallotInclusiveBitCount, true, res, uintType);
5202 break; // most pass through unchanged
5207 // Handle seeing function call syntax in the grammar, which could be any of
5208 // - .length() method
5210 // - a call to a built-in function mapped to an operator
5211 // - a call to a built-in function that will remain a function call (e.g., texturing)
5213 // - subroutine call (not implemented yet)
5215 TIntermTyped* HlslParseContext::handleFunctionCall(const TSourceLoc& loc, TFunction* function, TIntermTyped* arguments)
5217 TIntermTyped* result = nullptr;
5219 TOperator op = function->getBuiltInOp();
5220 if (op != EOpNull) {
5222 // Then this should be a constructor.
5223 // Don't go through the symbol table for constructors.
5224 // Their parameters will be verified algorithmically.
5226 TType type(EbtVoid); // use this to get the type back
5227 if (! constructorError(loc, arguments, *function, op, type)) {
5229 // It's a constructor, of type 'type'.
5231 result = handleConstructor(loc, arguments, type);
5232 if (result == nullptr) {
5233 error(loc, "cannot construct with these arguments", type.getCompleteString().c_str(), "");
5239 // Find it in the symbol table.
5241 const TFunction* fnCandidate = nullptr;
5242 bool builtIn = false;
5245 // For mat mul, the situation is unusual: we have to compare vector sizes to mat row or col sizes,
5246 // and clamp the opposite arg. Since that's complex, we farm it off to a separate method.
5247 // It doesn't naturally fall out of processing an argument at a time in isolation.
5248 if (function->getName() == "mul")
5249 addGenMulArgumentConversion(loc, *function, arguments);
5251 TIntermAggregate* aggregate = arguments ? arguments->getAsAggregate() : nullptr;
5253 // TODO: this needs improvement: there's no way at present to look up a signature in
5254 // the symbol table for an arbitrary type. This is a temporary hack until that ability exists.
5255 // It will have false positives, since it doesn't check arg counts or types.
5257 // Check if first argument is struct buffer type. It may be an aggregate or a symbol, so we
5258 // look for either case.
5260 TIntermTyped* arg0 = nullptr;
5262 if (aggregate && aggregate->getSequence().size() > 0)
5263 arg0 = aggregate->getSequence()[0]->getAsTyped();
5264 else if (arguments->getAsSymbolNode())
5265 arg0 = arguments->getAsSymbolNode();
5267 if (arg0 != nullptr && isStructBufferType(arg0->getType())) {
5268 static const int methodPrefixSize = sizeof(BUILTIN_PREFIX)-1;
5270 if (function->getName().length() > methodPrefixSize &&
5271 isStructBufferMethod(function->getName().substr(methodPrefixSize))) {
5272 const TString mangle = function->getName() + "(";
5273 TSymbol* symbol = symbolTable.find(mangle, &builtIn);
5276 fnCandidate = symbol->getAsFunction();
5281 if (fnCandidate == nullptr)
5282 fnCandidate = findFunction(loc, *function, builtIn, thisDepth, arguments);
5285 // This is a declared function that might map to
5286 // - a built-in operator,
5287 // - a built-in function not mapped to an operator, or
5288 // - a user function.
5290 // Error check for a function requiring specific extensions present.
5291 if (builtIn && fnCandidate->getNumExtensions())
5292 requireExtensions(loc, fnCandidate->getNumExtensions(), fnCandidate->getExtensions(),
5293 fnCandidate->getName().c_str());
5295 // turn an implicit member-function resolution into an explicit call
5298 callerName = fnCandidate->getMangledName();
5300 // get the explicit (full) name of the function
5301 callerName = currentTypePrefix[currentTypePrefix.size() - thisDepth];
5302 callerName += fnCandidate->getMangledName();
5303 // insert the implicit calling argument
5304 pushFrontArguments(intermediate.addSymbol(*getImplicitThis(thisDepth)), arguments);
5307 // Convert 'in' arguments, so that types match.
5308 // However, skip those that need expansion, that is covered next.
5310 addInputArgumentConversions(*fnCandidate, arguments);
5312 // Expand arguments. Some arguments must physically expand to a different set
5313 // than what the shader declared and passes.
5314 if (arguments && !builtIn)
5315 expandArguments(loc, *fnCandidate, arguments);
5317 // Expansion may have changed the form of arguments
5318 aggregate = arguments ? arguments->getAsAggregate() : nullptr;
5320 op = fnCandidate->getBuiltInOp();
5321 if (builtIn && op != EOpNull) {
5322 // A function call mapped to a built-in operation.
5323 result = intermediate.addBuiltInFunctionCall(loc, op, fnCandidate->getParamCount() == 1, arguments,
5324 fnCandidate->getType());
5325 if (result == nullptr) {
5326 error(arguments->getLoc(), " wrong operand type", "Internal Error",
5327 "built in unary operator function. Type: %s",
5328 static_cast<TIntermTyped*>(arguments)->getCompleteString().c_str());
5329 } else if (result->getAsOperator()) {
5330 builtInOpCheck(loc, *fnCandidate, *result->getAsOperator());
5333 // This is a function call not mapped to built-in operator.
5334 // It could still be a built-in function, but only if PureOperatorBuiltins == false.
5335 result = intermediate.setAggregateOperator(arguments, EOpFunctionCall, fnCandidate->getType(), loc);
5336 TIntermAggregate* call = result->getAsAggregate();
5337 call->setName(callerName);
5339 // this is how we know whether the given function is a built-in function or a user-defined function
5340 // if builtIn == false, it's a userDefined -> could be an overloaded built-in function also
5341 // if builtIn == true, it's definitely a built-in function with EOpNull
5343 call->setUserDefined();
5344 intermediate.addToCallGraph(infoSink, currentCaller, callerName);
5348 // for decompositions, since we want to operate on the function node, not the aggregate holding
5349 // output conversions.
5350 const TIntermTyped* fnNode = result;
5352 decomposeStructBufferMethods(loc, result, arguments); // HLSL->AST struct buffer method decompositions
5353 decomposeIntrinsic(loc, result, arguments); // HLSL->AST intrinsic decompositions
5354 decomposeSampleMethods(loc, result, arguments); // HLSL->AST sample method decompositions
5355 decomposeGeometryMethods(loc, result, arguments); // HLSL->AST geometry method decompositions
5357 // Create the qualifier list, carried in the AST for the call.
5358 // Because some arguments expand to multiple arguments, the qualifier list will
5359 // be longer than the formal parameter list.
5360 if (result == fnNode && result->getAsAggregate()) {
5361 TQualifierList& qualifierList = result->getAsAggregate()->getQualifierList();
5362 for (int i = 0; i < fnCandidate->getParamCount(); ++i) {
5363 TStorageQualifier qual = (*fnCandidate)[i].type->getQualifier().storage;
5364 if (hasStructBuffCounter(*(*fnCandidate)[i].type)) {
5365 // add buffer and counter buffer argument qualifier
5366 qualifierList.push_back(qual);
5367 qualifierList.push_back(qual);
5368 } else if (shouldFlatten(*(*fnCandidate)[i].type, (*fnCandidate)[i].type->getQualifier().storage,
5370 // add structure member expansion
5371 for (int memb = 0; memb < (int)(*fnCandidate)[i].type->getStruct()->size(); ++memb)
5372 qualifierList.push_back(qual);
5375 qualifierList.push_back(qual);
5380 // Convert 'out' arguments. If it was a constant folded built-in, it won't be an aggregate anymore.
5381 // Built-ins with a single argument aren't called with an aggregate, but they also don't have an output.
5382 // Also, build the qualifier list for user function calls, which are always called with an aggregate.
5383 // We don't do this is if there has been a decomposition, which will have added its own conversions
5384 // for output parameters.
5385 if (result == fnNode && result->getAsAggregate())
5386 result = addOutputArgumentConversions(*fnCandidate, *result->getAsOperator());
5390 // generic error recovery
5391 // TODO: simplification: localize all the error recoveries that look like this, and taking type into account to
5393 if (result == nullptr)
5394 result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
5399 // An initial argument list is difficult: it can be null, or a single node,
5400 // or an aggregate if more than one argument. Add one to the front, maintaining
5401 // this lack of uniformity.
5402 void HlslParseContext::pushFrontArguments(TIntermTyped* front, TIntermTyped*& arguments)
5404 if (arguments == nullptr)
5406 else if (arguments->getAsAggregate() != nullptr)
5407 arguments->getAsAggregate()->getSequence().insert(arguments->getAsAggregate()->getSequence().begin(), front);
5409 arguments = intermediate.growAggregate(front, arguments);
5413 // HLSL allows mismatched dimensions on vec*mat, mat*vec, vec*vec, and mat*mat. This is a
5414 // situation not well suited to resolution in intrinsic selection, but we can do so here, since we
5415 // can look at both arguments insert explicit shape changes if required.
5417 void HlslParseContext::addGenMulArgumentConversion(const TSourceLoc& loc, TFunction& call, TIntermTyped*& args)
5419 TIntermAggregate* argAggregate = args ? args->getAsAggregate() : nullptr;
5421 if (argAggregate == nullptr || argAggregate->getSequence().size() != 2) {
5422 // It really ought to have two arguments.
5423 error(loc, "expected: mul arguments", "", "");
5427 TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
5428 TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
5430 if (arg0->isVector() && arg1->isVector()) {
5432 // vec * vec: it's handled during intrinsic selection, so while we could do it here,
5433 // we can also ignore it, which is easier.
5434 } else if (arg0->isVector() && arg1->isMatrix()) {
5435 // vec * mat: we clamp the vec if the mat col is smaller, else clamp the mat col.
5436 if (arg0->getVectorSize() < arg1->getMatrixCols()) {
5437 // vec is smaller, so truncate larger mat dimension
5438 const TType truncType(arg1->getBasicType(), arg1->getQualifier().storage, arg1->getQualifier().precision,
5439 0, arg0->getVectorSize(), arg1->getMatrixRows());
5440 arg1 = addConstructor(loc, arg1, truncType);
5441 } else if (arg0->getVectorSize() > arg1->getMatrixCols()) {
5442 // vec is larger, so truncate vec to mat size
5443 const TType truncType(arg0->getBasicType(), arg0->getQualifier().storage, arg0->getQualifier().precision,
5444 arg1->getMatrixCols());
5445 arg0 = addConstructor(loc, arg0, truncType);
5447 } else if (arg0->isMatrix() && arg1->isVector()) {
5448 // mat * vec: we clamp the vec if the mat col is smaller, else clamp the mat col.
5449 if (arg1->getVectorSize() < arg0->getMatrixRows()) {
5450 // vec is smaller, so truncate larger mat dimension
5451 const TType truncType(arg0->getBasicType(), arg0->getQualifier().storage, arg0->getQualifier().precision,
5452 0, arg0->getMatrixCols(), arg1->getVectorSize());
5453 arg0 = addConstructor(loc, arg0, truncType);
5454 } else if (arg1->getVectorSize() > arg0->getMatrixRows()) {
5455 // vec is larger, so truncate vec to mat size
5456 const TType truncType(arg1->getBasicType(), arg1->getQualifier().storage, arg1->getQualifier().precision,
5457 arg0->getMatrixRows());
5458 arg1 = addConstructor(loc, arg1, truncType);
5460 } else if (arg0->isMatrix() && arg1->isMatrix()) {
5461 // mat * mat: we clamp the smaller inner dimension to match the other matrix size.
5462 // Remember, HLSL Mrc = GLSL/SPIRV Mcr.
5463 if (arg0->getMatrixRows() > arg1->getMatrixCols()) {
5464 const TType truncType(arg0->getBasicType(), arg0->getQualifier().storage, arg0->getQualifier().precision,
5465 0, arg0->getMatrixCols(), arg1->getMatrixCols());
5466 arg0 = addConstructor(loc, arg0, truncType);
5467 } else if (arg0->getMatrixRows() < arg1->getMatrixCols()) {
5468 const TType truncType(arg1->getBasicType(), arg1->getQualifier().storage, arg1->getQualifier().precision,
5469 0, arg0->getMatrixRows(), arg1->getMatrixRows());
5470 arg1 = addConstructor(loc, arg1, truncType);
5473 // It's something with scalars: we'll just leave it alone. Function selection will handle it
5477 // Warn if we altered one of the arguments
5478 if (arg0 != argAggregate->getSequence()[0] || arg1 != argAggregate->getSequence()[1])
5479 warn(loc, "mul() matrix size mismatch", "", "");
5481 // Put arguments back. (They might be unchanged, in which case this is harmless).
5482 argAggregate->getSequence()[0] = arg0;
5483 argAggregate->getSequence()[1] = arg1;
5485 call[0].type = &arg0->getWritableType();
5486 call[1].type = &arg1->getWritableType();
5490 // Add any needed implicit conversions for function-call arguments to input parameters.
5492 void HlslParseContext::addInputArgumentConversions(const TFunction& function, TIntermTyped*& arguments)
5494 TIntermAggregate* aggregate = arguments->getAsAggregate();
5496 // Replace a single argument with a single argument.
5497 const auto setArg = [&](int paramNum, TIntermTyped* arg) {
5498 if (function.getParamCount() == 1)
5501 if (aggregate == nullptr)
5504 aggregate->getSequence()[paramNum] = arg;
5508 // Process each argument's conversion
5509 for (int param = 0; param < function.getParamCount(); ++param) {
5510 if (! function[param].type->getQualifier().isParamInput())
5513 // At this early point there is a slight ambiguity between whether an aggregate 'arguments'
5514 // is the single argument itself or its children are the arguments. Only one argument
5515 // means take 'arguments' itself as the one argument.
5516 TIntermTyped* arg = function.getParamCount() == 1
5517 ? arguments->getAsTyped()
5519 aggregate->getSequence()[param]->getAsTyped() :
5520 arguments->getAsTyped());
5521 if (*function[param].type != arg->getType()) {
5522 // In-qualified arguments just need an extra node added above the argument to
5523 // convert to the correct type.
5524 TIntermTyped* convArg = intermediate.addConversion(EOpFunctionCall, *function[param].type, arg);
5525 if (convArg != nullptr)
5526 convArg = intermediate.addUniShapeConversion(EOpFunctionCall, *function[param].type, convArg);
5527 if (convArg != nullptr)
5528 setArg(param, convArg);
5530 error(arg->getLoc(), "cannot convert input argument, argument", "", "%d", param);
5532 if (wasFlattened(arg)) {
5533 // If both formal and calling arg are to be flattened, leave that to argument
5534 // expansion, not conversion.
5535 if (!shouldFlatten(*function[param].type, function[param].type->getQualifier().storage, true)) {
5536 // Will make a two-level subtree.
5537 // The deepest will copy member-by-member to build the structure to pass.
5538 // The level above that will be a two-operand EOpComma sequence that follows the copy by the
5540 TVariable* internalAggregate = makeInternalVariable("aggShadow", *function[param].type);
5541 internalAggregate->getWritableType().getQualifier().makeTemporary();
5542 TIntermSymbol* internalSymbolNode = new TIntermSymbol(internalAggregate->getUniqueId(),
5543 internalAggregate->getName(),
5544 internalAggregate->getType());
5545 internalSymbolNode->setLoc(arg->getLoc());
5546 // This makes the deepest level, the member-wise copy
5547 TIntermAggregate* assignAgg = handleAssign(arg->getLoc(), EOpAssign,
5548 internalSymbolNode, arg)->getAsAggregate();
5550 // Now, pair that with the resulting aggregate.
5551 assignAgg = intermediate.growAggregate(assignAgg, internalSymbolNode, arg->getLoc());
5552 assignAgg->setOperator(EOpComma);
5553 assignAgg->setType(internalAggregate->getType());
5554 setArg(param, assignAgg);
5562 // Add any needed implicit expansion of calling arguments from what the shader listed to what's
5563 // internally needed for the AST (given the constraints downstream).
5565 void HlslParseContext::expandArguments(const TSourceLoc& loc, const TFunction& function, TIntermTyped*& arguments)
5567 TIntermAggregate* aggregate = arguments->getAsAggregate();
5568 int functionParamNumberOffset = 0;
5570 // Replace a single argument with a single argument.
5571 const auto setArg = [&](int paramNum, TIntermTyped* arg) {
5572 if (function.getParamCount() + functionParamNumberOffset == 1)
5575 if (aggregate == nullptr)
5578 aggregate->getSequence()[paramNum] = arg;
5582 // Replace a single argument with a list of arguments
5583 const auto setArgList = [&](int paramNum, const TVector<TIntermTyped*>& args) {
5584 if (args.size() == 1)
5585 setArg(paramNum, args.front());
5586 else if (args.size() > 1) {
5587 if (function.getParamCount() + functionParamNumberOffset == 1) {
5588 arguments = intermediate.makeAggregate(args.front());
5589 std::for_each(args.begin() + 1, args.end(),
5590 [&](TIntermTyped* arg) {
5591 arguments = intermediate.growAggregate(arguments, arg);
5594 auto it = aggregate->getSequence().erase(aggregate->getSequence().begin() + paramNum);
5595 aggregate->getSequence().insert(it, args.begin(), args.end());
5597 functionParamNumberOffset += (int)(args.size() - 1);
5601 // Process each argument's conversion
5602 for (int param = 0; param < function.getParamCount(); ++param) {
5603 // At this early point there is a slight ambiguity between whether an aggregate 'arguments'
5604 // is the single argument itself or its children are the arguments. Only one argument
5605 // means take 'arguments' itself as the one argument.
5606 TIntermTyped* arg = function.getParamCount() == 1
5607 ? arguments->getAsTyped()
5609 aggregate->getSequence()[param + functionParamNumberOffset]->getAsTyped() :
5610 arguments->getAsTyped());
5612 if (wasFlattened(arg) && shouldFlatten(*function[param].type, function[param].type->getQualifier().storage, true)) {
5613 // Need to pass the structure members instead of the structure.
5614 TVector<TIntermTyped*> memberArgs;
5615 for (int memb = 0; memb < (int)arg->getType().getStruct()->size(); ++memb)
5616 memberArgs.push_back(flattenAccess(arg, memb));
5617 setArgList(param + functionParamNumberOffset, memberArgs);
5621 // TODO: if we need both hidden counter args (below) and struct expansion (above)
5622 // the two algorithms need to be merged: Each assumes the list starts out 1:1 between
5623 // parameters and arguments.
5625 // If any argument is a pass-by-reference struct buffer with an associated counter
5626 // buffer, we have to add another hidden parameter for that counter.
5628 addStructBuffArguments(loc, aggregate);
5632 // Add any needed implicit output conversions for function-call arguments. This
5633 // can require a new tree topology, complicated further by whether the function
5634 // has a return value.
5636 // Returns a node of a subtree that evaluates to the return value of the function.
5638 TIntermTyped* HlslParseContext::addOutputArgumentConversions(const TFunction& function, TIntermOperator& intermNode)
5640 assert (intermNode.getAsAggregate() != nullptr || intermNode.getAsUnaryNode() != nullptr);
5642 const TSourceLoc& loc = intermNode.getLoc();
5644 TIntermSequence argSequence; // temp sequence for unary node args
5646 if (intermNode.getAsUnaryNode())
5647 argSequence.push_back(intermNode.getAsUnaryNode()->getOperand());
5649 TIntermSequence& arguments = argSequence.empty() ? intermNode.getAsAggregate()->getSequence() : argSequence;
5651 const auto needsConversion = [&](int argNum) {
5652 return function[argNum].type->getQualifier().isParamOutput() &&
5653 (*function[argNum].type != arguments[argNum]->getAsTyped()->getType() ||
5654 shouldConvertLValue(arguments[argNum]) ||
5655 wasFlattened(arguments[argNum]->getAsTyped()));
5658 // Will there be any output conversions?
5659 bool outputConversions = false;
5660 for (int i = 0; i < function.getParamCount(); ++i) {
5661 if (needsConversion(i)) {
5662 outputConversions = true;
5667 if (! outputConversions)
5670 // Setup for the new tree, if needed:
5672 // Output conversions need a different tree topology.
5673 // Out-qualified arguments need a temporary of the correct type, with the call
5674 // followed by an assignment of the temporary to the original argument:
5675 // void: function(arg, ...) -> ( function(tempArg, ...), arg = tempArg, ...)
5676 // ret = function(arg, ...) -> ret = (tempRet = function(tempArg, ...), arg = tempArg, ..., tempRet)
5677 // Where the "tempArg" type needs no conversion as an argument, but will convert on assignment.
5678 TIntermTyped* conversionTree = nullptr;
5679 TVariable* tempRet = nullptr;
5680 if (intermNode.getBasicType() != EbtVoid) {
5681 // do the "tempRet = function(...), " bit from above
5682 tempRet = makeInternalVariable("tempReturn", intermNode.getType());
5683 TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, loc);
5684 conversionTree = intermediate.addAssign(EOpAssign, tempRetNode, &intermNode, loc);
5686 conversionTree = &intermNode;
5688 conversionTree = intermediate.makeAggregate(conversionTree);
5690 // Process each argument's conversion
5691 for (int i = 0; i < function.getParamCount(); ++i) {
5692 if (needsConversion(i)) {
5693 // Out-qualified arguments needing conversion need to use the topology setup above.
5694 // Do the " ...(tempArg, ...), arg = tempArg" bit from above.
5696 // Make a temporary for what the function expects the argument to look like.
5697 TVariable* tempArg = makeInternalVariable("tempArg", *function[i].type);
5698 tempArg->getWritableType().getQualifier().makeTemporary();
5699 TIntermSymbol* tempArgNode = intermediate.addSymbol(*tempArg, loc);
5701 // This makes the deepest level, the member-wise copy
5702 TIntermTyped* tempAssign = handleAssign(arguments[i]->getLoc(), EOpAssign, arguments[i]->getAsTyped(),
5704 tempAssign = handleLvalue(arguments[i]->getLoc(), "assign", tempAssign);
5705 conversionTree = intermediate.growAggregate(conversionTree, tempAssign, arguments[i]->getLoc());
5707 // replace the argument with another node for the same tempArg variable
5708 arguments[i] = intermediate.addSymbol(*tempArg, loc);
5712 // Finalize the tree topology (see bigger comment above).
5714 // do the "..., tempRet" bit from above
5715 TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, loc);
5716 conversionTree = intermediate.growAggregate(conversionTree, tempRetNode, loc);
5719 conversionTree = intermediate.setAggregateOperator(conversionTree, EOpComma, intermNode.getType(), loc);
5721 return conversionTree;
5725 // Add any needed "hidden" counter buffer arguments for function calls.
5727 // Modifies the 'aggregate' argument if needed. Otherwise, is no-op.
5729 void HlslParseContext::addStructBuffArguments(const TSourceLoc& loc, TIntermAggregate*& aggregate)
5731 // See if there are any SB types with counters.
5732 const bool hasStructBuffArg =
5733 std::any_of(aggregate->getSequence().begin(),
5734 aggregate->getSequence().end(),
5735 [this](const TIntermNode* node) {
5736 return (node->getAsTyped() != nullptr) && hasStructBuffCounter(node->getAsTyped()->getType());
5739 // Nothing to do, if we didn't find one.
5740 if (! hasStructBuffArg)
5743 TIntermSequence argsWithCounterBuffers;
5745 for (int param = 0; param < int(aggregate->getSequence().size()); ++param) {
5746 argsWithCounterBuffers.push_back(aggregate->getSequence()[param]);
5748 if (hasStructBuffCounter(aggregate->getSequence()[param]->getAsTyped()->getType())) {
5749 const TIntermSymbol* blockSym = aggregate->getSequence()[param]->getAsSymbolNode();
5750 if (blockSym != nullptr) {
5752 counterBufferType(loc, counterType);
5754 const TString counterBlockName(intermediate.addCounterBufferName(blockSym->getName()));
5756 TVariable* variable = makeInternalVariable(counterBlockName, counterType);
5758 // Mark this buffer's counter block as being in use
5759 structBufferCounter[counterBlockName] = true;
5761 TIntermSymbol* sym = intermediate.addSymbol(*variable, loc);
5762 argsWithCounterBuffers.push_back(sym);
5767 // Swap with the temp list we've built up.
5768 aggregate->getSequence().swap(argsWithCounterBuffers);
5773 // Do additional checking of built-in function calls that is not caught
5774 // by normal semantic checks on argument type, extension tagging, etc.
5776 // Assumes there has been a semantically correct match to a built-in function prototype.
5778 void HlslParseContext::builtInOpCheck(const TSourceLoc& loc, const TFunction& fnCandidate, TIntermOperator& callNode)
5780 // Set up convenience accessors to the argument(s). There is almost always
5781 // multiple arguments for the cases below, but when there might be one,
5782 // check the unaryArg first.
5783 const TIntermSequence* argp = nullptr; // confusing to use [] syntax on a pointer, so this is to help get a reference
5784 const TIntermTyped* unaryArg = nullptr;
5785 const TIntermTyped* arg0 = nullptr;
5786 if (callNode.getAsAggregate()) {
5787 argp = &callNode.getAsAggregate()->getSequence();
5788 if (argp->size() > 0)
5789 arg0 = (*argp)[0]->getAsTyped();
5791 assert(callNode.getAsUnaryNode());
5792 unaryArg = callNode.getAsUnaryNode()->getOperand();
5795 const TIntermSequence& aggArgs = *argp; // only valid when unaryArg is nullptr
5797 switch (callNode.getOp()) {
5798 case EOpTextureGather:
5799 case EOpTextureGatherOffset:
5800 case EOpTextureGatherOffsets:
5802 // Figure out which variants are allowed by what extensions,
5803 // and what arguments must be constant for which situations.
5805 TString featureString = fnCandidate.getName() + "(...)";
5806 const char* feature = featureString.c_str();
5807 int compArg = -1; // track which argument, if any, is the constant component argument
5808 switch (callNode.getOp()) {
5809 case EOpTextureGather:
5810 // More than two arguments needs gpu_shader5, and rectangular or shadow needs gpu_shader5,
5811 // otherwise, need GL_ARB_texture_gather.
5812 if (fnCandidate.getParamCount() > 2 || fnCandidate[0].type->getSampler().dim == EsdRect ||
5813 fnCandidate[0].type->getSampler().shadow) {
5814 if (! fnCandidate[0].type->getSampler().shadow)
5818 case EOpTextureGatherOffset:
5819 // GL_ARB_texture_gather is good enough for 2D non-shadow textures with no component argument
5820 if (! fnCandidate[0].type->getSampler().shadow)
5823 case EOpTextureGatherOffsets:
5824 if (! fnCandidate[0].type->getSampler().shadow)
5831 if (compArg > 0 && compArg < fnCandidate.getParamCount()) {
5832 if (aggArgs[compArg]->getAsConstantUnion()) {
5833 int value = aggArgs[compArg]->getAsConstantUnion()->getConstArray()[0].getIConst();
5834 if (value < 0 || value > 3)
5835 error(loc, "must be 0, 1, 2, or 3:", feature, "component argument");
5837 error(loc, "must be a compile-time constant:", feature, "component argument");
5843 case EOpTextureOffset:
5844 case EOpTextureFetchOffset:
5845 case EOpTextureProjOffset:
5846 case EOpTextureLodOffset:
5847 case EOpTextureProjLodOffset:
5848 case EOpTextureGradOffset:
5849 case EOpTextureProjGradOffset:
5851 // Handle texture-offset limits checking
5852 // Pick which argument has to hold constant offsets
5854 switch (callNode.getOp()) {
5855 case EOpTextureOffset: arg = 2; break;
5856 case EOpTextureFetchOffset: arg = (arg0->getType().getSampler().dim != EsdRect) ? 3 : 2; break;
5857 case EOpTextureProjOffset: arg = 2; break;
5858 case EOpTextureLodOffset: arg = 3; break;
5859 case EOpTextureProjLodOffset: arg = 3; break;
5860 case EOpTextureGradOffset: arg = 4; break;
5861 case EOpTextureProjGradOffset: arg = 4; break;
5868 if (aggArgs[arg]->getAsConstantUnion() == nullptr)
5869 error(loc, "argument must be compile-time constant", "texel offset", "");
5871 const TType& type = aggArgs[arg]->getAsTyped()->getType();
5872 for (int c = 0; c < type.getVectorSize(); ++c) {
5873 int offset = aggArgs[arg]->getAsConstantUnion()->getConstArray()[c].getIConst();
5874 if (offset > resources.maxProgramTexelOffset || offset < resources.minProgramTexelOffset)
5875 error(loc, "value is out of range:", "texel offset",
5876 "[gl_MinProgramTexelOffset, gl_MaxProgramTexelOffset]");
5884 case EOpTextureQuerySamples:
5885 case EOpImageQuerySamples:
5888 case EOpImageAtomicAdd:
5889 case EOpImageAtomicMin:
5890 case EOpImageAtomicMax:
5891 case EOpImageAtomicAnd:
5892 case EOpImageAtomicOr:
5893 case EOpImageAtomicXor:
5894 case EOpImageAtomicExchange:
5895 case EOpImageAtomicCompSwap:
5898 case EOpInterpolateAtCentroid:
5899 case EOpInterpolateAtSample:
5900 case EOpInterpolateAtOffset:
5901 // Make sure the first argument is an interpolant, or an array element of an interpolant
5902 if (arg0->getType().getQualifier().storage != EvqVaryingIn) {
5903 // It might still be an array element.
5905 // We could check more, but the semantics of the first argument are already met; the
5906 // only way to turn an array into a float/vec* is array dereference and swizzle.
5908 // ES and desktop 4.3 and earlier: swizzles may not be used
5909 // desktop 4.4 and later: swizzles may be used
5910 const TIntermTyped* base = TIntermediate::findLValueBase(arg0, true);
5911 if (base == nullptr || base->getType().getQualifier().storage != EvqVaryingIn)
5912 error(loc, "first argument must be an interpolant, or interpolant-array element",
5913 fnCandidate.getName().c_str(), "");
5923 // Handle seeing something in a grammar production that can be done by calling
5926 // The constructor still must be "handled" by handleFunctionCall(), which will
5927 // then call handleConstructor().
5929 TFunction* HlslParseContext::makeConstructorCall(const TSourceLoc& loc, const TType& type)
5931 TOperator op = intermediate.mapTypeToConstructorOp(type);
5933 if (op == EOpNull) {
5934 error(loc, "cannot construct this type", type.getBasicString(), "");
5940 return new TFunction(&empty, type, op);
5944 // Handle seeing a "COLON semantic" at the end of a type declaration,
5945 // by updating the type according to the semantic.
5947 void HlslParseContext::handleSemantic(TSourceLoc loc, TQualifier& qualifier, TBuiltInVariable builtIn,
5948 const TString& upperCase)
5950 // Parse and return semantic number. If limit is 0, it will be ignored. Otherwise, if the parsed
5951 // semantic number is >= limit, errorMsg is issued and 0 is returned.
5952 // TODO: it would be nicer if limit and errorMsg had default parameters, but some compilers don't yet
5953 // accept those in lambda functions.
5954 const auto getSemanticNumber = [this, loc](const TString& semantic, unsigned int limit, const char* errorMsg) -> unsigned int {
5955 size_t pos = semantic.find_last_not_of("0123456789");
5956 if (pos == std::string::npos)
5959 unsigned int semanticNum = (unsigned int)atoi(semantic.c_str() + pos + 1);
5961 if (limit != 0 && semanticNum >= limit) {
5962 error(loc, errorMsg, semantic.c_str(), "");
5971 // Get location numbers from fragment outputs, instead of
5972 // auto-assigning them.
5973 if (language == EShLangFragment && upperCase.compare(0, 9, "SV_TARGET") == 0) {
5974 qualifier.layoutLocation = getSemanticNumber(upperCase, 0, nullptr);
5975 nextOutLocation = std::max(nextOutLocation, qualifier.layoutLocation + 1u);
5976 } else if (upperCase.compare(0, 15, "SV_CLIPDISTANCE") == 0) {
5977 builtIn = EbvClipDistance;
5978 qualifier.layoutLocation = getSemanticNumber(upperCase, maxClipCullRegs, "invalid clip semantic");
5979 } else if (upperCase.compare(0, 15, "SV_CULLDISTANCE") == 0) {
5980 builtIn = EbvCullDistance;
5981 qualifier.layoutLocation = getSemanticNumber(upperCase, maxClipCullRegs, "invalid cull semantic");
5985 // adjust for stage in/out
5986 if (language == EShLangFragment)
5987 builtIn = EbvFragCoord;
5989 case EbvFragStencilRef:
5990 error(loc, "unimplemented; need ARB_shader_stencil_export", "SV_STENCILREF", "");
5992 case EbvTessLevelInner:
5993 case EbvTessLevelOuter:
5994 qualifier.patch = true;
6000 if (qualifier.builtIn == EbvNone)
6001 qualifier.builtIn = builtIn;
6002 qualifier.semanticName = intermediate.addSemanticName(upperCase);
6006 // Handle seeing something like "PACKOFFSET LEFT_PAREN c[Subcomponent][.component] RIGHT_PAREN"
6008 // 'location' has the "c[Subcomponent]" part.
6009 // 'component' points to the "component" part, or nullptr if not present.
6011 void HlslParseContext::handlePackOffset(const TSourceLoc& loc, TQualifier& qualifier, const glslang::TString& location,
6012 const glslang::TString* component)
6014 if (location.size() == 0 || location[0] != 'c') {
6015 error(loc, "expected 'c'", "packoffset", "");
6018 if (location.size() == 1)
6020 if (! isdigit(location[1])) {
6021 error(loc, "expected number after 'c'", "packoffset", "");
6025 qualifier.layoutOffset = 16 * atoi(location.substr(1, location.size()).c_str());
6026 if (component != nullptr) {
6027 int componentOffset = 0;
6028 switch ((*component)[0]) {
6029 case 'x': componentOffset = 0; break;
6030 case 'y': componentOffset = 4; break;
6031 case 'z': componentOffset = 8; break;
6032 case 'w': componentOffset = 12; break;
6034 componentOffset = -1;
6037 if (componentOffset < 0 || component->size() > 1) {
6038 error(loc, "expected {x, y, z, w} for component", "packoffset", "");
6041 qualifier.layoutOffset += componentOffset;
6046 // Handle seeing something like "REGISTER LEFT_PAREN [shader_profile,] Type# RIGHT_PAREN"
6048 // 'profile' points to the shader_profile part, or nullptr if not present.
6049 // 'desc' is the type# part.
6051 void HlslParseContext::handleRegister(const TSourceLoc& loc, TQualifier& qualifier, const glslang::TString* profile,
6052 const glslang::TString& desc, int subComponent, const glslang::TString* spaceDesc)
6054 if (profile != nullptr)
6055 warn(loc, "ignoring shader_profile", "register", "");
6057 if (desc.size() < 1) {
6058 error(loc, "expected register type", "register", "");
6063 if (desc.size() > 1) {
6064 if (isdigit(desc[1]))
6065 regNumber = atoi(desc.substr(1, desc.size()).c_str());
6067 error(loc, "expected register number after register type", "register", "");
6072 // TODO: learn what all these really mean and how they interact with regNumber and subComponent
6073 const std::vector<std::string>& resourceInfo = intermediate.getResourceSetBinding();
6074 switch (std::tolower(desc[0])) {
6080 // if nothing else has set the binding, do so now
6081 // (other mechanisms override this one)
6082 if (!qualifier.hasBinding())
6083 qualifier.layoutBinding = regNumber + subComponent;
6085 // This handles per-register layout sets numbers. For the global mode which sets
6086 // every symbol to the same value, see setLinkageLayoutSets().
6087 if ((resourceInfo.size() % 3) == 0) {
6088 // Apply per-symbol resource set and binding.
6089 for (auto it = resourceInfo.cbegin(); it != resourceInfo.cend(); it = it + 3) {
6090 if (strcmp(desc.c_str(), it[0].c_str()) == 0) {
6091 qualifier.layoutSet = atoi(it[1].c_str());
6092 qualifier.layoutBinding = atoi(it[2].c_str()) + subComponent;
6099 warn(loc, "ignoring unrecognized register type", "register", "%c", desc[0]);
6104 unsigned int setNumber;
6105 const auto crackSpace = [&]() -> bool {
6106 const int spaceLen = 5;
6107 if (spaceDesc->size() < spaceLen + 1)
6109 if (spaceDesc->compare(0, spaceLen, "space") != 0)
6111 if (! isdigit((*spaceDesc)[spaceLen]))
6113 setNumber = atoi(spaceDesc->substr(spaceLen, spaceDesc->size()).c_str());
6117 // if nothing else has set the set, do so now
6118 // (other mechanisms override this one)
6119 if (spaceDesc && !qualifier.hasSet()) {
6120 if (! crackSpace()) {
6121 error(loc, "expected spaceN", "register", "");
6124 qualifier.layoutSet = setNumber;
6128 // Convert to a scalar boolean, or if not allowed by HLSL semantics,
6129 // report an error and return nullptr.
6130 TIntermTyped* HlslParseContext::convertConditionalExpression(const TSourceLoc& loc, TIntermTyped* condition,
6133 if (mustBeScalar && !condition->getType().isScalarOrVec1()) {
6134 error(loc, "requires a scalar", "conditional expression", "");
6138 return intermediate.addConversion(EOpConstructBool, TType(EbtBool, EvqTemporary, condition->getVectorSize()),
6143 // Same error message for all places assignments don't work.
6145 void HlslParseContext::assignError(const TSourceLoc& loc, const char* op, TString left, TString right)
6147 error(loc, "", op, "cannot convert from '%s' to '%s'",
6148 right.c_str(), left.c_str());
6152 // Same error message for all places unary operations don't work.
6154 void HlslParseContext::unaryOpError(const TSourceLoc& loc, const char* op, TString operand)
6156 error(loc, " wrong operand type", op,
6157 "no operation '%s' exists that takes an operand of type %s (or there is no acceptable conversion)",
6158 op, operand.c_str());
6162 // Same error message for all binary operations don't work.
6164 void HlslParseContext::binaryOpError(const TSourceLoc& loc, const char* op, TString left, TString right)
6166 error(loc, " wrong operand types:", op,
6167 "no operation '%s' exists that takes a left-hand operand of type '%s' and "
6168 "a right operand of type '%s' (or there is no acceptable conversion)",
6169 op, left.c_str(), right.c_str());
6173 // A basic type of EbtVoid is a key that the name string was seen in the source, but
6174 // it was not found as a variable in the symbol table. If so, give the error
6175 // message and insert a dummy variable in the symbol table to prevent future errors.
6177 void HlslParseContext::variableCheck(TIntermTyped*& nodePtr)
6179 TIntermSymbol* symbol = nodePtr->getAsSymbolNode();
6183 if (symbol->getType().getBasicType() == EbtVoid) {
6184 error(symbol->getLoc(), "undeclared identifier", symbol->getName().c_str(), "");
6186 // Add to symbol table to prevent future error messages on the same name
6187 if (symbol->getName().size() > 0) {
6188 TVariable* fakeVariable = new TVariable(&symbol->getName(), TType(EbtFloat));
6189 symbolTable.insert(*fakeVariable);
6191 // substitute a symbol node for this new variable
6192 nodePtr = intermediate.addSymbol(*fakeVariable, symbol->getLoc());
6198 // Both test, and if necessary spit out an error, to see if the node is really
6201 void HlslParseContext::constantValueCheck(TIntermTyped* node, const char* token)
6203 if (node->getQualifier().storage != EvqConst)
6204 error(node->getLoc(), "constant expression required", token, "");
6208 // Both test, and if necessary spit out an error, to see if the node is really
6211 void HlslParseContext::integerCheck(const TIntermTyped* node, const char* token)
6213 if ((node->getBasicType() == EbtInt || node->getBasicType() == EbtUint) && node->isScalar())
6216 error(node->getLoc(), "scalar integer expression required", token, "");
6220 // Both test, and if necessary spit out an error, to see if we are currently
6223 void HlslParseContext::globalCheck(const TSourceLoc& loc, const char* token)
6225 if (! symbolTable.atGlobalLevel())
6226 error(loc, "not allowed in nested scope", token, "");
6229 bool HlslParseContext::builtInName(const TString& /*identifier*/)
6235 // Make sure there is enough data and not too many arguments provided to the
6236 // constructor to build something of the type of the constructor. Also returns
6237 // the type of the constructor.
6239 // Returns true if there was an error in construction.
6241 bool HlslParseContext::constructorError(const TSourceLoc& loc, TIntermNode* node, TFunction& function,
6242 TOperator op, TType& type)
6244 type.shallowCopy(function.getType());
6246 bool constructingMatrix = false;
6248 case EOpConstructTextureSampler:
6249 return constructorTextureSamplerError(loc, function);
6250 case EOpConstructMat2x2:
6251 case EOpConstructMat2x3:
6252 case EOpConstructMat2x4:
6253 case EOpConstructMat3x2:
6254 case EOpConstructMat3x3:
6255 case EOpConstructMat3x4:
6256 case EOpConstructMat4x2:
6257 case EOpConstructMat4x3:
6258 case EOpConstructMat4x4:
6259 case EOpConstructDMat2x2:
6260 case EOpConstructDMat2x3:
6261 case EOpConstructDMat2x4:
6262 case EOpConstructDMat3x2:
6263 case EOpConstructDMat3x3:
6264 case EOpConstructDMat3x4:
6265 case EOpConstructDMat4x2:
6266 case EOpConstructDMat4x3:
6267 case EOpConstructDMat4x4:
6268 case EOpConstructIMat2x2:
6269 case EOpConstructIMat2x3:
6270 case EOpConstructIMat2x4:
6271 case EOpConstructIMat3x2:
6272 case EOpConstructIMat3x3:
6273 case EOpConstructIMat3x4:
6274 case EOpConstructIMat4x2:
6275 case EOpConstructIMat4x3:
6276 case EOpConstructIMat4x4:
6277 case EOpConstructUMat2x2:
6278 case EOpConstructUMat2x3:
6279 case EOpConstructUMat2x4:
6280 case EOpConstructUMat3x2:
6281 case EOpConstructUMat3x3:
6282 case EOpConstructUMat3x4:
6283 case EOpConstructUMat4x2:
6284 case EOpConstructUMat4x3:
6285 case EOpConstructUMat4x4:
6286 case EOpConstructBMat2x2:
6287 case EOpConstructBMat2x3:
6288 case EOpConstructBMat2x4:
6289 case EOpConstructBMat3x2:
6290 case EOpConstructBMat3x3:
6291 case EOpConstructBMat3x4:
6292 case EOpConstructBMat4x2:
6293 case EOpConstructBMat4x3:
6294 case EOpConstructBMat4x4:
6295 constructingMatrix = true;
6302 // Walk the arguments for first-pass checks and collection of information.
6306 bool constType = true;
6308 bool overFull = false;
6309 bool matrixInMatrix = false;
6310 bool arrayArg = false;
6311 for (int arg = 0; arg < function.getParamCount(); ++arg) {
6312 if (function[arg].type->isArray()) {
6313 if (function[arg].type->isUnsizedArray()) {
6314 // Can't construct from an unsized array.
6315 error(loc, "array argument must be sized", "constructor", "");
6320 if (constructingMatrix && function[arg].type->isMatrix())
6321 matrixInMatrix = true;
6323 // 'full' will go to true when enough args have been seen. If we loop
6324 // again, there is an extra argument.
6326 // For vectors and matrices, it's okay to have too many components
6327 // available, but not okay to have unused arguments.
6331 size += function[arg].type->computeNumComponents();
6332 if (op != EOpConstructStruct && ! type.isArray() && size >= type.computeNumComponents())
6335 if (function[arg].type->getQualifier().storage != EvqConst)
6340 type.getQualifier().storage = EvqConst;
6342 if (type.isArray()) {
6343 if (function.getParamCount() == 0) {
6344 error(loc, "array constructor must have at least one argument", "constructor", "");
6348 if (type.isUnsizedArray()) {
6349 // auto adapt the constructor type to the number of arguments
6350 type.changeOuterArraySize(function.getParamCount());
6351 } else if (type.getOuterArraySize() != function.getParamCount() && type.computeNumComponents() > size) {
6352 error(loc, "array constructor needs one argument per array element", "constructor", "");
6356 if (type.isArrayOfArrays()) {
6357 // Types have to match, but we're still making the type.
6358 // Finish making the type, and the comparison is done later
6359 // when checking for conversion.
6360 TArraySizes& arraySizes = *type.getArraySizes();
6362 // At least the dimensionalities have to match.
6363 if (! function[0].type->isArray() ||
6364 arraySizes.getNumDims() != function[0].type->getArraySizes()->getNumDims() + 1) {
6365 error(loc, "array constructor argument not correct type to construct array element", "constructor", "");
6369 if (arraySizes.isInnerUnsized()) {
6370 // "Arrays of arrays ..., and the size for any dimension is optional"
6371 // That means we need to adopt (from the first argument) the other array sizes into the type.
6372 for (int d = 1; d < arraySizes.getNumDims(); ++d) {
6373 if (arraySizes.getDimSize(d) == UnsizedArraySize) {
6374 arraySizes.setDimSize(d, function[0].type->getArraySizes()->getDimSize(d - 1));
6381 // Some array -> array type casts are okay
6382 if (arrayArg && function.getParamCount() == 1 && op != EOpConstructStruct && type.isArray() &&
6383 !type.isArrayOfArrays() && !function[0].type->isArrayOfArrays() &&
6384 type.getVectorSize() >= 1 && function[0].type->getVectorSize() >= 1)
6387 if (arrayArg && op != EOpConstructStruct && ! type.isArrayOfArrays()) {
6388 error(loc, "constructing non-array constituent from array argument", "constructor", "");
6392 if (matrixInMatrix && ! type.isArray()) {
6397 error(loc, "too many arguments", "constructor", "");
6401 if (op == EOpConstructStruct && ! type.isArray()) {
6402 if (isScalarConstructor(node))
6405 // Self-type construction: e.g, we can construct a struct from a single identically typed object.
6406 if (function.getParamCount() == 1 && type == *function[0].type)
6409 if ((int)type.getStruct()->size() != function.getParamCount()) {
6410 error(loc, "Number of constructor parameters does not match the number of structure fields", "constructor", "");
6415 if ((op != EOpConstructStruct && size != 1 && size < type.computeNumComponents()) ||
6416 (op == EOpConstructStruct && size < type.computeNumComponents())) {
6417 error(loc, "not enough data provided for construction", "constructor", "");
6424 // See if 'node', in the context of constructing aggregates, is a scalar argument
6425 // to a constructor.
6427 bool HlslParseContext::isScalarConstructor(const TIntermNode* node)
6429 // Obviously, it must be a scalar, but an aggregate node might not be fully
6430 // completed yet: holding a sequence of initializers under an aggregate
6431 // would not yet be typed, so don't check it's type. This corresponds to
6432 // the aggregate operator also not being set yet. (An aggregate operation
6433 // that legitimately yields a scalar will have a getOp() of that operator,
6436 return node->getAsTyped() != nullptr &&
6437 node->getAsTyped()->isScalar() &&
6438 (node->getAsAggregate() == nullptr || node->getAsAggregate()->getOp() != EOpNull);
6441 // Verify all the correct semantics for constructing a combined texture/sampler.
6442 // Return true if the semantics are incorrect.
6443 bool HlslParseContext::constructorTextureSamplerError(const TSourceLoc& loc, const TFunction& function)
6445 TString constructorName = function.getType().getBasicTypeString(); // TODO: performance: should not be making copy; interface needs to change
6446 const char* token = constructorName.c_str();
6448 // exactly two arguments needed
6449 if (function.getParamCount() != 2) {
6450 error(loc, "sampler-constructor requires two arguments", token, "");
6454 // For now, not allowing arrayed constructors, the rest of this function
6455 // is set up to allow them, if this test is removed:
6456 if (function.getType().isArray()) {
6457 error(loc, "sampler-constructor cannot make an array of samplers", token, "");
6462 // * the constructor's first argument must be a texture type
6463 // * the dimensionality (1D, 2D, 3D, Cube, Rect, Buffer, MS, and Array)
6464 // of the texture type must match that of the constructed sampler type
6465 // (that is, the suffixes of the type of the first argument and the
6466 // type of the constructor will be spelled the same way)
6467 if (function[0].type->getBasicType() != EbtSampler ||
6468 ! function[0].type->getSampler().isTexture() ||
6469 function[0].type->isArray()) {
6470 error(loc, "sampler-constructor first argument must be a scalar textureXXX type", token, "");
6473 // simulate the first argument's impact on the result type, so it can be compared with the encapsulated operator!=()
6474 TSampler texture = function.getType().getSampler();
6475 texture.combined = false;
6476 texture.shadow = false;
6477 if (texture != function[0].type->getSampler()) {
6478 error(loc, "sampler-constructor first argument must match type and dimensionality of constructor type", token, "");
6483 // * the constructor's second argument must be a scalar of type
6484 // *sampler* or *samplerShadow*
6485 // * the presence or absence of depth comparison (Shadow) must match
6486 // between the constructed sampler type and the type of the second argument
6487 if (function[1].type->getBasicType() != EbtSampler ||
6488 ! function[1].type->getSampler().isPureSampler() ||
6489 function[1].type->isArray()) {
6490 error(loc, "sampler-constructor second argument must be a scalar type 'sampler'", token, "");
6493 if (function.getType().getSampler().shadow != function[1].type->getSampler().shadow) {
6494 error(loc, "sampler-constructor second argument presence of shadow must match constructor presence of shadow",
6502 // Checks to see if a void variable has been declared and raise an error message for such a case
6504 // returns true in case of an error
6506 bool HlslParseContext::voidErrorCheck(const TSourceLoc& loc, const TString& identifier, const TBasicType basicType)
6508 if (basicType == EbtVoid) {
6509 error(loc, "illegal use of type 'void'", identifier.c_str(), "");
6517 // Fix just a full qualifier (no variables or types yet, but qualifier is complete) at global level.
6519 void HlslParseContext::globalQualifierFix(const TSourceLoc&, TQualifier& qualifier)
6521 // move from parameter/unknown qualifiers to pipeline in/out qualifiers
6522 switch (qualifier.storage) {
6524 qualifier.storage = EvqVaryingIn;
6527 qualifier.storage = EvqVaryingOut;
6535 // Merge characteristics of the 'src' qualifier into the 'dst'.
6536 // If there is duplication, issue error messages, unless 'force'
6537 // is specified, which means to just override default settings.
6539 // Also, when force is false, it will be assumed that 'src' follows
6540 // 'dst', for the purpose of error checking order for versions
6541 // that require specific orderings of qualifiers.
6543 void HlslParseContext::mergeQualifiers(TQualifier& dst, const TQualifier& src)
6545 // Storage qualification
6546 if (dst.storage == EvqTemporary || dst.storage == EvqGlobal)
6547 dst.storage = src.storage;
6548 else if ((dst.storage == EvqIn && src.storage == EvqOut) ||
6549 (dst.storage == EvqOut && src.storage == EvqIn))
6550 dst.storage = EvqInOut;
6551 else if ((dst.storage == EvqIn && src.storage == EvqConst) ||
6552 (dst.storage == EvqConst && src.storage == EvqIn))
6553 dst.storage = EvqConstReadOnly;
6555 // Layout qualifiers
6556 mergeObjectLayoutQualifiers(dst, src, false);
6558 // individual qualifiers
6559 bool repeated = false;
6560 #define MERGE_SINGLETON(field) repeated |= dst.field && src.field; dst.field |= src.field;
6561 MERGE_SINGLETON(invariant);
6562 MERGE_SINGLETON(noContraction);
6563 MERGE_SINGLETON(centroid);
6564 MERGE_SINGLETON(smooth);
6565 MERGE_SINGLETON(flat);
6566 MERGE_SINGLETON(nopersp);
6567 MERGE_SINGLETON(patch);
6568 MERGE_SINGLETON(sample);
6569 MERGE_SINGLETON(coherent);
6570 MERGE_SINGLETON(volatil);
6571 MERGE_SINGLETON(restrict);
6572 MERGE_SINGLETON(readonly);
6573 MERGE_SINGLETON(writeonly);
6574 MERGE_SINGLETON(specConstant);
6575 MERGE_SINGLETON(nonUniform);
6578 // used to flatten the sampler type space into a single dimension
6579 // correlates with the declaration of defaultSamplerPrecision[]
6580 int HlslParseContext::computeSamplerTypeIndex(TSampler& sampler)
6582 int arrayIndex = sampler.arrayed ? 1 : 0;
6583 int shadowIndex = sampler.shadow ? 1 : 0;
6584 int externalIndex = sampler.external ? 1 : 0;
6587 (EbtNumTypes * (2 * (2 * arrayIndex + shadowIndex) + externalIndex) + sampler.type) + sampler.dim;
6591 // Do size checking for an array type's size.
6593 void HlslParseContext::arraySizeCheck(const TSourceLoc& loc, TIntermTyped* expr, TArraySize& sizePair)
6595 bool isConst = false;
6597 sizePair.node = nullptr;
6599 TIntermConstantUnion* constant = expr->getAsConstantUnion();
6601 // handle true (non-specialization) constant
6602 sizePair.size = constant->getConstArray()[0].getIConst();
6605 // see if it's a specialization constant instead
6606 if (expr->getQualifier().isSpecConstant()) {
6608 sizePair.node = expr;
6609 TIntermSymbol* symbol = expr->getAsSymbolNode();
6610 if (symbol && symbol->getConstArray().size() > 0)
6611 sizePair.size = symbol->getConstArray()[0].getIConst();
6615 if (! isConst || (expr->getBasicType() != EbtInt && expr->getBasicType() != EbtUint)) {
6616 error(loc, "array size must be a constant integer expression", "", "");
6620 if (sizePair.size <= 0) {
6621 error(loc, "array size must be a positive integer", "", "");
6627 // Require array to be completely sized
6629 void HlslParseContext::arraySizeRequiredCheck(const TSourceLoc& loc, const TArraySizes& arraySizes)
6631 if (arraySizes.hasUnsized())
6632 error(loc, "array size required", "", "");
6635 void HlslParseContext::structArrayCheck(const TSourceLoc& /*loc*/, const TType& type)
6637 const TTypeList& structure = *type.getStruct();
6638 for (int m = 0; m < (int)structure.size(); ++m) {
6639 const TType& member = *structure[m].type;
6640 if (member.isArray())
6641 arraySizeRequiredCheck(structure[m].loc, *member.getArraySizes());
6646 // Do all the semantic checking for declaring or redeclaring an array, with and
6647 // without a size, and make the right changes to the symbol table.
6649 void HlslParseContext::declareArray(const TSourceLoc& loc, const TString& identifier, const TType& type,
6650 TSymbol*& symbol, bool track)
6652 if (symbol == nullptr) {
6654 symbol = symbolTable.find(identifier, nullptr, ¤tScope);
6656 if (symbol && builtInName(identifier) && ! symbolTable.atBuiltInLevel()) {
6657 // bad shader (errors already reported) trying to redeclare a built-in name as an array
6660 if (symbol == nullptr || ! currentScope) {
6662 // Successfully process a new definition.
6663 // (Redeclarations have to take place at the same scope; otherwise they are hiding declarations)
6665 symbol = new TVariable(&identifier, type);
6666 symbolTable.insert(*symbol);
6667 if (track && symbolTable.atGlobalLevel())
6668 trackLinkage(*symbol);
6672 if (symbol->getAsAnonMember()) {
6673 error(loc, "cannot redeclare a user-block member array", identifier.c_str(), "");
6680 // Process a redeclaration.
6683 if (symbol == nullptr) {
6684 error(loc, "array variable name expected", identifier.c_str(), "");
6688 // redeclareBuiltinVariable() should have already done the copyUp()
6689 TType& existingType = symbol->getWritableType();
6691 if (existingType.isSizedArray()) {
6692 // be more lenient for input arrays to geometry shaders and tessellation control outputs,
6693 // where the redeclaration is the same size
6697 existingType.updateArraySizes(type);
6701 // Enforce non-initializer type/qualifier rules.
6703 void HlslParseContext::fixConstInit(const TSourceLoc& loc, const TString& identifier, TType& type,
6704 TIntermTyped*& initializer)
6707 // Make the qualifier make sense, given that there is an initializer.
6709 if (initializer == nullptr) {
6710 if (type.getQualifier().storage == EvqConst ||
6711 type.getQualifier().storage == EvqConstReadOnly) {
6712 initializer = intermediate.makeAggregate(loc);
6713 warn(loc, "variable with qualifier 'const' not initialized; zero initializing", identifier.c_str(), "");
6719 // See if the identifier is a built-in symbol that can be redeclared, and if so,
6720 // copy the symbol table's read-only built-in variable to the current
6721 // global level, where it can be modified based on the passed in type.
6723 // Returns nullptr if no redeclaration took place; meaning a normal declaration still
6724 // needs to occur for it, not necessarily an error.
6726 // Returns a redeclared and type-modified variable if a redeclared occurred.
6728 TSymbol* HlslParseContext::redeclareBuiltinVariable(const TSourceLoc& /*loc*/, const TString& identifier,
6729 const TQualifier& /*qualifier*/,
6730 const TShaderQualifiers& /*publicType*/)
6732 if (! builtInName(identifier) || symbolTable.atBuiltInLevel() || ! symbolTable.atGlobalLevel())
6739 // Generate index to the array element in a structure buffer (SSBO)
6741 TIntermTyped* HlslParseContext::indexStructBufferContent(const TSourceLoc& loc, TIntermTyped* buffer) const
6743 // Bail out if not a struct buffer
6744 if (buffer == nullptr || ! isStructBufferType(buffer->getType()))
6747 // Runtime sized array is always the last element.
6748 const TTypeList* bufferStruct = buffer->getType().getStruct();
6749 TIntermTyped* arrayPosition = intermediate.addConstantUnion(unsigned(bufferStruct->size()-1), loc);
6751 TIntermTyped* argArray = intermediate.addIndex(EOpIndexDirectStruct, buffer, arrayPosition, loc);
6752 argArray->setType(*(*bufferStruct)[bufferStruct->size()-1].type);
6758 // IFF type is a structuredbuffer/byteaddressbuffer type, return the content
6759 // (template) type. E.g, StructuredBuffer<MyType> -> MyType. Else return nullptr.
6761 TType* HlslParseContext::getStructBufferContentType(const TType& type) const
6763 if (type.getBasicType() != EbtBlock || type.getQualifier().storage != EvqBuffer)
6766 const int memberCount = (int)type.getStruct()->size();
6767 assert(memberCount > 0);
6769 TType* contentType = (*type.getStruct())[memberCount-1].type;
6771 return contentType->isUnsizedArray() ? contentType : nullptr;
6775 // If an existing struct buffer has a sharable type, then share it.
6777 void HlslParseContext::shareStructBufferType(TType& type)
6779 // PackOffset must be equivalent to share types on a per-member basis.
6780 // Note: cannot use auto type due to recursion. Thus, this is a std::function.
6781 const std::function<bool(TType& lhs, TType& rhs)>
6782 compareQualifiers = [&](TType& lhs, TType& rhs) -> bool {
6783 if (lhs.getQualifier().layoutOffset != rhs.getQualifier().layoutOffset)
6786 if (lhs.isStruct() != rhs.isStruct())
6789 if (lhs.isStruct() && rhs.isStruct()) {
6790 if (lhs.getStruct()->size() != rhs.getStruct()->size())
6793 for (int i = 0; i < int(lhs.getStruct()->size()); ++i)
6794 if (!compareQualifiers(*(*lhs.getStruct())[i].type, *(*rhs.getStruct())[i].type))
6801 // We need to compare certain qualifiers in addition to the type.
6802 const auto typeEqual = [compareQualifiers](TType& lhs, TType& rhs) -> bool {
6803 if (lhs.getQualifier().readonly != rhs.getQualifier().readonly)
6806 // If both are structures, recursively look for packOffset equality
6807 // as well as type equality.
6808 return compareQualifiers(lhs, rhs) && lhs == rhs;
6811 // This is an exhaustive O(N) search, but real world shaders have
6812 // only a small number of these.
6813 for (int idx = 0; idx < int(structBufferTypes.size()); ++idx) {
6814 // If the deep structure matches, modulo qualifiers, use it
6815 if (typeEqual(*structBufferTypes[idx], type)) {
6816 type.shallowCopy(*structBufferTypes[idx]);
6821 // Otherwise, remember it:
6822 TType* typeCopy = new TType;
6823 typeCopy->shallowCopy(type);
6824 structBufferTypes.push_back(typeCopy);
6827 void HlslParseContext::paramFix(TType& type)
6829 switch (type.getQualifier().storage) {
6831 type.getQualifier().storage = EvqConstReadOnly;
6836 type.getQualifier().storage = EvqIn;
6840 // SSBO parameter. These do not go through the declareBlock path since they are fn parameters.
6841 correctUniform(type.getQualifier());
6842 TQualifier bufferQualifier = globalBufferDefaults;
6843 mergeObjectLayoutQualifiers(bufferQualifier, type.getQualifier(), true);
6844 bufferQualifier.storage = type.getQualifier().storage;
6845 bufferQualifier.readonly = type.getQualifier().readonly;
6846 bufferQualifier.coherent = type.getQualifier().coherent;
6847 bufferQualifier.declaredBuiltIn = type.getQualifier().declaredBuiltIn;
6848 type.getQualifier() = bufferQualifier;
6856 void HlslParseContext::specializationCheck(const TSourceLoc& loc, const TType& type, const char* op)
6858 if (type.containsSpecializationSize())
6859 error(loc, "can't use with types containing arrays sized with a specialization constant", op, "");
6863 // Layout qualifier stuff.
6866 // Put the id's layout qualification into the public type, for qualifiers not having a number set.
6867 // This is before we know any type information for error checking.
6868 void HlslParseContext::setLayoutQualifier(const TSourceLoc& loc, TQualifier& qualifier, TString& id)
6870 std::transform(id.begin(), id.end(), id.begin(), ::tolower);
6872 if (id == TQualifier::getLayoutMatrixString(ElmColumnMajor)) {
6873 qualifier.layoutMatrix = ElmRowMajor;
6876 if (id == TQualifier::getLayoutMatrixString(ElmRowMajor)) {
6877 qualifier.layoutMatrix = ElmColumnMajor;
6880 if (id == "push_constant") {
6881 requireVulkan(loc, "push_constant");
6882 qualifier.layoutPushConstant = true;
6885 if (language == EShLangGeometry || language == EShLangTessEvaluation) {
6886 if (id == TQualifier::getGeometryString(ElgTriangles)) {
6887 // publicType.shaderQualifiers.geometry = ElgTriangles;
6888 warn(loc, "ignored", id.c_str(), "");
6891 if (language == EShLangGeometry) {
6892 if (id == TQualifier::getGeometryString(ElgPoints)) {
6893 // publicType.shaderQualifiers.geometry = ElgPoints;
6894 warn(loc, "ignored", id.c_str(), "");
6897 if (id == TQualifier::getGeometryString(ElgLineStrip)) {
6898 // publicType.shaderQualifiers.geometry = ElgLineStrip;
6899 warn(loc, "ignored", id.c_str(), "");
6902 if (id == TQualifier::getGeometryString(ElgLines)) {
6903 // publicType.shaderQualifiers.geometry = ElgLines;
6904 warn(loc, "ignored", id.c_str(), "");
6907 if (id == TQualifier::getGeometryString(ElgLinesAdjacency)) {
6908 // publicType.shaderQualifiers.geometry = ElgLinesAdjacency;
6909 warn(loc, "ignored", id.c_str(), "");
6912 if (id == TQualifier::getGeometryString(ElgTrianglesAdjacency)) {
6913 // publicType.shaderQualifiers.geometry = ElgTrianglesAdjacency;
6914 warn(loc, "ignored", id.c_str(), "");
6917 if (id == TQualifier::getGeometryString(ElgTriangleStrip)) {
6918 // publicType.shaderQualifiers.geometry = ElgTriangleStrip;
6919 warn(loc, "ignored", id.c_str(), "");
6923 assert(language == EShLangTessEvaluation);
6926 if (id == TQualifier::getGeometryString(ElgTriangles)) {
6927 // publicType.shaderQualifiers.geometry = ElgTriangles;
6928 warn(loc, "ignored", id.c_str(), "");
6931 if (id == TQualifier::getGeometryString(ElgQuads)) {
6932 // publicType.shaderQualifiers.geometry = ElgQuads;
6933 warn(loc, "ignored", id.c_str(), "");
6936 if (id == TQualifier::getGeometryString(ElgIsolines)) {
6937 // publicType.shaderQualifiers.geometry = ElgIsolines;
6938 warn(loc, "ignored", id.c_str(), "");
6943 if (id == TQualifier::getVertexSpacingString(EvsEqual)) {
6944 // publicType.shaderQualifiers.spacing = EvsEqual;
6945 warn(loc, "ignored", id.c_str(), "");
6948 if (id == TQualifier::getVertexSpacingString(EvsFractionalEven)) {
6949 // publicType.shaderQualifiers.spacing = EvsFractionalEven;
6950 warn(loc, "ignored", id.c_str(), "");
6953 if (id == TQualifier::getVertexSpacingString(EvsFractionalOdd)) {
6954 // publicType.shaderQualifiers.spacing = EvsFractionalOdd;
6955 warn(loc, "ignored", id.c_str(), "");
6960 if (id == TQualifier::getVertexOrderString(EvoCw)) {
6961 // publicType.shaderQualifiers.order = EvoCw;
6962 warn(loc, "ignored", id.c_str(), "");
6965 if (id == TQualifier::getVertexOrderString(EvoCcw)) {
6966 // publicType.shaderQualifiers.order = EvoCcw;
6967 warn(loc, "ignored", id.c_str(), "");
6972 if (id == "point_mode") {
6973 // publicType.shaderQualifiers.pointMode = true;
6974 warn(loc, "ignored", id.c_str(), "");
6979 if (language == EShLangFragment) {
6980 if (id == "origin_upper_left") {
6981 // publicType.shaderQualifiers.originUpperLeft = true;
6982 warn(loc, "ignored", id.c_str(), "");
6985 if (id == "pixel_center_integer") {
6986 // publicType.shaderQualifiers.pixelCenterInteger = true;
6987 warn(loc, "ignored", id.c_str(), "");
6990 if (id == "early_fragment_tests") {
6991 // publicType.shaderQualifiers.earlyFragmentTests = true;
6992 warn(loc, "ignored", id.c_str(), "");
6995 for (TLayoutDepth depth = (TLayoutDepth)(EldNone + 1); depth < EldCount; depth = (TLayoutDepth)(depth + 1)) {
6996 if (id == TQualifier::getLayoutDepthString(depth)) {
6997 // publicType.shaderQualifiers.layoutDepth = depth;
6998 warn(loc, "ignored", id.c_str(), "");
7002 if (id.compare(0, 13, "blend_support") == 0) {
7004 for (TBlendEquationShift be = (TBlendEquationShift)0; be < EBlendCount; be = (TBlendEquationShift)(be + 1)) {
7005 if (id == TQualifier::getBlendEquationString(be)) {
7006 requireExtensions(loc, 1, &E_GL_KHR_blend_equation_advanced, "blend equation");
7007 intermediate.addBlendEquation(be);
7008 // publicType.shaderQualifiers.blendEquation = true;
7009 warn(loc, "ignored", id.c_str(), "");
7015 error(loc, "unknown blend equation", "blend_support", "");
7019 error(loc, "unrecognized layout identifier, or qualifier requires assignment (e.g., binding = 4)", id.c_str(), "");
7022 // Put the id's layout qualifier value into the public type, for qualifiers having a number set.
7023 // This is before we know any type information for error checking.
7024 void HlslParseContext::setLayoutQualifier(const TSourceLoc& loc, TQualifier& qualifier, TString& id,
7025 const TIntermTyped* node)
7027 const char* feature = "layout-id value";
7028 // const char* nonLiteralFeature = "non-literal layout-id value";
7030 integerCheck(node, feature);
7031 const TIntermConstantUnion* constUnion = node->getAsConstantUnion();
7034 value = constUnion->getConstArray()[0].getIConst();
7037 std::transform(id.begin(), id.end(), id.begin(), ::tolower);
7039 if (id == "offset") {
7040 qualifier.layoutOffset = value;
7042 } else if (id == "align") {
7043 // "The specified alignment must be a power of 2, or a compile-time error results."
7044 if (! IsPow2(value))
7045 error(loc, "must be a power of 2", "align", "");
7047 qualifier.layoutAlign = value;
7049 } else if (id == "location") {
7050 if ((unsigned int)value >= TQualifier::layoutLocationEnd)
7051 error(loc, "location is too large", id.c_str(), "");
7053 qualifier.layoutLocation = value;
7055 } else if (id == "set") {
7056 if ((unsigned int)value >= TQualifier::layoutSetEnd)
7057 error(loc, "set is too large", id.c_str(), "");
7059 qualifier.layoutSet = value;
7061 } else if (id == "binding") {
7062 if ((unsigned int)value >= TQualifier::layoutBindingEnd)
7063 error(loc, "binding is too large", id.c_str(), "");
7065 qualifier.layoutBinding = value;
7067 } else if (id == "component") {
7068 if ((unsigned)value >= TQualifier::layoutComponentEnd)
7069 error(loc, "component is too large", id.c_str(), "");
7071 qualifier.layoutComponent = value;
7073 } else if (id.compare(0, 4, "xfb_") == 0) {
7074 // "Any shader making any static use (after preprocessing) of any of these
7075 // *xfb_* qualifiers will cause the shader to be in a transform feedback
7076 // capturing mode and hence responsible for describing the transform feedback
7078 intermediate.setXfbMode();
7079 if (id == "xfb_buffer") {
7080 // "It is a compile-time error to specify an *xfb_buffer* that is greater than
7081 // the implementation-dependent constant gl_MaxTransformFeedbackBuffers."
7082 if (value >= resources.maxTransformFeedbackBuffers)
7083 error(loc, "buffer is too large:", id.c_str(), "gl_MaxTransformFeedbackBuffers is %d",
7084 resources.maxTransformFeedbackBuffers);
7085 if (value >= (int)TQualifier::layoutXfbBufferEnd)
7086 error(loc, "buffer is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbBufferEnd - 1);
7088 qualifier.layoutXfbBuffer = value;
7090 } else if (id == "xfb_offset") {
7091 if (value >= (int)TQualifier::layoutXfbOffsetEnd)
7092 error(loc, "offset is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbOffsetEnd - 1);
7094 qualifier.layoutXfbOffset = value;
7096 } else if (id == "xfb_stride") {
7097 // "The resulting stride (implicit or explicit), when divided by 4, must be less than or equal to the
7098 // implementation-dependent constant gl_MaxTransformFeedbackInterleavedComponents."
7099 if (value > 4 * resources.maxTransformFeedbackInterleavedComponents)
7100 error(loc, "1/4 stride is too large:", id.c_str(), "gl_MaxTransformFeedbackInterleavedComponents is %d",
7101 resources.maxTransformFeedbackInterleavedComponents);
7102 else if (value >= (int)TQualifier::layoutXfbStrideEnd)
7103 error(loc, "stride is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbStrideEnd - 1);
7104 if (value < (int)TQualifier::layoutXfbStrideEnd)
7105 qualifier.layoutXfbStride = value;
7110 if (id == "input_attachment_index") {
7111 requireVulkan(loc, "input_attachment_index");
7112 if (value >= (int)TQualifier::layoutAttachmentEnd)
7113 error(loc, "attachment index is too large", id.c_str(), "");
7115 qualifier.layoutAttachment = value;
7118 if (id == "constant_id") {
7119 setSpecConstantId(loc, qualifier, value);
7127 case EShLangTessControl:
7128 if (id == "vertices") {
7130 error(loc, "must be greater than 0", "vertices", "");
7132 // publicType.shaderQualifiers.vertices = value;
7133 warn(loc, "ignored", id.c_str(), "");
7138 case EShLangTessEvaluation:
7141 case EShLangGeometry:
7142 if (id == "invocations") {
7144 error(loc, "must be at least 1", "invocations", "");
7146 // publicType.shaderQualifiers.invocations = value;
7147 warn(loc, "ignored", id.c_str(), "");
7150 if (id == "max_vertices") {
7151 // publicType.shaderQualifiers.vertices = value;
7152 warn(loc, "ignored", id.c_str(), "");
7153 if (value > resources.maxGeometryOutputVertices)
7154 error(loc, "too large, must be less than gl_MaxGeometryOutputVertices", "max_vertices", "");
7157 if (id == "stream") {
7158 qualifier.layoutStream = value;
7163 case EShLangFragment:
7164 if (id == "index") {
7165 qualifier.layoutIndex = value;
7170 case EShLangCompute:
7171 if (id.compare(0, 11, "local_size_") == 0) {
7172 if (id == "local_size_x") {
7173 // publicType.shaderQualifiers.localSize[0] = value;
7174 warn(loc, "ignored", id.c_str(), "");
7177 if (id == "local_size_y") {
7178 // publicType.shaderQualifiers.localSize[1] = value;
7179 warn(loc, "ignored", id.c_str(), "");
7182 if (id == "local_size_z") {
7183 // publicType.shaderQualifiers.localSize[2] = value;
7184 warn(loc, "ignored", id.c_str(), "");
7187 if (spvVersion.spv != 0) {
7188 if (id == "local_size_x_id") {
7189 // publicType.shaderQualifiers.localSizeSpecId[0] = value;
7190 warn(loc, "ignored", id.c_str(), "");
7193 if (id == "local_size_y_id") {
7194 // publicType.shaderQualifiers.localSizeSpecId[1] = value;
7195 warn(loc, "ignored", id.c_str(), "");
7198 if (id == "local_size_z_id") {
7199 // publicType.shaderQualifiers.localSizeSpecId[2] = value;
7200 warn(loc, "ignored", id.c_str(), "");
7211 error(loc, "there is no such layout identifier for this stage taking an assigned value", id.c_str(), "");
7214 void HlslParseContext::setSpecConstantId(const TSourceLoc& loc, TQualifier& qualifier, int value)
7216 if (value >= (int)TQualifier::layoutSpecConstantIdEnd) {
7217 error(loc, "specialization-constant id is too large", "constant_id", "");
7219 qualifier.layoutSpecConstantId = value;
7220 qualifier.specConstant = true;
7221 if (! intermediate.addUsedConstantId(value))
7222 error(loc, "specialization-constant id already used", "constant_id", "");
7227 // Merge any layout qualifier information from src into dst, leaving everything else in dst alone
7229 // "More than one layout qualifier may appear in a single declaration.
7230 // Additionally, the same layout-qualifier-name can occur multiple times
7231 // within a layout qualifier or across multiple layout qualifiers in the
7232 // same declaration. When the same layout-qualifier-name occurs
7233 // multiple times, in a single declaration, the last occurrence overrides
7234 // the former occurrence(s). Further, if such a layout-qualifier-name
7235 // will effect subsequent declarations or other observable behavior, it
7236 // is only the last occurrence that will have any effect, behaving as if
7237 // the earlier occurrence(s) within the declaration are not present.
7238 // This is also true for overriding layout-qualifier-names, where one
7239 // overrides the other (e.g., row_major vs. column_major); only the last
7240 // occurrence has any effect."
7242 void HlslParseContext::mergeObjectLayoutQualifiers(TQualifier& dst, const TQualifier& src, bool inheritOnly)
7244 if (src.hasMatrix())
7245 dst.layoutMatrix = src.layoutMatrix;
7246 if (src.hasPacking())
7247 dst.layoutPacking = src.layoutPacking;
7249 if (src.hasStream())
7250 dst.layoutStream = src.layoutStream;
7252 if (src.hasFormat())
7253 dst.layoutFormat = src.layoutFormat;
7255 if (src.hasXfbBuffer())
7256 dst.layoutXfbBuffer = src.layoutXfbBuffer;
7259 dst.layoutAlign = src.layoutAlign;
7261 if (! inheritOnly) {
7262 if (src.hasLocation())
7263 dst.layoutLocation = src.layoutLocation;
7264 if (src.hasComponent())
7265 dst.layoutComponent = src.layoutComponent;
7267 dst.layoutIndex = src.layoutIndex;
7269 if (src.hasOffset())
7270 dst.layoutOffset = src.layoutOffset;
7273 dst.layoutSet = src.layoutSet;
7274 if (src.layoutBinding != TQualifier::layoutBindingEnd)
7275 dst.layoutBinding = src.layoutBinding;
7277 if (src.hasXfbStride())
7278 dst.layoutXfbStride = src.layoutXfbStride;
7279 if (src.hasXfbOffset())
7280 dst.layoutXfbOffset = src.layoutXfbOffset;
7281 if (src.hasAttachment())
7282 dst.layoutAttachment = src.layoutAttachment;
7283 if (src.hasSpecConstantId())
7284 dst.layoutSpecConstantId = src.layoutSpecConstantId;
7286 if (src.layoutPushConstant)
7287 dst.layoutPushConstant = true;
7293 // Look up a function name in the symbol table, and make sure it is a function.
7295 // First, look for an exact match. If there is none, use the generic selector
7296 // TParseContextBase::selectFunction() to find one, parameterized by the
7297 // convertible() and better() predicates defined below.
7299 // Return the function symbol if found, otherwise nullptr.
7301 const TFunction* HlslParseContext::findFunction(const TSourceLoc& loc, TFunction& call, bool& builtIn, int& thisDepth,
7302 TIntermTyped*& args)
7304 if (symbolTable.isFunctionNameVariable(call.getName())) {
7305 error(loc, "can't use function syntax on variable", call.getName().c_str(), "");
7309 // first, look for an exact match
7311 TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn, &dummyScope, &thisDepth);
7313 return symbol->getAsFunction();
7315 // no exact match, use the generic selector, parameterized by the GLSL rules
7317 // create list of candidates to send
7318 TVector<const TFunction*> candidateList;
7319 symbolTable.findFunctionNameList(call.getMangledName(), candidateList, builtIn);
7321 // These built-in ops can accept any type, so we bypass the argument selection
7322 if (candidateList.size() == 1 && builtIn &&
7323 (candidateList[0]->getBuiltInOp() == EOpMethodAppend ||
7324 candidateList[0]->getBuiltInOp() == EOpMethodRestartStrip ||
7325 candidateList[0]->getBuiltInOp() == EOpMethodIncrementCounter ||
7326 candidateList[0]->getBuiltInOp() == EOpMethodDecrementCounter ||
7327 candidateList[0]->getBuiltInOp() == EOpMethodAppend ||
7328 candidateList[0]->getBuiltInOp() == EOpMethodConsume)) {
7329 return candidateList[0];
7332 bool allowOnlyUpConversions = true;
7334 // can 'from' convert to 'to'?
7335 const auto convertible = [&](const TType& from, const TType& to, TOperator op, int arg) -> bool {
7339 // no aggregate conversions
7340 if (from.isArray() || to.isArray() ||
7341 from.isStruct() || to.isStruct())
7345 case EOpInterlockedAdd:
7346 case EOpInterlockedAnd:
7347 case EOpInterlockedCompareExchange:
7348 case EOpInterlockedCompareStore:
7349 case EOpInterlockedExchange:
7350 case EOpInterlockedMax:
7351 case EOpInterlockedMin:
7352 case EOpInterlockedOr:
7353 case EOpInterlockedXor:
7354 // We do not promote the texture or image type for these ocodes. Normally that would not
7355 // be an issue because it's a buffer, but we haven't decomposed the opcode yet, and at this
7356 // stage it's merely e.g, a basic integer type.
7358 // Instead, we want to promote other arguments, but stay within the same family. In other
7359 // words, InterlockedAdd(RWBuffer<int>, ...) will always use the int flavor, never the uint flavor,
7360 // but it is allowed to promote its other arguments.
7364 case EOpMethodSample:
7365 case EOpMethodSampleBias:
7366 case EOpMethodSampleCmp:
7367 case EOpMethodSampleCmpLevelZero:
7368 case EOpMethodSampleGrad:
7369 case EOpMethodSampleLevel:
7371 case EOpMethodGetDimensions:
7372 case EOpMethodGetSamplePosition:
7373 case EOpMethodGather:
7374 case EOpMethodCalculateLevelOfDetail:
7375 case EOpMethodCalculateLevelOfDetailUnclamped:
7376 case EOpMethodGatherRed:
7377 case EOpMethodGatherGreen:
7378 case EOpMethodGatherBlue:
7379 case EOpMethodGatherAlpha:
7380 case EOpMethodGatherCmp:
7381 case EOpMethodGatherCmpRed:
7382 case EOpMethodGatherCmpGreen:
7383 case EOpMethodGatherCmpBlue:
7384 case EOpMethodGatherCmpAlpha:
7385 case EOpMethodAppend:
7386 case EOpMethodRestartStrip:
7387 // those are method calls, the object type can not be changed
7388 // they are equal if the dim and type match (is dim sufficient?)
7390 return from.getSampler().type == to.getSampler().type &&
7391 from.getSampler().arrayed == to.getSampler().arrayed &&
7392 from.getSampler().shadow == to.getSampler().shadow &&
7393 from.getSampler().ms == to.getSampler().ms &&
7394 from.getSampler().dim == to.getSampler().dim;
7400 // basic types have to be convertible
7401 if (allowOnlyUpConversions)
7402 if (! intermediate.canImplicitlyPromote(from.getBasicType(), to.getBasicType(), EOpFunctionCall))
7405 // shapes have to be convertible
7406 if ((from.isScalarOrVec1() && to.isScalarOrVec1()) ||
7407 (from.isScalarOrVec1() && to.isVector()) ||
7408 (from.isScalarOrVec1() && to.isMatrix()) ||
7409 (from.isVector() && to.isVector() && from.getVectorSize() >= to.getVectorSize()))
7412 // TODO: what are the matrix rules? they go here
7417 // Is 'to2' a better conversion than 'to1'?
7418 // Ties should not be considered as better.
7419 // Assumes 'convertible' already said true.
7420 const auto better = [](const TType& from, const TType& to1, const TType& to2) -> bool {
7421 // exact match is always better than mismatch
7427 // shape changes are always worse
7428 if (from.isScalar() || from.isVector()) {
7429 if (from.getVectorSize() == to2.getVectorSize() &&
7430 from.getVectorSize() != to1.getVectorSize())
7432 if (from.getVectorSize() == to1.getVectorSize() &&
7433 from.getVectorSize() != to2.getVectorSize())
7437 // Handle sampler betterness: An exact sampler match beats a non-exact match.
7438 // (If we just looked at basic type, all EbtSamplers would look the same).
7439 // If any type is not a sampler, just use the linearize function below.
7440 if (from.getBasicType() == EbtSampler && to1.getBasicType() == EbtSampler && to2.getBasicType() == EbtSampler) {
7441 // We can ignore the vector size in the comparison.
7442 TSampler to1Sampler = to1.getSampler();
7443 TSampler to2Sampler = to2.getSampler();
7445 to1Sampler.vectorSize = to2Sampler.vectorSize = from.getSampler().vectorSize;
7447 if (from.getSampler() == to2Sampler)
7448 return from.getSampler() != to1Sampler;
7449 if (from.getSampler() == to1Sampler)
7453 // Might or might not be changing shape, which means basic type might
7454 // or might not match, so within that, the question is how big a
7455 // basic-type conversion is being done.
7457 // Use a hierarchy of domains, translated to order of magnitude
7458 // in a linearized view:
7459 // - floating-point vs. integer
7460 // - 32 vs. 64 bit (or width in general)
7461 // - bool vs. non bool
7462 // - signed vs. not signed
7463 const auto linearize = [](const TBasicType& basicType) -> int {
7464 switch (basicType) {
7465 case EbtBool: return 1;
7466 case EbtInt: return 10;
7467 case EbtUint: return 11;
7468 case EbtInt64: return 20;
7469 case EbtUint64: return 21;
7470 case EbtFloat: return 100;
7471 case EbtDouble: return 110;
7476 return abs(linearize(to2.getBasicType()) - linearize(from.getBasicType())) <
7477 abs(linearize(to1.getBasicType()) - linearize(from.getBasicType()));
7480 // for ambiguity reporting
7483 // send to the generic selector
7484 const TFunction* bestMatch = selectFunction(candidateList, call, convertible, better, tie);
7486 if (bestMatch == nullptr) {
7487 // If there is nothing selected by allowing only up-conversions (to a larger linearize() value),
7488 // we instead try down-conversions, which are valid in HLSL, but not preferred if there are any
7489 // upconversions possible.
7490 allowOnlyUpConversions = false;
7491 bestMatch = selectFunction(candidateList, call, convertible, better, tie);
7494 if (bestMatch == nullptr) {
7495 error(loc, "no matching overloaded function found", call.getName().c_str(), "");
7499 // For built-ins, we can convert across the arguments. This will happen in several steps:
7500 // Step 1: If there's an exact match, use it.
7501 // Step 2a: Otherwise, get the operator from the best match and promote arguments:
7502 // Step 2b: reconstruct the TFunction based on the new arg types
7503 // Step 3: Re-select after type promotion is applied, to find proper candidate.
7505 // Step 1: If there's an exact match, use it.
7506 if (call.getMangledName() == bestMatch->getMangledName())
7509 // Step 2a: Otherwise, get the operator from the best match and promote arguments as if we
7510 // are that kind of operator.
7511 if (args != nullptr) {
7512 // The arg list can be a unary node, or an aggregate. We have to handle both.
7513 // We will use the normal promote() facilities, which require an interm node.
7514 TIntermOperator* promote = nullptr;
7516 if (call.getParamCount() == 1) {
7517 promote = new TIntermUnary(bestMatch->getBuiltInOp());
7518 promote->getAsUnaryNode()->setOperand(args->getAsTyped());
7520 promote = new TIntermAggregate(bestMatch->getBuiltInOp());
7521 promote->getAsAggregate()->getSequence().swap(args->getAsAggregate()->getSequence());
7524 if (! intermediate.promote(promote))
7527 // Obtain the promoted arg list.
7528 if (call.getParamCount() == 1) {
7529 args = promote->getAsUnaryNode()->getOperand();
7531 promote->getAsAggregate()->getSequence().swap(args->getAsAggregate()->getSequence());
7535 // Step 2b: reconstruct the TFunction based on the new arg types
7536 TFunction convertedCall(&call.getName(), call.getType(), call.getBuiltInOp());
7538 if (args->getAsAggregate()) {
7539 // Handle aggregates: put all args into the new function call
7540 for (int arg=0; arg<int(args->getAsAggregate()->getSequence().size()); ++arg) {
7541 // TODO: But for constness, we could avoid the new & shallowCopy, and use the pointer directly.
7542 TParameter param = { 0, new TType, nullptr };
7543 param.type->shallowCopy(args->getAsAggregate()->getSequence()[arg]->getAsTyped()->getType());
7544 convertedCall.addParameter(param);
7546 } else if (args->getAsUnaryNode()) {
7547 // Handle unaries: put all args into the new function call
7548 TParameter param = { 0, new TType, nullptr };
7549 param.type->shallowCopy(args->getAsUnaryNode()->getOperand()->getAsTyped()->getType());
7550 convertedCall.addParameter(param);
7551 } else if (args->getAsTyped()) {
7552 // Handle bare e.g, floats, not in an aggregate.
7553 TParameter param = { 0, new TType, nullptr };
7554 param.type->shallowCopy(args->getAsTyped()->getType());
7555 convertedCall.addParameter(param);
7557 assert(0); // unknown argument list.
7561 // Step 3: Re-select after type promotion, to find proper candidate
7562 // send to the generic selector
7563 bestMatch = selectFunction(candidateList, convertedCall, convertible, better, tie);
7565 // At this point, there should be no tie.
7569 error(loc, "ambiguous best function under implicit type conversion", call.getName().c_str(), "");
7571 // Append default parameter values if needed
7572 if (!tie && bestMatch != nullptr) {
7573 for (int defParam = call.getParamCount(); defParam < bestMatch->getParamCount(); ++defParam) {
7574 handleFunctionArgument(&call, args, (*bestMatch)[defParam].defaultValue);
7582 // Do everything necessary to handle a typedef declaration, for a single symbol.
7584 // 'parseType' is the type part of the declaration (to the left)
7585 // 'arraySizes' is the arrayness tagged on the identifier (to the right)
7587 void HlslParseContext::declareTypedef(const TSourceLoc& loc, const TString& identifier, const TType& parseType)
7589 TVariable* typeSymbol = new TVariable(&identifier, parseType, true);
7590 if (! symbolTable.insert(*typeSymbol))
7591 error(loc, "name already defined", "typedef", identifier.c_str());
7594 // Do everything necessary to handle a struct declaration, including
7595 // making IO aliases because HLSL allows mixed IO in a struct that specializes
7596 // based on the usage (input, output, uniform, none).
7597 void HlslParseContext::declareStruct(const TSourceLoc& loc, TString& structName, TType& type)
7599 // If it was named, which means the type can be reused later, add
7600 // it to the symbol table. (Unless it's a block, in which
7601 // case the name is not a type.)
7602 if (type.getBasicType() == EbtBlock || structName.size() == 0)
7605 TVariable* userTypeDef = new TVariable(&structName, type, true);
7606 if (! symbolTable.insert(*userTypeDef)) {
7607 error(loc, "redefinition", structName.c_str(), "struct");
7611 // See if we need IO aliases for the structure typeList
7613 const auto condAlloc = [](bool pred, TTypeList*& list) {
7614 if (pred && list == nullptr)
7615 list = new TTypeList;
7618 tIoKinds newLists = { nullptr, nullptr, nullptr }; // allocate for each kind found
7619 for (auto member = type.getStruct()->begin(); member != type.getStruct()->end(); ++member) {
7620 condAlloc(hasUniform(member->type->getQualifier()), newLists.uniform);
7621 condAlloc( hasInput(member->type->getQualifier()), newLists.input);
7622 condAlloc( hasOutput(member->type->getQualifier()), newLists.output);
7624 if (member->type->isStruct()) {
7625 auto it = ioTypeMap.find(member->type->getStruct());
7626 if (it != ioTypeMap.end()) {
7627 condAlloc(it->second.uniform != nullptr, newLists.uniform);
7628 condAlloc(it->second.input != nullptr, newLists.input);
7629 condAlloc(it->second.output != nullptr, newLists.output);
7633 if (newLists.uniform == nullptr &&
7634 newLists.input == nullptr &&
7635 newLists.output == nullptr) {
7636 // Won't do any IO caching, clear up the type and get out now.
7637 for (auto member = type.getStruct()->begin(); member != type.getStruct()->end(); ++member)
7638 clearUniformInputOutput(member->type->getQualifier());
7642 // We have IO involved.
7644 // Make a pure typeList for the symbol table, and cache side copies of IO versions.
7645 for (auto member = type.getStruct()->begin(); member != type.getStruct()->end(); ++member) {
7646 const auto inheritStruct = [&](TTypeList* s, TTypeLoc& ioMember) {
7648 ioMember.type = new TType;
7649 ioMember.type->shallowCopy(*member->type);
7650 ioMember.type->setStruct(s);
7653 const auto newMember = [&](TTypeLoc& m) {
7654 if (m.type == nullptr) {
7656 m.type->shallowCopy(*member->type);
7660 TTypeLoc newUniformMember = { nullptr, member->loc };
7661 TTypeLoc newInputMember = { nullptr, member->loc };
7662 TTypeLoc newOutputMember = { nullptr, member->loc };
7663 if (member->type->isStruct()) {
7664 // swap in an IO child if there is one
7665 auto it = ioTypeMap.find(member->type->getStruct());
7666 if (it != ioTypeMap.end()) {
7667 inheritStruct(it->second.uniform, newUniformMember);
7668 inheritStruct(it->second.input, newInputMember);
7669 inheritStruct(it->second.output, newOutputMember);
7672 if (newLists.uniform) {
7673 newMember(newUniformMember);
7675 // inherit default matrix layout (changeable via #pragma pack_matrix), if none given.
7676 if (member->type->isMatrix() && member->type->getQualifier().layoutMatrix == ElmNone)
7677 newUniformMember.type->getQualifier().layoutMatrix = globalUniformDefaults.layoutMatrix;
7679 correctUniform(newUniformMember.type->getQualifier());
7680 newLists.uniform->push_back(newUniformMember);
7682 if (newLists.input) {
7683 newMember(newInputMember);
7684 correctInput(newInputMember.type->getQualifier());
7685 newLists.input->push_back(newInputMember);
7687 if (newLists.output) {
7688 newMember(newOutputMember);
7689 correctOutput(newOutputMember.type->getQualifier());
7690 newLists.output->push_back(newOutputMember);
7693 // make original pure
7694 clearUniformInputOutput(member->type->getQualifier());
7696 ioTypeMap[type.getStruct()] = newLists;
7699 // Lookup a user-type by name.
7700 // If found, fill in the type and return the defining symbol.
7701 // If not found, return nullptr.
7702 TSymbol* HlslParseContext::lookupUserType(const TString& typeName, TType& type)
7704 TSymbol* symbol = symbolTable.find(typeName);
7705 if (symbol && symbol->getAsVariable() && symbol->getAsVariable()->isUserType()) {
7706 type.shallowCopy(symbol->getType());
7713 // Do everything necessary to handle a variable (non-block) declaration.
7714 // Either redeclaring a variable, or making a new one, updating the symbol
7715 // table, and all error checking.
7717 // Returns a subtree node that computes an initializer, if needed.
7718 // Returns nullptr if there is no code to execute for initialization.
7720 // 'parseType' is the type part of the declaration (to the left)
7721 // 'arraySizes' is the arrayness tagged on the identifier (to the right)
7723 TIntermNode* HlslParseContext::declareVariable(const TSourceLoc& loc, const TString& identifier, TType& type,
7724 TIntermTyped* initializer)
7726 if (voidErrorCheck(loc, identifier, type.getBasicType()))
7729 // Global consts with initializers that are non-const act like EvqGlobal in HLSL.
7730 // This test is implicitly recursive, because initializers propagate constness
7731 // up the aggregate node tree during creation. E.g, for:
7732 // { { 1, 2 }, { 3, 4 } }
7733 // the initializer list is marked EvqConst at the top node, and remains so here. However:
7734 // { 1, { myvar, 2 }, 3 }
7735 // is not a const intializer, and still becomes EvqGlobal here.
7737 const bool nonConstInitializer = (initializer != nullptr && initializer->getQualifier().storage != EvqConst);
7739 if (type.getQualifier().storage == EvqConst && symbolTable.atGlobalLevel() && nonConstInitializer) {
7741 type.getQualifier().storage = EvqGlobal;
7744 // make const and initialization consistent
7745 fixConstInit(loc, identifier, type, initializer);
7747 // Check for redeclaration of built-ins and/or attempting to declare a reserved name
7748 TSymbol* symbol = nullptr;
7750 inheritGlobalDefaults(type.getQualifier());
7752 const bool flattenVar = shouldFlatten(type, type.getQualifier().storage, true);
7754 // correct IO in the type
7755 switch (type.getQualifier().storage) {
7758 clearUniformInputOutput(type.getQualifier());
7762 correctUniform(type.getQualifier());
7763 if (type.isStruct()) {
7764 auto it = ioTypeMap.find(type.getStruct());
7765 if (it != ioTypeMap.end())
7766 type.setStruct(it->second.uniform);
7774 // Declare the variable
7775 if (type.isArray()) {
7777 declareArray(loc, identifier, type, symbol, !flattenVar);
7780 if (symbol == nullptr)
7781 symbol = declareNonArray(loc, identifier, type, !flattenVar);
7782 else if (type != symbol->getType())
7783 error(loc, "cannot change the type of", "redeclaration", symbol->getName().c_str());
7786 if (symbol == nullptr)
7790 flatten(*symbol->getAsVariable(), symbolTable.atGlobalLevel());
7792 if (initializer == nullptr)
7795 // Deal with initializer
7796 TVariable* variable = symbol->getAsVariable();
7797 if (variable == nullptr) {
7798 error(loc, "initializer requires a variable, not a member", identifier.c_str(), "");
7801 return executeInitializer(loc, initializer, variable);
7804 // Pick up global defaults from the provide global defaults into dst.
7805 void HlslParseContext::inheritGlobalDefaults(TQualifier& dst) const
7807 if (dst.storage == EvqVaryingOut) {
7808 if (! dst.hasStream() && language == EShLangGeometry)
7809 dst.layoutStream = globalOutputDefaults.layoutStream;
7810 if (! dst.hasXfbBuffer())
7811 dst.layoutXfbBuffer = globalOutputDefaults.layoutXfbBuffer;
7816 // Make an internal-only variable whose name is for debug purposes only
7817 // and won't be searched for. Callers will only use the return value to use
7818 // the variable, not the name to look it up. It is okay if the name
7819 // is the same as other names; there won't be any conflict.
7821 TVariable* HlslParseContext::makeInternalVariable(const char* name, const TType& type) const
7823 TString* nameString = NewPoolTString(name);
7824 TVariable* variable = new TVariable(nameString, type);
7825 symbolTable.makeInternalVariable(*variable);
7830 // Make a symbol node holding a new internal temporary variable.
7831 TIntermSymbol* HlslParseContext::makeInternalVariableNode(const TSourceLoc& loc, const char* name,
7832 const TType& type) const
7834 TVariable* tmpVar = makeInternalVariable(name, type);
7835 tmpVar->getWritableType().getQualifier().makeTemporary();
7837 return intermediate.addSymbol(*tmpVar, loc);
7841 // Declare a non-array variable, the main point being there is no redeclaration
7842 // for resizing allowed.
7844 // Return the successfully declared variable.
7846 TVariable* HlslParseContext::declareNonArray(const TSourceLoc& loc, const TString& identifier, const TType& type,
7849 // make a new variable
7850 TVariable* variable = new TVariable(&identifier, type);
7852 // add variable to symbol table
7853 if (symbolTable.insert(*variable)) {
7854 if (track && symbolTable.atGlobalLevel())
7855 trackLinkage(*variable);
7859 error(loc, "redefinition", variable->getName().c_str(), "");
7864 // Handle all types of initializers from the grammar.
7866 // Returning nullptr just means there is no code to execute to handle the
7867 // initializer, which will, for example, be the case for constant initializers.
7869 // Returns a subtree that accomplished the initialization.
7871 TIntermNode* HlslParseContext::executeInitializer(const TSourceLoc& loc, TIntermTyped* initializer, TVariable* variable)
7874 // Identifier must be of type constant, a global, or a temporary, and
7875 // starting at version 120, desktop allows uniforms to have initializers.
7877 TStorageQualifier qualifier = variable->getType().getQualifier().storage;
7880 // If the initializer was from braces { ... }, we convert the whole subtree to a
7881 // constructor-style subtree, allowing the rest of the code to operate
7882 // identically for both kinds of initializers.
7885 // Type can't be deduced from the initializer list, so a skeletal type to
7886 // follow has to be passed in. Constness and specialization-constness
7887 // should be deduced bottom up, not dictated by the skeletal type.
7890 skeletalType.shallowCopy(variable->getType());
7891 skeletalType.getQualifier().makeTemporary();
7892 if (initializer->getAsAggregate() && initializer->getAsAggregate()->getOp() == EOpNull)
7893 initializer = convertInitializerList(loc, skeletalType, initializer, nullptr);
7894 if (initializer == nullptr) {
7895 // error recovery; don't leave const without constant values
7896 if (qualifier == EvqConst)
7897 variable->getWritableType().getQualifier().storage = EvqTemporary;
7901 // Fix outer arrayness if variable is unsized, getting size from the initializer
7902 if (initializer->getType().isSizedArray() && variable->getType().isUnsizedArray())
7903 variable->getWritableType().changeOuterArraySize(initializer->getType().getOuterArraySize());
7905 // Inner arrayness can also get set by an initializer
7906 if (initializer->getType().isArrayOfArrays() && variable->getType().isArrayOfArrays() &&
7907 initializer->getType().getArraySizes()->getNumDims() ==
7908 variable->getType().getArraySizes()->getNumDims()) {
7909 // adopt unsized sizes from the initializer's sizes
7910 for (int d = 1; d < variable->getType().getArraySizes()->getNumDims(); ++d) {
7911 if (variable->getType().getArraySizes()->getDimSize(d) == UnsizedArraySize) {
7912 variable->getWritableType().getArraySizes()->setDimSize(d,
7913 initializer->getType().getArraySizes()->getDimSize(d));
7918 // Uniform and global consts require a constant initializer
7919 if (qualifier == EvqUniform && initializer->getType().getQualifier().storage != EvqConst) {
7920 error(loc, "uniform initializers must be constant", "=", "'%s'", variable->getType().getCompleteString().c_str());
7921 variable->getWritableType().getQualifier().storage = EvqTemporary;
7925 // Const variables require a constant initializer
7926 if (qualifier == EvqConst) {
7927 if (initializer->getType().getQualifier().storage != EvqConst) {
7928 variable->getWritableType().getQualifier().storage = EvqConstReadOnly;
7929 qualifier = EvqConstReadOnly;
7933 if (qualifier == EvqConst || qualifier == EvqUniform) {
7934 // Compile-time tagging of the variable with its constant value...
7936 initializer = intermediate.addConversion(EOpAssign, variable->getType(), initializer);
7937 if (initializer != nullptr && variable->getType() != initializer->getType())
7938 initializer = intermediate.addUniShapeConversion(EOpAssign, variable->getType(), initializer);
7939 if (initializer == nullptr || !initializer->getAsConstantUnion() ||
7940 variable->getType() != initializer->getType()) {
7941 error(loc, "non-matching or non-convertible constant type for const initializer",
7942 variable->getType().getStorageQualifierString(), "");
7943 variable->getWritableType().getQualifier().storage = EvqTemporary;
7947 variable->setConstArray(initializer->getAsConstantUnion()->getConstArray());
7949 // normal assigning of a value to a variable...
7950 specializationCheck(loc, initializer->getType(), "initializer");
7951 TIntermSymbol* intermSymbol = intermediate.addSymbol(*variable, loc);
7952 TIntermNode* initNode = handleAssign(loc, EOpAssign, intermSymbol, initializer);
7953 if (initNode == nullptr)
7954 assignError(loc, "=", intermSymbol->getCompleteString(), initializer->getCompleteString());
7962 // Reprocess any initializer-list { ... } parts of the initializer.
7963 // Need to hierarchically assign correct types and implicit
7964 // conversions. Will do this mimicking the same process used for
7965 // creating a constructor-style initializer, ensuring we get the
7968 // Returns a node representing an expression for the initializer list expressed
7969 // as the correct type.
7971 // Returns nullptr if there is an error.
7973 TIntermTyped* HlslParseContext::convertInitializerList(const TSourceLoc& loc, const TType& type,
7974 TIntermTyped* initializer, TIntermTyped* scalarInit)
7976 // Will operate recursively. Once a subtree is found that is constructor style,
7977 // everything below it is already good: Only the "top part" of the initializer
7978 // can be an initializer list, where "top part" can extend for several (or all) levels.
7980 // see if we have bottomed out in the tree within the initializer-list part
7981 TIntermAggregate* initList = initializer->getAsAggregate();
7982 if (initList == nullptr || initList->getOp() != EOpNull) {
7983 // We don't have a list, but if it's a scalar and the 'type' is a
7984 // composite, we need to lengthen below to make it useful.
7985 // Otherwise, this is an already formed object to initialize with.
7986 if (type.isScalar() || !initializer->getType().isScalar())
7989 initList = intermediate.makeAggregate(initializer);
7992 // Of the initializer-list set of nodes, need to process bottom up,
7993 // so recurse deep, then process on the way up.
7995 // Go down the tree here...
7996 if (type.isArray()) {
7997 // The type's array might be unsized, which could be okay, so base sizes on the size of the aggregate.
7998 // Later on, initializer execution code will deal with array size logic.
8000 arrayType.shallowCopy(type); // sharing struct stuff is fine
8001 arrayType.copyArraySizes(*type.getArraySizes()); // but get a fresh copy of the array information, to edit below
8003 // edit array sizes to fill in unsized dimensions
8004 if (type.isUnsizedArray())
8005 arrayType.changeOuterArraySize((int)initList->getSequence().size());
8007 // set unsized array dimensions that can be derived from the initializer's first element
8008 if (arrayType.isArrayOfArrays() && initList->getSequence().size() > 0) {
8009 TIntermTyped* firstInit = initList->getSequence()[0]->getAsTyped();
8010 if (firstInit->getType().isArray() &&
8011 arrayType.getArraySizes()->getNumDims() == firstInit->getType().getArraySizes()->getNumDims() + 1) {
8012 for (int d = 1; d < arrayType.getArraySizes()->getNumDims(); ++d) {
8013 if (arrayType.getArraySizes()->getDimSize(d) == UnsizedArraySize)
8014 arrayType.getArraySizes()->setDimSize(d, firstInit->getType().getArraySizes()->getDimSize(d - 1));
8019 // lengthen list to be long enough
8020 lengthenList(loc, initList->getSequence(), arrayType.getOuterArraySize(), scalarInit);
8022 // recursively process each element
8023 TType elementType(arrayType, 0); // dereferenced type
8024 for (int i = 0; i < arrayType.getOuterArraySize(); ++i) {
8025 initList->getSequence()[i] = convertInitializerList(loc, elementType,
8026 initList->getSequence()[i]->getAsTyped(), scalarInit);
8027 if (initList->getSequence()[i] == nullptr)
8031 return addConstructor(loc, initList, arrayType);
8032 } else if (type.isStruct()) {
8033 // do we have implicit assignments to opaques?
8034 for (size_t i = initList->getSequence().size(); i < type.getStruct()->size(); ++i) {
8035 if ((*type.getStruct())[i].type->containsOpaque()) {
8036 error(loc, "cannot implicitly initialize opaque members", "initializer list", "");
8041 // lengthen list to be long enough
8042 lengthenList(loc, initList->getSequence(), static_cast<int>(type.getStruct()->size()), scalarInit);
8044 if (type.getStruct()->size() != initList->getSequence().size()) {
8045 error(loc, "wrong number of structure members", "initializer list", "");
8048 for (size_t i = 0; i < type.getStruct()->size(); ++i) {
8049 initList->getSequence()[i] = convertInitializerList(loc, *(*type.getStruct())[i].type,
8050 initList->getSequence()[i]->getAsTyped(), scalarInit);
8051 if (initList->getSequence()[i] == nullptr)
8054 } else if (type.isMatrix()) {
8055 if (type.computeNumComponents() == (int)initList->getSequence().size()) {
8056 // This means the matrix is initialized component-wise, rather than as
8057 // a series of rows and columns. We can just use the list directly as
8058 // a constructor; no further processing needed.
8060 // lengthen list to be long enough
8061 lengthenList(loc, initList->getSequence(), type.getMatrixCols(), scalarInit);
8063 if (type.getMatrixCols() != (int)initList->getSequence().size()) {
8064 error(loc, "wrong number of matrix columns:", "initializer list", type.getCompleteString().c_str());
8067 TType vectorType(type, 0); // dereferenced type
8068 for (int i = 0; i < type.getMatrixCols(); ++i) {
8069 initList->getSequence()[i] = convertInitializerList(loc, vectorType,
8070 initList->getSequence()[i]->getAsTyped(), scalarInit);
8071 if (initList->getSequence()[i] == nullptr)
8075 } else if (type.isVector()) {
8076 // lengthen list to be long enough
8077 lengthenList(loc, initList->getSequence(), type.getVectorSize(), scalarInit);
8079 // error check; we're at bottom, so work is finished below
8080 if (type.getVectorSize() != (int)initList->getSequence().size()) {
8081 error(loc, "wrong vector size (or rows in a matrix column):", "initializer list",
8082 type.getCompleteString().c_str());
8085 } else if (type.isScalar()) {
8086 // lengthen list to be long enough
8087 lengthenList(loc, initList->getSequence(), 1, scalarInit);
8089 if ((int)initList->getSequence().size() != 1) {
8090 error(loc, "scalar expected one element:", "initializer list", type.getCompleteString().c_str());
8094 error(loc, "unexpected initializer-list type:", "initializer list", type.getCompleteString().c_str());
8098 // Now that the subtree is processed, process this node as if the
8099 // initializer list is a set of arguments to a constructor.
8100 TIntermTyped* emulatedConstructorArguments;
8101 if (initList->getSequence().size() == 1)
8102 emulatedConstructorArguments = initList->getSequence()[0]->getAsTyped();
8104 emulatedConstructorArguments = initList;
8106 return addConstructor(loc, emulatedConstructorArguments, type);
8109 // Lengthen list to be long enough to cover any gap from the current list size
8110 // to 'size'. If the list is longer, do nothing.
8111 // The value to lengthen with is the default for short lists.
8113 // By default, lists that are too short due to lack of initializers initialize to zero.
8114 // Alternatively, it could be a scalar initializer for a structure. Both cases are handled,
8115 // based on whether something is passed in as 'scalarInit'.
8117 // 'scalarInit' must be safe to use each time this is called (no side effects replication).
8119 void HlslParseContext::lengthenList(const TSourceLoc& loc, TIntermSequence& list, int size, TIntermTyped* scalarInit)
8121 for (int c = (int)list.size(); c < size; ++c) {
8122 if (scalarInit == nullptr)
8123 list.push_back(intermediate.addConstantUnion(0, loc));
8125 list.push_back(scalarInit);
8130 // Test for the correctness of the parameters passed to various constructor functions
8131 // and also convert them to the right data type, if allowed and required.
8133 // Returns nullptr for an error or the constructed node (aggregate or typed) for no error.
8135 TIntermTyped* HlslParseContext::handleConstructor(const TSourceLoc& loc, TIntermTyped* node, const TType& type)
8137 if (node == nullptr)
8140 // Construct identical type
8141 if (type == node->getType())
8144 // Handle the idiom "(struct type)<scalar value>"
8145 if (type.isStruct() && isScalarConstructor(node)) {
8146 // 'node' will almost always get used multiple times, so should not be used directly,
8147 // it would create a DAG instead of a tree, which might be okay (would
8148 // like to formalize that for constants and symbols), but if it has
8149 // side effects, they would get executed multiple times, which is not okay.
8150 if (node->getAsConstantUnion() == nullptr && node->getAsSymbolNode() == nullptr) {
8151 TIntermAggregate* seq = intermediate.makeAggregate(loc);
8152 TIntermSymbol* copy = makeInternalVariableNode(loc, "scalarCopy", node->getType());
8153 seq = intermediate.growAggregate(seq, intermediate.addBinaryNode(EOpAssign, copy, node, loc));
8154 seq = intermediate.growAggregate(seq, convertInitializerList(loc, type, intermediate.makeAggregate(loc), copy));
8155 seq->setOp(EOpComma);
8159 return convertInitializerList(loc, type, intermediate.makeAggregate(loc), node);
8162 return addConstructor(loc, node, type);
8165 // Add a constructor, either from the grammar, or other programmatic reasons.
8167 // 'node' is what to construct from.
8168 // 'type' is what type to construct.
8170 // Returns the constructed object.
8171 // Return nullptr if it can't be done.
8173 TIntermTyped* HlslParseContext::addConstructor(const TSourceLoc& loc, TIntermTyped* node, const TType& type)
8175 TIntermAggregate* aggrNode = node->getAsAggregate();
8176 TOperator op = intermediate.mapTypeToConstructorOp(type);
8178 // Combined texture-sampler constructors are completely semantic checked
8179 // in constructorTextureSamplerError()
8180 if (op == EOpConstructTextureSampler)
8181 return intermediate.setAggregateOperator(aggrNode, op, type, loc);
8183 TTypeList::const_iterator memberTypes;
8184 if (op == EOpConstructStruct)
8185 memberTypes = type.getStruct()->begin();
8188 if (type.isArray()) {
8189 TType dereferenced(type, 0);
8190 elementType.shallowCopy(dereferenced);
8192 elementType.shallowCopy(type);
8195 if (aggrNode != nullptr) {
8196 if (aggrNode->getOp() != EOpNull)
8203 TIntermTyped *newNode;
8205 // Handle array -> array conversion
8206 // Constructing an array of one type from an array of another type is allowed,
8207 // assuming there are enough components available (semantic-checked earlier).
8208 if (type.isArray() && node->isArray())
8209 newNode = convertArray(node, type);
8211 // If structure constructor or array constructor is being called
8212 // for only one parameter inside the aggregate, we need to call constructAggregate function once.
8213 else if (type.isArray())
8214 newNode = constructAggregate(node, elementType, 1, node->getLoc());
8215 else if (op == EOpConstructStruct)
8216 newNode = constructAggregate(node, *(*memberTypes).type, 1, node->getLoc());
8218 // shape conversion for matrix constructor from scalar. HLSL semantics are: scalar
8219 // is replicated into every element of the matrix (not just the diagnonal), so
8220 // that is handled specially here.
8221 if (type.isMatrix() && node->getType().isScalarOrVec1())
8222 node = intermediate.addShapeConversion(type, node);
8224 newNode = constructBuiltIn(type, op, node, node->getLoc(), false);
8227 if (newNode && (type.isArray() || op == EOpConstructStruct))
8228 newNode = intermediate.setAggregateOperator(newNode, EOpConstructStruct, type, loc);
8234 // Handle list of arguments.
8236 TIntermSequence& sequenceVector = aggrNode->getSequence(); // Stores the information about the parameter to the constructor
8237 // if the structure constructor contains more than one parameter, then construct
8240 int paramCount = 0; // keeps a track of the constructor parameter number being checked
8242 // for each parameter to the constructor call, check to see if the right type is passed or convert them
8243 // to the right type if possible (and allowed).
8244 // for structure constructors, just check if the right type is passed, no conversion is allowed.
8246 for (TIntermSequence::iterator p = sequenceVector.begin();
8247 p != sequenceVector.end(); p++, paramCount++) {
8249 newNode = constructAggregate(*p, elementType, paramCount + 1, node->getLoc());
8250 else if (op == EOpConstructStruct)
8251 newNode = constructAggregate(*p, *(memberTypes[paramCount]).type, paramCount + 1, node->getLoc());
8253 newNode = constructBuiltIn(type, op, (*p)->getAsTyped(), node->getLoc(), true);
8261 TIntermTyped* constructor = intermediate.setAggregateOperator(aggrNode, op, type, loc);
8266 // Function for constructor implementation. Calls addUnaryMath with appropriate EOp value
8267 // for the parameter to the constructor (passed to this function). Essentially, it converts
8268 // the parameter types correctly. If a constructor expects an int (like ivec2) and is passed a
8269 // float, then float is converted to int.
8271 // Returns nullptr for an error or the constructed node.
8273 TIntermTyped* HlslParseContext::constructBuiltIn(const TType& type, TOperator op, TIntermTyped* node,
8274 const TSourceLoc& loc, bool subset)
8276 TIntermTyped* newNode;
8280 // First, convert types as needed.
8283 case EOpConstructF16Vec2:
8284 case EOpConstructF16Vec3:
8285 case EOpConstructF16Vec4:
8286 case EOpConstructF16Mat2x2:
8287 case EOpConstructF16Mat2x3:
8288 case EOpConstructF16Mat2x4:
8289 case EOpConstructF16Mat3x2:
8290 case EOpConstructF16Mat3x3:
8291 case EOpConstructF16Mat3x4:
8292 case EOpConstructF16Mat4x2:
8293 case EOpConstructF16Mat4x3:
8294 case EOpConstructF16Mat4x4:
8295 case EOpConstructFloat16:
8296 basicOp = EOpConstructFloat16;
8299 case EOpConstructVec2:
8300 case EOpConstructVec3:
8301 case EOpConstructVec4:
8302 case EOpConstructMat2x2:
8303 case EOpConstructMat2x3:
8304 case EOpConstructMat2x4:
8305 case EOpConstructMat3x2:
8306 case EOpConstructMat3x3:
8307 case EOpConstructMat3x4:
8308 case EOpConstructMat4x2:
8309 case EOpConstructMat4x3:
8310 case EOpConstructMat4x4:
8311 case EOpConstructFloat:
8312 basicOp = EOpConstructFloat;
8315 case EOpConstructDVec2:
8316 case EOpConstructDVec3:
8317 case EOpConstructDVec4:
8318 case EOpConstructDMat2x2:
8319 case EOpConstructDMat2x3:
8320 case EOpConstructDMat2x4:
8321 case EOpConstructDMat3x2:
8322 case EOpConstructDMat3x3:
8323 case EOpConstructDMat3x4:
8324 case EOpConstructDMat4x2:
8325 case EOpConstructDMat4x3:
8326 case EOpConstructDMat4x4:
8327 case EOpConstructDouble:
8328 basicOp = EOpConstructDouble;
8331 case EOpConstructI16Vec2:
8332 case EOpConstructI16Vec3:
8333 case EOpConstructI16Vec4:
8334 case EOpConstructInt16:
8335 basicOp = EOpConstructInt16;
8338 case EOpConstructIVec2:
8339 case EOpConstructIVec3:
8340 case EOpConstructIVec4:
8341 case EOpConstructIMat2x2:
8342 case EOpConstructIMat2x3:
8343 case EOpConstructIMat2x4:
8344 case EOpConstructIMat3x2:
8345 case EOpConstructIMat3x3:
8346 case EOpConstructIMat3x4:
8347 case EOpConstructIMat4x2:
8348 case EOpConstructIMat4x3:
8349 case EOpConstructIMat4x4:
8350 case EOpConstructInt:
8351 basicOp = EOpConstructInt;
8354 case EOpConstructU16Vec2:
8355 case EOpConstructU16Vec3:
8356 case EOpConstructU16Vec4:
8357 case EOpConstructUint16:
8358 basicOp = EOpConstructUint16;
8361 case EOpConstructUVec2:
8362 case EOpConstructUVec3:
8363 case EOpConstructUVec4:
8364 case EOpConstructUMat2x2:
8365 case EOpConstructUMat2x3:
8366 case EOpConstructUMat2x4:
8367 case EOpConstructUMat3x2:
8368 case EOpConstructUMat3x3:
8369 case EOpConstructUMat3x4:
8370 case EOpConstructUMat4x2:
8371 case EOpConstructUMat4x3:
8372 case EOpConstructUMat4x4:
8373 case EOpConstructUint:
8374 basicOp = EOpConstructUint;
8377 case EOpConstructBVec2:
8378 case EOpConstructBVec3:
8379 case EOpConstructBVec4:
8380 case EOpConstructBMat2x2:
8381 case EOpConstructBMat2x3:
8382 case EOpConstructBMat2x4:
8383 case EOpConstructBMat3x2:
8384 case EOpConstructBMat3x3:
8385 case EOpConstructBMat3x4:
8386 case EOpConstructBMat4x2:
8387 case EOpConstructBMat4x3:
8388 case EOpConstructBMat4x4:
8389 case EOpConstructBool:
8390 basicOp = EOpConstructBool;
8394 error(loc, "unsupported construction", "", "");
8398 newNode = intermediate.addUnaryMath(basicOp, node, node->getLoc());
8399 if (newNode == nullptr) {
8400 error(loc, "can't convert", "constructor", "");
8405 // Now, if there still isn't an operation to do the construction, and we need one, add one.
8408 // Otherwise, skip out early.
8409 if (subset || (newNode != node && newNode->getType() == type))
8412 // setAggregateOperator will insert a new node for the constructor, as needed.
8413 return intermediate.setAggregateOperator(newNode, op, type, loc);
8416 // Convert the array in node to the requested type, which is also an array.
8417 // Returns nullptr on failure, otherwise returns aggregate holding the list of
8418 // elements needed to construct the array.
8419 TIntermTyped* HlslParseContext::convertArray(TIntermTyped* node, const TType& type)
8421 assert(node->isArray() && type.isArray());
8422 if (node->getType().computeNumComponents() < type.computeNumComponents())
8425 // TODO: write an argument replicator, for the case the argument should not be
8426 // executed multiple times, yet multiple copies are needed.
8428 TIntermTyped* constructee = node->getAsTyped();
8429 // track where we are in consuming the argument
8430 int constructeeElement = 0;
8431 int constructeeComponent = 0;
8433 // bump up to the next component to consume
8434 const auto getNextComponent = [&]() {
8435 TIntermTyped* component;
8436 component = handleBracketDereference(node->getLoc(), constructee,
8437 intermediate.addConstantUnion(constructeeElement, node->getLoc()));
8438 if (component->isVector())
8439 component = handleBracketDereference(node->getLoc(), component,
8440 intermediate.addConstantUnion(constructeeComponent, node->getLoc()));
8441 // bump component pointer up
8442 ++constructeeComponent;
8443 if (constructeeComponent == constructee->getVectorSize()) {
8444 constructeeComponent = 0;
8445 ++constructeeElement;
8450 // make one subnode per constructed array element
8451 TIntermAggregate* constructor = nullptr;
8452 TType derefType(type, 0);
8453 TType speculativeComponentType(derefType, 0);
8454 TType* componentType = derefType.isVector() ? &speculativeComponentType : &derefType;
8455 TOperator componentOp = intermediate.mapTypeToConstructorOp(*componentType);
8456 TType crossType(node->getBasicType(), EvqTemporary, type.getVectorSize());
8457 for (int e = 0; e < type.getOuterArraySize(); ++e) {
8458 // construct an element
8459 TIntermTyped* elementArg;
8460 if (type.getVectorSize() == constructee->getVectorSize()) {
8461 // same element shape
8462 elementArg = handleBracketDereference(node->getLoc(), constructee,
8463 intermediate.addConstantUnion(e, node->getLoc()));
8465 // mismatched element shapes
8466 if (type.getVectorSize() == 1)
8467 elementArg = getNextComponent();
8470 TIntermAggregate* elementConstructee = nullptr;
8471 for (int c = 0; c < type.getVectorSize(); ++c)
8472 elementConstructee = intermediate.growAggregate(elementConstructee, getNextComponent());
8473 elementArg = addConstructor(node->getLoc(), elementConstructee, crossType);
8476 // convert basic types
8477 elementArg = intermediate.addConversion(componentOp, derefType, elementArg);
8478 if (elementArg == nullptr)
8480 // combine with top-level constructor
8481 constructor = intermediate.growAggregate(constructor, elementArg);
8487 // This function tests for the type of the parameters to the structure or array constructor. Raises
8488 // an error message if the expected type does not match the parameter passed to the constructor.
8490 // Returns nullptr for an error or the input node itself if the expected and the given parameter types match.
8492 TIntermTyped* HlslParseContext::constructAggregate(TIntermNode* node, const TType& type, int paramCount,
8493 const TSourceLoc& loc)
8495 // Handle cases that map more 1:1 between constructor arguments and constructed.
8496 TIntermTyped* converted = intermediate.addConversion(EOpConstructStruct, type, node->getAsTyped());
8497 if (converted == nullptr || converted->getType() != type) {
8498 error(loc, "", "constructor", "cannot convert parameter %d from '%s' to '%s'", paramCount,
8499 node->getAsTyped()->getType().getCompleteString().c_str(), type.getCompleteString().c_str());
8508 // Do everything needed to add an interface block.
8510 void HlslParseContext::declareBlock(const TSourceLoc& loc, TType& type, const TString* instanceName)
8512 assert(type.getWritableStruct() != nullptr);
8514 // Clean up top-level decorations that don't belong.
8515 switch (type.getQualifier().storage) {
8518 correctUniform(type.getQualifier());
8521 correctInput(type.getQualifier());
8524 correctOutput(type.getQualifier());
8530 TTypeList& typeList = *type.getWritableStruct();
8531 // fix and check for member storage qualifiers and types that don't belong within a block
8532 for (unsigned int member = 0; member < typeList.size(); ++member) {
8533 TType& memberType = *typeList[member].type;
8534 TQualifier& memberQualifier = memberType.getQualifier();
8535 const TSourceLoc& memberLoc = typeList[member].loc;
8536 globalQualifierFix(memberLoc, memberQualifier);
8537 memberQualifier.storage = type.getQualifier().storage;
8539 if (memberType.isStruct()) {
8540 // clean up and pick up the right set of decorations
8541 auto it = ioTypeMap.find(memberType.getStruct());
8542 switch (type.getQualifier().storage) {
8545 correctUniform(type.getQualifier());
8546 if (it != ioTypeMap.end() && it->second.uniform)
8547 memberType.setStruct(it->second.uniform);
8550 correctInput(type.getQualifier());
8551 if (it != ioTypeMap.end() && it->second.input)
8552 memberType.setStruct(it->second.input);
8555 correctOutput(type.getQualifier());
8556 if (it != ioTypeMap.end() && it->second.output)
8557 memberType.setStruct(it->second.output);
8565 // Make default block qualification, and adjust the member qualifications
8567 TQualifier defaultQualification;
8568 switch (type.getQualifier().storage) {
8569 case EvqUniform: defaultQualification = globalUniformDefaults; break;
8570 case EvqBuffer: defaultQualification = globalBufferDefaults; break;
8571 case EvqVaryingIn: defaultQualification = globalInputDefaults; break;
8572 case EvqVaryingOut: defaultQualification = globalOutputDefaults; break;
8573 default: defaultQualification.clear(); break;
8576 // Special case for "push_constant uniform", which has a default of std430,
8577 // contrary to normal uniform defaults, and can't have a default tracked for it.
8578 if (type.getQualifier().layoutPushConstant && ! type.getQualifier().hasPacking())
8579 type.getQualifier().layoutPacking = ElpStd430;
8581 // fix and check for member layout qualifiers
8583 mergeObjectLayoutQualifiers(defaultQualification, type.getQualifier(), true);
8585 bool memberWithLocation = false;
8586 bool memberWithoutLocation = false;
8587 for (unsigned int member = 0; member < typeList.size(); ++member) {
8588 TQualifier& memberQualifier = typeList[member].type->getQualifier();
8589 const TSourceLoc& memberLoc = typeList[member].loc;
8590 if (memberQualifier.hasStream()) {
8591 if (defaultQualification.layoutStream != memberQualifier.layoutStream)
8592 error(memberLoc, "member cannot contradict block", "stream", "");
8595 // "This includes a block's inheritance of the
8596 // current global default buffer, a block member's inheritance of the block's
8597 // buffer, and the requirement that any *xfb_buffer* declared on a block
8598 // member must match the buffer inherited from the block."
8599 if (memberQualifier.hasXfbBuffer()) {
8600 if (defaultQualification.layoutXfbBuffer != memberQualifier.layoutXfbBuffer)
8601 error(memberLoc, "member cannot contradict block (or what block inherited from global)", "xfb_buffer", "");
8604 if (memberQualifier.hasLocation()) {
8605 switch (type.getQualifier().storage) {
8608 memberWithLocation = true;
8614 memberWithoutLocation = true;
8616 TQualifier newMemberQualification = defaultQualification;
8617 mergeQualifiers(newMemberQualification, memberQualifier);
8618 memberQualifier = newMemberQualification;
8621 // Process the members
8622 fixBlockLocations(loc, type.getQualifier(), typeList, memberWithLocation, memberWithoutLocation);
8623 fixBlockXfbOffsets(type.getQualifier(), typeList);
8624 fixBlockUniformOffsets(type.getQualifier(), typeList);
8626 // reverse merge, so that currentBlockQualifier now has all layout information
8627 // (can't use defaultQualification directly, it's missing other non-layout-default-class qualifiers)
8628 mergeObjectLayoutQualifiers(type.getQualifier(), defaultQualification, true);
8631 // Build and add the interface block as a new type named 'blockName'
8634 // Use the instance name as the interface name if one exists, else the block name.
8635 const TString& interfaceName = (instanceName && !instanceName->empty()) ? *instanceName : type.getTypeName();
8637 TType blockType(&typeList, interfaceName, type.getQualifier());
8639 blockType.transferArraySizes(type.getArraySizes());
8641 // Add the variable, as anonymous or named instanceName.
8642 // Make an anonymous variable if no name was provided.
8643 if (instanceName == nullptr)
8644 instanceName = NewPoolTString("");
8646 TVariable& variable = *new TVariable(instanceName, blockType);
8647 if (! symbolTable.insert(variable)) {
8648 if (*instanceName == "")
8649 error(loc, "nameless block contains a member that already has a name at global scope",
8650 "" /* blockName->c_str() */, "");
8652 error(loc, "block instance name redefinition", variable.getName().c_str(), "");
8657 // Save it in the AST for linker use.
8658 if (symbolTable.atGlobalLevel())
8659 trackLinkage(variable);
8663 // "For a block, this process applies to the entire block, or until the first member
8664 // is reached that has a location layout qualifier. When a block member is declared with a location
8665 // qualifier, its location comes from that qualifier: The member's location qualifier overrides the block-level
8666 // declaration. Subsequent members are again assigned consecutive locations, based on the newest location,
8667 // until the next member declared with a location qualifier. The values used for locations do not have to be
8668 // declared in increasing order."
8669 void HlslParseContext::fixBlockLocations(const TSourceLoc& loc, TQualifier& qualifier, TTypeList& typeList, bool memberWithLocation, bool memberWithoutLocation)
8671 // "If a block has no block-level location layout qualifier, it is required that either all or none of its members
8672 // have a location layout qualifier, or a compile-time error results."
8673 if (! qualifier.hasLocation() && memberWithLocation && memberWithoutLocation)
8674 error(loc, "either the block needs a location, or all members need a location, or no members have a location", "location", "");
8676 if (memberWithLocation) {
8677 // remove any block-level location and make it per *every* member
8678 int nextLocation = 0; // by the rule above, initial value is not relevant
8679 if (qualifier.hasAnyLocation()) {
8680 nextLocation = qualifier.layoutLocation;
8681 qualifier.layoutLocation = TQualifier::layoutLocationEnd;
8682 if (qualifier.hasComponent()) {
8683 // "It is a compile-time error to apply the *component* qualifier to a ... block"
8684 error(loc, "cannot apply to a block", "component", "");
8686 if (qualifier.hasIndex()) {
8687 error(loc, "cannot apply to a block", "index", "");
8690 for (unsigned int member = 0; member < typeList.size(); ++member) {
8691 TQualifier& memberQualifier = typeList[member].type->getQualifier();
8692 const TSourceLoc& memberLoc = typeList[member].loc;
8693 if (! memberQualifier.hasLocation()) {
8694 if (nextLocation >= (int)TQualifier::layoutLocationEnd)
8695 error(memberLoc, "location is too large", "location", "");
8696 memberQualifier.layoutLocation = nextLocation;
8697 memberQualifier.layoutComponent = 0;
8699 nextLocation = memberQualifier.layoutLocation +
8700 intermediate.computeTypeLocationSize(*typeList[member].type, language);
8706 void HlslParseContext::fixBlockXfbOffsets(TQualifier& qualifier, TTypeList& typeList)
8708 // "If a block is qualified with xfb_offset, all its
8709 // members are assigned transform feedback buffer offsets. If a block is not qualified with xfb_offset, any
8710 // members of that block not qualified with an xfb_offset will not be assigned transform feedback buffer
8713 if (! qualifier.hasXfbBuffer() || ! qualifier.hasXfbOffset())
8716 int nextOffset = qualifier.layoutXfbOffset;
8717 for (unsigned int member = 0; member < typeList.size(); ++member) {
8718 TQualifier& memberQualifier = typeList[member].type->getQualifier();
8719 bool containsDouble = false;
8720 int memberSize = intermediate.computeTypeXfbSize(*typeList[member].type, containsDouble);
8721 // see if we need to auto-assign an offset to this member
8722 if (! memberQualifier.hasXfbOffset()) {
8723 // "if applied to an aggregate containing a double, the offset must also be a multiple of 8"
8725 RoundToPow2(nextOffset, 8);
8726 memberQualifier.layoutXfbOffset = nextOffset;
8728 nextOffset = memberQualifier.layoutXfbOffset;
8729 nextOffset += memberSize;
8732 // The above gave all block members an offset, so we can take it off the block now,
8733 // which will avoid double counting the offset usage.
8734 qualifier.layoutXfbOffset = TQualifier::layoutXfbOffsetEnd;
8737 // Calculate and save the offset of each block member, using the recursively
8738 // defined block offset rules and the user-provided offset and align.
8740 // Also, compute and save the total size of the block. For the block's size, arrayness
8741 // is not taken into account, as each element is backed by a separate buffer.
8743 void HlslParseContext::fixBlockUniformOffsets(const TQualifier& qualifier, TTypeList& typeList)
8745 if (! qualifier.isUniformOrBuffer())
8747 if (qualifier.layoutPacking != ElpStd140 && qualifier.layoutPacking != ElpStd430)
8752 for (unsigned int member = 0; member < typeList.size(); ++member) {
8753 TQualifier& memberQualifier = typeList[member].type->getQualifier();
8754 const TSourceLoc& memberLoc = typeList[member].loc;
8756 // "When align is applied to an array, it effects only the start of the array, not the array's internal stride."
8758 // modify just the children's view of matrix layout, if there is one for this member
8759 TLayoutMatrix subMatrixLayout = typeList[member].type->getQualifier().layoutMatrix;
8761 int memberAlignment = intermediate.getBaseAlignment(*typeList[member].type, memberSize, dummyStride,
8762 qualifier.layoutPacking == ElpStd140,
8763 subMatrixLayout != ElmNone
8764 ? subMatrixLayout == ElmRowMajor
8765 : qualifier.layoutMatrix == ElmRowMajor);
8766 if (memberQualifier.hasOffset()) {
8767 // "The specified offset must be a multiple
8768 // of the base alignment of the type of the block member it qualifies, or a compile-time error results."
8769 if (! IsMultipleOfPow2(memberQualifier.layoutOffset, memberAlignment))
8770 error(memberLoc, "must be a multiple of the member's alignment", "offset", "");
8772 // "The offset qualifier forces the qualified member to start at or after the specified
8773 // integral-constant expression, which will be its byte offset from the beginning of the buffer.
8774 // "The actual offset of a member is computed as
8775 // follows: If offset was declared, start with that offset, otherwise start with the next available offset."
8776 offset = std::max(offset, memberQualifier.layoutOffset);
8779 // "The actual alignment of a member will be the greater of the specified align alignment and the standard
8780 // (e.g., std140) base alignment for the member's type."
8781 if (memberQualifier.hasAlign())
8782 memberAlignment = std::max(memberAlignment, memberQualifier.layoutAlign);
8784 // "If the resulting offset is not a multiple of the actual alignment,
8785 // increase it to the first offset that is a multiple of
8786 // the actual alignment."
8787 RoundToPow2(offset, memberAlignment);
8788 typeList[member].type->getQualifier().layoutOffset = offset;
8789 offset += memberSize;
8793 // For an identifier that is already declared, add more qualification to it.
8794 void HlslParseContext::addQualifierToExisting(const TSourceLoc& loc, TQualifier qualifier, const TString& identifier)
8796 TSymbol* symbol = symbolTable.find(identifier);
8797 if (symbol == nullptr) {
8798 error(loc, "identifier not previously declared", identifier.c_str(), "");
8801 if (symbol->getAsFunction()) {
8802 error(loc, "cannot re-qualify a function name", identifier.c_str(), "");
8806 if (qualifier.isAuxiliary() ||
8807 qualifier.isMemory() ||
8808 qualifier.isInterpolation() ||
8809 qualifier.hasLayout() ||
8810 qualifier.storage != EvqTemporary ||
8811 qualifier.precision != EpqNone) {
8812 error(loc, "cannot add storage, auxiliary, memory, interpolation, layout, or precision qualifier to an existing variable", identifier.c_str(), "");
8816 // For read-only built-ins, add a new symbol for holding the modified qualifier.
8817 // This will bring up an entire block, if a block type has to be modified (e.g., gl_Position inside a block)
8818 if (symbol->isReadOnly())
8819 symbol = symbolTable.copyUp(symbol);
8821 if (qualifier.invariant) {
8822 if (intermediate.inIoAccessed(identifier))
8823 error(loc, "cannot change qualification after use", "invariant", "");
8824 symbol->getWritableType().getQualifier().invariant = true;
8825 } else if (qualifier.noContraction) {
8826 if (intermediate.inIoAccessed(identifier))
8827 error(loc, "cannot change qualification after use", "precise", "");
8828 symbol->getWritableType().getQualifier().noContraction = true;
8829 } else if (qualifier.specConstant) {
8830 symbol->getWritableType().getQualifier().makeSpecConstant();
8831 if (qualifier.hasSpecConstantId())
8832 symbol->getWritableType().getQualifier().layoutSpecConstantId = qualifier.layoutSpecConstantId;
8834 warn(loc, "unknown requalification", "", "");
8837 void HlslParseContext::addQualifierToExisting(const TSourceLoc& loc, TQualifier qualifier, TIdentifierList& identifiers)
8839 for (unsigned int i = 0; i < identifiers.size(); ++i)
8840 addQualifierToExisting(loc, qualifier, *identifiers[i]);
8844 // Update the intermediate for the given input geometry
8846 bool HlslParseContext::handleInputGeometry(const TSourceLoc& loc, const TLayoutGeometry& geometry)
8849 case ElgPoints: // fall through
8850 case ElgLines: // ...
8851 case ElgTriangles: // ...
8852 case ElgLinesAdjacency: // ...
8853 case ElgTrianglesAdjacency: // ...
8854 if (! intermediate.setInputPrimitive(geometry)) {
8855 error(loc, "input primitive geometry redefinition", TQualifier::getGeometryString(geometry), "");
8861 error(loc, "cannot apply to 'in'", TQualifier::getGeometryString(geometry), "");
8869 // Update the intermediate for the given output geometry
8871 bool HlslParseContext::handleOutputGeometry(const TSourceLoc& loc, const TLayoutGeometry& geometry)
8873 // If this is not a geometry shader, ignore. It might be a mixed shader including several stages.
8874 // Since that's an OK situation, return true for success.
8875 if (language != EShLangGeometry)
8881 case ElgTriangleStrip:
8882 if (! intermediate.setOutputPrimitive(geometry)) {
8883 error(loc, "output primitive geometry redefinition", TQualifier::getGeometryString(geometry), "");
8888 error(loc, "cannot apply to 'out'", TQualifier::getGeometryString(geometry), "");
8896 // Selection attributes
8898 void HlslParseContext::handleSelectionAttributes(const TSourceLoc& loc, TIntermSelection* selection,
8899 const TAttributes& attributes)
8901 if (selection == nullptr)
8904 for (auto it = attributes.begin(); it != attributes.end(); ++it) {
8907 selection->setFlatten();
8910 selection->setDontFlatten();
8913 warn(loc, "attribute does not apply to a selection", "", "");
8920 // Switch attributes
8922 void HlslParseContext::handleSwitchAttributes(const TSourceLoc& loc, TIntermSwitch* selection,
8923 const TAttributes& attributes)
8925 if (selection == nullptr)
8928 for (auto it = attributes.begin(); it != attributes.end(); ++it) {
8931 selection->setFlatten();
8934 selection->setDontFlatten();
8937 warn(loc, "attribute does not apply to a switch", "", "");
8946 void HlslParseContext::handleLoopAttributes(const TSourceLoc& loc, TIntermLoop* loop,
8947 const TAttributes& attributes)
8949 if (loop == nullptr)
8952 for (auto it = attributes.begin(); it != attributes.end(); ++it) {
8958 loop->setDontUnroll();
8961 warn(loc, "attribute does not apply to a loop", "", "");
8968 // Updating default qualifier for the case of a declaration with just a qualifier,
8969 // no type, block, or identifier.
8971 void HlslParseContext::updateStandaloneQualifierDefaults(const TSourceLoc& loc, const TPublicType& publicType)
8973 if (publicType.shaderQualifiers.vertices != TQualifier::layoutNotSet) {
8974 assert(language == EShLangTessControl || language == EShLangGeometry);
8975 // const char* id = (language == EShLangTessControl) ? "vertices" : "max_vertices";
8977 if (publicType.shaderQualifiers.invocations != TQualifier::layoutNotSet) {
8978 if (! intermediate.setInvocations(publicType.shaderQualifiers.invocations))
8979 error(loc, "cannot change previously set layout value", "invocations", "");
8981 if (publicType.shaderQualifiers.geometry != ElgNone) {
8982 if (publicType.qualifier.storage == EvqVaryingIn) {
8983 switch (publicType.shaderQualifiers.geometry) {
8986 case ElgLinesAdjacency:
8988 case ElgTrianglesAdjacency:
8993 error(loc, "cannot apply to input", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry),
8996 } else if (publicType.qualifier.storage == EvqVaryingOut) {
8997 handleOutputGeometry(loc, publicType.shaderQualifiers.geometry);
8999 error(loc, "cannot apply to:", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry),
9000 GetStorageQualifierString(publicType.qualifier.storage));
9002 if (publicType.shaderQualifiers.spacing != EvsNone)
9003 intermediate.setVertexSpacing(publicType.shaderQualifiers.spacing);
9004 if (publicType.shaderQualifiers.order != EvoNone)
9005 intermediate.setVertexOrder(publicType.shaderQualifiers.order);
9006 if (publicType.shaderQualifiers.pointMode)
9007 intermediate.setPointMode();
9008 for (int i = 0; i < 3; ++i) {
9009 if (publicType.shaderQualifiers.localSize[i] > 1) {
9012 case 0: max = resources.maxComputeWorkGroupSizeX; break;
9013 case 1: max = resources.maxComputeWorkGroupSizeY; break;
9014 case 2: max = resources.maxComputeWorkGroupSizeZ; break;
9017 if (intermediate.getLocalSize(i) > (unsigned int)max)
9018 error(loc, "too large; see gl_MaxComputeWorkGroupSize", "local_size", "");
9020 // Fix the existing constant gl_WorkGroupSize with this new information.
9021 TVariable* workGroupSize = getEditableVariable("gl_WorkGroupSize");
9022 workGroupSize->getWritableConstArray()[i].setUConst(intermediate.getLocalSize(i));
9024 if (publicType.shaderQualifiers.localSizeSpecId[i] != TQualifier::layoutNotSet) {
9025 intermediate.setLocalSizeSpecId(i, publicType.shaderQualifiers.localSizeSpecId[i]);
9026 // Set the workgroup built-in variable as a specialization constant
9027 TVariable* workGroupSize = getEditableVariable("gl_WorkGroupSize");
9028 workGroupSize->getWritableType().getQualifier().specConstant = true;
9031 if (publicType.shaderQualifiers.earlyFragmentTests)
9032 intermediate.setEarlyFragmentTests();
9034 const TQualifier& qualifier = publicType.qualifier;
9036 switch (qualifier.storage) {
9038 if (qualifier.hasMatrix())
9039 globalUniformDefaults.layoutMatrix = qualifier.layoutMatrix;
9040 if (qualifier.hasPacking())
9041 globalUniformDefaults.layoutPacking = qualifier.layoutPacking;
9044 if (qualifier.hasMatrix())
9045 globalBufferDefaults.layoutMatrix = qualifier.layoutMatrix;
9046 if (qualifier.hasPacking())
9047 globalBufferDefaults.layoutPacking = qualifier.layoutPacking;
9052 if (qualifier.hasStream())
9053 globalOutputDefaults.layoutStream = qualifier.layoutStream;
9054 if (qualifier.hasXfbBuffer())
9055 globalOutputDefaults.layoutXfbBuffer = qualifier.layoutXfbBuffer;
9056 if (globalOutputDefaults.hasXfbBuffer() && qualifier.hasXfbStride()) {
9057 if (! intermediate.setXfbBufferStride(globalOutputDefaults.layoutXfbBuffer, qualifier.layoutXfbStride))
9058 error(loc, "all stride settings must match for xfb buffer", "xfb_stride", "%d",
9059 qualifier.layoutXfbBuffer);
9063 error(loc, "default qualifier requires 'uniform', 'buffer', 'in', or 'out' storage qualification", "", "");
9069 // Take the sequence of statements that has been built up since the last case/default,
9070 // put it on the list of top-level nodes for the current (inner-most) switch statement,
9071 // and follow that by the case/default we are on now. (See switch topology comment on
9074 void HlslParseContext::wrapupSwitchSubsequence(TIntermAggregate* statements, TIntermNode* branchNode)
9076 TIntermSequence* switchSequence = switchSequenceStack.back();
9079 statements->setOperator(EOpSequence);
9080 switchSequence->push_back(statements);
9083 // check all previous cases for the same label (or both are 'default')
9084 for (unsigned int s = 0; s < switchSequence->size(); ++s) {
9085 TIntermBranch* prevBranch = (*switchSequence)[s]->getAsBranchNode();
9087 TIntermTyped* prevExpression = prevBranch->getExpression();
9088 TIntermTyped* newExpression = branchNode->getAsBranchNode()->getExpression();
9089 if (prevExpression == nullptr && newExpression == nullptr)
9090 error(branchNode->getLoc(), "duplicate label", "default", "");
9091 else if (prevExpression != nullptr &&
9092 newExpression != nullptr &&
9093 prevExpression->getAsConstantUnion() &&
9094 newExpression->getAsConstantUnion() &&
9095 prevExpression->getAsConstantUnion()->getConstArray()[0].getIConst() ==
9096 newExpression->getAsConstantUnion()->getConstArray()[0].getIConst())
9097 error(branchNode->getLoc(), "duplicated value", "case", "");
9100 switchSequence->push_back(branchNode);
9105 // Turn the top-level node sequence built up of wrapupSwitchSubsequence
9106 // into a switch node.
9108 TIntermNode* HlslParseContext::addSwitch(const TSourceLoc& loc, TIntermTyped* expression,
9109 TIntermAggregate* lastStatements, const TAttributes& attributes)
9111 wrapupSwitchSubsequence(lastStatements, nullptr);
9113 if (expression == nullptr ||
9114 (expression->getBasicType() != EbtInt && expression->getBasicType() != EbtUint) ||
9115 expression->getType().isArray() || expression->getType().isMatrix() || expression->getType().isVector())
9116 error(loc, "condition must be a scalar integer expression", "switch", "");
9118 // If there is nothing to do, drop the switch but still execute the expression
9119 TIntermSequence* switchSequence = switchSequenceStack.back();
9120 if (switchSequence->size() == 0)
9123 if (lastStatements == nullptr) {
9124 // emulate a break for error recovery
9125 lastStatements = intermediate.makeAggregate(intermediate.addBranch(EOpBreak, loc));
9126 lastStatements->setOperator(EOpSequence);
9127 switchSequence->push_back(lastStatements);
9130 TIntermAggregate* body = new TIntermAggregate(EOpSequence);
9131 body->getSequence() = *switchSequenceStack.back();
9134 TIntermSwitch* switchNode = new TIntermSwitch(expression, body);
9135 switchNode->setLoc(loc);
9136 handleSwitchAttributes(loc, switchNode, attributes);
9141 // Make a new symbol-table level that is made out of the members of a structure.
9142 // This should be done as an anonymous struct (name is "") so that the symbol table
9143 // finds the members with no explicit reference to a 'this' variable.
9144 void HlslParseContext::pushThisScope(const TType& thisStruct, const TVector<TFunctionDeclarator>& functionDeclarators)
9147 TVariable& thisVariable = *new TVariable(NewPoolTString(""), thisStruct);
9148 symbolTable.pushThis(thisVariable);
9151 for (auto it = functionDeclarators.begin(); it != functionDeclarators.end(); ++it) {
9152 // member should have a prefix matching currentTypePrefix.back()
9153 // but, symbol lookup within the class scope will just use the
9154 // unprefixed name. Hence, there are two: one fully prefixed and
9155 // one with no prefix.
9156 TFunction& member = *it->function->clone();
9157 member.removePrefix(currentTypePrefix.back());
9158 symbolTable.insert(member);
9162 // Track levels of class/struct/namespace nesting with a prefix string using
9163 // the type names separated by the scoping operator. E.g., two levels
9168 // The string is empty when at normal global level.
9170 void HlslParseContext::pushNamespace(const TString& typeName)
9172 // make new type prefix
9174 if (currentTypePrefix.size() > 0)
9175 newPrefix = currentTypePrefix.back();
9176 newPrefix.append(typeName);
9177 newPrefix.append(scopeMangler);
9178 currentTypePrefix.push_back(newPrefix);
9181 // Opposite of pushNamespace(), see above
9182 void HlslParseContext::popNamespace()
9184 currentTypePrefix.pop_back();
9187 // Use the class/struct nesting string to create a global name for
9188 // a member of a class/struct.
9189 void HlslParseContext::getFullNamespaceName(TString*& name) const
9191 if (currentTypePrefix.size() == 0)
9194 TString* fullName = NewPoolTString(currentTypePrefix.back().c_str());
9195 fullName->append(*name);
9199 // Helper function to add the namespace scope mangling syntax to a string.
9200 void HlslParseContext::addScopeMangler(TString& name)
9202 name.append(scopeMangler);
9205 // Return true if this has uniform-interface like decorations.
9206 bool HlslParseContext::hasUniform(const TQualifier& qualifier) const
9208 return qualifier.hasUniformLayout() ||
9209 qualifier.layoutPushConstant;
9212 // Potentially not the opposite of hasUniform(), as if some characteristic is
9213 // ever used for more than one thing (e.g., uniform or input), hasUniform() should
9214 // say it exists, but clearUniform() should leave it in place.
9215 void HlslParseContext::clearUniform(TQualifier& qualifier)
9217 qualifier.clearUniformLayout();
9218 qualifier.layoutPushConstant = false;
9221 // Return false if builtIn by itself doesn't force this qualifier to be an input qualifier.
9222 bool HlslParseContext::isInputBuiltIn(const TQualifier& qualifier) const
9224 switch (qualifier.builtIn) {
9227 return language != EShLangVertex && language != EShLangCompute && language != EShLangFragment;
9228 case EbvClipDistance:
9229 case EbvCullDistance:
9230 return language != EShLangVertex && language != EShLangCompute;
9233 case EbvHelperInvocation:
9238 case EbvSamplePosition:
9239 case EbvViewportIndex:
9240 return language == EShLangFragment;
9241 case EbvGlobalInvocationId:
9242 case EbvLocalInvocationIndex:
9243 case EbvLocalInvocationId:
9244 case EbvNumWorkGroups:
9245 case EbvWorkGroupId:
9246 case EbvWorkGroupSize:
9247 return language == EShLangCompute;
9248 case EbvInvocationId:
9249 return language == EShLangTessControl || language == EShLangTessEvaluation || language == EShLangGeometry;
9250 case EbvPatchVertices:
9251 return language == EShLangTessControl || language == EShLangTessEvaluation;
9253 case EbvInstanceIndex:
9255 case EbvVertexIndex:
9256 return language == EShLangVertex;
9257 case EbvPrimitiveId:
9258 return language == EShLangGeometry || language == EShLangFragment || language == EShLangTessControl;
9259 case EbvTessLevelInner:
9260 case EbvTessLevelOuter:
9261 return language == EShLangTessEvaluation;
9263 return language == EShLangTessEvaluation;
9269 // Return true if there are decorations to preserve for input-like storage.
9270 bool HlslParseContext::hasInput(const TQualifier& qualifier) const
9272 if (qualifier.hasAnyLocation())
9275 if (language == EShLangFragment && (qualifier.isInterpolation() || qualifier.centroid || qualifier.sample))
9278 if (language == EShLangTessEvaluation && qualifier.patch)
9281 if (isInputBuiltIn(qualifier))
9287 // Return false if builtIn by itself doesn't force this qualifier to be an output qualifier.
9288 bool HlslParseContext::isOutputBuiltIn(const TQualifier& qualifier) const
9290 switch (qualifier.builtIn) {
9294 case EbvClipDistance:
9295 case EbvCullDistance:
9296 return language != EShLangFragment && language != EShLangCompute;
9298 case EbvFragDepthGreater:
9299 case EbvFragDepthLesser:
9301 return language == EShLangFragment;
9303 case EbvViewportIndex:
9304 return language == EShLangGeometry || language == EShLangVertex;
9305 case EbvPrimitiveId:
9306 return language == EShLangGeometry;
9307 case EbvTessLevelInner:
9308 case EbvTessLevelOuter:
9309 return language == EShLangTessControl;
9315 // Return true if there are decorations to preserve for output-like storage.
9316 bool HlslParseContext::hasOutput(const TQualifier& qualifier) const
9318 if (qualifier.hasAnyLocation())
9321 if (language != EShLangFragment && language != EShLangCompute && qualifier.hasXfb())
9324 if (language == EShLangTessControl && qualifier.patch)
9327 if (language == EShLangGeometry && qualifier.hasStream())
9330 if (isOutputBuiltIn(qualifier))
9336 // Make the IO decorations etc. be appropriate only for an input interface.
9337 void HlslParseContext::correctInput(TQualifier& qualifier)
9339 clearUniform(qualifier);
9340 if (language == EShLangVertex)
9341 qualifier.clearInterstage();
9342 if (language != EShLangTessEvaluation)
9343 qualifier.patch = false;
9344 if (language != EShLangFragment) {
9345 qualifier.clearInterpolation();
9346 qualifier.sample = false;
9349 qualifier.clearStreamLayout();
9350 qualifier.clearXfbLayout();
9352 if (! isInputBuiltIn(qualifier))
9353 qualifier.builtIn = EbvNone;
9356 // Make the IO decorations etc. be appropriate only for an output interface.
9357 void HlslParseContext::correctOutput(TQualifier& qualifier)
9359 clearUniform(qualifier);
9360 if (language == EShLangFragment)
9361 qualifier.clearInterstage();
9362 if (language != EShLangGeometry)
9363 qualifier.clearStreamLayout();
9364 if (language == EShLangFragment)
9365 qualifier.clearXfbLayout();
9366 if (language != EShLangTessControl)
9367 qualifier.patch = false;
9369 switch (qualifier.builtIn) {
9371 intermediate.setDepthReplacing();
9372 intermediate.setDepth(EldAny);
9374 case EbvFragDepthGreater:
9375 intermediate.setDepthReplacing();
9376 intermediate.setDepth(EldGreater);
9377 qualifier.builtIn = EbvFragDepth;
9379 case EbvFragDepthLesser:
9380 intermediate.setDepthReplacing();
9381 intermediate.setDepth(EldLess);
9382 qualifier.builtIn = EbvFragDepth;
9388 if (! isOutputBuiltIn(qualifier))
9389 qualifier.builtIn = EbvNone;
9392 // Make the IO decorations etc. be appropriate only for uniform type interfaces.
9393 void HlslParseContext::correctUniform(TQualifier& qualifier)
9395 if (qualifier.declaredBuiltIn == EbvNone)
9396 qualifier.declaredBuiltIn = qualifier.builtIn;
9398 qualifier.builtIn = EbvNone;
9399 qualifier.clearInterstage();
9400 qualifier.clearInterstageLayout();
9403 // Clear out all IO/Uniform stuff, so this has nothing to do with being an IO interface.
9404 void HlslParseContext::clearUniformInputOutput(TQualifier& qualifier)
9406 clearUniform(qualifier);
9407 correctUniform(qualifier);
9411 // Set texture return type. Returns success (not all types are valid).
9412 bool HlslParseContext::setTextureReturnType(TSampler& sampler, const TType& retType, const TSourceLoc& loc)
9414 // Seed the output with an invalid index. We will set it to a valid one if we can.
9415 sampler.structReturnIndex = TSampler::noReturnStruct;
9417 // Arrays aren't supported.
9418 if (retType.isArray()) {
9419 error(loc, "Arrays not supported in texture template types", "", "");
9423 // If return type is a vector, remember the vector size in the sampler, and return.
9424 if (retType.isVector() || retType.isScalar()) {
9425 sampler.vectorSize = retType.getVectorSize();
9429 // If it wasn't a vector, it must be a struct meeting certain requirements. The requirements
9430 // are checked below: just check for struct-ness here.
9431 if (!retType.isStruct()) {
9432 error(loc, "Invalid texture template type", "", "");
9436 // TODO: Subpass doesn't handle struct returns, due to some oddities with fn overloading.
9437 if (sampler.isSubpass()) {
9438 error(loc, "Unimplemented: structure template type in subpass input", "", "");
9442 TTypeList* members = retType.getWritableStruct();
9444 // Check for too many or not enough structure members.
9445 if (members->size() > 4 || members->size() == 0) {
9446 error(loc, "Invalid member count in texture template structure", "", "");
9450 // Error checking: We must have <= 4 total components, all of the same basic type.
9451 unsigned totalComponents = 0;
9452 for (unsigned m = 0; m < members->size(); ++m) {
9453 // Check for bad member types
9454 if (!(*members)[m].type->isScalar() && !(*members)[m].type->isVector()) {
9455 error(loc, "Invalid texture template struct member type", "", "");
9459 const unsigned memberVectorSize = (*members)[m].type->getVectorSize();
9460 totalComponents += memberVectorSize;
9462 // too many total member components
9463 if (totalComponents > 4) {
9464 error(loc, "Too many components in texture template structure type", "", "");
9468 // All members must be of a common basic type
9469 if ((*members)[m].type->getBasicType() != (*members)[0].type->getBasicType()) {
9470 error(loc, "Texture template structure members must same basic type", "", "");
9475 // If the structure in the return type already exists in the table, we'll use it. Otherwise, we'll make
9476 // a new entry. This is a linear search, but it hardly ever happens, and the list cannot be very large.
9477 for (unsigned int idx = 0; idx < textureReturnStruct.size(); ++idx) {
9478 if (textureReturnStruct[idx] == members) {
9479 sampler.structReturnIndex = idx;
9484 // It wasn't found as an existing entry. See if we have room for a new one.
9485 if (textureReturnStruct.size() >= TSampler::structReturnSlots) {
9486 error(loc, "Texture template struct return slots exceeded", "", "");
9490 // Insert it in the vector that tracks struct return types.
9491 sampler.structReturnIndex = unsigned(textureReturnStruct.size());
9492 textureReturnStruct.push_back(members);
9498 // Return the sampler return type in retType.
9499 void HlslParseContext::getTextureReturnType(const TSampler& sampler, TType& retType) const
9501 if (sampler.hasReturnStruct()) {
9502 assert(textureReturnStruct.size() >= sampler.structReturnIndex);
9504 // We land here if the texture return is a structure.
9505 TTypeList* blockStruct = textureReturnStruct[sampler.structReturnIndex];
9507 const TType resultType(blockStruct, "");
9508 retType.shallowCopy(resultType);
9510 // We land here if the texture return is a vector or scalar.
9511 const TType resultType(sampler.type, EvqTemporary, sampler.getVectorSize());
9512 retType.shallowCopy(resultType);
9517 // Return a symbol for the tessellation linkage variable of the given TBuiltInVariable type
9518 TIntermSymbol* HlslParseContext::findTessLinkageSymbol(TBuiltInVariable biType) const
9520 const auto it = builtInTessLinkageSymbols.find(biType);
9521 if (it == builtInTessLinkageSymbols.end()) // if it wasn't declared by the user, return nullptr
9524 return intermediate.addSymbol(*it->second->getAsVariable());
9527 // Find the patch constant function (issues error, returns nullptr if not found)
9528 const TFunction* HlslParseContext::findPatchConstantFunction(const TSourceLoc& loc)
9530 if (symbolTable.isFunctionNameVariable(patchConstantFunctionName)) {
9531 error(loc, "can't use variable in patch constant function", patchConstantFunctionName.c_str(), "");
9535 const TString mangledName = patchConstantFunctionName + "(";
9537 // create list of PCF candidates
9538 TVector<const TFunction*> candidateList;
9540 symbolTable.findFunctionNameList(mangledName, candidateList, builtIn);
9542 // We have to have one and only one, or we don't know which to pick: the patchconstantfunc does not
9543 // allow any disambiguation of overloads.
9544 if (candidateList.empty()) {
9545 error(loc, "patch constant function not found", patchConstantFunctionName.c_str(), "");
9549 // Based on directed experiments, it appears that if there are overloaded patchconstantfunctions,
9550 // HLSL picks the last one in shader source order. Since that isn't yet implemented here, error
9551 // out if there is more than one candidate.
9552 if (candidateList.size() > 1) {
9553 error(loc, "ambiguous patch constant function", patchConstantFunctionName.c_str(), "");
9557 return candidateList[0];
9560 // Finalization step: Add patch constant function invocation
9561 void HlslParseContext::addPatchConstantInvocation()
9566 // If there's no patch constant function, or we're not a HS, do nothing.
9567 if (patchConstantFunctionName.empty() || language != EShLangTessControl)
9570 // Look for built-in variables in a function's parameter list.
9571 const auto findBuiltIns = [&](const TFunction& function, std::set<tInterstageIoData>& builtIns) {
9572 for (int p=0; p<function.getParamCount(); ++p) {
9573 TStorageQualifier storage = function[p].type->getQualifier().storage;
9575 if (storage == EvqConstReadOnly) // treated identically to input
9578 if (function[p].getDeclaredBuiltIn() != EbvNone)
9579 builtIns.insert(HlslParseContext::tInterstageIoData(function[p].getDeclaredBuiltIn(), storage));
9581 builtIns.insert(HlslParseContext::tInterstageIoData(function[p].type->getQualifier().builtIn, storage));
9585 // If we synthesize a built-in interface variable, we must add it to the linkage.
9586 const auto addToLinkage = [&](const TType& type, const TString* name, TIntermSymbol** symbolNode) {
9587 if (name == nullptr) {
9588 error(loc, "unable to locate patch function parameter name", "", "");
9591 TVariable& variable = *new TVariable(name, type);
9592 if (! symbolTable.insert(variable)) {
9593 error(loc, "unable to declare patch constant function interface variable", name->c_str(), "");
9597 globalQualifierFix(loc, variable.getWritableType().getQualifier());
9599 if (symbolNode != nullptr)
9600 *symbolNode = intermediate.addSymbol(variable);
9602 trackLinkage(variable);
9606 const auto isOutputPatch = [](TFunction& patchConstantFunction, int param) {
9607 const TType& type = *patchConstantFunction[param].type;
9608 const TBuiltInVariable biType = patchConstantFunction[param].getDeclaredBuiltIn();
9610 return type.isSizedArray() && biType == EbvOutputPatch;
9613 // We will perform these steps. Each is in a scoped block for separation: they could
9614 // become separate functions to make addPatchConstantInvocation shorter.
9616 // 1. Union the interfaces, and create built-ins for anything present in the PCF and
9617 // declared as a built-in variable that isn't present in the entry point's signature.
9619 // 2. Synthesizes a call to the patchconstfunction using built-in variables from either main,
9620 // or the ones we created. Matching is based on built-in type. We may use synthesized
9621 // variables from (1) above.
9623 // 2B: Synthesize per control point invocations of wrapped entry point if the PCF requires them.
9625 // 3. Create a return sequence: copy the return value (if any) from the PCF to a
9626 // (non-sanitized) output variable. In case this may involve multiple copies, such as for
9627 // an arrayed variable, a temporary copy of the PCF output is created to avoid multiple
9628 // indirections into a complex R-value coming from the call to the PCF.
9630 // 4. Create a barrier.
9632 // 5/5B. Call the PCF inside an if test for (invocation id == 0).
9634 TFunction* patchConstantFunctionPtr = const_cast<TFunction*>(findPatchConstantFunction(loc));
9636 if (patchConstantFunctionPtr == nullptr)
9639 TFunction& patchConstantFunction = *patchConstantFunctionPtr;
9641 const int pcfParamCount = patchConstantFunction.getParamCount();
9642 TIntermSymbol* invocationIdSym = findTessLinkageSymbol(EbvInvocationId);
9643 TIntermSequence& epBodySeq = entryPointFunctionBody->getAsAggregate()->getSequence();
9645 int outPatchParam = -1; // -1 means there isn't one.
9647 // ================ Step 1A: Union Interfaces ================
9648 // Our patch constant function.
9650 std::set<tInterstageIoData> pcfBuiltIns; // patch constant function built-ins
9651 std::set<tInterstageIoData> epfBuiltIns; // entry point function built-ins
9653 assert(entryPointFunction);
9654 assert(entryPointFunctionBody);
9656 findBuiltIns(patchConstantFunction, pcfBuiltIns);
9657 findBuiltIns(*entryPointFunction, epfBuiltIns);
9659 // Find the set of built-ins in the PCF that are not present in the entry point.
9660 std::set<tInterstageIoData> notInEntryPoint;
9662 notInEntryPoint = pcfBuiltIns;
9664 // std::set_difference not usable on unordered containers
9665 for (auto bi = epfBuiltIns.begin(); bi != epfBuiltIns.end(); ++bi)
9666 notInEntryPoint.erase(*bi);
9668 // Now we'll add those to the entry and to the linkage.
9669 for (int p=0; p<pcfParamCount; ++p) {
9670 const TBuiltInVariable biType = patchConstantFunction[p].getDeclaredBuiltIn();
9671 TStorageQualifier storage = patchConstantFunction[p].type->getQualifier().storage;
9673 // Track whether there is an output patch param
9674 if (isOutputPatch(patchConstantFunction, p)) {
9675 if (outPatchParam >= 0) {
9676 // Presently we only support one per ctrl pt input.
9677 error(loc, "unimplemented: multiple output patches in patch constant function", "", "");
9683 if (biType != EbvNone) {
9684 TType* paramType = patchConstantFunction[p].type->clone();
9686 if (storage == EvqConstReadOnly) // treated identically to input
9689 // Presently, the only non-built-in we support is InputPatch, which is treated as
9690 // a pseudo-built-in.
9691 if (biType == EbvInputPatch) {
9692 builtInTessLinkageSymbols[biType] = inputPatch;
9693 } else if (biType == EbvOutputPatch) {
9696 // Use the original declaration type for the linkage
9697 paramType->getQualifier().builtIn = biType;
9699 if (notInEntryPoint.count(tInterstageIoData(biType, storage)) == 1)
9700 addToLinkage(*paramType, patchConstantFunction[p].name, nullptr);
9705 // If we didn't find it because the shader made one, add our own.
9706 if (invocationIdSym == nullptr) {
9707 TType invocationIdType(EbtUint, EvqIn, 1);
9708 TString* invocationIdName = NewPoolTString("InvocationId");
9709 invocationIdType.getQualifier().builtIn = EbvInvocationId;
9710 addToLinkage(invocationIdType, invocationIdName, &invocationIdSym);
9713 assert(invocationIdSym);
9716 TIntermTyped* pcfArguments = nullptr;
9717 TVariable* perCtrlPtVar = nullptr;
9719 // ================ Step 1B: Argument synthesis ================
9720 // Create pcfArguments for synthesis of patchconstantfunction invocation
9722 for (int p=0; p<pcfParamCount; ++p) {
9723 TIntermTyped* inputArg = nullptr;
9725 if (p == outPatchParam) {
9726 if (perCtrlPtVar == nullptr) {
9727 perCtrlPtVar = makeInternalVariable(*patchConstantFunction[outPatchParam].name,
9728 *patchConstantFunction[outPatchParam].type);
9730 perCtrlPtVar->getWritableType().getQualifier().makeTemporary();
9732 inputArg = intermediate.addSymbol(*perCtrlPtVar, loc);
9734 // find which built-in it is
9735 const TBuiltInVariable biType = patchConstantFunction[p].getDeclaredBuiltIn();
9737 if (biType == EbvInputPatch && inputPatch == nullptr) {
9738 error(loc, "unimplemented: PCF input patch without entry point input patch parameter", "", "");
9742 inputArg = findTessLinkageSymbol(biType);
9744 if (inputArg == nullptr) {
9745 error(loc, "unable to find patch constant function built-in variable", "", "");
9750 if (pcfParamCount == 1)
9751 pcfArguments = inputArg;
9753 pcfArguments = intermediate.growAggregate(pcfArguments, inputArg);
9757 // ================ Step 2: Synthesize call to PCF ================
9758 TIntermAggregate* pcfCallSequence = nullptr;
9759 TIntermTyped* pcfCall = nullptr;
9762 // Create a function call to the patchconstantfunction
9764 addInputArgumentConversions(patchConstantFunction, pcfArguments);
9767 pcfCall = intermediate.setAggregateOperator(pcfArguments, EOpFunctionCall, patchConstantFunction.getType(), loc);
9768 pcfCall->getAsAggregate()->setUserDefined();
9769 pcfCall->getAsAggregate()->setName(patchConstantFunction.getMangledName());
9770 intermediate.addToCallGraph(infoSink, intermediate.getEntryPointMangledName().c_str(),
9771 patchConstantFunction.getMangledName());
9773 if (pcfCall->getAsAggregate()) {
9774 TQualifierList& qualifierList = pcfCall->getAsAggregate()->getQualifierList();
9775 for (int i = 0; i < patchConstantFunction.getParamCount(); ++i) {
9776 TStorageQualifier qual = patchConstantFunction[i].type->getQualifier().storage;
9777 qualifierList.push_back(qual);
9779 pcfCall = addOutputArgumentConversions(patchConstantFunction, *pcfCall->getAsOperator());
9783 // ================ Step 2B: Per Control Point synthesis ================
9784 // If there is per control point data, we must either emulate that with multiple
9785 // invocations of the entry point to build up an array, or (TODO:) use a yet
9786 // unavailable extension to look across the SIMD lanes. This is the former
9787 // as a placeholder for the latter.
9788 if (outPatchParam >= 0) {
9789 // We must introduce a local temp variable of the type wanted by the PCF input.
9790 const int arraySize = patchConstantFunction[outPatchParam].type->getOuterArraySize();
9792 if (entryPointFunction->getType().getBasicType() == EbtVoid) {
9793 error(loc, "entry point must return a value for use with patch constant function", "", "");
9797 // Create calls to wrapped main to fill in the array. We will substitute fixed values
9798 // of invocation ID when calling the wrapped main.
9800 // This is the type of the each member of the per ctrl point array.
9801 const TType derefType(perCtrlPtVar->getType(), 0);
9803 for (int cpt = 0; cpt < arraySize; ++cpt) {
9804 // TODO: improve. substr(1) here is to avoid the '@' that was grafted on but isn't in the symtab
9805 // for this function.
9806 const TString origName = entryPointFunction->getName().substr(1);
9807 TFunction callee(&origName, TType(EbtVoid));
9808 TIntermTyped* callingArgs = nullptr;
9810 for (int i = 0; i < entryPointFunction->getParamCount(); i++) {
9811 TParameter& param = (*entryPointFunction)[i];
9812 TType& paramType = *param.type;
9814 if (paramType.getQualifier().isParamOutput()) {
9815 error(loc, "unimplemented: entry point outputs in patch constant function invocation", "", "");
9819 if (paramType.getQualifier().isParamInput()) {
9820 TIntermTyped* arg = nullptr;
9821 if ((*entryPointFunction)[i].getDeclaredBuiltIn() == EbvInvocationId) {
9822 // substitute invocation ID with the array element ID
9823 arg = intermediate.addConstantUnion(cpt, loc);
9825 TVariable* argVar = makeInternalVariable(*param.name, *param.type);
9826 argVar->getWritableType().getQualifier().makeTemporary();
9827 arg = intermediate.addSymbol(*argVar);
9830 handleFunctionArgument(&callee, callingArgs, arg);
9834 // Call and assign to per ctrl point variable
9835 currentCaller = intermediate.getEntryPointMangledName().c_str();
9836 TIntermTyped* callReturn = handleFunctionCall(loc, &callee, callingArgs);
9837 TIntermTyped* index = intermediate.addConstantUnion(cpt, loc);
9838 TIntermSymbol* perCtrlPtSym = intermediate.addSymbol(*perCtrlPtVar, loc);
9839 TIntermTyped* element = intermediate.addIndex(EOpIndexDirect, perCtrlPtSym, index, loc);
9840 element->setType(derefType);
9841 element->setLoc(loc);
9843 pcfCallSequence = intermediate.growAggregate(pcfCallSequence,
9844 handleAssign(loc, EOpAssign, element, callReturn));
9848 // ================ Step 3: Create return Sequence ================
9849 // Return sequence: copy PCF result to a temporary, then to shader output variable.
9850 if (pcfCall->getBasicType() != EbtVoid) {
9851 const TType* retType = &patchConstantFunction.getType(); // return type from the PCF
9852 TType outType; // output type that goes with the return type.
9853 outType.shallowCopy(*retType);
9855 // substitute the output type
9856 const auto newLists = ioTypeMap.find(retType->getStruct());
9857 if (newLists != ioTypeMap.end())
9858 outType.setStruct(newLists->second.output);
9860 // Substitute the top level type's built-in type
9861 if (patchConstantFunction.getDeclaredBuiltInType() != EbvNone)
9862 outType.getQualifier().builtIn = patchConstantFunction.getDeclaredBuiltInType();
9864 outType.getQualifier().patch = true; // make it a per-patch variable
9866 TVariable* pcfOutput = makeInternalVariable("@patchConstantOutput", outType);
9867 pcfOutput->getWritableType().getQualifier().storage = EvqVaryingOut;
9869 if (pcfOutput->getType().containsBuiltIn())
9872 assignToInterface(*pcfOutput);
9874 TIntermSymbol* pcfOutputSym = intermediate.addSymbol(*pcfOutput, loc);
9876 // The call to the PCF is a complex R-value: we want to store it in a temp to avoid
9877 // repeated calls to the PCF:
9878 TVariable* pcfCallResult = makeInternalVariable("@patchConstantResult", *retType);
9879 pcfCallResult->getWritableType().getQualifier().makeTemporary();
9881 TIntermSymbol* pcfResultVar = intermediate.addSymbol(*pcfCallResult, loc);
9882 TIntermNode* pcfResultAssign = handleAssign(loc, EOpAssign, pcfResultVar, pcfCall);
9883 TIntermNode* pcfResultToOut = handleAssign(loc, EOpAssign, pcfOutputSym,
9884 intermediate.addSymbol(*pcfCallResult, loc));
9886 pcfCallSequence = intermediate.growAggregate(pcfCallSequence, pcfResultAssign);
9887 pcfCallSequence = intermediate.growAggregate(pcfCallSequence, pcfResultToOut);
9889 pcfCallSequence = intermediate.growAggregate(pcfCallSequence, pcfCall);
9892 // ================ Step 4: Barrier ================
9893 TIntermTyped* barrier = new TIntermAggregate(EOpBarrier);
9894 barrier->setLoc(loc);
9895 barrier->setType(TType(EbtVoid));
9896 epBodySeq.insert(epBodySeq.end(), barrier);
9898 // ================ Step 5: Test on invocation ID ================
9899 TIntermTyped* zero = intermediate.addConstantUnion(0, loc, true);
9900 TIntermTyped* cmp = intermediate.addBinaryNode(EOpEqual, invocationIdSym, zero, loc, TType(EbtBool));
9903 // ================ Step 5B: Create if statement on Invocation ID == 0 ================
9904 intermediate.setAggregateOperator(pcfCallSequence, EOpSequence, TType(EbtVoid), loc);
9905 TIntermTyped* invocationIdTest = new TIntermSelection(cmp, pcfCallSequence, nullptr);
9906 invocationIdTest->setLoc(loc);
9908 // add our test sequence before the return.
9909 epBodySeq.insert(epBodySeq.end(), invocationIdTest);
9912 // Finalization step: remove unused buffer blocks from linkage (we don't know until the
9913 // shader is entirely compiled).
9914 // Preserve order of remaining symbols.
9915 void HlslParseContext::removeUnusedStructBufferCounters()
9917 const auto endIt = std::remove_if(linkageSymbols.begin(), linkageSymbols.end(),
9918 [this](const TSymbol* sym) {
9919 const auto sbcIt = structBufferCounter.find(sym->getName());
9920 return sbcIt != structBufferCounter.end() && !sbcIt->second;
9923 linkageSymbols.erase(endIt, linkageSymbols.end());
9926 // Finalization step: patch texture shadow modes to match samplers they were combined with
9927 void HlslParseContext::fixTextureShadowModes()
9929 for (auto symbol = linkageSymbols.begin(); symbol != linkageSymbols.end(); ++symbol) {
9930 TSampler& sampler = (*symbol)->getWritableType().getSampler();
9932 if (sampler.isTexture()) {
9933 const auto shadowMode = textureShadowVariant.find((*symbol)->getUniqueId());
9934 if (shadowMode != textureShadowVariant.end()) {
9936 if (shadowMode->second->overloaded())
9937 // Texture needs legalization if it's been seen with both shadow and non-shadow modes.
9938 intermediate.setNeedsLegalization();
9940 sampler.shadow = shadowMode->second->isShadowId((*symbol)->getUniqueId());
9946 // Finalization step: patch append methods to use proper stream output, which isn't known until
9947 // main is parsed, which could happen after the append method is parsed.
9948 void HlslParseContext::finalizeAppendMethods()
9953 // Nothing to do: bypass test for valid stream output.
9954 if (gsAppends.empty())
9957 if (gsStreamOutput == nullptr) {
9958 error(loc, "unable to find output symbol for Append()", "", "");
9962 // Patch append sequences, now that we know the stream output symbol.
9963 for (auto append = gsAppends.begin(); append != gsAppends.end(); ++append) {
9964 append->node->getSequence()[0] =
9965 handleAssign(append->loc, EOpAssign,
9966 intermediate.addSymbol(*gsStreamOutput, append->loc),
9967 append->node->getSequence()[0]->getAsTyped());
9972 void HlslParseContext::finish()
9974 // Error check: There was a dangling .mips operator. These are not nested constructs in the grammar, so
9975 // cannot be detected there. This is not strictly needed in a non-validating parser; it's just helpful.
9976 if (! mipsOperatorMipArg.empty()) {
9977 error(mipsOperatorMipArg.back().loc, "unterminated mips operator:", "", "");
9980 removeUnusedStructBufferCounters();
9981 addPatchConstantInvocation();
9982 fixTextureShadowModes();
9983 finalizeAppendMethods();
9985 // Communicate out (esp. for command line) that we formed AST that will make
9986 // illegal AST SPIR-V and it needs transforms to legalize it.
9987 if (intermediate.needsLegalization() && (messages & EShMsgHlslLegalization))
9988 infoSink.info << "WARNING: AST will form illegal SPIR-V; need to transform to legalize";
9990 TParseContextBase::finish();
9993 } // end namespace glslang