blob: 4f58c4f529ee487de0dcb3e96edb0cf249d1d259 [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich927608b2017-01-06 12:34:14 -07002// Copyright (C) 2014-2016 LunarG, Inc.
John Kessenichb23d2322018-12-14 10:47:35 -07003// Copyright (C) 2015-2018 Google, Inc.
John Kessenich66011cb2018-03-06 16:12:04 -07004// Copyright (C) 2017 ARM Limited.
John Kessenich140f3df2015-06-26 16:58:36 -06005//
John Kessenich927608b2017-01-06 12:34:14 -07006// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06007//
John Kessenich927608b2017-01-06 12:34:14 -07008// Redistribution and use in source and binary forms, with or without
9// modification, are permitted provided that the following conditions
10// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060011//
12// Redistributions of source code must retain the above copyright
13// notice, this list of conditions and the following disclaimer.
14//
15// Redistributions in binary form must reproduce the above
16// copyright notice, this list of conditions and the following
17// disclaimer in the documentation and/or other materials provided
18// with the distribution.
19//
20// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
21// contributors may be used to endorse or promote products derived
22// from this software without specific prior written permission.
23//
John Kessenich927608b2017-01-06 12:34:14 -070024// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
27// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
28// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
29// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
30// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35// POSSIBILITY OF SUCH DAMAGE.
John Kessenich140f3df2015-06-26 16:58:36 -060036
37//
John Kessenich140f3df2015-06-26 16:58:36 -060038// Visit the nodes in the glslang intermediate tree representation to
39// translate them to SPIR-V.
40//
41
John Kessenich5e4b1242015-08-06 22:53:06 -060042#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060043#include "GlslangToSpv.h"
44#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060045namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080046 #include "GLSL.std.450.h"
47 #include "GLSL.ext.KHR.h"
Piers Daniell1c5443c2017-12-13 13:07:22 -070048 #include "GLSL.ext.EXT.h"
Rex Xu9d93a232016-05-05 12:30:44 +080049#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080050 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080051#endif
chaoc0ad6a4e2016-12-19 16:29:34 -080052 #include "GLSL.ext.NV.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060053}
John Kessenich140f3df2015-06-26 16:58:36 -060054
55// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020056#include "../glslang/MachineIndependent/localintermediate.h"
57#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060058#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050059#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060060
John Kessenich140f3df2015-06-26 16:58:36 -060061#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050062#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040063#include <list>
64#include <map>
65#include <stack>
66#include <string>
67#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060068
69namespace {
70
qining4c912612016-04-01 10:35:16 -040071namespace {
72class SpecConstantOpModeGuard {
73public:
74 SpecConstantOpModeGuard(spv::Builder* builder)
75 : builder_(builder) {
76 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040077 }
78 ~SpecConstantOpModeGuard() {
79 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
80 : builder_->setToNormalCodeGenMode();
81 }
qining40887662016-04-03 22:20:42 -040082 void turnOnSpecConstantOpMode() {
83 builder_->setToSpecConstCodeGenMode();
84 }
qining4c912612016-04-01 10:35:16 -040085
86private:
87 spv::Builder* builder_;
88 bool previous_flag_;
89};
John Kessenichead86222018-03-28 18:01:20 -060090
91struct OpDecorations {
92 spv::Decoration precision;
93 spv::Decoration noContraction;
John Kessenich5611c6d2018-04-05 11:25:02 -060094 spv::Decoration nonUniform;
John Kessenichead86222018-03-28 18:01:20 -060095};
96
97} // namespace
qining4c912612016-04-01 10:35:16 -040098
John Kessenich140f3df2015-06-26 16:58:36 -060099//
100// The main holder of information for translating glslang to SPIR-V.
101//
102// Derives from the AST walking base class.
103//
104class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
105public:
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700106 TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger,
107 glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700108 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600109
110 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
111 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
112 void visitConstantUnion(glslang::TIntermConstantUnion*);
113 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
114 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
115 void visitSymbol(glslang::TIntermSymbol* symbol);
116 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
117 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
118 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
119
John Kessenichfca82622016-11-26 13:23:20 -0700120 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700121 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600122
123protected:
John Kessenich5d610ee2018-03-07 18:05:55 -0700124 TGlslangToSpvTraverser(TGlslangToSpvTraverser&);
125 TGlslangToSpvTraverser& operator=(TGlslangToSpvTraverser&);
126
Rex Xu17ff3432016-10-14 17:41:45 +0800127 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800128 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
John Kessenich5611c6d2018-04-05 11:25:02 -0600129 spv::Decoration TranslateNonUniformDecoration(const glslang::TQualifier& qualifier);
Jeff Bolz36831c92018-09-05 10:11:41 -0500130 spv::Builder::AccessChain::CoherentFlags TranslateCoherent(const glslang::TType& type);
131 spv::MemoryAccessMask TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
132 spv::ImageOperandsMask TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
133 spv::Scope TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
David Netoa901ffe2016-06-08 14:11:40 +0100134 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700135 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kesseniche18fd202018-01-30 11:01:39 -0700136 spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const;
137 spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const;
John Kessenich1f4d0462019-01-12 17:31:41 +0700138 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, std::vector<unsigned int>& operands) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600139 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich5611c6d2018-04-05 11:25:02 -0600140 void addIndirectionIndexCapabilities(const glslang::TType& baseType, const glslang::TType& indexType);
John Kessenich140f3df2015-06-26 16:58:36 -0600141 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
142 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600143 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
144 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
145 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600146 spv::Id convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly = false);
John Kessenichead86222018-03-28 18:01:20 -0600147 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&,
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600148 bool lastBufferBlockMember, bool forwardReferenceOnly = false);
John Kessenich0e737842017-03-24 18:38:16 -0600149 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600150 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
151 glslang::TLayoutPacking, const glslang::TQualifier&);
152 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
153 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700154 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700155 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800156 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600157 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700158 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700159 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
160 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich5d610ee2018-03-07 18:05:55 -0700161 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset,
162 int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100163 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600164
John Kessenich6fccb3c2016-09-19 16:01:41 -0600165 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd3ed90b2018-05-04 11:43:03 -0600166 bool writableParam(glslang::TStorageQualifier) const;
John Kessenichd41993d2017-09-10 15:21:05 -0600167 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600168 void makeFunctions(const glslang::TIntermSequence&);
169 void makeGlobalInitializers(const glslang::TIntermSequence&);
170 void visitFunctions(const glslang::TIntermSequence&);
171 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Jeff Bolz38a52fc2019-06-14 09:56:28 -0500172 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments, spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -0600173 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
174 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600175 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
176
John Kessenichead86222018-03-28 18:01:20 -0600177 spv::Id createBinaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right,
178 glslang::TBasicType typeProxy, bool reduceComparison = true);
179 spv::Id createBinaryMatrixOperation(spv::Op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right);
180 spv::Id createUnaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id operand,
Jeff Bolz38a52fc2019-06-14 09:56:28 -0500181 glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -0600182 spv::Id createUnaryMatrixOperation(spv::Op op, OpDecorations&, spv::Id typeId, spv::Id operand,
183 glslang::TBasicType typeProxy);
184 spv::Id createConversion(glslang::TOperator op, OpDecorations&, spv::Id destTypeId, spv::Id operand,
185 glslang::TBasicType typeProxy);
John Kessenichad7645f2018-06-04 19:11:25 -0600186 spv::Id createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize);
John Kessenich140f3df2015-06-26 16:58:36 -0600187 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Jeff Bolz38a52fc2019-06-14 09:56:28 -0500188 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
Rex Xu51596642016-09-21 18:56:12 +0800189 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800190 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich66011cb2018-03-06 16:12:04 -0700191 spv::Id createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -0600192 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800193 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600194 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
Chao Chen3c366992018-09-19 11:41:59 -0700195#ifdef NV_EXTENSIONS
196 void addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier & qualifier);
197#endif
qining08408382016-03-21 09:51:37 -0400198 spv::Id createSpvConstant(const glslang::TIntermTyped&);
199 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600200 bool isTrivialLeaf(const glslang::TIntermTyped* node);
201 bool isTrivial(const glslang::TIntermTyped* node);
202 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500203#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +0800204 spv::Id getExtBuiltins(const char* name);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500205#endif
John Kessenich66011cb2018-03-06 16:12:04 -0700206 void addPre13Extension(const char* ext)
207 {
208 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
209 builder.addExtension(ext);
210 }
John Kessenich140f3df2015-06-26 16:58:36 -0600211
John Kessenich121853f2017-05-31 17:11:16 -0600212 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600213 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600214 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700215 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600216 int sequenceDepth;
217
Lei Zhang17535f72016-05-04 15:55:59 -0400218 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400219
John Kessenich140f3df2015-06-26 16:58:36 -0600220 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
221 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700222 bool inEntryPoint;
223 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700224 bool linkageOnly; // true when visiting the set of objects in the AST present only for establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700225 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600226 const glslang::TIntermediate* glslangIntermediate;
John Kessenich605afc72019-06-17 23:33:09 -0600227 bool nanMinMaxClamp; // true if use NMin/NMax/NClamp instead of FMin/FMax/FClamp
John Kessenich140f3df2015-06-26 16:58:36 -0600228 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800229 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600230
John Kessenich2f273362015-07-18 22:34:27 -0600231 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600232 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600233 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700234 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700235 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
236 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper;
John Kessenich140f3df2015-06-26 16:58:36 -0600237 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700238 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600239 // Map pointee types for EbtReference to their forward pointers
240 std::map<const glslang::TType *, spv::Id> forwardPointers;
John Kessenich140f3df2015-06-26 16:58:36 -0600241};
242
243//
244// Helper functions for translating glslang representations to SPIR-V enumerants.
245//
246
247// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700248spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600249{
John Kessenich66e2faf2016-03-12 18:34:36 -0700250 switch (source) {
251 case glslang::EShSourceGlsl:
252 switch (profile) {
253 case ENoProfile:
254 case ECoreProfile:
255 case ECompatibilityProfile:
256 return spv::SourceLanguageGLSL;
257 case EEsProfile:
258 return spv::SourceLanguageESSL;
259 default:
260 return spv::SourceLanguageUnknown;
261 }
262 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600263 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600264 default:
265 return spv::SourceLanguageUnknown;
266 }
267}
268
269// Translate glslang language (stage) to SPIR-V execution model.
270spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
271{
272 switch (stage) {
273 case EShLangVertex: return spv::ExecutionModelVertex;
274 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
275 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
276 case EShLangGeometry: return spv::ExecutionModelGeometry;
277 case EShLangFragment: return spv::ExecutionModelFragment;
278 case EShLangCompute: return spv::ExecutionModelGLCompute;
Chao Chen3c366992018-09-19 11:41:59 -0700279#ifdef NV_EXTENSIONS
Ashwin Leleff1783d2018-10-22 16:41:44 -0700280 case EShLangRayGenNV: return spv::ExecutionModelRayGenerationNV;
281 case EShLangIntersectNV: return spv::ExecutionModelIntersectionNV;
282 case EShLangAnyHitNV: return spv::ExecutionModelAnyHitNV;
283 case EShLangClosestHitNV: return spv::ExecutionModelClosestHitNV;
284 case EShLangMissNV: return spv::ExecutionModelMissNV;
285 case EShLangCallableNV: return spv::ExecutionModelCallableNV;
Chao Chen3c366992018-09-19 11:41:59 -0700286 case EShLangTaskNV: return spv::ExecutionModelTaskNV;
287 case EShLangMeshNV: return spv::ExecutionModelMeshNV;
288#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600289 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700290 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600291 return spv::ExecutionModelFragment;
292 }
293}
294
John Kessenich140f3df2015-06-26 16:58:36 -0600295// Translate glslang sampler type to SPIR-V dimensionality.
296spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
297{
298 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700299 case glslang::Esd1D: return spv::Dim1D;
300 case glslang::Esd2D: return spv::Dim2D;
301 case glslang::Esd3D: return spv::Dim3D;
302 case glslang::EsdCube: return spv::DimCube;
303 case glslang::EsdRect: return spv::DimRect;
304 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700305 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600306 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700307 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600308 return spv::Dim2D;
309 }
310}
311
John Kessenichf6640762016-08-01 19:44:00 -0600312// Translate glslang precision to SPIR-V precision decorations.
313spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600314{
John Kessenichf6640762016-08-01 19:44:00 -0600315 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700316 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600317 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600318 default:
319 return spv::NoPrecision;
320 }
321}
322
John Kessenichf6640762016-08-01 19:44:00 -0600323// Translate glslang type to SPIR-V precision decorations.
324spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
325{
326 return TranslatePrecisionDecoration(type.getQualifier().precision);
327}
328
John Kessenich140f3df2015-06-26 16:58:36 -0600329// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600330spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600331{
332 if (type.getBasicType() == glslang::EbtBlock) {
333 switch (type.getQualifier().storage) {
334 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600335 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600336 case glslang::EvqVaryingIn: return spv::DecorationBlock;
337 case glslang::EvqVaryingOut: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700338#ifdef NV_EXTENSIONS
339 case glslang::EvqPayloadNV: return spv::DecorationBlock;
340 case glslang::EvqPayloadInNV: return spv::DecorationBlock;
341 case glslang::EvqHitAttrNV: return spv::DecorationBlock;
Ashwin Leleff1783d2018-10-22 16:41:44 -0700342 case glslang::EvqCallableDataNV: return spv::DecorationBlock;
343 case glslang::EvqCallableDataInNV: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700344#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600345 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700346 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600347 break;
348 }
349 }
350
John Kessenich4016e382016-07-15 11:53:56 -0600351 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600352}
353
Rex Xu1da878f2016-02-21 20:59:01 +0800354// Translate glslang type to SPIR-V memory decorations.
Jeff Bolz36831c92018-09-05 10:11:41 -0500355void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory, bool useVulkanMemoryModel)
Rex Xu1da878f2016-02-21 20:59:01 +0800356{
Jeff Bolz36831c92018-09-05 10:11:41 -0500357 if (!useVulkanMemoryModel) {
358 if (qualifier.coherent)
359 memory.push_back(spv::DecorationCoherent);
360 if (qualifier.volatil) {
361 memory.push_back(spv::DecorationVolatile);
362 memory.push_back(spv::DecorationCoherent);
363 }
John Kessenich14b85d32018-06-04 15:36:03 -0600364 }
Rex Xu1da878f2016-02-21 20:59:01 +0800365 if (qualifier.restrict)
366 memory.push_back(spv::DecorationRestrict);
367 if (qualifier.readonly)
368 memory.push_back(spv::DecorationNonWritable);
369 if (qualifier.writeonly)
370 memory.push_back(spv::DecorationNonReadable);
371}
372
John Kessenich140f3df2015-06-26 16:58:36 -0600373// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700374spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600375{
376 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700377 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600378 case glslang::ElmRowMajor:
379 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700380 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600381 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700382 default:
383 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600384 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600385 }
386 } else {
387 switch (type.getBasicType()) {
388 default:
John Kessenich4016e382016-07-15 11:53:56 -0600389 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600390 break;
391 case glslang::EbtBlock:
392 switch (type.getQualifier().storage) {
393 case glslang::EvqUniform:
394 case glslang::EvqBuffer:
395 switch (type.getQualifier().layoutPacking) {
396 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600397 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
398 default:
John Kessenich4016e382016-07-15 11:53:56 -0600399 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600400 }
401 case glslang::EvqVaryingIn:
402 case glslang::EvqVaryingOut:
Chao Chen3c366992018-09-19 11:41:59 -0700403 if (type.getQualifier().isTaskMemory()) {
404 switch (type.getQualifier().layoutPacking) {
405 case glslang::ElpShared: return spv::DecorationGLSLShared;
406 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
407 default: break;
408 }
409 } else {
410 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
411 }
John Kessenich4016e382016-07-15 11:53:56 -0600412 return spv::DecorationMax;
Chao Chenb50c02e2018-09-19 11:42:24 -0700413#ifdef NV_EXTENSIONS
414 case glslang::EvqPayloadNV:
415 case glslang::EvqPayloadInNV:
416 case glslang::EvqHitAttrNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700417 case glslang::EvqCallableDataNV:
418 case glslang::EvqCallableDataInNV:
Chao Chenb50c02e2018-09-19 11:42:24 -0700419 return spv::DecorationMax;
420#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600421 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700422 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600423 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600424 }
425 }
426 }
427}
428
429// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600430// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700431// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800432spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600433{
Rex Xubbceed72016-05-21 09:40:44 +0800434 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700435 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600436 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800437 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700438 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700439 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600440 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800441#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800442 else if (qualifier.explicitInterp) {
443 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800444 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800445 }
Rex Xu9d93a232016-05-05 12:30:44 +0800446#endif
Rex Xubbceed72016-05-21 09:40:44 +0800447 else
John Kessenich4016e382016-07-15 11:53:56 -0600448 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800449}
450
451// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600452// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800453// should be applied.
454spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
455{
456 if (qualifier.patch)
457 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700458 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600459 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700460 else if (qualifier.sample) {
461 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600462 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700463 } else
John Kessenich4016e382016-07-15 11:53:56 -0600464 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600465}
466
John Kessenich92187592016-02-01 13:45:25 -0700467// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700468spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600469{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700470 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600471 return spv::DecorationInvariant;
472 else
John Kessenich4016e382016-07-15 11:53:56 -0600473 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600474}
475
qining9220dbb2016-05-04 17:34:38 -0400476// If glslang type is noContraction, return SPIR-V NoContraction decoration.
477spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
478{
479 if (qualifier.noContraction)
480 return spv::DecorationNoContraction;
481 else
John Kessenich4016e382016-07-15 11:53:56 -0600482 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400483}
484
John Kessenich5611c6d2018-04-05 11:25:02 -0600485// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
486spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
487{
488 if (qualifier.isNonUniform()) {
489 builder.addExtension("SPV_EXT_descriptor_indexing");
490 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
491 return spv::DecorationNonUniformEXT;
492 } else
493 return spv::DecorationMax;
494}
495
Jeff Bolz36831c92018-09-05 10:11:41 -0500496spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
497{
498 if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage) {
499 return spv::MemoryAccessMaskNone;
500 }
501 spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
502 if (coherentFlags.volatil ||
503 coherentFlags.coherent ||
504 coherentFlags.devicecoherent ||
505 coherentFlags.queuefamilycoherent ||
506 coherentFlags.workgroupcoherent ||
507 coherentFlags.subgroupcoherent) {
508 mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
509 spv::MemoryAccessMakePointerVisibleKHRMask;
510 }
511 if (coherentFlags.nonprivate) {
512 mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
513 }
514 if (coherentFlags.volatil) {
515 mask = mask | spv::MemoryAccessVolatileMask;
516 }
517 if (mask != spv::MemoryAccessMaskNone) {
518 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
519 }
520 return mask;
521}
522
523spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
524{
525 if (!glslangIntermediate->usingVulkanMemoryModel()) {
526 return spv::ImageOperandsMaskNone;
527 }
528 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
529 if (coherentFlags.volatil ||
530 coherentFlags.coherent ||
531 coherentFlags.devicecoherent ||
532 coherentFlags.queuefamilycoherent ||
533 coherentFlags.workgroupcoherent ||
534 coherentFlags.subgroupcoherent) {
535 mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
536 spv::ImageOperandsMakeTexelVisibleKHRMask;
537 }
538 if (coherentFlags.nonprivate) {
539 mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
540 }
541 if (coherentFlags.volatil) {
542 mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
543 }
544 if (mask != spv::ImageOperandsMaskNone) {
545 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
546 }
547 return mask;
548}
549
550spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
551{
552 spv::Builder::AccessChain::CoherentFlags flags;
553 flags.coherent = type.getQualifier().coherent;
554 flags.devicecoherent = type.getQualifier().devicecoherent;
555 flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
556 // shared variables are implicitly workgroupcoherent in GLSL.
557 flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
558 type.getQualifier().storage == glslang::EvqShared;
559 flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600560 flags.volatil = type.getQualifier().volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500561 // *coherent variables are implicitly nonprivate in GLSL
562 flags.nonprivate = type.getQualifier().nonprivate ||
Jeff Bolzab3c9652018-10-15 22:46:48 -0500563 flags.subgroupcoherent ||
564 flags.workgroupcoherent ||
565 flags.queuefamilycoherent ||
566 flags.devicecoherent ||
Jeff Bolz38cbad12019-03-05 14:40:07 -0600567 flags.coherent ||
568 flags.volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500569 flags.isImage = type.getBasicType() == glslang::EbtSampler;
570 return flags;
571}
572
573spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
574{
575 spv::Scope scope;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600576 if (coherentFlags.volatil || coherentFlags.coherent) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500577 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
578 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
579 } else if (coherentFlags.devicecoherent) {
580 scope = spv::ScopeDevice;
581 } else if (coherentFlags.queuefamilycoherent) {
582 scope = spv::ScopeQueueFamilyKHR;
583 } else if (coherentFlags.workgroupcoherent) {
584 scope = spv::ScopeWorkgroup;
585 } else if (coherentFlags.subgroupcoherent) {
586 scope = spv::ScopeSubgroup;
587 } else {
588 scope = spv::ScopeMax;
589 }
590 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
591 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
592 }
593 return scope;
594}
595
David Netoa901ffe2016-06-08 14:11:40 +0100596// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
597// associated capabilities when required. For some built-in variables, a capability
598// is generated only when using the variable in an executable instruction, but not when
599// just declaring a struct member variable with it. This is true for PointSize,
600// ClipDistance, and CullDistance.
601spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600602{
603 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700604 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600605 // Defer adding the capability until the built-in is actually used.
606 if (! memberDeclaration) {
607 switch (glslangIntermediate->getStage()) {
608 case EShLangGeometry:
609 builder.addCapability(spv::CapabilityGeometryPointSize);
610 break;
611 case EShLangTessControl:
612 case EShLangTessEvaluation:
613 builder.addCapability(spv::CapabilityTessellationPointSize);
614 break;
615 default:
616 break;
617 }
John Kessenich92187592016-02-01 13:45:25 -0700618 }
619 return spv::BuiltInPointSize;
620
John Kessenichebb50532016-05-16 19:22:05 -0600621 // These *Distance capabilities logically belong here, but if the member is declared and
622 // then never used, consumers of SPIR-V prefer the capability not be declared.
623 // They are now generated when used, rather than here when declared.
624 // Potentially, the specification should be more clear what the minimum
625 // use needed is to trigger the capability.
626 //
John Kessenich92187592016-02-01 13:45:25 -0700627 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100628 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800629 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700630 return spv::BuiltInClipDistance;
631
632 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100633 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800634 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700635 return spv::BuiltInCullDistance;
636
637 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600638 builder.addCapability(spv::CapabilityMultiViewport);
639 if (glslangIntermediate->getStage() == EShLangVertex ||
640 glslangIntermediate->getStage() == EShLangTessControl ||
641 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800642
John Kessenichba6a3c22017-09-13 13:22:50 -0600643 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
644 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800645 }
John Kessenich92187592016-02-01 13:45:25 -0700646 return spv::BuiltInViewportIndex;
647
John Kessenich5e801132016-02-15 11:09:46 -0700648 case glslang::EbvSampleId:
649 builder.addCapability(spv::CapabilitySampleRateShading);
650 return spv::BuiltInSampleId;
651
652 case glslang::EbvSamplePosition:
653 builder.addCapability(spv::CapabilitySampleRateShading);
654 return spv::BuiltInSamplePosition;
655
656 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700657 return spv::BuiltInSampleMask;
658
John Kessenich78a45572016-07-08 14:05:15 -0600659 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700660#ifdef NV_EXTENSIONS
661 if (glslangIntermediate->getStage() == EShLangMeshNV) {
662 return spv::BuiltInLayer;
663 }
664#endif
John Kessenichba6a3c22017-09-13 13:22:50 -0600665 builder.addCapability(spv::CapabilityGeometry);
666 if (glslangIntermediate->getStage() == EShLangVertex ||
667 glslangIntermediate->getStage() == EShLangTessControl ||
668 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800669
John Kessenichba6a3c22017-09-13 13:22:50 -0600670 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
671 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800672 }
John Kessenich78a45572016-07-08 14:05:15 -0600673 return spv::BuiltInLayer;
674
John Kessenich140f3df2015-06-26 16:58:36 -0600675 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600676 case glslang::EbvVertexId: return spv::BuiltInVertexId;
677 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700678 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
679 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800680
John Kessenichda581a22015-10-14 14:10:30 -0600681 case glslang::EbvBaseVertex:
John Kessenich66011cb2018-03-06 16:12:04 -0700682 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800683 builder.addCapability(spv::CapabilityDrawParameters);
684 return spv::BuiltInBaseVertex;
685
John Kessenichda581a22015-10-14 14:10:30 -0600686 case glslang::EbvBaseInstance:
John Kessenich66011cb2018-03-06 16:12:04 -0700687 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800688 builder.addCapability(spv::CapabilityDrawParameters);
689 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200690
John Kessenichda581a22015-10-14 14:10:30 -0600691 case glslang::EbvDrawId:
John Kessenich66011cb2018-03-06 16:12:04 -0700692 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800693 builder.addCapability(spv::CapabilityDrawParameters);
694 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200695
696 case glslang::EbvPrimitiveId:
697 if (glslangIntermediate->getStage() == EShLangFragment)
698 builder.addCapability(spv::CapabilityGeometry);
699 return spv::BuiltInPrimitiveId;
700
Rex Xu37cdcee2017-06-29 17:46:34 +0800701 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800702 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
703 builder.addCapability(spv::CapabilityStencilExportEXT);
704 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800705
John Kessenich140f3df2015-06-26 16:58:36 -0600706 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600707 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
708 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
709 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
710 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
711 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
712 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
713 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600714 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
715 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
716 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
717 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
718 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
719 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
720 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
721 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800722
Rex Xu574ab042016-04-14 16:53:07 +0800723 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800724 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800725 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
726 return spv::BuiltInSubgroupSize;
727
Rex Xu574ab042016-04-14 16:53:07 +0800728 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800729 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800730 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
731 return spv::BuiltInSubgroupLocalInvocationId;
732
Rex Xu574ab042016-04-14 16:53:07 +0800733 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800734 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
735 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
736 return spv::BuiltInSubgroupEqMaskKHR;
737
Rex Xu574ab042016-04-14 16:53:07 +0800738 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800739 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
740 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
741 return spv::BuiltInSubgroupGeMaskKHR;
742
Rex Xu574ab042016-04-14 16:53:07 +0800743 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800744 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
745 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
746 return spv::BuiltInSubgroupGtMaskKHR;
747
Rex Xu574ab042016-04-14 16:53:07 +0800748 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800749 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
750 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
751 return spv::BuiltInSubgroupLeMaskKHR;
752
Rex Xu574ab042016-04-14 16:53:07 +0800753 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800754 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
755 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
756 return spv::BuiltInSubgroupLtMaskKHR;
757
John Kessenich66011cb2018-03-06 16:12:04 -0700758 case glslang::EbvNumSubgroups:
759 builder.addCapability(spv::CapabilityGroupNonUniform);
760 return spv::BuiltInNumSubgroups;
761
762 case glslang::EbvSubgroupID:
763 builder.addCapability(spv::CapabilityGroupNonUniform);
764 return spv::BuiltInSubgroupId;
765
766 case glslang::EbvSubgroupSize2:
767 builder.addCapability(spv::CapabilityGroupNonUniform);
768 return spv::BuiltInSubgroupSize;
769
770 case glslang::EbvSubgroupInvocation2:
771 builder.addCapability(spv::CapabilityGroupNonUniform);
772 return spv::BuiltInSubgroupLocalInvocationId;
773
774 case glslang::EbvSubgroupEqMask2:
775 builder.addCapability(spv::CapabilityGroupNonUniform);
776 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
777 return spv::BuiltInSubgroupEqMask;
778
779 case glslang::EbvSubgroupGeMask2:
780 builder.addCapability(spv::CapabilityGroupNonUniform);
781 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
782 return spv::BuiltInSubgroupGeMask;
783
784 case glslang::EbvSubgroupGtMask2:
785 builder.addCapability(spv::CapabilityGroupNonUniform);
786 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
787 return spv::BuiltInSubgroupGtMask;
788
789 case glslang::EbvSubgroupLeMask2:
790 builder.addCapability(spv::CapabilityGroupNonUniform);
791 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
792 return spv::BuiltInSubgroupLeMask;
793
794 case glslang::EbvSubgroupLtMask2:
795 builder.addCapability(spv::CapabilityGroupNonUniform);
796 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
797 return spv::BuiltInSubgroupLtMask;
Rex Xu9d93a232016-05-05 12:30:44 +0800798#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800799 case glslang::EbvBaryCoordNoPersp:
800 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
801 return spv::BuiltInBaryCoordNoPerspAMD;
802
803 case glslang::EbvBaryCoordNoPerspCentroid:
804 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
805 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
806
807 case glslang::EbvBaryCoordNoPerspSample:
808 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
809 return spv::BuiltInBaryCoordNoPerspSampleAMD;
810
811 case glslang::EbvBaryCoordSmooth:
812 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
813 return spv::BuiltInBaryCoordSmoothAMD;
814
815 case glslang::EbvBaryCoordSmoothCentroid:
816 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
817 return spv::BuiltInBaryCoordSmoothCentroidAMD;
818
819 case glslang::EbvBaryCoordSmoothSample:
820 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
821 return spv::BuiltInBaryCoordSmoothSampleAMD;
822
823 case glslang::EbvBaryCoordPullModel:
824 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
825 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800826#endif
chaoc771d89f2017-01-13 01:10:53 -0800827
John Kessenich6c8aaac2017-02-27 01:20:51 -0700828 case glslang::EbvDeviceIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700829 addPre13Extension(spv::E_SPV_KHR_device_group);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700830 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700831 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700832
833 case glslang::EbvViewIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700834 addPre13Extension(spv::E_SPV_KHR_multiview);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700835 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700836 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700837
Daniel Koch5154db52018-11-26 10:01:58 -0500838 case glslang::EbvFragSizeEXT:
839 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
840 builder.addCapability(spv::CapabilityFragmentDensityEXT);
841 return spv::BuiltInFragSizeEXT;
842
843 case glslang::EbvFragInvocationCountEXT:
844 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
845 builder.addCapability(spv::CapabilityFragmentDensityEXT);
846 return spv::BuiltInFragInvocationCountEXT;
847
chaoc771d89f2017-01-13 01:10:53 -0800848#ifdef NV_EXTENSIONS
849 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800850 if (!memberDeclaration) {
851 builder.addExtension(spv::E_SPV_NV_viewport_array2);
852 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
853 }
chaoc771d89f2017-01-13 01:10:53 -0800854 return spv::BuiltInViewportMaskNV;
855 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800856 if (!memberDeclaration) {
857 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
858 builder.addCapability(spv::CapabilityShaderStereoViewNV);
859 }
chaoc771d89f2017-01-13 01:10:53 -0800860 return spv::BuiltInSecondaryPositionNV;
861 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800862 if (!memberDeclaration) {
863 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
864 builder.addCapability(spv::CapabilityShaderStereoViewNV);
865 }
chaoc771d89f2017-01-13 01:10:53 -0800866 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800867 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800868 if (!memberDeclaration) {
869 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
870 builder.addCapability(spv::CapabilityPerViewAttributesNV);
871 }
chaocdf3956c2017-02-14 14:52:34 -0800872 return spv::BuiltInPositionPerViewNV;
873 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800874 if (!memberDeclaration) {
875 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
876 builder.addCapability(spv::CapabilityPerViewAttributesNV);
877 }
chaocdf3956c2017-02-14 14:52:34 -0800878 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700879 case glslang::EbvFragFullyCoveredNV:
880 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
881 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
882 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700883 case glslang::EbvFragmentSizeNV:
884 builder.addExtension(spv::E_SPV_NV_shading_rate);
885 builder.addCapability(spv::CapabilityShadingRateNV);
886 return spv::BuiltInFragmentSizeNV;
887 case glslang::EbvInvocationsPerPixelNV:
888 builder.addExtension(spv::E_SPV_NV_shading_rate);
889 builder.addCapability(spv::CapabilityShadingRateNV);
890 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700891
Daniel Koch593a4e02019-05-27 16:46:31 -0400892 // ray tracing
Chao Chenb50c02e2018-09-19 11:42:24 -0700893 case glslang::EbvLaunchIdNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700894 return spv::BuiltInLaunchIdNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700895 case glslang::EbvLaunchSizeNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700896 return spv::BuiltInLaunchSizeNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700897 case glslang::EbvWorldRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700898 return spv::BuiltInWorldRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700899 case glslang::EbvWorldRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700900 return spv::BuiltInWorldRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700901 case glslang::EbvObjectRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700902 return spv::BuiltInObjectRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700903 case glslang::EbvObjectRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700904 return spv::BuiltInObjectRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700905 case glslang::EbvRayTminNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700906 return spv::BuiltInRayTminNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700907 case glslang::EbvRayTmaxNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700908 return spv::BuiltInRayTmaxNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700909 case glslang::EbvInstanceCustomIndexNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700910 return spv::BuiltInInstanceCustomIndexNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700911 case glslang::EbvHitTNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700912 return spv::BuiltInHitTNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700913 case glslang::EbvHitKindNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700914 return spv::BuiltInHitKindNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700915 case glslang::EbvObjectToWorldNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700916 return spv::BuiltInObjectToWorldNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700917 case glslang::EbvWorldToObjectNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700918 return spv::BuiltInWorldToObjectNV;
919 case glslang::EbvIncomingRayFlagsNV:
920 return spv::BuiltInIncomingRayFlagsNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400921
922 // barycentrics
Chao Chen9eada4b2018-09-19 11:39:56 -0700923 case glslang::EbvBaryCoordNV:
924 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
925 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
926 return spv::BuiltInBaryCoordNV;
927 case glslang::EbvBaryCoordNoPerspNV:
928 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
929 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
930 return spv::BuiltInBaryCoordNoPerspNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400931
932 // mesh shaders
933 case glslang::EbvTaskCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700934 return spv::BuiltInTaskCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400935 case glslang::EbvPrimitiveCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700936 return spv::BuiltInPrimitiveCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400937 case glslang::EbvPrimitiveIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -0700938 return spv::BuiltInPrimitiveIndicesNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400939 case glslang::EbvClipDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700940 return spv::BuiltInClipDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400941 case glslang::EbvCullDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700942 return spv::BuiltInCullDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400943 case glslang::EbvLayerPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700944 return spv::BuiltInLayerPerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400945 case glslang::EbvMeshViewCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700946 return spv::BuiltInMeshViewCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400947 case glslang::EbvMeshViewIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -0700948 return spv::BuiltInMeshViewIndicesNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400949#endif
Daniel Koch2cb2f192019-06-04 08:43:32 -0400950
951 // sm builtins
952 case glslang::EbvWarpsPerSM:
953 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
954 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
955 return spv::BuiltInWarpsPerSMNV;
956 case glslang::EbvSMCount:
957 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
958 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
959 return spv::BuiltInSMCountNV;
960 case glslang::EbvWarpID:
961 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
962 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
963 return spv::BuiltInWarpIDNV;
964 case glslang::EbvSMID:
965 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
966 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
967 return spv::BuiltInSMIDNV;
Rex Xu3e783f92017-02-22 16:44:48 +0800968 default:
969 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600970 }
971}
972
Rex Xufc618912015-09-09 16:42:49 +0800973// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700974spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800975{
976 assert(type.getBasicType() == glslang::EbtSampler);
977
John Kessenich5d0fa972016-02-15 11:57:00 -0700978 // Check for capabilities
979 switch (type.getQualifier().layoutFormat) {
980 case glslang::ElfRg32f:
981 case glslang::ElfRg16f:
982 case glslang::ElfR11fG11fB10f:
983 case glslang::ElfR16f:
984 case glslang::ElfRgba16:
985 case glslang::ElfRgb10A2:
986 case glslang::ElfRg16:
987 case glslang::ElfRg8:
988 case glslang::ElfR16:
989 case glslang::ElfR8:
990 case glslang::ElfRgba16Snorm:
991 case glslang::ElfRg16Snorm:
992 case glslang::ElfRg8Snorm:
993 case glslang::ElfR16Snorm:
994 case glslang::ElfR8Snorm:
995
996 case glslang::ElfRg32i:
997 case glslang::ElfRg16i:
998 case glslang::ElfRg8i:
999 case glslang::ElfR16i:
1000 case glslang::ElfR8i:
1001
1002 case glslang::ElfRgb10a2ui:
1003 case glslang::ElfRg32ui:
1004 case glslang::ElfRg16ui:
1005 case glslang::ElfRg8ui:
1006 case glslang::ElfR16ui:
1007 case glslang::ElfR8ui:
1008 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
1009 break;
1010
1011 default:
1012 break;
1013 }
1014
1015 // do the translation
Rex Xufc618912015-09-09 16:42:49 +08001016 switch (type.getQualifier().layoutFormat) {
1017 case glslang::ElfNone: return spv::ImageFormatUnknown;
1018 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
1019 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
1020 case glslang::ElfR32f: return spv::ImageFormatR32f;
1021 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
1022 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
1023 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1024 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1025 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1026 case glslang::ElfR16f: return spv::ImageFormatR16f;
1027 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1028 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1029 case glslang::ElfRg16: return spv::ImageFormatRg16;
1030 case glslang::ElfRg8: return spv::ImageFormatRg8;
1031 case glslang::ElfR16: return spv::ImageFormatR16;
1032 case glslang::ElfR8: return spv::ImageFormatR8;
1033 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1034 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1035 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1036 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1037 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1038 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1039 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1040 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1041 case glslang::ElfR32i: return spv::ImageFormatR32i;
1042 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1043 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1044 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1045 case glslang::ElfR16i: return spv::ImageFormatR16i;
1046 case glslang::ElfR8i: return spv::ImageFormatR8i;
1047 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1048 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1049 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1050 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1051 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1052 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1053 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1054 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1055 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1056 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001057 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001058 }
1059}
1060
John Kesseniche18fd202018-01-30 11:01:39 -07001061spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001062{
John Kesseniche18fd202018-01-30 11:01:39 -07001063 if (selectionNode.getFlatten())
1064 return spv::SelectionControlFlattenMask;
1065 if (selectionNode.getDontFlatten())
1066 return spv::SelectionControlDontFlattenMask;
1067 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001068}
1069
John Kesseniche18fd202018-01-30 11:01:39 -07001070spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -06001071{
John Kesseniche18fd202018-01-30 11:01:39 -07001072 if (switchNode.getFlatten())
1073 return spv::SelectionControlFlattenMask;
1074 if (switchNode.getDontFlatten())
1075 return spv::SelectionControlDontFlattenMask;
1076 return spv::SelectionControlMaskNone;
1077}
1078
John Kessenicha2858d92018-01-31 08:11:18 -07001079// return a non-0 dependency if the dependency argument must be set
1080spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
John Kessenich1f4d0462019-01-12 17:31:41 +07001081 std::vector<unsigned int>& operands) const
John Kesseniche18fd202018-01-30 11:01:39 -07001082{
1083 spv::LoopControlMask control = spv::LoopControlMaskNone;
1084
1085 if (loopNode.getDontUnroll())
1086 control = control | spv::LoopControlDontUnrollMask;
1087 if (loopNode.getUnroll())
1088 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001089 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001090 control = control | spv::LoopControlDependencyInfiniteMask;
1091 else if (loopNode.getLoopDependency() > 0) {
1092 control = control | spv::LoopControlDependencyLengthMask;
John Kessenich1f4d0462019-01-12 17:31:41 +07001093 operands.push_back((unsigned int)loopNode.getLoopDependency());
1094 }
1095 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
1096 if (loopNode.getMinIterations() > 0) {
1097 control = control | spv::LoopControlMinIterationsMask;
1098 operands.push_back(loopNode.getMinIterations());
1099 }
1100 if (loopNode.getMaxIterations() < glslang::TIntermLoop::iterationsInfinite) {
1101 control = control | spv::LoopControlMaxIterationsMask;
1102 operands.push_back(loopNode.getMaxIterations());
1103 }
1104 if (loopNode.getIterationMultiple() > 1) {
1105 control = control | spv::LoopControlIterationMultipleMask;
1106 operands.push_back(loopNode.getIterationMultiple());
1107 }
1108 if (loopNode.getPeelCount() > 0) {
1109 control = control | spv::LoopControlPeelCountMask;
1110 operands.push_back(loopNode.getPeelCount());
1111 }
1112 if (loopNode.getPartialCount() > 0) {
1113 control = control | spv::LoopControlPartialCountMask;
1114 operands.push_back(loopNode.getPartialCount());
1115 }
John Kessenicha2858d92018-01-31 08:11:18 -07001116 }
John Kesseniche18fd202018-01-30 11:01:39 -07001117
1118 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001119}
1120
John Kessenicha5c5fb62017-05-05 05:09:58 -06001121// Translate glslang type to SPIR-V storage class.
1122spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1123{
1124 if (type.getQualifier().isPipeInput())
1125 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001126 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001127 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001128
1129 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
1130 type.getQualifier().storage == glslang::EvqUniform) {
1131 if (type.getBasicType() == glslang::EbtAtomicUint)
1132 return spv::StorageClassAtomicCounter;
1133 if (type.containsOpaque())
1134 return spv::StorageClassUniformConstant;
1135 }
1136
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001137#ifdef NV_EXTENSIONS
1138 if (type.getQualifier().isUniformOrBuffer() &&
1139 type.getQualifier().layoutShaderRecordNV) {
1140 return spv::StorageClassShaderRecordBufferNV;
1141 }
1142#endif
1143
John Kessenichbed4e4f2017-09-08 02:38:07 -06001144 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich66011cb2018-03-06 16:12:04 -07001145 addPre13Extension(spv::E_SPV_KHR_storage_buffer_storage_class);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001146 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001147 }
1148
1149 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -06001150 if (type.getQualifier().layoutPushConstant)
1151 return spv::StorageClassPushConstant;
1152 if (type.getBasicType() == glslang::EbtBlock)
1153 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001154 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001155 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001156
1157 switch (type.getQualifier().storage) {
1158 case glslang::EvqShared: return spv::StorageClassWorkgroup;
1159 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1160 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1161 case glslang::EvqTemporary: return spv::StorageClassFunction;
Chao Chenb50c02e2018-09-19 11:42:24 -07001162#ifdef NV_EXTENSIONS
Ashwin Leleff1783d2018-10-22 16:41:44 -07001163 case glslang::EvqPayloadNV: return spv::StorageClassRayPayloadNV;
1164 case glslang::EvqPayloadInNV: return spv::StorageClassIncomingRayPayloadNV;
1165 case glslang::EvqHitAttrNV: return spv::StorageClassHitAttributeNV;
1166 case glslang::EvqCallableDataNV: return spv::StorageClassCallableDataNV;
1167 case glslang::EvqCallableDataInNV: return spv::StorageClassIncomingCallableDataNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07001168#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001169 default:
1170 assert(0);
1171 break;
1172 }
1173
1174 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001175}
1176
John Kessenich5611c6d2018-04-05 11:25:02 -06001177// Add capabilities pertaining to how an array is indexed.
1178void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1179 const glslang::TType& indexType)
1180{
1181 if (indexType.getQualifier().isNonUniform()) {
1182 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001183 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001184 if (baseType.getBasicType() == glslang::EbtSampler) {
1185 if (baseType.getQualifier().hasAttachment())
1186 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
1187 else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer)
1188 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
1189 else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer)
1190 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1191 else if (baseType.isImage())
1192 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1193 else if (baseType.isTexture())
1194 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1195 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1196 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1197 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1198 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1199 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1200 }
1201 } else {
1202 // assume a dynamically uniform index
1203 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001204 if (baseType.getQualifier().hasAttachment()) {
1205 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001206 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001207 } else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer) {
1208 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001209 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001210 } else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer) {
1211 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001212 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001213 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001214 }
1215 }
1216}
1217
qining25262b32016-05-06 17:25:16 -04001218// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001219// descriptor set.
1220bool IsDescriptorResource(const glslang::TType& type)
1221{
John Kessenichf7497e22016-03-08 21:36:22 -07001222 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001223 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001224 return type.getQualifier().isUniformOrBuffer() &&
1225#ifdef NV_EXTENSIONS
1226 ! type.getQualifier().layoutShaderRecordNV &&
1227#endif
1228 ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -07001229
1230 // non block...
1231 // basically samplerXXX/subpass/sampler/texture are all included
1232 // if they are the global-scope-class, not the function parameter
1233 // (or local, if they ever exist) class.
1234 if (type.getBasicType() == glslang::EbtSampler)
1235 return type.getQualifier().isUniformOrBuffer();
1236
1237 // None of the above.
1238 return false;
1239}
1240
John Kesseniche0b6cad2015-12-24 10:30:13 -07001241void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1242{
1243 if (child.layoutMatrix == glslang::ElmNone)
1244 child.layoutMatrix = parent.layoutMatrix;
1245
1246 if (parent.invariant)
1247 child.invariant = true;
1248 if (parent.nopersp)
1249 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001250#ifdef AMD_EXTENSIONS
1251 if (parent.explicitInterp)
1252 child.explicitInterp = true;
1253#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001254 if (parent.flat)
1255 child.flat = true;
1256 if (parent.centroid)
1257 child.centroid = true;
1258 if (parent.patch)
1259 child.patch = true;
1260 if (parent.sample)
1261 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001262 if (parent.coherent)
1263 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001264 if (parent.devicecoherent)
1265 child.devicecoherent = true;
1266 if (parent.queuefamilycoherent)
1267 child.queuefamilycoherent = true;
1268 if (parent.workgroupcoherent)
1269 child.workgroupcoherent = true;
1270 if (parent.subgroupcoherent)
1271 child.subgroupcoherent = true;
1272 if (parent.nonprivate)
1273 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001274 if (parent.volatil)
1275 child.volatil = true;
1276 if (parent.restrict)
1277 child.restrict = true;
1278 if (parent.readonly)
1279 child.readonly = true;
1280 if (parent.writeonly)
1281 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001282#ifdef NV_EXTENSIONS
1283 if (parent.perPrimitiveNV)
1284 child.perPrimitiveNV = true;
1285 if (parent.perViewNV)
1286 child.perViewNV = true;
1287 if (parent.perTaskNV)
1288 child.perTaskNV = true;
1289#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001290}
1291
John Kessenichf2b7f332016-09-01 17:05:23 -06001292bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001293{
John Kessenich7b9fa252016-01-21 18:56:57 -07001294 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001295 // - struct members might inherit from a struct declaration
1296 // (note that non-block structs don't explicitly inherit,
1297 // only implicitly, meaning no decoration involved)
1298 // - affect decorations on the struct members
1299 // (note smooth does not, and expecting something like volatile
1300 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001301 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001302 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001303}
1304
John Kessenich140f3df2015-06-26 16:58:36 -06001305//
1306// Implement the TGlslangToSpvTraverser class.
1307//
1308
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001309TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001310 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1311 : TIntermTraverser(true, false, true),
1312 options(options),
1313 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001314 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001315 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001316 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich605afc72019-06-17 23:33:09 -06001317 glslangIntermediate(glslangIntermediate),
1318 nanMinMaxClamp(glslangIntermediate->getNanMinMaxClamp())
John Kessenich140f3df2015-06-26 16:58:36 -06001319{
1320 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1321
1322 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001323 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1324 glslangIntermediate->getVersion());
1325
John Kessenich121853f2017-05-31 17:11:16 -06001326 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001327 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001328 builder.setSourceFile(glslangIntermediate->getSourceFile());
1329
1330 // Set the source shader's text. If for SPV version 1.0, include
1331 // a preamble in comments stating the OpModuleProcessed instructions.
1332 // Otherwise, emit those as actual instructions.
1333 std::string text;
1334 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1335 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001336 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001337 text.append("// OpModuleProcessed ");
1338 text.append(processes[p]);
1339 text.append("\n");
1340 } else
1341 builder.addModuleProcessed(processes[p]);
1342 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001343 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001344 text.append("#line 1\n");
1345 text.append(glslangIntermediate->getSourceText());
1346 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001347 // Pass name and text for all included files
1348 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1349 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1350 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001351 }
John Kessenich140f3df2015-06-26 16:58:36 -06001352 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001353
1354 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1355 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1356
1357 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1358 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
1359 builder.addExtension(spv::E_SPV_EXT_physical_storage_buffer);
1360 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
1361 };
Jeff Bolz36831c92018-09-05 10:11:41 -05001362 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001363 memoryModel = spv::MemoryModelVulkanKHR;
1364 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
Jeff Bolz36831c92018-09-05 10:11:41 -05001365 builder.addExtension(spv::E_SPV_KHR_vulkan_memory_model);
Jeff Bolz36831c92018-09-05 10:11:41 -05001366 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001367 builder.setMemoryModel(addressingModel, memoryModel);
1368
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001369 if (glslangIntermediate->usingVariablePointers()) {
1370 builder.addCapability(spv::CapabilityVariablePointers);
1371 }
1372
John Kessenicheee9d532016-09-19 18:09:30 -06001373 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1374 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001375
1376 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001377 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1378 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001379 builder.addSourceExtension(it->c_str());
1380
1381 // Add the top-level modes for this shader.
1382
John Kessenich92187592016-02-01 13:45:25 -07001383 if (glslangIntermediate->getXfbMode()) {
1384 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001385 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001386 }
John Kessenich140f3df2015-06-26 16:58:36 -06001387
1388 unsigned int mode;
1389 switch (glslangIntermediate->getStage()) {
1390 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001391 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001392 break;
1393
steve-lunarge7412492017-03-23 11:56:07 -06001394 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001395 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001396 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001397
steve-lunarge7412492017-03-23 11:56:07 -06001398 glslang::TLayoutGeometry primitive;
1399
1400 if (glslangIntermediate->getStage() == EShLangTessControl) {
1401 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1402 primitive = glslangIntermediate->getOutputPrimitive();
1403 } else {
1404 primitive = glslangIntermediate->getInputPrimitive();
1405 }
1406
1407 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001408 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1409 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1410 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001411 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001412 }
John Kessenich4016e382016-07-15 11:53:56 -06001413 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001414 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1415
John Kesseniche6903322015-10-13 16:29:02 -06001416 switch (glslangIntermediate->getVertexSpacing()) {
1417 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1418 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1419 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001420 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001421 }
John Kessenich4016e382016-07-15 11:53:56 -06001422 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001423 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1424
1425 switch (glslangIntermediate->getVertexOrder()) {
1426 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1427 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001428 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001429 }
John Kessenich4016e382016-07-15 11:53:56 -06001430 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001431 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1432
1433 if (glslangIntermediate->getPointMode())
1434 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001435 break;
1436
1437 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001438 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001439 switch (glslangIntermediate->getInputPrimitive()) {
1440 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1441 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1442 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001443 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001444 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001445 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001446 }
John Kessenich4016e382016-07-15 11:53:56 -06001447 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001448 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001449
John Kessenich140f3df2015-06-26 16:58:36 -06001450 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1451
1452 switch (glslangIntermediate->getOutputPrimitive()) {
1453 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1454 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1455 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001456 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001457 }
John Kessenich4016e382016-07-15 11:53:56 -06001458 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001459 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1460 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1461 break;
1462
1463 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001464 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001465 if (glslangIntermediate->getPixelCenterInteger())
1466 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001467
John Kessenich140f3df2015-06-26 16:58:36 -06001468 if (glslangIntermediate->getOriginUpperLeft())
1469 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001470 else
1471 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001472
1473 if (glslangIntermediate->getEarlyFragmentTests())
1474 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1475
chaocc1204522017-06-30 17:14:30 -07001476 if (glslangIntermediate->getPostDepthCoverage()) {
1477 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1478 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1479 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1480 }
1481
John Kesseniche6903322015-10-13 16:29:02 -06001482 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001483 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1484 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001485 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001486 }
John Kessenich4016e382016-07-15 11:53:56 -06001487 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001488 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1489
1490 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1491 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05001492
1493 switch (glslangIntermediate->getInterlockOrdering()) {
1494 case glslang::EioPixelInterlockOrdered: mode = spv::ExecutionModePixelInterlockOrderedEXT; break;
1495 case glslang::EioPixelInterlockUnordered: mode = spv::ExecutionModePixelInterlockUnorderedEXT; break;
1496 case glslang::EioSampleInterlockOrdered: mode = spv::ExecutionModeSampleInterlockOrderedEXT; break;
1497 case glslang::EioSampleInterlockUnordered: mode = spv::ExecutionModeSampleInterlockUnorderedEXT; break;
1498 case glslang::EioShadingRateInterlockOrdered: mode = spv::ExecutionModeShadingRateInterlockOrderedEXT; break;
1499 case glslang::EioShadingRateInterlockUnordered: mode = spv::ExecutionModeShadingRateInterlockUnorderedEXT; break;
1500 default: mode = spv::ExecutionModeMax; break;
1501 }
1502 if (mode != spv::ExecutionModeMax) {
1503 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1504 if (mode == spv::ExecutionModeShadingRateInterlockOrderedEXT ||
1505 mode == spv::ExecutionModeShadingRateInterlockUnorderedEXT) {
1506 builder.addCapability(spv::CapabilityFragmentShaderShadingRateInterlockEXT);
1507 } else if (mode == spv::ExecutionModePixelInterlockOrderedEXT ||
1508 mode == spv::ExecutionModePixelInterlockUnorderedEXT) {
1509 builder.addCapability(spv::CapabilityFragmentShaderPixelInterlockEXT);
1510 } else {
1511 builder.addCapability(spv::CapabilityFragmentShaderSampleInterlockEXT);
1512 }
1513 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
1514 }
1515
John Kessenich140f3df2015-06-26 16:58:36 -06001516 break;
1517
1518 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001519 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001520 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1521 glslangIntermediate->getLocalSize(1),
1522 glslangIntermediate->getLocalSize(2));
Chao Chenbeae2252018-09-19 11:40:45 -07001523#ifdef NV_EXTENSIONS
1524 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1525 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1526 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1527 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1528 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1529 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1530 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1531 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1532 }
1533#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001534 break;
1535
Chao Chen3c366992018-09-19 11:41:59 -07001536#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07001537 case EShLangRayGenNV:
1538 case EShLangIntersectNV:
1539 case EShLangAnyHitNV:
1540 case EShLangClosestHitNV:
1541 case EShLangMissNV:
1542 case EShLangCallableNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07001543 builder.addCapability(spv::CapabilityRayTracingNV);
1544 builder.addExtension("SPV_NV_ray_tracing");
Chao Chenb50c02e2018-09-19 11:42:24 -07001545 break;
Chao Chen3c366992018-09-19 11:41:59 -07001546 case EShLangTaskNV:
1547 case EShLangMeshNV:
1548 builder.addCapability(spv::CapabilityMeshShadingNV);
1549 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1550 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1551 glslangIntermediate->getLocalSize(1),
1552 glslangIntermediate->getLocalSize(2));
1553 if (glslangIntermediate->getStage() == EShLangMeshNV) {
1554 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1555 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV, glslangIntermediate->getPrimitives());
1556
1557 switch (glslangIntermediate->getOutputPrimitive()) {
1558 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1559 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1560 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1561 default: mode = spv::ExecutionModeMax; break;
1562 }
1563 if (mode != spv::ExecutionModeMax)
1564 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1565 }
1566 break;
1567#endif
1568
John Kessenich140f3df2015-06-26 16:58:36 -06001569 default:
1570 break;
1571 }
John Kessenich140f3df2015-06-26 16:58:36 -06001572}
1573
John Kessenichfca82622016-11-26 13:23:20 -07001574// Finish creating SPV, after the traversal is complete.
1575void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001576{
John Kessenichf04c51b2018-08-03 15:56:12 -06001577 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001578 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001579 builder.setBuildPoint(shaderEntry->getLastBlock());
1580 builder.leaveFunction();
1581 }
1582
John Kessenich7ba63412015-12-20 17:37:07 -07001583 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001584 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1585 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001586
John Kessenichf04c51b2018-08-03 15:56:12 -06001587 // Add capabilities, extensions, remove unneeded decorations, etc.,
1588 // based on the resulting SPIR-V.
1589 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001590}
1591
John Kessenichfca82622016-11-26 13:23:20 -07001592// Write the SPV into 'out'.
1593void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001594{
John Kessenichfca82622016-11-26 13:23:20 -07001595 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001596}
1597
1598//
1599// Implement the traversal functions.
1600//
1601// Return true from interior nodes to have the external traversal
1602// continue on to children. Return false if children were
1603// already processed.
1604//
1605
1606//
qining25262b32016-05-06 17:25:16 -04001607// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001608// - uniform/input reads
1609// - output writes
1610// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1611// - something simple that degenerates into the last bullet
1612//
1613void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1614{
qining75d1d802016-04-06 14:42:01 -04001615 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1616 if (symbol->getType().getQualifier().isSpecConstant())
1617 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1618
John Kessenich140f3df2015-06-26 16:58:36 -06001619 // getSymbolId() will set up all the IO decorations on the first call.
1620 // Formal function parameters were mapped during makeFunctions().
1621 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001622
1623 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1624 if (builder.isPointer(id)) {
John Kessenich7c7731e2019-01-04 16:47:06 +07001625 // Consider adding to the OpEntryPoint interface list.
1626 // Only looking at structures if they have at least one member.
1627 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1628 spv::StorageClass sc = builder.getStorageClass(id);
1629 // Before SPIR-V 1.4, we only want to include Input and Output.
1630 // Starting with SPIR-V 1.4, we want all globals.
1631 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && sc != spv::StorageClassFunction) ||
1632 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
John Kessenich5f77d862017-09-19 11:09:59 -06001633 iOSet.insert(id);
John Kessenich7c7731e2019-01-04 16:47:06 +07001634 }
John Kessenich5f77d862017-09-19 11:09:59 -06001635 }
John Kessenich7ba63412015-12-20 17:37:07 -07001636 }
1637
1638 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001639 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001640 // Prepare to generate code for the access
1641
1642 // L-value chains will be computed left to right. We're on the symbol now,
1643 // which is the left-most part of the access chain, so now is "clear" time,
1644 // followed by setting the base.
1645 builder.clearAccessChain();
1646
1647 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001648 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001649 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001650 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001651 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001652 // These are also pure R-values.
1653 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001654 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001655 builder.setAccessChainRValue(id);
1656 else
1657 builder.setAccessChainLValue(id);
1658 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001659
1660 // Process linkage-only nodes for any special additional interface work.
1661 if (linkageOnly) {
1662 if (glslangIntermediate->getHlslFunctionality1()) {
1663 // Map implicit counter buffers to their originating buffers, which should have been
1664 // seen by now, given earlier pruning of unused counters, and preservation of order
1665 // of declaration.
1666 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1667 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1668 // Save possible originating buffers for counter buffers, keyed by
1669 // making the potential counter-buffer name.
1670 std::string keyName = symbol->getName().c_str();
1671 keyName = glslangIntermediate->addCounterBufferName(keyName);
1672 counterOriginator[keyName] = symbol;
1673 } else {
1674 // Handle a counter buffer, by finding the saved originating buffer.
1675 std::string keyName = symbol->getName().c_str();
1676 auto it = counterOriginator.find(keyName);
1677 if (it != counterOriginator.end()) {
1678 id = getSymbolId(it->second);
1679 if (id != spv::NoResult) {
1680 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001681 if (counterId != spv::NoResult) {
1682 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001683 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001684 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001685 }
1686 }
1687 }
1688 }
1689 }
1690 }
John Kessenich140f3df2015-06-26 16:58:36 -06001691}
1692
1693bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1694{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001695 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001696
qining40887662016-04-03 22:20:42 -04001697 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1698 if (node->getType().getQualifier().isSpecConstant())
1699 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1700
John Kessenich140f3df2015-06-26 16:58:36 -06001701 // First, handle special cases
1702 switch (node->getOp()) {
1703 case glslang::EOpAssign:
1704 case glslang::EOpAddAssign:
1705 case glslang::EOpSubAssign:
1706 case glslang::EOpMulAssign:
1707 case glslang::EOpVectorTimesMatrixAssign:
1708 case glslang::EOpVectorTimesScalarAssign:
1709 case glslang::EOpMatrixTimesScalarAssign:
1710 case glslang::EOpMatrixTimesMatrixAssign:
1711 case glslang::EOpDivAssign:
1712 case glslang::EOpModAssign:
1713 case glslang::EOpAndAssign:
1714 case glslang::EOpInclusiveOrAssign:
1715 case glslang::EOpExclusiveOrAssign:
1716 case glslang::EOpLeftShiftAssign:
1717 case glslang::EOpRightShiftAssign:
1718 // A bin-op assign "a += b" means the same thing as "a = a + b"
1719 // where a is evaluated before b. For a simple assignment, GLSL
1720 // says to evaluate the left before the right. So, always, left
1721 // node then right node.
1722 {
1723 // get the left l-value, save it away
1724 builder.clearAccessChain();
1725 node->getLeft()->traverse(this);
1726 spv::Builder::AccessChain lValue = builder.getAccessChain();
1727
1728 // evaluate the right
1729 builder.clearAccessChain();
1730 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001731 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001732
1733 if (node->getOp() != glslang::EOpAssign) {
1734 // the left is also an r-value
1735 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001736 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001737
1738 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001739 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001740 TranslateNoContractionDecoration(node->getType().getQualifier()),
1741 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001742 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001743 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1744 node->getType().getBasicType());
1745
1746 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001747 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001748 }
1749
1750 // store the result
1751 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001752 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001753
1754 // assignments are expressions having an rValue after they are evaluated...
1755 builder.clearAccessChain();
1756 builder.setAccessChainRValue(rValue);
1757 }
1758 return false;
1759 case glslang::EOpIndexDirect:
1760 case glslang::EOpIndexDirectStruct:
1761 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001762 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001763 // Get the left part of the access chain.
1764 node->getLeft()->traverse(this);
1765
1766 // Add the next element in the chain
1767
David Netoa901ffe2016-06-08 14:11:40 +01001768 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001769 if (! node->getLeft()->getType().isArray() &&
1770 node->getLeft()->getType().isVector() &&
1771 node->getOp() == glslang::EOpIndexDirect) {
1772 // This is essentially a hard-coded vector swizzle of size 1,
1773 // so short circuit the access-chain stuff with a swizzle.
1774 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001775 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001776 int dummySize;
1777 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1778 TranslateCoherent(node->getLeft()->getType()),
1779 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001780 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001781
1782 // Load through a block reference is performed with a dot operator that
1783 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1784 // do a load and reset the access chain.
1785 if (node->getLeft()->getBasicType() == glslang::EbtReference &&
1786 !node->getLeft()->getType().isArray() &&
1787 node->getOp() == glslang::EOpIndexDirectStruct)
1788 {
1789 spv::Id left = accessChainLoad(node->getLeft()->getType());
1790 builder.clearAccessChain();
1791 builder.setAccessChainLValue(left);
1792 }
1793
David Netoa901ffe2016-06-08 14:11:40 +01001794 int spvIndex = glslangIndex;
1795 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1796 node->getOp() == glslang::EOpIndexDirectStruct)
1797 {
1798 // This may be, e.g., an anonymous block-member selection, which generally need
1799 // index remapping due to hidden members in anonymous blocks.
1800 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1801 assert(remapper.size() > 0);
1802 spvIndex = remapper[glslangIndex];
1803 }
John Kessenichebb50532016-05-16 19:22:05 -06001804
David Netoa901ffe2016-06-08 14:11:40 +01001805 // normal case for indexing array or structure or block
Jeff Bolz7895e472019-03-06 13:34:10 -06001806 builder.accessChainPush(builder.makeIntConstant(spvIndex), TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001807
1808 // Add capabilities here for accessing PointSize and clip/cull distance.
1809 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001810 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001811 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001812 }
1813 }
1814 return false;
1815 case glslang::EOpIndexIndirect:
1816 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001817 // Array, matrix, or vector indirection with variable index.
1818 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06001819 // matrices are arrays of vectors, so will also work for a matrix.
1820 // Will use the access chain's 'component' for variable index into a vector.
1821
1822 // This adapter is building access chains left to right.
1823 // Set up the access chain to the left.
1824 node->getLeft()->traverse(this);
1825
1826 // save it so that computing the right side doesn't trash it
1827 spv::Builder::AccessChain partial = builder.getAccessChain();
1828
1829 // compute the next index in the chain
1830 builder.clearAccessChain();
1831 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001832 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001833
John Kessenich5611c6d2018-04-05 11:25:02 -06001834 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1835
John Kessenich140f3df2015-06-26 16:58:36 -06001836 // restore the saved access chain
1837 builder.setAccessChain(partial);
1838
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001839 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1840 int dummySize;
1841 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1842 TranslateCoherent(node->getLeft()->getType()),
1843 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
1844 } else
Jeff Bolz7895e472019-03-06 13:34:10 -06001845 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001846 }
1847 return false;
1848 case glslang::EOpVectorSwizzle:
1849 {
1850 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001851 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001852 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001853 int dummySize;
1854 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1855 TranslateCoherent(node->getLeft()->getType()),
1856 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001857 }
1858 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001859 case glslang::EOpMatrixSwizzle:
1860 logger->missingFunctionality("matrix swizzle");
1861 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001862 case glslang::EOpLogicalOr:
1863 case glslang::EOpLogicalAnd:
1864 {
1865
1866 // These may require short circuiting, but can sometimes be done as straight
1867 // binary operations. The right operand must be short circuited if it has
1868 // side effects, and should probably be if it is complex.
1869 if (isTrivial(node->getRight()->getAsTyped()))
1870 break; // handle below as a normal binary operation
1871 // otherwise, we need to do dynamic short circuiting on the right operand
1872 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1873 builder.clearAccessChain();
1874 builder.setAccessChainRValue(result);
1875 }
1876 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001877 default:
1878 break;
1879 }
1880
1881 // Assume generic binary op...
1882
John Kessenich32cfd492016-02-02 12:37:46 -07001883 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001884 builder.clearAccessChain();
1885 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001886 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001887
John Kessenich32cfd492016-02-02 12:37:46 -07001888 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001889 builder.clearAccessChain();
1890 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001891 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001892
John Kessenich32cfd492016-02-02 12:37:46 -07001893 // get result
John Kessenichead86222018-03-28 18:01:20 -06001894 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001895 TranslateNoContractionDecoration(node->getType().getQualifier()),
1896 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001897 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001898 convertGlslangToSpvType(node->getType()), left, right,
1899 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001900
John Kessenich50e57562015-12-21 21:21:11 -07001901 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001902 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001903 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001904 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001905 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001906 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001907 return false;
1908 }
John Kessenich140f3df2015-06-26 16:58:36 -06001909}
1910
1911bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1912{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001913 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001914
qining40887662016-04-03 22:20:42 -04001915 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1916 if (node->getType().getQualifier().isSpecConstant())
1917 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1918
John Kessenichfc51d282015-08-19 13:34:18 -06001919 spv::Id result = spv::NoResult;
1920
1921 // try texturing first
1922 result = createImageTextureFunctionCall(node);
1923 if (result != spv::NoResult) {
1924 builder.clearAccessChain();
1925 builder.setAccessChainRValue(result);
1926
1927 return false; // done with this node
1928 }
1929
1930 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001931
1932 if (node->getOp() == glslang::EOpArrayLength) {
1933 // Quite special; won't want to evaluate the operand.
1934
John Kessenich5611c6d2018-04-05 11:25:02 -06001935 // Currently, the front-end does not allow .length() on an array until it is sized,
1936 // except for the last block membeor of an SSBO.
1937 // TODO: If this changes, link-time sized arrays might show up here, and need their
1938 // size extracted.
1939
John Kessenichc9a80832015-09-12 12:17:44 -06001940 // Normal .length() would have been constant folded by the front-end.
1941 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001942 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06001943
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001944 spv::Id length;
1945 if (node->getOperand()->getType().isCoopMat()) {
1946 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1947
1948 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
1949 assert(builder.isCooperativeMatrixType(typeId));
1950
1951 length = builder.createCooperativeMatrixLength(typeId);
1952 } else {
1953 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1954 block->traverse(this);
1955 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1956 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
1957 }
John Kessenichc9a80832015-09-12 12:17:44 -06001958
John Kessenich8c869672018-11-28 07:01:37 -07001959 // GLSL semantics say the result of .length() is an int, while SPIR-V says
1960 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
1961 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001962 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
1963 if (builder.isInSpecConstCodeGenMode()) {
1964 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
1965 } else {
1966 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
1967 }
1968 }
John Kessenich8c869672018-11-28 07:01:37 -07001969
John Kessenichc9a80832015-09-12 12:17:44 -06001970 builder.clearAccessChain();
1971 builder.setAccessChainRValue(length);
1972
1973 return false;
1974 }
1975
John Kessenichfc51d282015-08-19 13:34:18 -06001976 // Start by evaluating the operand
1977
John Kessenich8c8505c2016-07-26 12:50:38 -06001978 // Does it need a swizzle inversion? If so, evaluation is inverted;
1979 // operate first on the swizzle base, then apply the swizzle.
1980 spv::Id invertedType = spv::NoType;
1981 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1982 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1983 invertedType = getInvertedSwizzleType(*node->getOperand());
1984
John Kessenich140f3df2015-06-26 16:58:36 -06001985 builder.clearAccessChain();
Jeff Bolz38a52fc2019-06-14 09:56:28 -05001986 TIntermNode *operandNode;
John Kessenich8c8505c2016-07-26 12:50:38 -06001987 if (invertedType != spv::NoType)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05001988 operandNode = node->getOperand()->getAsBinaryNode()->getLeft();
John Kessenich8c8505c2016-07-26 12:50:38 -06001989 else
Jeff Bolz38a52fc2019-06-14 09:56:28 -05001990 operandNode = node->getOperand();
1991
1992 operandNode->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001993
Rex Xufc618912015-09-09 16:42:49 +08001994 spv::Id operand = spv::NoResult;
1995
Jeff Bolz38a52fc2019-06-14 09:56:28 -05001996 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
1997
Rex Xufc618912015-09-09 16:42:49 +08001998 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1999 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08002000 node->getOp() == glslang::EOpAtomicCounter ||
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002001 node->getOp() == glslang::EOpInterpolateAtCentroid) {
Rex Xufc618912015-09-09 16:42:49 +08002002 operand = builder.accessChainGetLValue(); // Special case l-value operands
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002003 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2004 lvalueCoherentFlags |= TranslateCoherent(operandNode->getAsTyped()->getType());
2005 } else
John Kessenich32cfd492016-02-02 12:37:46 -07002006 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002007
John Kessenichead86222018-03-28 18:01:20 -06002008 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002009 TranslateNoContractionDecoration(node->getType().getQualifier()),
2010 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06002011
2012 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06002013 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06002014 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002015
2016 // if not, then possibly an operation
2017 if (! result)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002018 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType(), lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002019
2020 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06002021 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06002022 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich5611c6d2018-04-05 11:25:02 -06002023 builder.addDecoration(result, decorations.nonUniform);
2024 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002025
John Kessenich140f3df2015-06-26 16:58:36 -06002026 builder.clearAccessChain();
2027 builder.setAccessChainRValue(result);
2028
2029 return false; // done with this node
2030 }
2031
2032 // it must be a special case, check...
2033 switch (node->getOp()) {
2034 case glslang::EOpPostIncrement:
2035 case glslang::EOpPostDecrement:
2036 case glslang::EOpPreIncrement:
2037 case glslang::EOpPreDecrement:
2038 {
2039 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08002040 spv::Id one = 0;
2041 if (node->getBasicType() == glslang::EbtFloat)
2042 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08002043 else if (node->getBasicType() == glslang::EbtDouble)
2044 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002045 else if (node->getBasicType() == glslang::EbtFloat16)
2046 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07002047 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
2048 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08002049 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
2050 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002051 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2052 one = builder.makeInt64Constant(1);
Rex Xu8ff43de2016-04-22 16:51:45 +08002053 else
2054 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002055 glslang::TOperator op;
2056 if (node->getOp() == glslang::EOpPreIncrement ||
2057 node->getOp() == glslang::EOpPostIncrement)
2058 op = glslang::EOpAdd;
2059 else
2060 op = glslang::EOpSub;
2061
John Kessenichead86222018-03-28 18:01:20 -06002062 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002063 convertGlslangToSpvType(node->getType()), operand, one,
2064 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002065 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002066
2067 // The result of operation is always stored, but conditionally the
2068 // consumed result. The consumed result is always an r-value.
2069 builder.accessChainStore(result);
2070 builder.clearAccessChain();
2071 if (node->getOp() == glslang::EOpPreIncrement ||
2072 node->getOp() == glslang::EOpPreDecrement)
2073 builder.setAccessChainRValue(result);
2074 else
2075 builder.setAccessChainRValue(operand);
2076 }
2077
2078 return false;
2079
2080 case glslang::EOpEmitStreamVertex:
2081 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2082 return false;
2083 case glslang::EOpEndStreamPrimitive:
2084 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2085 return false;
2086
2087 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002088 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002089 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002090 }
John Kessenich140f3df2015-06-26 16:58:36 -06002091}
2092
2093bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2094{
qining27e04a02016-04-14 16:40:20 -04002095 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2096 if (node->getType().getQualifier().isSpecConstant())
2097 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2098
John Kessenichfc51d282015-08-19 13:34:18 -06002099 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06002100 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2101 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002102
2103 // try texturing
2104 result = createImageTextureFunctionCall(node);
2105 if (result != spv::NoResult) {
2106 builder.clearAccessChain();
2107 builder.setAccessChainRValue(result);
2108
2109 return false;
Jeff Bolz36831c92018-09-05 10:11:41 -05002110 } else if (node->getOp() == glslang::EOpImageStore ||
Rex Xu129799a2017-07-05 17:23:28 +08002111#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05002112 node->getOp() == glslang::EOpImageStoreLod ||
Rex Xu129799a2017-07-05 17:23:28 +08002113#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05002114 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002115 // "imageStore" is a special case, which has no result
2116 return false;
2117 }
John Kessenichfc51d282015-08-19 13:34:18 -06002118
John Kessenich140f3df2015-06-26 16:58:36 -06002119 glslang::TOperator binOp = glslang::EOpNull;
2120 bool reduceComparison = true;
2121 bool isMatrix = false;
2122 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002123 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002124
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002125 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2126
John Kessenich140f3df2015-06-26 16:58:36 -06002127 assert(node->getOp());
2128
John Kessenichf6640762016-08-01 19:44:00 -06002129 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002130
2131 switch (node->getOp()) {
2132 case glslang::EOpSequence:
2133 {
2134 if (preVisit)
2135 ++sequenceDepth;
2136 else
2137 --sequenceDepth;
2138
2139 if (sequenceDepth == 1) {
2140 // If this is the parent node of all the functions, we want to see them
2141 // early, so all call points have actual SPIR-V functions to reference.
2142 // In all cases, still let the traverser visit the children for us.
2143 makeFunctions(node->getAsAggregate()->getSequence());
2144
John Kessenich6fccb3c2016-09-19 16:01:41 -06002145 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002146 // anything else gets there, so visit out of order, doing them all now.
2147 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2148
John Kessenich6a60c2f2016-12-08 21:01:59 -07002149 // Initializers are done, don't want to visit again, but functions and link objects need to be processed,
John Kessenich140f3df2015-06-26 16:58:36 -06002150 // so do them manually.
2151 visitFunctions(node->getAsAggregate()->getSequence());
2152
2153 return false;
2154 }
2155
2156 return true;
2157 }
2158 case glslang::EOpLinkerObjects:
2159 {
2160 if (visit == glslang::EvPreVisit)
2161 linkageOnly = true;
2162 else
2163 linkageOnly = false;
2164
2165 return true;
2166 }
2167 case glslang::EOpComma:
2168 {
2169 // processing from left to right naturally leaves the right-most
2170 // lying around in the access chain
2171 glslang::TIntermSequence& glslangOperands = node->getSequence();
2172 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2173 glslangOperands[i]->traverse(this);
2174
2175 return false;
2176 }
2177 case glslang::EOpFunction:
2178 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002179 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002180 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002181 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002182 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002183 } else {
2184 handleFunctionEntry(node);
2185 }
2186 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002187 if (inEntryPoint)
2188 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002189 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002190 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002191 }
2192
2193 return true;
2194 case glslang::EOpParameters:
2195 // Parameters will have been consumed by EOpFunction processing, but not
2196 // the body, so we still visited the function node's children, making this
2197 // child redundant.
2198 return false;
2199 case glslang::EOpFunctionCall:
2200 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002201 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002202 if (node->isUserDefined())
2203 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07002204 // assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
John Kessenich6c292d32016-02-15 20:58:50 -07002205 if (result) {
2206 builder.clearAccessChain();
2207 builder.setAccessChainRValue(result);
2208 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002209 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002210
2211 return false;
2212 }
2213 case glslang::EOpConstructMat2x2:
2214 case glslang::EOpConstructMat2x3:
2215 case glslang::EOpConstructMat2x4:
2216 case glslang::EOpConstructMat3x2:
2217 case glslang::EOpConstructMat3x3:
2218 case glslang::EOpConstructMat3x4:
2219 case glslang::EOpConstructMat4x2:
2220 case glslang::EOpConstructMat4x3:
2221 case glslang::EOpConstructMat4x4:
2222 case glslang::EOpConstructDMat2x2:
2223 case glslang::EOpConstructDMat2x3:
2224 case glslang::EOpConstructDMat2x4:
2225 case glslang::EOpConstructDMat3x2:
2226 case glslang::EOpConstructDMat3x3:
2227 case glslang::EOpConstructDMat3x4:
2228 case glslang::EOpConstructDMat4x2:
2229 case glslang::EOpConstructDMat4x3:
2230 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002231 case glslang::EOpConstructIMat2x2:
2232 case glslang::EOpConstructIMat2x3:
2233 case glslang::EOpConstructIMat2x4:
2234 case glslang::EOpConstructIMat3x2:
2235 case glslang::EOpConstructIMat3x3:
2236 case glslang::EOpConstructIMat3x4:
2237 case glslang::EOpConstructIMat4x2:
2238 case glslang::EOpConstructIMat4x3:
2239 case glslang::EOpConstructIMat4x4:
2240 case glslang::EOpConstructUMat2x2:
2241 case glslang::EOpConstructUMat2x3:
2242 case glslang::EOpConstructUMat2x4:
2243 case glslang::EOpConstructUMat3x2:
2244 case glslang::EOpConstructUMat3x3:
2245 case glslang::EOpConstructUMat3x4:
2246 case glslang::EOpConstructUMat4x2:
2247 case glslang::EOpConstructUMat4x3:
2248 case glslang::EOpConstructUMat4x4:
2249 case glslang::EOpConstructBMat2x2:
2250 case glslang::EOpConstructBMat2x3:
2251 case glslang::EOpConstructBMat2x4:
2252 case glslang::EOpConstructBMat3x2:
2253 case glslang::EOpConstructBMat3x3:
2254 case glslang::EOpConstructBMat3x4:
2255 case glslang::EOpConstructBMat4x2:
2256 case glslang::EOpConstructBMat4x3:
2257 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002258 case glslang::EOpConstructF16Mat2x2:
2259 case glslang::EOpConstructF16Mat2x3:
2260 case glslang::EOpConstructF16Mat2x4:
2261 case glslang::EOpConstructF16Mat3x2:
2262 case glslang::EOpConstructF16Mat3x3:
2263 case glslang::EOpConstructF16Mat3x4:
2264 case glslang::EOpConstructF16Mat4x2:
2265 case glslang::EOpConstructF16Mat4x3:
2266 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002267 isMatrix = true;
2268 // fall through
2269 case glslang::EOpConstructFloat:
2270 case glslang::EOpConstructVec2:
2271 case glslang::EOpConstructVec3:
2272 case glslang::EOpConstructVec4:
2273 case glslang::EOpConstructDouble:
2274 case glslang::EOpConstructDVec2:
2275 case glslang::EOpConstructDVec3:
2276 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002277 case glslang::EOpConstructFloat16:
2278 case glslang::EOpConstructF16Vec2:
2279 case glslang::EOpConstructF16Vec3:
2280 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002281 case glslang::EOpConstructBool:
2282 case glslang::EOpConstructBVec2:
2283 case glslang::EOpConstructBVec3:
2284 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002285 case glslang::EOpConstructInt8:
2286 case glslang::EOpConstructI8Vec2:
2287 case glslang::EOpConstructI8Vec3:
2288 case glslang::EOpConstructI8Vec4:
2289 case glslang::EOpConstructUint8:
2290 case glslang::EOpConstructU8Vec2:
2291 case glslang::EOpConstructU8Vec3:
2292 case glslang::EOpConstructU8Vec4:
2293 case glslang::EOpConstructInt16:
2294 case glslang::EOpConstructI16Vec2:
2295 case glslang::EOpConstructI16Vec3:
2296 case glslang::EOpConstructI16Vec4:
2297 case glslang::EOpConstructUint16:
2298 case glslang::EOpConstructU16Vec2:
2299 case glslang::EOpConstructU16Vec3:
2300 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002301 case glslang::EOpConstructInt:
2302 case glslang::EOpConstructIVec2:
2303 case glslang::EOpConstructIVec3:
2304 case glslang::EOpConstructIVec4:
2305 case glslang::EOpConstructUint:
2306 case glslang::EOpConstructUVec2:
2307 case glslang::EOpConstructUVec3:
2308 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002309 case glslang::EOpConstructInt64:
2310 case glslang::EOpConstructI64Vec2:
2311 case glslang::EOpConstructI64Vec3:
2312 case glslang::EOpConstructI64Vec4:
2313 case glslang::EOpConstructUint64:
2314 case glslang::EOpConstructU64Vec2:
2315 case glslang::EOpConstructU64Vec3:
2316 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002317 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002318 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002319 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002320 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002321 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002322 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002323 std::vector<spv::Id> arguments;
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002324 translateArguments(*node, arguments, lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002325 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002326 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002327 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002328 else if (node->getOp() == glslang::EOpConstructStruct ||
2329 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2330 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002331 std::vector<spv::Id> constituents;
2332 for (int c = 0; c < (int)arguments.size(); ++c)
2333 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06002334 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002335 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002336 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002337 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002338 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002339
2340 builder.clearAccessChain();
2341 builder.setAccessChainRValue(constructed);
2342
2343 return false;
2344 }
2345
2346 // These six are component-wise compares with component-wise results.
2347 // Forward on to createBinaryOperation(), requesting a vector result.
2348 case glslang::EOpLessThan:
2349 case glslang::EOpGreaterThan:
2350 case glslang::EOpLessThanEqual:
2351 case glslang::EOpGreaterThanEqual:
2352 case glslang::EOpVectorEqual:
2353 case glslang::EOpVectorNotEqual:
2354 {
2355 // Map the operation to a binary
2356 binOp = node->getOp();
2357 reduceComparison = false;
2358 switch (node->getOp()) {
2359 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2360 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2361 default: binOp = node->getOp(); break;
2362 }
2363
2364 break;
2365 }
2366 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002367 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002368 binOp = glslang::EOpMul;
2369 break;
2370 case glslang::EOpOuterProduct:
2371 // two vectors multiplied to make a matrix
2372 binOp = glslang::EOpOuterProduct;
2373 break;
2374 case glslang::EOpDot:
2375 {
qining25262b32016-05-06 17:25:16 -04002376 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002377 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002378 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002379 binOp = glslang::EOpMul;
2380 break;
2381 }
2382 case glslang::EOpMod:
2383 // when an aggregate, this is the floating-point mod built-in function,
2384 // which can be emitted by the one in createBinaryOperation()
2385 binOp = glslang::EOpMod;
2386 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002387 case glslang::EOpEmitVertex:
2388 case glslang::EOpEndPrimitive:
2389 case glslang::EOpBarrier:
2390 case glslang::EOpMemoryBarrier:
2391 case glslang::EOpMemoryBarrierAtomicCounter:
2392 case glslang::EOpMemoryBarrierBuffer:
2393 case glslang::EOpMemoryBarrierImage:
2394 case glslang::EOpMemoryBarrierShared:
2395 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002396 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002397 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002398 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002399 case glslang::EOpWorkgroupMemoryBarrier:
2400 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002401 case glslang::EOpSubgroupBarrier:
2402 case glslang::EOpSubgroupMemoryBarrier:
2403 case glslang::EOpSubgroupMemoryBarrierBuffer:
2404 case glslang::EOpSubgroupMemoryBarrierImage:
2405 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002406 noReturnValue = true;
2407 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2408 break;
2409
Jeff Bolz36831c92018-09-05 10:11:41 -05002410 case glslang::EOpAtomicStore:
2411 noReturnValue = true;
2412 // fallthrough
2413 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06002414 case glslang::EOpAtomicAdd:
2415 case glslang::EOpAtomicMin:
2416 case glslang::EOpAtomicMax:
2417 case glslang::EOpAtomicAnd:
2418 case glslang::EOpAtomicOr:
2419 case glslang::EOpAtomicXor:
2420 case glslang::EOpAtomicExchange:
2421 case glslang::EOpAtomicCompSwap:
2422 atomic = true;
2423 break;
2424
John Kessenich0d0c6d32017-07-23 16:08:26 -06002425 case glslang::EOpAtomicCounterAdd:
2426 case glslang::EOpAtomicCounterSubtract:
2427 case glslang::EOpAtomicCounterMin:
2428 case glslang::EOpAtomicCounterMax:
2429 case glslang::EOpAtomicCounterAnd:
2430 case glslang::EOpAtomicCounterOr:
2431 case glslang::EOpAtomicCounterXor:
2432 case glslang::EOpAtomicCounterExchange:
2433 case glslang::EOpAtomicCounterCompSwap:
2434 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2435 builder.addCapability(spv::CapabilityAtomicStorageOps);
2436 atomic = true;
2437 break;
2438
Chao Chen3c366992018-09-19 11:41:59 -07002439#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07002440 case glslang::EOpIgnoreIntersectionNV:
2441 case glslang::EOpTerminateRayNV:
2442 case glslang::EOpTraceNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07002443 case glslang::EOpExecuteCallableNV:
Chao Chen3c366992018-09-19 11:41:59 -07002444 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2445 noReturnValue = true;
2446 break;
2447#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002448 case glslang::EOpCooperativeMatrixLoad:
2449 case glslang::EOpCooperativeMatrixStore:
2450 noReturnValue = true;
2451 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002452 case glslang::EOpBeginInvocationInterlock:
2453 case glslang::EOpEndInvocationInterlock:
2454 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2455 noReturnValue = true;
2456 break;
Chao Chen3c366992018-09-19 11:41:59 -07002457
John Kessenich140f3df2015-06-26 16:58:36 -06002458 default:
2459 break;
2460 }
2461
2462 //
2463 // See if it maps to a regular operation.
2464 //
John Kessenich140f3df2015-06-26 16:58:36 -06002465 if (binOp != glslang::EOpNull) {
2466 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2467 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2468 assert(left && right);
2469
2470 builder.clearAccessChain();
2471 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002472 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002473
2474 builder.clearAccessChain();
2475 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002476 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002477
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002478 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002479 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002480 TranslateNoContractionDecoration(node->getType().getQualifier()),
2481 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002482 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002483 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002484 left->getType().getBasicType(), reduceComparison);
2485
2486 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002487 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002488 builder.clearAccessChain();
2489 builder.setAccessChainRValue(result);
2490
2491 return false;
2492 }
2493
John Kessenich426394d2015-07-23 10:22:48 -06002494 //
2495 // Create the list of operands.
2496 //
John Kessenich140f3df2015-06-26 16:58:36 -06002497 glslang::TIntermSequence& glslangOperands = node->getSequence();
2498 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002499 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002500 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002501 // special case l-value operands; there are just a few
2502 bool lvalue = false;
2503 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07002504 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06002505 case glslang::EOpModf:
2506 if (arg == 1)
2507 lvalue = true;
2508 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002509 case glslang::EOpInterpolateAtSample:
2510 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002511#ifdef AMD_EXTENSIONS
2512 case glslang::EOpInterpolateAtVertex:
2513#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06002514 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002515 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002516
2517 // Does it need a swizzle inversion? If so, evaluation is inverted;
2518 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002519 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002520 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2521 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2522 }
Rex Xu7a26c172015-12-08 17:12:09 +08002523 break;
Rex Xud4782c12015-09-06 16:30:11 +08002524 case glslang::EOpAtomicAdd:
2525 case glslang::EOpAtomicMin:
2526 case glslang::EOpAtomicMax:
2527 case glslang::EOpAtomicAnd:
2528 case glslang::EOpAtomicOr:
2529 case glslang::EOpAtomicXor:
2530 case glslang::EOpAtomicExchange:
2531 case glslang::EOpAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05002532 case glslang::EOpAtomicLoad:
2533 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002534 case glslang::EOpAtomicCounterAdd:
2535 case glslang::EOpAtomicCounterSubtract:
2536 case glslang::EOpAtomicCounterMin:
2537 case glslang::EOpAtomicCounterMax:
2538 case glslang::EOpAtomicCounterAnd:
2539 case glslang::EOpAtomicCounterOr:
2540 case glslang::EOpAtomicCounterXor:
2541 case glslang::EOpAtomicCounterExchange:
2542 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002543 if (arg == 0)
2544 lvalue = true;
2545 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002546 case glslang::EOpAddCarry:
2547 case glslang::EOpSubBorrow:
2548 if (arg == 2)
2549 lvalue = true;
2550 break;
2551 case glslang::EOpUMulExtended:
2552 case glslang::EOpIMulExtended:
2553 if (arg >= 2)
2554 lvalue = true;
2555 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002556 case glslang::EOpCooperativeMatrixLoad:
2557 if (arg == 0 || arg == 1)
2558 lvalue = true;
2559 break;
2560 case glslang::EOpCooperativeMatrixStore:
2561 if (arg == 1)
2562 lvalue = true;
2563 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002564 default:
2565 break;
2566 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002567 builder.clearAccessChain();
2568 if (invertedType != spv::NoType && arg == 0)
2569 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2570 else
2571 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002572
2573 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2574 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2575
2576 if (arg == 1) {
2577 // fold "element" parameter into the access chain
2578 spv::Builder::AccessChain save = builder.getAccessChain();
2579 builder.clearAccessChain();
2580 glslangOperands[2]->traverse(this);
2581
2582 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2583
2584 builder.setAccessChain(save);
2585
2586 // Point to the first element of the array.
2587 builder.accessChainPush(elementId, TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
Jeff Bolz7895e472019-03-06 13:34:10 -06002588 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002589
2590 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2591 unsigned int alignment = builder.getAccessChain().alignment;
2592
2593 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2594 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2595 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2596 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2597 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
2598 if (builder.getStorageClass(builder.getAccessChain().base) == spv::StorageClassPhysicalStorageBufferEXT) {
2599 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2600 }
2601
2602 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2603
2604 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2605 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2606 }
2607
2608 if (memoryAccess & (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2609 memoryAccessOperands.push_back(spv::IdImmediate(true, builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
2610 }
2611 } else if (arg == 2) {
2612 continue;
2613 }
2614 }
2615
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002616 if (lvalue) {
John Kessenich140f3df2015-06-26 16:58:36 -06002617 operands.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002618 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2619 lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
2620 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002621 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich32cfd492016-02-02 12:37:46 -07002622 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002623 }
John Kessenich140f3df2015-06-26 16:58:36 -06002624 }
John Kessenich426394d2015-07-23 10:22:48 -06002625
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002626 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002627 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
2628 std::vector<spv::IdImmediate> idImmOps;
2629
2630 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2631 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2632 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2633 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2634 // get the pointee type
2635 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
2636 assert(builder.isCooperativeMatrixType(typeId));
2637 // do the op
2638 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
2639 // store the result to the pointer (out param 'm')
2640 builder.createStore(result, operands[0]);
2641 result = 0;
2642 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
2643 std::vector<spv::IdImmediate> idImmOps;
2644
2645 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2646 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
2647 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2648 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2649 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2650
2651 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
2652 result = 0;
2653 } else if (atomic) {
John Kessenich426394d2015-07-23 10:22:48 -06002654 // Handle all atomics
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002655 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(), lvalueCoherentFlags);
John Kessenich426394d2015-07-23 10:22:48 -06002656 } else {
2657 // Pass through to generic operations.
2658 switch (glslangOperands.size()) {
2659 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002660 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002661 break;
2662 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002663 {
2664 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002665 TranslateNoContractionDecoration(node->getType().getQualifier()),
2666 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002667 result = createUnaryOperation(
2668 node->getOp(), decorations,
2669 resultType(), operands.front(),
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002670 glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -06002671 }
John Kessenich426394d2015-07-23 10:22:48 -06002672 break;
2673 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002674 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002675 break;
2676 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002677 if (invertedType)
2678 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002679 }
2680
2681 if (noReturnValue)
2682 return false;
2683
2684 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002685 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002686 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002687 } else {
2688 builder.clearAccessChain();
2689 builder.setAccessChainRValue(result);
2690 return false;
2691 }
2692}
2693
John Kessenich433e9ff2017-01-26 20:31:11 -07002694// This path handles both if-then-else and ?:
2695// The if-then-else has a node type of void, while
2696// ?: has either a void or a non-void node type
2697//
2698// Leaving the result, when not void:
2699// GLSL only has r-values as the result of a :?, but
2700// if we have an l-value, that can be more efficient if it will
2701// become the base of a complex r-value expression, because the
2702// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002703bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2704{
John Kessenich0c1e71a2019-01-10 18:23:06 +07002705 // see if OpSelect can handle it
2706 const auto isOpSelectable = [&]() {
2707 if (node->getBasicType() == glslang::EbtVoid)
2708 return false;
2709 // OpSelect can do all other types starting with SPV 1.4
2710 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
2711 // pre-1.4, only scalars and vectors can be handled
2712 if ((!node->getType().isScalar() && !node->getType().isVector()))
2713 return false;
2714 }
2715 return true;
2716 };
2717
John Kessenich4bee5312018-02-20 21:29:05 -07002718 // See if it simple and safe, or required, to execute both sides.
2719 // Crucially, side effects must be either semantically required or avoided,
2720 // and there are performance trade-offs.
2721 // Return true if required or a good idea (and safe) to execute both sides,
2722 // false otherwise.
2723 const auto bothSidesPolicy = [&]() -> bool {
2724 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002725 if (node->getTrueBlock() == nullptr ||
2726 node->getFalseBlock() == nullptr)
2727 return false;
2728
John Kessenich4bee5312018-02-20 21:29:05 -07002729 // required? (unless we write additional code to look for side effects
2730 // and make performance trade-offs if none are present)
2731 if (!node->getShortCircuit())
2732 return true;
2733
2734 // if not required to execute both, decide based on performance/practicality...
2735
John Kessenich0c1e71a2019-01-10 18:23:06 +07002736 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07002737 return false;
2738
John Kessenich433e9ff2017-01-26 20:31:11 -07002739 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2740 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2741
2742 // return true if a single operand to ? : is okay for OpSelect
2743 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002744 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002745 };
2746
2747 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2748 operandOkay(node->getFalseBlock()->getAsTyped());
2749 };
2750
John Kessenich4bee5312018-02-20 21:29:05 -07002751 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2752 // emit the condition before doing anything with selection
2753 node->getCondition()->traverse(this);
2754 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2755
2756 // Find a way of executing both sides and selecting the right result.
2757 const auto executeBothSides = [&]() -> void {
2758 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002759 node->getTrueBlock()->traverse(this);
2760 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2761 node->getFalseBlock()->traverse(this);
2762 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2763
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002764 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002765
John Kessenich4bee5312018-02-20 21:29:05 -07002766 // done if void
2767 if (node->getBasicType() == glslang::EbtVoid)
2768 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002769
John Kessenich4bee5312018-02-20 21:29:05 -07002770 // emit code to select between trueValue and falseValue
2771
2772 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07002773 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07002774 // Emit OpSelect for this selection.
2775
2776 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07002777 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
2778 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07002779 condition = builder.smearScalar(spv::NoPrecision, condition,
2780 builder.makeVectorType(builder.makeBoolType(),
2781 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07002782 }
John Kessenich4bee5312018-02-20 21:29:05 -07002783
2784 // OpSelect
2785 result = builder.createTriOp(spv::OpSelect,
2786 convertGlslangToSpvType(node->getType()), condition,
2787 trueValue, falseValue);
2788
2789 builder.clearAccessChain();
2790 builder.setAccessChainRValue(result);
2791 } else {
2792 // We need control flow to select the result.
2793 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2794 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2795
2796 // Selection control:
2797 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2798
2799 // make an "if" based on the value created by the condition
2800 spv::Builder::If ifBuilder(condition, control, builder);
2801
2802 // emit the "then" statement
2803 builder.createStore(trueValue, result);
2804 ifBuilder.makeBeginElse();
2805 // emit the "else" statement
2806 builder.createStore(falseValue, result);
2807
2808 // finish off the control flow
2809 ifBuilder.makeEndIf();
2810
2811 builder.clearAccessChain();
2812 builder.setAccessChainLValue(result);
2813 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002814 };
2815
John Kessenich4bee5312018-02-20 21:29:05 -07002816 // Execute the one side needed, as per the condition
2817 const auto executeOneSide = [&]() {
2818 // Always emit control flow.
2819 if (node->getBasicType() != glslang::EbtVoid)
2820 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002821
John Kessenich4bee5312018-02-20 21:29:05 -07002822 // Selection control:
2823 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2824
2825 // make an "if" based on the value created by the condition
2826 spv::Builder::If ifBuilder(condition, control, builder);
2827
2828 // emit the "then" statement
2829 if (node->getTrueBlock() != nullptr) {
2830 node->getTrueBlock()->traverse(this);
2831 if (result != spv::NoResult)
2832 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2833 }
2834
2835 if (node->getFalseBlock() != nullptr) {
2836 ifBuilder.makeBeginElse();
2837 // emit the "else" statement
2838 node->getFalseBlock()->traverse(this);
2839 if (result != spv::NoResult)
2840 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2841 }
2842
2843 // finish off the control flow
2844 ifBuilder.makeEndIf();
2845
2846 if (result != spv::NoResult) {
2847 builder.clearAccessChain();
2848 builder.setAccessChainLValue(result);
2849 }
2850 };
2851
2852 // Try for OpSelect (or a requirement to execute both sides)
2853 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002854 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2855 if (node->getType().getQualifier().isSpecConstant())
2856 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002857 executeBothSides();
2858 } else
2859 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002860
2861 return false;
2862}
2863
2864bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2865{
2866 // emit and get the condition before doing anything with switch
2867 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002868 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002869
Rex Xu57e65922017-07-04 23:23:40 +08002870 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002871 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002872
John Kessenich140f3df2015-06-26 16:58:36 -06002873 // browse the children to sort out code segments
2874 int defaultSegment = -1;
2875 std::vector<TIntermNode*> codeSegments;
2876 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2877 std::vector<int> caseValues;
2878 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2879 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2880 TIntermNode* child = *c;
2881 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002882 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002883 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002884 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002885 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2886 } else
2887 codeSegments.push_back(child);
2888 }
2889
qining25262b32016-05-06 17:25:16 -04002890 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002891 // statements between the last case and the end of the switch statement
2892 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2893 (int)codeSegments.size() == defaultSegment)
2894 codeSegments.push_back(nullptr);
2895
2896 // make the switch statement
2897 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002898 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002899
2900 // emit all the code in the segments
2901 breakForLoop.push(false);
2902 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2903 builder.nextSwitchSegment(segmentBlocks, s);
2904 if (codeSegments[s])
2905 codeSegments[s]->traverse(this);
2906 else
2907 builder.addSwitchBreak();
2908 }
2909 breakForLoop.pop();
2910
2911 builder.endSwitch(segmentBlocks);
2912
2913 return false;
2914}
2915
2916void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2917{
2918 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002919 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002920
2921 builder.clearAccessChain();
2922 builder.setAccessChainRValue(constant);
2923}
2924
2925bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2926{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002927 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002928 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002929
2930 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07002931 std::vector<unsigned int> operands;
2932 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06002933
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002934 // Spec requires back edges to target header blocks, and every header block
2935 // must dominate its merge block. Make a header block first to ensure these
2936 // conditions are met. By definition, it will contain OpLoopMerge, followed
2937 // by a block-ending branch. But we don't want to put any other body/test
2938 // instructions in it, since the body/test may have arbitrary instructions,
2939 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002940 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002941 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07002942 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002943 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002944 spv::Block& test = builder.makeNewBlock();
2945 builder.createBranch(&test);
2946
2947 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002948 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002949 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002950 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2951
2952 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002953 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002954 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002955 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002956 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002957 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002958
2959 builder.setBuildPoint(&blocks.continue_target);
2960 if (node->getTerminal())
2961 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002962 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002963 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002964 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002965 builder.createBranch(&blocks.body);
2966
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002967 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002968 builder.setBuildPoint(&blocks.body);
2969 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002970 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002971 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002972 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002973
2974 builder.setBuildPoint(&blocks.continue_target);
2975 if (node->getTerminal())
2976 node->getTerminal()->traverse(this);
2977 if (node->getTest()) {
2978 node->getTest()->traverse(this);
2979 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002980 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002981 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002982 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002983 // TODO: unless there was a break/return/discard instruction
2984 // somewhere in the body, this is an infinite loop, so we should
2985 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002986 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002987 }
John Kessenich140f3df2015-06-26 16:58:36 -06002988 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002989 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002990 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002991 return false;
2992}
2993
2994bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2995{
2996 if (node->getExpression())
2997 node->getExpression()->traverse(this);
2998
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002999 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003000
John Kessenich140f3df2015-06-26 16:58:36 -06003001 switch (node->getFlowOp()) {
3002 case glslang::EOpKill:
3003 builder.makeDiscard();
3004 break;
3005 case glslang::EOpBreak:
3006 if (breakForLoop.top())
3007 builder.createLoopExit();
3008 else
3009 builder.addSwitchBreak();
3010 break;
3011 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06003012 builder.createLoopContinue();
3013 break;
3014 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06003015 if (node->getExpression()) {
3016 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3017 spv::Id returnId = accessChainLoad(glslangReturnType);
3018 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
3019 builder.clearAccessChain();
3020 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
3021 builder.setAccessChainLValue(copyId);
3022 multiTypeStore(glslangReturnType, returnId);
3023 returnId = builder.createLoad(copyId);
3024 }
3025 builder.makeReturn(false, returnId);
3026 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003027 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003028
3029 builder.clearAccessChain();
3030 break;
3031
3032 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003033 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003034 break;
3035 }
3036
3037 return false;
3038}
3039
3040spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
3041{
qining25262b32016-05-06 17:25:16 -04003042 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003043 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003044 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003045 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003046 spv::Id result = createSpvConstant(*node);
3047 if (result != spv::NoResult)
3048 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003049 }
3050
3051 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003052 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06003053 spv::Id spvType = convertGlslangToSpvType(node->getType());
3054
Rex Xucabbb782017-03-24 13:41:14 +08003055 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
3056 node->getType().containsBasicType(glslang::EbtInt16) ||
3057 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08003058 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003059 switch (storageClass) {
3060 case spv::StorageClassInput:
3061 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07003062 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003063 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003064 break;
3065 case spv::StorageClassPushConstant:
John Kessenich66011cb2018-03-06 16:12:04 -07003066 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003067 builder.addCapability(spv::CapabilityStoragePushConstant16);
John Kessenich18310872018-05-14 22:08:53 -06003068 break;
3069 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07003070 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003071 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3072 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003073 else
3074 builder.addCapability(spv::CapabilityStorageUniform16);
3075 break;
3076 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003077 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich18310872018-05-14 22:08:53 -06003078 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
3079 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3080 break;
3081 default:
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003082 if (node->getType().containsBasicType(glslang::EbtFloat16))
3083 builder.addCapability(spv::CapabilityFloat16);
3084 if (node->getType().containsBasicType(glslang::EbtInt16) ||
3085 node->getType().containsBasicType(glslang::EbtUint16))
3086 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06003087 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003088 }
3089 }
Rex Xuf89ad982017-04-07 23:22:33 +08003090
John Kessenich312dcfb2018-07-03 13:19:51 -06003091 const bool contains8BitType = node->getType().containsBasicType(glslang::EbtInt8) ||
3092 node->getType().containsBasicType(glslang::EbtUint8);
3093 if (contains8BitType) {
3094 if (storageClass == spv::StorageClassPushConstant) {
3095 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3096 builder.addCapability(spv::CapabilityStoragePushConstant8);
3097 } else if (storageClass == spv::StorageClassUniform) {
3098 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3099 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003100 } else if (storageClass == spv::StorageClassStorageBuffer) {
3101 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3102 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003103 } else {
3104 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06003105 }
3106 }
3107
John Kessenich140f3df2015-06-26 16:58:36 -06003108 const char* name = node->getName().c_str();
3109 if (glslang::IsAnonymous(name))
3110 name = "";
3111
3112 return builder.createVariable(storageClass, spvType, name);
3113}
3114
3115// Return type Id of the sampled type.
3116spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3117{
3118 switch (sampler.type) {
3119 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08003120#ifdef AMD_EXTENSIONS
3121 case glslang::EbtFloat16:
3122 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3123 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3124 return builder.makeFloatType(16);
3125#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003126 case glslang::EbtInt: return builder.makeIntType(32);
3127 case glslang::EbtUint: return builder.makeUintType(32);
3128 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003129 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003130 return builder.makeFloatType(32);
3131 }
3132}
3133
John Kessenich8c8505c2016-07-26 12:50:38 -06003134// If node is a swizzle operation, return the type that should be used if
3135// the swizzle base is first consumed by another operation, before the swizzle
3136// is applied.
3137spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3138{
John Kessenichecba76f2017-01-06 00:34:48 -07003139 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003140 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3141 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3142 else
3143 return spv::NoType;
3144}
3145
3146// When inverting a swizzle with a parent op, this function
3147// will apply the swizzle operation to a completed parent operation.
3148spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
3149{
3150 std::vector<unsigned> swizzle;
3151 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3152 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3153}
3154
John Kessenich8c8505c2016-07-26 12:50:38 -06003155// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3156void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3157{
3158 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3159 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3160 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3161}
3162
John Kessenich3ac051e2015-12-20 11:29:16 -07003163// Convert from a glslang type to an SPV type, by calling into a
3164// recursive version of this function. This establishes the inherited
3165// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003166spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003167{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003168 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003169}
3170
3171// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003172// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003173// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003174spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003175 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3176 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003177{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003178 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003179
3180 switch (type.getBasicType()) {
3181 case glslang::EbtVoid:
3182 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003183 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003184 break;
3185 case glslang::EbtFloat:
3186 spvType = builder.makeFloatType(32);
3187 break;
3188 case glslang::EbtDouble:
3189 spvType = builder.makeFloatType(64);
3190 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003191 case glslang::EbtFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003192 spvType = builder.makeFloatType(16);
3193 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003194 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003195 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3196 // a 32-bit int where non-0 means true.
3197 if (explicitLayout != glslang::ElpNone)
3198 spvType = builder.makeUintType(32);
3199 else
3200 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003201 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003202 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003203 spvType = builder.makeIntType(8);
3204 break;
3205 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003206 spvType = builder.makeUintType(8);
3207 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003208 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003209 spvType = builder.makeIntType(16);
3210 break;
3211 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003212 spvType = builder.makeUintType(16);
3213 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003214 case glslang::EbtInt:
3215 spvType = builder.makeIntType(32);
3216 break;
3217 case glslang::EbtUint:
3218 spvType = builder.makeUintType(32);
3219 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003220 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003221 spvType = builder.makeIntType(64);
3222 break;
3223 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003224 spvType = builder.makeUintType(64);
3225 break;
John Kessenich426394d2015-07-23 10:22:48 -06003226 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003227 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003228 spvType = builder.makeUintType(32);
3229 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003230#ifdef NV_EXTENSIONS
3231 case glslang::EbtAccStructNV:
3232 spvType = builder.makeAccelerationStructureNVType();
3233 break;
3234#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003235 case glslang::EbtSampler:
3236 {
3237 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07003238 if (sampler.sampler) {
3239 // pure sampler
3240 spvType = builder.makeSamplerType();
3241 } else {
3242 // an image is present, make its type
3243 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
3244 sampler.image ? 2 : 1, TranslateImageFormat(type));
3245 if (sampler.combined) {
3246 // already has both image and sampler, make the combined type
3247 spvType = builder.makeSampledImageType(spvType);
3248 }
John Kessenich55e7d112015-11-15 21:33:39 -07003249 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003250 }
John Kessenich140f3df2015-06-26 16:58:36 -06003251 break;
3252 case glslang::EbtStruct:
3253 case glslang::EbtBlock:
3254 {
3255 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003256 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003257
3258 // Try to share structs for different layouts, but not yet for other
3259 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003260 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003261 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003262 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003263 break;
3264
3265 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003266 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06003267 memberRemapper[glslangMembers].resize(glslangMembers->size());
3268 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003269 }
3270 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003271 case glslang::EbtReference:
3272 {
3273 // Make the forward pointer, then recurse to convert the structure type, then
3274 // patch up the forward pointer with a real pointer type.
3275 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3276 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3277 forwardPointers[type.getReferentType()] = forwardId;
3278 }
3279 spvType = forwardPointers[type.getReferentType()];
3280 if (!forwardReferenceOnly) {
3281 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3282 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3283 forwardPointers[type.getReferentType()],
3284 referentType);
3285 }
3286 }
3287 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003288 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003289 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003290 break;
3291 }
3292
3293 if (type.isMatrix())
3294 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3295 else {
3296 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3297 if (type.getVectorSize() > 1)
3298 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3299 }
3300
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003301 if (type.isCoopMat()) {
3302 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3303 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3304 if (type.getBasicType() == glslang::EbtFloat16)
3305 builder.addCapability(spv::CapabilityFloat16);
3306
3307 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3308 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3309 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3310
3311 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3312 }
3313
John Kessenich140f3df2015-06-26 16:58:36 -06003314 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003315 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3316
John Kessenichc9a80832015-09-12 12:17:44 -06003317 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003318 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003319 // We need to decorate array strides for types needing explicit layout, except blocks.
3320 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003321 // Use a dummy glslang type for querying internal strides of
3322 // arrays of arrays, but using just a one-dimensional array.
3323 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003324 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3325 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003326
3327 // Will compute the higher-order strides here, rather than making a whole
3328 // pile of types and doing repetitive recursion on their contents.
3329 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3330 }
John Kessenichf8842e52016-01-04 19:22:56 -07003331
3332 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003333 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003334 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003335 if (stride > 0)
3336 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003337 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003338 }
3339 } else {
3340 // single-dimensional array, and don't yet have stride
3341
John Kessenichf8842e52016-01-04 19:22:56 -07003342 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003343 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3344 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003345 }
John Kessenich31ed4832015-09-09 17:51:38 -06003346
John Kessenichead86222018-03-28 18:01:20 -06003347 // Do the outer dimension, which might not be known for a runtime-sized array.
3348 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3349 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003350 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003351 else {
3352 if (!lastBufferBlockMember) {
3353 builder.addExtension("SPV_EXT_descriptor_indexing");
3354 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3355 }
John Kessenichead86222018-03-28 18:01:20 -06003356 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003357 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003358 if (stride > 0)
3359 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003360 }
3361
3362 return spvType;
3363}
3364
John Kessenich0e737842017-03-24 18:38:16 -06003365// TODO: this functionality should exist at a higher level, in creating the AST
3366//
3367// Identify interface members that don't have their required extension turned on.
3368//
3369bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3370{
Chao Chen3c366992018-09-19 11:41:59 -07003371#ifdef NV_EXTENSIONS
John Kessenich0e737842017-03-24 18:38:16 -06003372 auto& extensions = glslangIntermediate->getRequestedExtensions();
3373
Rex Xubcf291a2017-03-29 23:01:36 +08003374 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3375 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3376 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003377 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3378 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3379 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003380
3381 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3382 if (member.getFieldName() == "gl_ViewportMask" &&
3383 extensions.find("GL_NV_viewport_array2") == extensions.end())
3384 return true;
3385 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3386 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3387 return true;
3388 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3389 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3390 return true;
3391 }
3392#endif
John Kessenich0e737842017-03-24 18:38:16 -06003393
3394 return false;
3395};
3396
John Kessenich6090df02016-06-30 21:18:02 -06003397// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3398// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3399// Mutually recursive with convertGlslangToSpvType().
3400spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3401 const glslang::TTypeList* glslangMembers,
3402 glslang::TLayoutPacking explicitLayout,
3403 const glslang::TQualifier& qualifier)
3404{
3405 // Create a vector of struct types for SPIR-V to consume
3406 std::vector<spv::Id> spvMembers;
3407 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003408 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003409 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3410 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3411 if (glslangMember.hiddenMember()) {
3412 ++memberDelta;
3413 if (type.getBasicType() == glslang::EbtBlock)
3414 memberRemapper[glslangMembers][i] = -1;
3415 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003416 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003417 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003418 if (filterMember(glslangMember))
3419 continue;
3420 }
John Kessenich6090df02016-06-30 21:18:02 -06003421 // modify just this child's view of the qualifier
3422 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3423 InheritQualifiers(memberQualifier, qualifier);
3424
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003425 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003426 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003427 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003428
3429 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003430 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3431 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003432
3433 // Make forward pointers for any pointer members, and create a list of members to
3434 // convert to spirv types after creating the struct.
3435 if (glslangMember.getBasicType() == glslang::EbtReference) {
3436 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3437 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3438 }
3439 spvMembers.push_back(
3440 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, true));
3441 } else {
3442 spvMembers.push_back(
3443 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, false));
3444 }
John Kessenich6090df02016-06-30 21:18:02 -06003445 }
3446 }
3447
3448 // Make the SPIR-V type
3449 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003450 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003451 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3452
3453 // Decorate it
3454 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3455
John Kessenichd72f4882019-01-16 14:55:37 +07003456 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003457 auto it = deferredForwardPointers[i];
3458 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3459 }
3460
John Kessenich6090df02016-06-30 21:18:02 -06003461 return spvType;
3462}
3463
3464void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3465 const glslang::TTypeList* glslangMembers,
3466 glslang::TLayoutPacking explicitLayout,
3467 const glslang::TQualifier& qualifier,
3468 spv::Id spvType)
3469{
3470 // Name and decorate the non-hidden members
3471 int offset = -1;
3472 int locationOffset = 0; // for use within the members of this struct
3473 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3474 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3475 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003476 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003477 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06003478 if (filterMember(glslangMember))
3479 continue;
3480 }
John Kessenich6090df02016-06-30 21:18:02 -06003481
3482 // modify just this child's view of the qualifier
3483 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3484 InheritQualifiers(memberQualifier, qualifier);
3485
3486 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003487 if (member < 0)
3488 continue;
3489
3490 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3491 builder.addMemberDecoration(spvType, member,
3492 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3493 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3494 // Add interpolation and auxiliary storage decorations only to
3495 // top-level members of Input and Output storage classes
3496 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3497 type.getQualifier().storage == glslang::EvqVaryingOut) {
3498 if (type.getBasicType() == glslang::EbtBlock ||
3499 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3500 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3501 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
Chao Chen3c366992018-09-19 11:41:59 -07003502#ifdef NV_EXTENSIONS
3503 addMeshNVDecoration(spvType, member, memberQualifier);
3504#endif
John Kessenich6090df02016-06-30 21:18:02 -06003505 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003506 }
3507 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003508
John Kessenich5d610ee2018-03-07 18:05:55 -07003509 if (type.getBasicType() == glslang::EbtBlock &&
3510 qualifier.storage == glslang::EvqBuffer) {
3511 // Add memory decorations only to top-level members of shader storage block
3512 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003513 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003514 for (unsigned int i = 0; i < memory.size(); ++i)
3515 builder.addMemberDecoration(spvType, member, memory[i]);
3516 }
John Kessenich6090df02016-06-30 21:18:02 -06003517
John Kessenich5d610ee2018-03-07 18:05:55 -07003518 // Location assignment was already completed correctly by the front end,
3519 // just track whether a member needs to be decorated.
3520 // Ignore member locations if the container is an array, as that's
3521 // ill-specified and decisions have been made to not allow this.
3522 if (! type.isArray() && memberQualifier.hasLocation())
3523 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003524
John Kessenich5d610ee2018-03-07 18:05:55 -07003525 if (qualifier.hasLocation()) // track for upcoming inheritance
3526 locationOffset += glslangIntermediate->computeTypeLocationSize(
3527 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003528
John Kessenich5d610ee2018-03-07 18:05:55 -07003529 // component, XFB, others
3530 if (glslangMember.getQualifier().hasComponent())
3531 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3532 glslangMember.getQualifier().layoutComponent);
3533 if (glslangMember.getQualifier().hasXfbOffset())
3534 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3535 glslangMember.getQualifier().layoutXfbOffset);
3536 else if (explicitLayout != glslang::ElpNone) {
3537 // figure out what to do with offset, which is accumulating
3538 int nextOffset;
3539 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3540 if (offset >= 0)
3541 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3542 offset = nextOffset;
3543 }
John Kessenich6090df02016-06-30 21:18:02 -06003544
John Kessenich5d610ee2018-03-07 18:05:55 -07003545 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3546 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3547 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003548
John Kessenich5d610ee2018-03-07 18:05:55 -07003549 // built-in variable decorations
3550 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3551 if (builtIn != spv::BuiltInMax)
3552 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003553
John Kessenich5611c6d2018-04-05 11:25:02 -06003554 // nonuniform
3555 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3556
John Kessenichead86222018-03-28 18:01:20 -06003557 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3558 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3559 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3560 memberQualifier.semanticName);
3561 }
3562
chaoc771d89f2017-01-13 01:10:53 -08003563#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07003564 if (builtIn == spv::BuiltInLayer) {
3565 // SPV_NV_viewport_array2 extension
3566 if (glslangMember.getQualifier().layoutViewportRelative){
3567 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3568 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3569 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003570 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003571 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3572 builder.addMemberDecoration(spvType, member,
3573 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3574 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3575 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3576 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003577 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003578 }
3579 if (glslangMember.getQualifier().layoutPassthrough) {
3580 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3581 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3582 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3583 }
chaoc771d89f2017-01-13 01:10:53 -08003584#endif
John Kessenich6090df02016-06-30 21:18:02 -06003585 }
3586
3587 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003588 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3589 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003590}
3591
John Kessenich6c292d32016-02-15 20:58:50 -07003592// Turn the expression forming the array size into an id.
3593// This is not quite trivial, because of specialization constants.
3594// Sometimes, a raw constant is turned into an Id, and sometimes
3595// a specialization constant expression is.
3596spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3597{
3598 // First, see if this is sized with a node, meaning a specialization constant:
3599 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3600 if (specNode != nullptr) {
3601 builder.clearAccessChain();
3602 specNode->traverse(this);
3603 return accessChainLoad(specNode->getAsTyped()->getType());
3604 }
qining25262b32016-05-06 17:25:16 -04003605
John Kessenich6c292d32016-02-15 20:58:50 -07003606 // Otherwise, need a compile-time (front end) size, get it:
3607 int size = arraySizes.getDimSize(dim);
3608 assert(size > 0);
3609 return builder.makeUintConstant(size);
3610}
3611
John Kessenich103bef92016-02-08 21:38:15 -07003612// Wrap the builder's accessChainLoad to:
3613// - localize handling of RelaxedPrecision
3614// - use the SPIR-V inferred type instead of another conversion of the glslang type
3615// (avoids unnecessary work and possible type punning for structures)
3616// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003617spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3618{
John Kessenich103bef92016-02-08 21:38:15 -07003619 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003620
3621 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3622 coherentFlags |= TranslateCoherent(type);
3623
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003624 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003625 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003626
John Kessenich5611c6d2018-04-05 11:25:02 -06003627 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003628 TranslateNonUniformDecoration(type.getQualifier()),
3629 nominalTypeId,
3630 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003631 TranslateMemoryScope(coherentFlags),
3632 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07003633
3634 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003635 if (type.getBasicType() == glslang::EbtBool) {
3636 if (builder.isScalarType(nominalTypeId)) {
3637 // Conversion for bool
3638 spv::Id boolType = builder.makeBoolType();
3639 if (nominalTypeId != boolType)
3640 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3641 } else if (builder.isVectorType(nominalTypeId)) {
3642 // Conversion for bvec
3643 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3644 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3645 if (nominalTypeId != bvecType)
3646 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3647 }
3648 }
John Kessenich103bef92016-02-08 21:38:15 -07003649
3650 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003651}
3652
Rex Xu27253232016-02-23 17:51:09 +08003653// Wrap the builder's accessChainStore to:
3654// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003655//
3656// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003657void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3658{
3659 // Need to convert to abstract types when necessary
3660 if (type.getBasicType() == glslang::EbtBool) {
3661 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3662
3663 if (builder.isScalarType(nominalTypeId)) {
3664 // Conversion for bool
3665 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003666 if (nominalTypeId != boolType) {
3667 // keep these outside arguments, for determinant order-of-evaluation
3668 spv::Id one = builder.makeUintConstant(1);
3669 spv::Id zero = builder.makeUintConstant(0);
3670 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3671 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003672 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003673 } else if (builder.isVectorType(nominalTypeId)) {
3674 // Conversion for bvec
3675 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3676 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003677 if (nominalTypeId != bvecType) {
3678 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003679 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3680 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3681 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003682 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003683 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3684 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003685 }
3686 }
3687
Jeff Bolz36831c92018-09-05 10:11:41 -05003688 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3689 coherentFlags |= TranslateCoherent(type);
3690
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003691 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003692 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003693
Jeff Bolz36831c92018-09-05 10:11:41 -05003694 builder.accessChainStore(rvalue,
3695 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003696 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08003697}
3698
John Kessenich4bf71552016-09-02 11:20:21 -06003699// For storing when types match at the glslang level, but not might match at the
3700// SPIR-V level.
3701//
3702// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003703// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003704// as in a member-decorated way.
3705//
3706// NOTE: This function can handle any store request; if it's not special it
3707// simplifies to a simple OpStore.
3708//
3709// Implicitly uses the existing builder.accessChain as the storage target.
3710void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3711{
John Kessenichb3e24e42016-09-11 12:33:43 -06003712 // we only do the complex path here if it's an aggregate
3713 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003714 accessChainStore(type, rValue);
3715 return;
3716 }
3717
John Kessenichb3e24e42016-09-11 12:33:43 -06003718 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003719 spv::Id rType = builder.getTypeId(rValue);
3720 spv::Id lValue = builder.accessChainGetLValue();
3721 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3722 if (lType == rType) {
3723 accessChainStore(type, rValue);
3724 return;
3725 }
3726
John Kessenichb3e24e42016-09-11 12:33:43 -06003727 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003728 // where the two types were the same type in GLSL. This requires member
3729 // by member copy, recursively.
3730
John Kessenichfbb6bdf2019-01-15 21:48:27 +07003731 // SPIR-V 1.4 added an instruction to do help do this.
3732 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
3733 // However, bool in uniform space is changed to int, so
3734 // OpCopyLogical does not work for that.
3735 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
3736 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
3737 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
3738 if (lBool == rBool) {
3739 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
3740 accessChainStore(type, logicalCopy);
3741 return;
3742 }
3743 }
3744
John Kessenichb3e24e42016-09-11 12:33:43 -06003745 // If an array, copy element by element.
3746 if (type.isArray()) {
3747 glslang::TType glslangElementType(type, 0);
3748 spv::Id elementRType = builder.getContainedTypeId(rType);
3749 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3750 // get the source member
3751 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003752
John Kessenichb3e24e42016-09-11 12:33:43 -06003753 // set up the target storage
3754 builder.clearAccessChain();
3755 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003756 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06003757
John Kessenichb3e24e42016-09-11 12:33:43 -06003758 // store the member
3759 multiTypeStore(glslangElementType, elementRValue);
3760 }
3761 } else {
3762 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003763
John Kessenichb3e24e42016-09-11 12:33:43 -06003764 // loop over structure members
3765 const glslang::TTypeList& members = *type.getStruct();
3766 for (int m = 0; m < (int)members.size(); ++m) {
3767 const glslang::TType& glslangMemberType = *members[m].type;
3768
3769 // get the source member
3770 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3771 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3772
3773 // set up the target storage
3774 builder.clearAccessChain();
3775 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003776 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06003777
3778 // store the member
3779 multiTypeStore(glslangMemberType, memberRValue);
3780 }
John Kessenich4bf71552016-09-02 11:20:21 -06003781 }
3782}
3783
John Kessenichf85e8062015-12-19 13:57:10 -07003784// Decide whether or not this type should be
3785// decorated with offsets and strides, and if so
3786// whether std140 or std430 rules should be applied.
3787glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003788{
John Kessenichf85e8062015-12-19 13:57:10 -07003789 // has to be a block
3790 if (type.getBasicType() != glslang::EbtBlock)
3791 return glslang::ElpNone;
3792
Chao Chen3c366992018-09-19 11:41:59 -07003793 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07003794 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07003795 type.getQualifier().storage != glslang::EvqBuffer &&
3796 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07003797 return glslang::ElpNone;
3798
3799 // return the layout to use
3800 switch (type.getQualifier().layoutPacking) {
3801 case glslang::ElpStd140:
3802 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003803 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07003804 return type.getQualifier().layoutPacking;
3805 default:
3806 return glslang::ElpNone;
3807 }
John Kessenich31ed4832015-09-09 17:51:38 -06003808}
3809
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003810// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003811int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003812{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003813 int size;
John Kessenich49987892015-12-29 17:11:44 -07003814 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003815 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003816
3817 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003818}
3819
John Kessenich49987892015-12-29 17:11:44 -07003820// Given a matrix type, or array (of array) of matrixes type, returns the integer stride required for that matrix
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003821// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003822int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003823{
John Kessenich49987892015-12-29 17:11:44 -07003824 glslang::TType elementType;
3825 elementType.shallowCopy(matrixType);
3826 elementType.clearArraySizes();
3827
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003828 int size;
John Kessenich49987892015-12-29 17:11:44 -07003829 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003830 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07003831
3832 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003833}
3834
John Kessenich5e4b1242015-08-06 22:53:06 -06003835// Given a member type of a struct, realign the current offset for it, and compute
3836// the next (not yet aligned) offset for the next member, which will get aligned
3837// on the next call.
3838// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3839// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3840// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003841void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003842 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003843{
3844 // this will get a positive value when deemed necessary
3845 nextOffset = -1;
3846
John Kessenich5e4b1242015-08-06 22:53:06 -06003847 // override anything in currentOffset with user-set offset
3848 if (memberType.getQualifier().hasOffset())
3849 currentOffset = memberType.getQualifier().layoutOffset;
3850
3851 // It could be that current linker usage in glslang updated all the layoutOffset,
3852 // in which case the following code does not matter. But, that's not quite right
3853 // once cross-compilation unit GLSL validation is done, as the original user
3854 // settings are needed in layoutOffset, and then the following will come into play.
3855
John Kessenichf85e8062015-12-19 13:57:10 -07003856 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003857 if (! memberType.getQualifier().hasOffset())
3858 currentOffset = -1;
3859
3860 return;
3861 }
3862
John Kessenichf85e8062015-12-19 13:57:10 -07003863 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003864 if (currentOffset < 0)
3865 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003866
John Kessenich5e4b1242015-08-06 22:53:06 -06003867 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3868 // but possibly not yet correctly aligned.
3869
3870 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003871 int dummyStride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003872 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003873
3874 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003875 // TODO: make this consistent in early phases of code:
3876 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3877 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3878 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06003879 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06003880 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06003881 int dummySize;
3882 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
3883 if (componentAlignment <= 4)
3884 memberAlignment = componentAlignment;
3885 }
3886
3887 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06003888 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06003889
3890 // Bump up to vec4 if there is a bad straddle
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003891 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06003892 glslang::RoundToPow2(currentOffset, 16);
3893
John Kessenich5e4b1242015-08-06 22:53:06 -06003894 nextOffset = currentOffset + memberSize;
3895}
3896
David Netoa901ffe2016-06-08 14:11:40 +01003897void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06003898{
David Netoa901ffe2016-06-08 14:11:40 +01003899 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3900 switch (glslangBuiltIn)
3901 {
3902 case glslang::EbvClipDistance:
3903 case glslang::EbvCullDistance:
3904 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003905#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003906 case glslang::EbvViewportMaskNV:
3907 case glslang::EbvSecondaryPositionNV:
3908 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003909 case glslang::EbvPositionPerViewNV:
3910 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07003911 case glslang::EbvTaskCountNV:
3912 case glslang::EbvPrimitiveCountNV:
3913 case glslang::EbvPrimitiveIndicesNV:
3914 case glslang::EbvClipDistancePerViewNV:
3915 case glslang::EbvCullDistancePerViewNV:
3916 case glslang::EbvLayerPerViewNV:
3917 case glslang::EbvMeshViewCountNV:
3918 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08003919#endif
David Netoa901ffe2016-06-08 14:11:40 +01003920 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
3921 // Alternately, we could just call this for any glslang built-in, since the
3922 // capability already guards against duplicates.
3923 TranslateBuiltInDecoration(glslangBuiltIn, false);
3924 break;
3925 default:
3926 // Capabilities were already generated when the struct was declared.
3927 break;
3928 }
John Kessenichebb50532016-05-16 19:22:05 -06003929}
3930
John Kessenich6fccb3c2016-09-19 16:01:41 -06003931bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06003932{
John Kessenicheee9d532016-09-19 18:09:30 -06003933 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003934}
3935
John Kessenichd41993d2017-09-10 15:21:05 -06003936// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07003937// Assumes called after originalParam(), which filters out block/buffer/opaque-based
3938// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06003939bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06003940{
John Kessenich6a14f782017-12-04 02:48:10 -07003941 assert(qualifier == glslang::EvqIn ||
3942 qualifier == glslang::EvqOut ||
3943 qualifier == glslang::EvqInOut ||
3944 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06003945 return qualifier != glslang::EvqConstReadOnly;
3946}
3947
3948// Is parameter pass-by-original?
3949bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3950 bool implicitThisParam)
3951{
3952 if (implicitThisParam) // implicit this
3953 return true;
3954 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003955 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003956 return paramType.containsOpaque() || // sampler, etc.
3957 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3958}
3959
John Kessenich140f3df2015-06-26 16:58:36 -06003960// Make all the functions, skeletally, without actually visiting their bodies.
3961void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3962{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003963 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06003964 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3965 if (paramPrecision != spv::NoPrecision)
3966 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05003967 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003968 if (type.getBasicType() == glslang::EbtReference) {
3969 // Original and non-writable params pass the pointer directly and
3970 // use restrict/aliased, others are stored to a pointer in Function
3971 // memory and use RestrictPointer/AliasedPointer.
3972 if (originalParam(type.getQualifier().storage, type, false) ||
3973 !writableParam(type.getQualifier().storage)) {
3974 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrict : spv::DecorationAliased);
3975 } else {
3976 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
3977 }
3978 }
John Kessenichfad62972017-07-18 02:35:46 -06003979 };
3980
John Kessenich140f3df2015-06-26 16:58:36 -06003981 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3982 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003983 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003984 continue;
3985
3986 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003987 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003988 //
qining25262b32016-05-06 17:25:16 -04003989 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003990 // function. What it is an address of varies:
3991 //
John Kessenich4bf71552016-09-02 11:20:21 -06003992 // - "in" parameters not marked as "const" can be written to without modifying the calling
3993 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003994 //
3995 // - "const in" parameters can just be the r-value, as no writes need occur.
3996 //
John Kessenich4bf71552016-09-02 11:20:21 -06003997 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3998 // GLSL has copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
John Kessenich140f3df2015-06-26 16:58:36 -06003999
4000 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004001 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004002 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4003
John Kessenichfad62972017-07-18 02:35:46 -06004004 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4005 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06004006
John Kessenichfad62972017-07-18 02:35:46 -06004007 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004008 for (int p = 0; p < (int)parameters.size(); ++p) {
4009 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4010 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004011 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004012 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004013 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004014 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4015 else
John Kessenich4bf71552016-09-02 11:20:21 -06004016 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004017 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004018 paramTypes.push_back(typeId);
4019 }
4020
4021 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004022 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4023 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004024 glslFunction->getName().c_str(), paramTypes,
4025 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004026 if (implicitThis)
4027 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004028
4029 // Track function to emit/call later
4030 functionMap[glslFunction->getName().c_str()] = function;
4031
4032 // Set the parameter id's
4033 for (int p = 0; p < (int)parameters.size(); ++p) {
4034 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4035 // give a name too
4036 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004037
4038 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4039 if (paramType.containsBasicType(glslang::EbtInt8) ||
4040 paramType.containsBasicType(glslang::EbtUint8))
4041 builder.addCapability(spv::CapabilityInt8);
4042 if (paramType.containsBasicType(glslang::EbtInt16) ||
4043 paramType.containsBasicType(glslang::EbtUint16))
4044 builder.addCapability(spv::CapabilityInt16);
4045 if (paramType.containsBasicType(glslang::EbtFloat16))
4046 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004047 }
4048 }
4049}
4050
4051// Process all the initializers, while skipping the functions and link objects
4052void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4053{
4054 builder.setBuildPoint(shaderEntry->getLastBlock());
4055 for (int i = 0; i < (int)initializers.size(); ++i) {
4056 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
4057 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
4058
4059 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004060 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004061 initializer->traverse(this);
4062 }
4063 }
4064}
4065
4066// Process all the functions, while skipping initializers.
4067void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4068{
4069 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4070 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004071 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004072 node->traverse(this);
4073 }
4074}
4075
4076void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4077{
qining25262b32016-05-06 17:25:16 -04004078 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004079 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004080 currentFunction = functionMap[node->getName().c_str()];
4081 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004082 builder.setBuildPoint(functionBlock);
4083}
4084
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004085void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments, spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004086{
Rex Xufc618912015-09-09 16:42:49 +08004087 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004088
4089 glslang::TSampler sampler = {};
4090 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004091#ifdef AMD_EXTENSIONS
4092 bool f16ShadowCompare = false;
4093#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004094 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004095 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4096 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004097#ifdef AMD_EXTENSIONS
4098 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
4099#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004100 }
4101
John Kessenich140f3df2015-06-26 16:58:36 -06004102 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4103 builder.clearAccessChain();
4104 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004105
4106 // Special case l-value operands
4107 bool lvalue = false;
4108 switch (node.getOp()) {
4109 case glslang::EOpImageAtomicAdd:
4110 case glslang::EOpImageAtomicMin:
4111 case glslang::EOpImageAtomicMax:
4112 case glslang::EOpImageAtomicAnd:
4113 case glslang::EOpImageAtomicOr:
4114 case glslang::EOpImageAtomicXor:
4115 case glslang::EOpImageAtomicExchange:
4116 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004117 case glslang::EOpImageAtomicLoad:
4118 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004119 if (i == 0)
4120 lvalue = true;
4121 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004122 case glslang::EOpSparseImageLoad:
4123 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4124 lvalue = true;
4125 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004126#ifdef AMD_EXTENSIONS
4127 case glslang::EOpSparseTexture:
4128 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4129 lvalue = true;
4130 break;
4131 case glslang::EOpSparseTextureClamp:
4132 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4133 lvalue = true;
4134 break;
4135 case glslang::EOpSparseTextureLod:
4136 case glslang::EOpSparseTextureOffset:
4137 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4138 lvalue = true;
4139 break;
4140#else
Rex Xu48edadf2015-12-31 16:11:41 +08004141 case glslang::EOpSparseTexture:
4142 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
4143 lvalue = true;
4144 break;
4145 case glslang::EOpSparseTextureClamp:
4146 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
4147 lvalue = true;
4148 break;
4149 case glslang::EOpSparseTextureLod:
4150 case glslang::EOpSparseTextureOffset:
4151 if (i == 3)
4152 lvalue = true;
4153 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004154#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004155 case glslang::EOpSparseTextureFetch:
4156 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4157 lvalue = true;
4158 break;
4159 case glslang::EOpSparseTextureFetchOffset:
4160 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4161 lvalue = true;
4162 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004163#ifdef AMD_EXTENSIONS
4164 case glslang::EOpSparseTextureLodOffset:
4165 case glslang::EOpSparseTextureGrad:
4166 case glslang::EOpSparseTextureOffsetClamp:
4167 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4168 lvalue = true;
4169 break;
4170 case glslang::EOpSparseTextureGradOffset:
4171 case glslang::EOpSparseTextureGradClamp:
4172 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4173 lvalue = true;
4174 break;
4175 case glslang::EOpSparseTextureGradOffsetClamp:
4176 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4177 lvalue = true;
4178 break;
4179#else
Rex Xu48edadf2015-12-31 16:11:41 +08004180 case glslang::EOpSparseTextureLodOffset:
4181 case glslang::EOpSparseTextureGrad:
4182 case glslang::EOpSparseTextureOffsetClamp:
4183 if (i == 4)
4184 lvalue = true;
4185 break;
4186 case glslang::EOpSparseTextureGradOffset:
4187 case glslang::EOpSparseTextureGradClamp:
4188 if (i == 5)
4189 lvalue = true;
4190 break;
4191 case glslang::EOpSparseTextureGradOffsetClamp:
4192 if (i == 6)
4193 lvalue = true;
4194 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004195#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004196 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004197 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4198 lvalue = true;
4199 break;
4200 case glslang::EOpSparseTextureGatherOffset:
4201 case glslang::EOpSparseTextureGatherOffsets:
4202 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4203 lvalue = true;
4204 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004205#ifdef AMD_EXTENSIONS
4206 case glslang::EOpSparseTextureGatherLod:
4207 if (i == 3)
4208 lvalue = true;
4209 break;
4210 case glslang::EOpSparseTextureGatherLodOffset:
4211 case glslang::EOpSparseTextureGatherLodOffsets:
4212 if (i == 4)
4213 lvalue = true;
4214 break;
Rex Xu129799a2017-07-05 17:23:28 +08004215 case glslang::EOpSparseImageLoadLod:
4216 if (i == 3)
4217 lvalue = true;
4218 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004219#endif
Chao Chen3a137962018-09-19 11:41:27 -07004220#ifdef NV_EXTENSIONS
4221 case glslang::EOpImageSampleFootprintNV:
4222 if (i == 4)
4223 lvalue = true;
4224 break;
4225 case glslang::EOpImageSampleFootprintClampNV:
4226 case glslang::EOpImageSampleFootprintLodNV:
4227 if (i == 5)
4228 lvalue = true;
4229 break;
4230 case glslang::EOpImageSampleFootprintGradNV:
4231 if (i == 6)
4232 lvalue = true;
4233 break;
4234 case glslang::EOpImageSampleFootprintGradClampNV:
4235 if (i == 7)
4236 lvalue = true;
4237 break;
4238#endif
Rex Xufc618912015-09-09 16:42:49 +08004239 default:
4240 break;
4241 }
4242
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004243 if (lvalue) {
Rex Xufc618912015-09-09 16:42:49 +08004244 arguments.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004245 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
4246 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4247 } else
John Kessenich32cfd492016-02-02 12:37:46 -07004248 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004249 }
4250}
4251
John Kessenichfc51d282015-08-19 13:34:18 -06004252void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004253{
John Kessenichfc51d282015-08-19 13:34:18 -06004254 builder.clearAccessChain();
4255 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004256 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004257}
John Kessenich140f3df2015-06-26 16:58:36 -06004258
John Kessenichfc51d282015-08-19 13:34:18 -06004259spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4260{
John Kesseniche485c7a2017-05-31 18:50:53 -06004261 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004262 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004263
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004264 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004265
John Kessenichfc51d282015-08-19 13:34:18 -06004266 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004267
John Kessenichf43c7392019-03-31 10:51:57 -06004268 const glslang::TType &imageType = node->getAsAggregate()
4269 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4270 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004271 const glslang::TSampler sampler = imageType.getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08004272#ifdef AMD_EXTENSIONS
4273 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004274 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4275 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004276#endif
4277
John Kessenichf43c7392019-03-31 10:51:57 -06004278 const auto signExtensionMask = [&]() {
4279 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4280 if (sampler.type == glslang::EbtUint)
4281 return spv::ImageOperandsZeroExtendMask;
4282 else if (sampler.type == glslang::EbtInt)
4283 return spv::ImageOperandsSignExtendMask;
4284 }
4285 return spv::ImageOperandsMaskNone;
4286 };
4287
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004288 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4289
John Kessenichfc51d282015-08-19 13:34:18 -06004290 std::vector<spv::Id> arguments;
4291 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004292 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004293 else
4294 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004295 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004296
4297 spv::Builder::TextureParameters params = { };
4298 params.sampler = arguments[0];
4299
Rex Xu04db3f52015-09-16 11:44:02 +08004300 glslang::TCrackedTextureOp cracked;
4301 node->crackTexture(sampler, cracked);
4302
amhagan05506bb2017-06-13 16:53:02 -04004303 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004304
John Kessenichfc51d282015-08-19 13:34:18 -06004305 // Check for queries
4306 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004307 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4308 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004309 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004310
John Kessenichfc51d282015-08-19 13:34:18 -06004311 switch (node->getOp()) {
4312 case glslang::EOpImageQuerySize:
4313 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004314 if (arguments.size() > 1) {
4315 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004316 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004317 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004318 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004319 case glslang::EOpImageQuerySamples:
4320 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004321 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004322 case glslang::EOpTextureQueryLod:
4323 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004324 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004325 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004326 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004327 case glslang::EOpSparseTexelsResident:
4328 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06004329 default:
4330 assert(0);
4331 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004332 }
John Kessenich140f3df2015-06-26 16:58:36 -06004333 }
4334
LoopDawg4425f242018-02-18 11:40:01 -07004335 int components = node->getType().getVectorSize();
4336
4337 if (node->getOp() == glslang::EOpTextureFetch) {
4338 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4339 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4340 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4341 // here around e.g. which ones return scalars or other types.
4342 components = 4;
4343 }
4344
4345 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4346
4347 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4348
Rex Xufc618912015-09-09 16:42:49 +08004349 // Check for image functions other than queries
4350 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004351 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004352 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004353 spv::IdImmediate image = { true, *(opIt++) };
4354 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004355
4356 // Handle subpass operations
4357 // TODO: GLSL should change to have the "MS" only on the type rather than the
4358 // built-in function.
4359 if (cracked.subpass) {
4360 // add on the (0,0) coordinate
4361 spv::Id zero = builder.makeIntConstant(0);
4362 std::vector<spv::Id> comps;
4363 comps.push_back(zero);
4364 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004365 spv::IdImmediate coord = { true,
4366 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4367 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004368 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4369 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich6c292d32016-02-15 20:58:50 -07004370 if (sampler.ms) {
John Kessenichf43c7392019-03-31 10:51:57 -06004371 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4372 }
4373 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004374 operands.push_back(imageOperands);
John Kessenichf43c7392019-03-31 10:51:57 -06004375 if (sampler.ms) {
4376 spv::IdImmediate imageOperand = { true, *(opIt++) };
4377 operands.push_back(imageOperand);
4378 }
John Kessenich6c292d32016-02-15 20:58:50 -07004379 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004380 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4381 builder.setPrecision(result, precision);
4382 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004383 }
4384
John Kessenich149afc32018-08-14 13:31:43 -06004385 spv::IdImmediate coord = { true, *(opIt++) };
4386 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004387#ifdef AMD_EXTENSIONS
4388 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
4389#else
John Kessenich56bab042015-09-16 10:54:31 -06004390 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004391#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004392 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich55e7d112015-11-15 21:33:39 -07004393 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004394 mask = mask | spv::ImageOperandsSampleMask;
4395 }
Rex Xu129799a2017-07-05 17:23:28 +08004396#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004397 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004398 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4399 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004400 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004401 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004402#endif
4403 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4404 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004405 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004406 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004407 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4408 operands.push_back(imageOperands);
4409 }
4410 if (mask & spv::ImageOperandsSampleMask) {
4411 spv::IdImmediate imageOperand = { true, *opIt++ };
4412 operands.push_back(imageOperand);
4413 }
4414#ifdef AMD_EXTENSIONS
4415 if (mask & spv::ImageOperandsLodMask) {
4416 spv::IdImmediate imageOperand = { true, *opIt++ };
4417 operands.push_back(imageOperand);
4418 }
4419#endif
4420 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004421 spv::IdImmediate imageOperand = { true,
4422 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004423 operands.push_back(imageOperand);
4424 }
4425
John Kessenich149afc32018-08-14 13:31:43 -06004426 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004427 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004428
John Kessenich149afc32018-08-14 13:31:43 -06004429 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004430 builder.setPrecision(result[0], precision);
4431
4432 // If needed, add a conversion constructor to the proper size.
4433 if (components != node->getType().getVectorSize())
4434 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4435
4436 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004437#ifdef AMD_EXTENSIONS
4438 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
4439#else
John Kessenich56bab042015-09-16 10:54:31 -06004440 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08004441#endif
Rex Xu129799a2017-07-05 17:23:28 +08004442
Jeff Bolz36831c92018-09-05 10:11:41 -05004443 // Push the texel value before the operands
4444#ifdef AMD_EXTENSIONS
4445 if (sampler.ms || cracked.lod) {
4446#else
4447 if (sampler.ms) {
4448#endif
John Kessenich149afc32018-08-14 13:31:43 -06004449 spv::IdImmediate texel = { true, *(opIt + 1) };
4450 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004451 } else {
4452 spv::IdImmediate texel = { true, *opIt };
4453 operands.push_back(texel);
4454 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004455
4456 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
4457 if (sampler.ms) {
4458 mask = mask | spv::ImageOperandsSampleMask;
4459 }
4460#ifdef AMD_EXTENSIONS
4461 if (cracked.lod) {
4462 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4463 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4464 mask = mask | spv::ImageOperandsLodMask;
4465 }
4466#endif
4467 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4468 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004469 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004470 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004471 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4472 operands.push_back(imageOperands);
4473 }
4474 if (mask & spv::ImageOperandsSampleMask) {
4475 spv::IdImmediate imageOperand = { true, *opIt++ };
4476 operands.push_back(imageOperand);
4477 }
4478#ifdef AMD_EXTENSIONS
4479 if (mask & spv::ImageOperandsLodMask) {
4480 spv::IdImmediate imageOperand = { true, *opIt++ };
4481 operands.push_back(imageOperand);
4482 }
4483#endif
4484 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004485 spv::IdImmediate imageOperand = { true,
4486 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004487 operands.push_back(imageOperand);
4488 }
4489
John Kessenich56bab042015-09-16 10:54:31 -06004490 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004491 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004492 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004493 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08004494#ifdef AMD_EXTENSIONS
John Kessenichf43c7392019-03-31 10:51:57 -06004495 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4496 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004497#else
Rex Xu5eafa472016-02-19 22:24:03 +08004498 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004499#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004500 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004501 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004502 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4503
Jeff Bolz36831c92018-09-05 10:11:41 -05004504 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
Rex Xu5eafa472016-02-19 22:24:03 +08004505 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004506 mask = mask | spv::ImageOperandsSampleMask;
4507 }
Rex Xu129799a2017-07-05 17:23:28 +08004508#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004509 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004510 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4511 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4512
Jeff Bolz36831c92018-09-05 10:11:41 -05004513 mask = mask | spv::ImageOperandsLodMask;
4514 }
4515#endif
4516 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4517 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004518 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004519 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004520 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004521 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004522 }
4523 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004524 spv::IdImmediate imageOperand = { true, *opIt++ };
4525 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004526 }
4527#ifdef AMD_EXTENSIONS
4528 if (mask & spv::ImageOperandsLodMask) {
4529 spv::IdImmediate imageOperand = { true, *opIt++ };
4530 operands.push_back(imageOperand);
4531 }
Rex Xu129799a2017-07-05 17:23:28 +08004532#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004533 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4534 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4535 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004536 }
4537
4538 // Create the return type that was a special structure
4539 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004540 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004541 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4542 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4543
4544 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4545
4546 // Decode the return type
4547 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4548 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004549 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004550 // Process image atomic operations
4551
4552 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4553 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004554 // For non-MS, the sample value should be 0
4555 spv::IdImmediate sample = { true, sampler.ms ? *(opIt++) : builder.makeUintConstant(0) };
4556 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004557
Jeff Bolz36831c92018-09-05 10:11:41 -05004558 spv::Id resultTypeId;
4559 // imageAtomicStore has a void return type so base the pointer type on
4560 // the type of the value operand.
4561 if (node->getOp() == glslang::EOpImageAtomicStore) {
4562 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
4563 } else {
4564 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4565 }
John Kessenich56bab042015-09-16 10:54:31 -06004566 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08004567
4568 std::vector<spv::Id> operands;
4569 operands.push_back(pointer);
4570 for (; opIt != arguments.end(); ++opIt)
4571 operands.push_back(*opIt);
4572
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004573 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(), lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08004574 }
4575 }
4576
amhagan05506bb2017-06-13 16:53:02 -04004577#ifdef AMD_EXTENSIONS
4578 // Check for fragment mask functions other than queries
4579 if (cracked.fragMask) {
4580 assert(sampler.ms);
4581
4582 auto opIt = arguments.begin();
4583 std::vector<spv::Id> operands;
4584
4585 // Extract the image if necessary
4586 if (builder.isSampledImage(params.sampler))
4587 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4588
4589 operands.push_back(params.sampler);
4590 ++opIt;
4591
4592 if (sampler.isSubpass()) {
4593 // add on the (0,0) coordinate
4594 spv::Id zero = builder.makeIntConstant(0);
4595 std::vector<spv::Id> comps;
4596 comps.push_back(zero);
4597 comps.push_back(zero);
4598 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
4599 }
4600
4601 for (; opIt != arguments.end(); ++opIt)
4602 operands.push_back(*opIt);
4603
4604 spv::Op fragMaskOp = spv::OpNop;
4605 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4606 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4607 else if (node->getOp() == glslang::EOpFragmentFetch)
4608 fragMaskOp = spv::OpFragmentFetchAMD;
4609
4610 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4611 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4612 return builder.createOp(fragMaskOp, resultType(), operands);
4613 }
4614#endif
4615
Rex Xufc618912015-09-09 16:42:49 +08004616 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004617 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004618#ifdef NV_EXTENSIONS
4619 bool imageFootprint = node->isImageFootprint();
4620#endif
4621
Rex Xu71519fe2015-11-11 15:35:47 +08004622 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
4623
John Kessenichfc51d282015-08-19 13:34:18 -06004624 // check for bias argument
4625 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004626#ifdef AMD_EXTENSIONS
4627 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
4628#else
Rex Xu71519fe2015-11-11 15:35:47 +08004629 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08004630#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004631 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004632#ifdef AMD_EXTENSIONS
4633 if (cracked.gather)
4634 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004635
4636 if (f16ShadowCompare)
4637 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004638#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004639 if (cracked.offset)
4640 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004641#ifdef AMD_EXTENSIONS
4642 else if (cracked.offsets)
4643 ++nonBiasArgCount;
4644#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004645 if (cracked.grad)
4646 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004647 if (cracked.lodClamp)
4648 ++nonBiasArgCount;
4649 if (sparse)
4650 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004651#ifdef NV_EXTENSIONS
4652 if (imageFootprint)
4653 //Following three extra arguments
4654 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4655 nonBiasArgCount += 3;
4656#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004657 if ((int)arguments.size() > nonBiasArgCount)
4658 bias = true;
4659 }
4660
John Kessenicha5c33d62016-06-02 23:45:21 -06004661 // See if the sampler param should really be just the SPV image part
4662 if (cracked.fetch) {
4663 // a fetch needs to have the image extracted first
4664 if (builder.isSampledImage(params.sampler))
4665 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4666 }
4667
Rex Xu225e0fc2016-11-17 17:47:59 +08004668#ifdef AMD_EXTENSIONS
4669 if (cracked.gather) {
4670 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4671 if (bias || cracked.lod ||
4672 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4673 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004674 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004675 }
4676 }
4677#endif
4678
John Kessenichfc51d282015-08-19 13:34:18 -06004679 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004680
John Kessenichfc51d282015-08-19 13:34:18 -06004681 params.coords = arguments[1];
4682 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004683 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004684
4685 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004686#ifdef AMD_EXTENSIONS
4687 if (cubeCompare || f16ShadowCompare) {
4688#else
Rex Xu48edadf2015-12-31 16:11:41 +08004689 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08004690#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004691 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004692 ++extraArgs;
4693 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004694 params.Dref = arguments[2];
4695 ++extraArgs;
4696 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004697 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004698 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004699 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004700 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004701 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004702 dRefComp = builder.getNumComponents(params.coords) - 1;
4703 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004704 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4705 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004706
4707 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004708 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004709 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004710 ++extraArgs;
Chao Chenbeae2252018-09-19 11:40:45 -07004711 } else if (glslangIntermediate->getStage() != EShLangFragment
4712#ifdef NV_EXTENSIONS
4713 // NV_compute_shader_derivatives layout qualifiers allow for implicit LODs
4714 && !(glslangIntermediate->getStage() == EShLangCompute &&
4715 (glslangIntermediate->getLayoutDerivativeModeNone() != glslang::LayoutDerivativeNone))
4716#endif
4717 ) {
John Kessenich019f08f2016-02-15 15:40:42 -07004718 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4719 noImplicitLod = true;
4720 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004721
4722 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07004723 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004724 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004725 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004726 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004727
4728 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004729 if (cracked.grad) {
4730 params.gradX = arguments[2 + extraArgs];
4731 params.gradY = arguments[3 + extraArgs];
4732 extraArgs += 2;
4733 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004734
4735 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004736 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004737 params.offset = arguments[2 + extraArgs];
4738 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004739 } else if (cracked.offsets) {
4740 params.offsets = arguments[2 + extraArgs];
4741 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004742 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004743
4744 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004745 if (cracked.lodClamp) {
4746 params.lodClamp = arguments[2 + extraArgs];
4747 ++extraArgs;
4748 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004749 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004750 if (sparse) {
4751 params.texelOut = arguments[2 + extraArgs];
4752 ++extraArgs;
4753 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004754
John Kessenich76d4dfc2016-06-16 12:43:23 -06004755 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004756 if (cracked.gather && ! sampler.shadow) {
4757 // default component is 0, if missing, otherwise an argument
4758 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004759 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004760 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004761 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004762 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004763 }
Chao Chen3a137962018-09-19 11:41:27 -07004764#ifdef NV_EXTENSIONS
4765 spv::Id resultStruct = spv::NoResult;
4766 if (imageFootprint) {
4767 //Following three extra arguments
4768 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4769 params.granularity = arguments[2 + extraArgs];
4770 params.coarse = arguments[3 + extraArgs];
4771 resultStruct = arguments[4 + extraArgs];
4772 extraArgs += 3;
4773 }
4774#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004775 // bias
4776 if (bias) {
4777 params.bias = arguments[2 + extraArgs];
4778 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004779 }
John Kessenichfc51d282015-08-19 13:34:18 -06004780
Chao Chen3a137962018-09-19 11:41:27 -07004781#ifdef NV_EXTENSIONS
4782 if (imageFootprint) {
4783 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
4784 builder.addCapability(spv::CapabilityImageFootprintNV);
4785
4786
4787 //resultStructType(OpenGL type) contains 5 elements:
4788 //struct gl_TextureFootprint2DNV {
4789 // uvec2 anchor;
4790 // uvec2 offset;
4791 // uvec2 mask;
4792 // uint lod;
4793 // uint granularity;
4794 //};
4795 //or
4796 //struct gl_TextureFootprint3DNV {
4797 // uvec3 anchor;
4798 // uvec3 offset;
4799 // uvec2 mask;
4800 // uint lod;
4801 // uint granularity;
4802 //};
4803 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
4804 assert(builder.isStructType(resultStructType));
4805
4806 //resType (SPIR-V type) contains 6 elements:
4807 //Member 0 must be a Boolean type scalar(LOD),
4808 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
4809 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
4810 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
4811 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
4812 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
4813 std::vector<spv::Id> members;
4814 members.push_back(resultType());
4815 for (int i = 0; i < 5; i++) {
4816 members.push_back(builder.getContainedTypeId(resultStructType, i));
4817 }
4818 spv::Id resType = builder.makeStructType(members, "ResType");
4819
4820 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06004821 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
4822 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07004823
4824 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
4825 for (int i = 0; i < 5; i++) {
4826 builder.clearAccessChain();
4827 builder.setAccessChainLValue(resultStruct);
4828
4829 //Accessing to a struct we created, no coherent flag is set
4830 spv::Builder::AccessChain::CoherentFlags flags;
4831 flags.clear();
4832
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004833 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
Chao Chen3a137962018-09-19 11:41:27 -07004834 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1), i+1));
4835 }
4836 return builder.createCompositeExtract(res, resultType(), 0);
4837 }
4838#endif
4839
John Kessenich65336482016-06-16 14:06:26 -06004840 // projective component (might not to move)
4841 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4842 // are divided by the last component of P."
4843 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4844 // unused components will appear after all used components."
4845 if (cracked.proj) {
4846 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4847 int projTargetComp;
4848 switch (sampler.dim) {
4849 case glslang::Esd1D: projTargetComp = 1; break;
4850 case glslang::Esd2D: projTargetComp = 2; break;
4851 case glslang::EsdRect: projTargetComp = 2; break;
4852 default: projTargetComp = projSourceComp; break;
4853 }
4854 // copy the projective coordinate if we have to
4855 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004856 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004857 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4858 projSourceComp);
4859 params.coords = builder.createCompositeInsert(projComp, params.coords,
4860 builder.getTypeId(params.coords), projTargetComp);
4861 }
4862 }
4863
Jeff Bolz36831c92018-09-05 10:11:41 -05004864 // nonprivate
4865 if (imageType.getQualifier().nonprivate) {
4866 params.nonprivate = true;
4867 }
4868
4869 // volatile
4870 if (imageType.getQualifier().volatil) {
4871 params.volatil = true;
4872 }
4873
St0fFa1184dd2018-04-09 21:08:14 +02004874 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06004875 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
4876 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02004877 );
LoopDawg4425f242018-02-18 11:40:01 -07004878
4879 if (components != node->getType().getVectorSize())
4880 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4881
4882 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06004883}
4884
4885spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
4886{
4887 // Grab the function's pointer from the previously created function
4888 spv::Function* function = functionMap[node->getName().c_str()];
4889 if (! function)
4890 return 0;
4891
4892 const glslang::TIntermSequence& glslangArgs = node->getSequence();
4893 const glslang::TQualifierList& qualifiers = node->getQualifierList();
4894
4895 // See comments in makeFunctions() for details about the semantics for parameter passing.
4896 //
4897 // These imply we need a four step process:
4898 // 1. Evaluate the arguments
4899 // 2. Allocate and make copies of in, out, and inout arguments
4900 // 3. Make the call
4901 // 4. Copy back the results
4902
John Kessenichd3ed90b2018-05-04 11:43:03 -06004903 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06004904 std::vector<spv::Builder::AccessChain> lValues;
4905 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07004906 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06004907 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004908 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06004909 // build l-value
4910 builder.clearAccessChain();
4911 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06004912 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06004913 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07004914 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004915 // save l-value
4916 lValues.push_back(builder.getAccessChain());
4917 } else {
4918 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07004919 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06004920 }
4921 }
4922
4923 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
4924 // copy the original into that space.
4925 //
4926 // Also, build up the list of actual arguments to pass in for the call
4927 int lValueCount = 0;
4928 int rValueCount = 0;
4929 std::vector<spv::Id> spvArgs;
4930 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
4931 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06004932 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07004933 builder.setAccessChain(lValues[lValueCount]);
4934 arg = builder.accessChainGetLValue();
4935 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06004936 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004937 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06004938 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06004939 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
4940 // need to copy the input into output space
4941 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07004942 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06004943 builder.clearAccessChain();
4944 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004945 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004946 }
4947 ++lValueCount;
4948 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004949 // process r-value, which involves a copy for a type mismatch
4950 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
4951 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
4952 builder.clearAccessChain();
4953 builder.setAccessChainLValue(argCopy);
4954 multiTypeStore(*argTypes[a], rValues[rValueCount]);
4955 arg = builder.createLoad(argCopy);
4956 } else
4957 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06004958 ++rValueCount;
4959 }
4960 spvArgs.push_back(arg);
4961 }
4962
4963 // 3. Make the call.
4964 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07004965 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004966
4967 // 4. Copy back out an "out" arguments.
4968 lValueCount = 0;
4969 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004970 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06004971 ++lValueCount;
4972 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004973 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
4974 spv::Id copy = builder.createLoad(spvArgs[a]);
4975 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004976 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004977 }
4978 ++lValueCount;
4979 }
4980 }
4981
4982 return result;
4983}
4984
4985// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06004986spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06004987 spv::Id typeId, spv::Id left, spv::Id right,
4988 glslang::TBasicType typeProxy, bool reduceComparison)
4989{
John Kessenich66011cb2018-03-06 16:12:04 -07004990 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4991 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08004992 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06004993
4994 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06004995 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06004996 bool comparison = false;
4997
4998 switch (op) {
4999 case glslang::EOpAdd:
5000 case glslang::EOpAddAssign:
5001 if (isFloat)
5002 binOp = spv::OpFAdd;
5003 else
5004 binOp = spv::OpIAdd;
5005 break;
5006 case glslang::EOpSub:
5007 case glslang::EOpSubAssign:
5008 if (isFloat)
5009 binOp = spv::OpFSub;
5010 else
5011 binOp = spv::OpISub;
5012 break;
5013 case glslang::EOpMul:
5014 case glslang::EOpMulAssign:
5015 if (isFloat)
5016 binOp = spv::OpFMul;
5017 else
5018 binOp = spv::OpIMul;
5019 break;
5020 case glslang::EOpVectorTimesScalar:
5021 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005022 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005023 if (builder.isVector(right))
5024 std::swap(left, right);
5025 assert(builder.isScalar(right));
5026 needMatchingVectors = false;
5027 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005028 } else if (isFloat)
5029 binOp = spv::OpFMul;
5030 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005031 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005032 break;
5033 case glslang::EOpVectorTimesMatrix:
5034 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005035 binOp = spv::OpVectorTimesMatrix;
5036 break;
5037 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005038 binOp = spv::OpMatrixTimesVector;
5039 break;
5040 case glslang::EOpMatrixTimesScalar:
5041 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005042 binOp = spv::OpMatrixTimesScalar;
5043 break;
5044 case glslang::EOpMatrixTimesMatrix:
5045 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005046 binOp = spv::OpMatrixTimesMatrix;
5047 break;
5048 case glslang::EOpOuterProduct:
5049 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005050 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005051 break;
5052
5053 case glslang::EOpDiv:
5054 case glslang::EOpDivAssign:
5055 if (isFloat)
5056 binOp = spv::OpFDiv;
5057 else if (isUnsigned)
5058 binOp = spv::OpUDiv;
5059 else
5060 binOp = spv::OpSDiv;
5061 break;
5062 case glslang::EOpMod:
5063 case glslang::EOpModAssign:
5064 if (isFloat)
5065 binOp = spv::OpFMod;
5066 else if (isUnsigned)
5067 binOp = spv::OpUMod;
5068 else
5069 binOp = spv::OpSMod;
5070 break;
5071 case glslang::EOpRightShift:
5072 case glslang::EOpRightShiftAssign:
5073 if (isUnsigned)
5074 binOp = spv::OpShiftRightLogical;
5075 else
5076 binOp = spv::OpShiftRightArithmetic;
5077 break;
5078 case glslang::EOpLeftShift:
5079 case glslang::EOpLeftShiftAssign:
5080 binOp = spv::OpShiftLeftLogical;
5081 break;
5082 case glslang::EOpAnd:
5083 case glslang::EOpAndAssign:
5084 binOp = spv::OpBitwiseAnd;
5085 break;
5086 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005087 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005088 binOp = spv::OpLogicalAnd;
5089 break;
5090 case glslang::EOpInclusiveOr:
5091 case glslang::EOpInclusiveOrAssign:
5092 binOp = spv::OpBitwiseOr;
5093 break;
5094 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005095 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005096 binOp = spv::OpLogicalOr;
5097 break;
5098 case glslang::EOpExclusiveOr:
5099 case glslang::EOpExclusiveOrAssign:
5100 binOp = spv::OpBitwiseXor;
5101 break;
5102 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005103 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005104 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005105 break;
5106
5107 case glslang::EOpLessThan:
5108 case glslang::EOpGreaterThan:
5109 case glslang::EOpLessThanEqual:
5110 case glslang::EOpGreaterThanEqual:
5111 case glslang::EOpEqual:
5112 case glslang::EOpNotEqual:
5113 case glslang::EOpVectorEqual:
5114 case glslang::EOpVectorNotEqual:
5115 comparison = true;
5116 break;
5117 default:
5118 break;
5119 }
5120
John Kessenich7c1aa102015-10-15 13:29:11 -06005121 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005122 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005123 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005124 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5125 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005126 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005127
5128 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005129 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005130 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005131
qining25262b32016-05-06 17:25:16 -04005132 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005133 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005134 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005135 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005136 }
5137
5138 if (! comparison)
5139 return 0;
5140
John Kessenich7c1aa102015-10-15 13:29:11 -06005141 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005142
John Kessenich4583b612016-08-07 19:14:22 -06005143 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005144 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5145 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06005146 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005147 return result;
5148 }
John Kessenich140f3df2015-06-26 16:58:36 -06005149
5150 switch (op) {
5151 case glslang::EOpLessThan:
5152 if (isFloat)
5153 binOp = spv::OpFOrdLessThan;
5154 else if (isUnsigned)
5155 binOp = spv::OpULessThan;
5156 else
5157 binOp = spv::OpSLessThan;
5158 break;
5159 case glslang::EOpGreaterThan:
5160 if (isFloat)
5161 binOp = spv::OpFOrdGreaterThan;
5162 else if (isUnsigned)
5163 binOp = spv::OpUGreaterThan;
5164 else
5165 binOp = spv::OpSGreaterThan;
5166 break;
5167 case glslang::EOpLessThanEqual:
5168 if (isFloat)
5169 binOp = spv::OpFOrdLessThanEqual;
5170 else if (isUnsigned)
5171 binOp = spv::OpULessThanEqual;
5172 else
5173 binOp = spv::OpSLessThanEqual;
5174 break;
5175 case glslang::EOpGreaterThanEqual:
5176 if (isFloat)
5177 binOp = spv::OpFOrdGreaterThanEqual;
5178 else if (isUnsigned)
5179 binOp = spv::OpUGreaterThanEqual;
5180 else
5181 binOp = spv::OpSGreaterThanEqual;
5182 break;
5183 case glslang::EOpEqual:
5184 case glslang::EOpVectorEqual:
5185 if (isFloat)
5186 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005187 else if (isBool)
5188 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005189 else
5190 binOp = spv::OpIEqual;
5191 break;
5192 case glslang::EOpNotEqual:
5193 case glslang::EOpVectorNotEqual:
5194 if (isFloat)
5195 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005196 else if (isBool)
5197 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005198 else
5199 binOp = spv::OpINotEqual;
5200 break;
5201 default:
5202 break;
5203 }
5204
qining25262b32016-05-06 17:25:16 -04005205 if (binOp != spv::OpNop) {
5206 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005207 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005208 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005209 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005210 }
John Kessenich140f3df2015-06-26 16:58:36 -06005211
5212 return 0;
5213}
5214
John Kessenich04bb8a02015-12-12 12:28:14 -07005215//
5216// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5217// These can be any of:
5218//
5219// matrix * scalar
5220// scalar * matrix
5221// matrix * matrix linear algebraic
5222// matrix * vector
5223// vector * matrix
5224// matrix * matrix componentwise
5225// matrix op matrix op in {+, -, /}
5226// matrix op scalar op in {+, -, /}
5227// scalar op matrix op in {+, -, /}
5228//
John Kessenichead86222018-03-28 18:01:20 -06005229spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5230 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005231{
5232 bool firstClass = true;
5233
5234 // First, handle first-class matrix operations (* and matrix/scalar)
5235 switch (op) {
5236 case spv::OpFDiv:
5237 if (builder.isMatrix(left) && builder.isScalar(right)) {
5238 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005239 spv::Id resultType = builder.getTypeId(right);
5240 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005241 op = spv::OpMatrixTimesScalar;
5242 } else
5243 firstClass = false;
5244 break;
5245 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005246 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005247 std::swap(left, right);
5248 assert(builder.isScalar(right));
5249 break;
5250 case spv::OpVectorTimesMatrix:
5251 assert(builder.isVector(left));
5252 assert(builder.isMatrix(right));
5253 break;
5254 case spv::OpMatrixTimesVector:
5255 assert(builder.isMatrix(left));
5256 assert(builder.isVector(right));
5257 break;
5258 case spv::OpMatrixTimesMatrix:
5259 assert(builder.isMatrix(left));
5260 assert(builder.isMatrix(right));
5261 break;
5262 default:
5263 firstClass = false;
5264 break;
5265 }
5266
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005267 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5268 firstClass = true;
5269
qining25262b32016-05-06 17:25:16 -04005270 if (firstClass) {
5271 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005272 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005273 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005274 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005275 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005276
LoopDawg592860c2016-06-09 08:57:35 -06005277 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005278 // The result type of all of them is the same type as the (a) matrix operand.
5279 // The algorithm is to:
5280 // - break the matrix(es) into vectors
5281 // - smear any scalar to a vector
5282 // - do vector operations
5283 // - make a matrix out the vector results
5284 switch (op) {
5285 case spv::OpFAdd:
5286 case spv::OpFSub:
5287 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005288 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005289 case spv::OpFMul:
5290 {
5291 // one time set up...
5292 bool leftMat = builder.isMatrix(left);
5293 bool rightMat = builder.isMatrix(right);
5294 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5295 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5296 spv::Id scalarType = builder.getScalarTypeId(typeId);
5297 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5298 std::vector<spv::Id> results;
5299 spv::Id smearVec = spv::NoResult;
5300 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005301 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005302 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005303 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005304
5305 // do each vector op
5306 for (unsigned int c = 0; c < numCols; ++c) {
5307 std::vector<unsigned int> indexes;
5308 indexes.push_back(c);
5309 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5310 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005311 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06005312 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005313 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005314 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005315 }
5316
5317 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005318 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005319 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005320 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005321 }
5322 default:
5323 assert(0);
5324 return spv::NoResult;
5325 }
5326}
5327
John Kessenichead86222018-03-28 18:01:20 -06005328spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005329 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005330{
5331 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005332 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005333 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005334 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5335 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005336
5337 switch (op) {
5338 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005339 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005340 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005341 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005342 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005343 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005344 unaryOp = spv::OpSNegate;
5345 break;
5346
5347 case glslang::EOpLogicalNot:
5348 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005349 unaryOp = spv::OpLogicalNot;
5350 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005351 case glslang::EOpBitwiseNot:
5352 unaryOp = spv::OpNot;
5353 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005354
John Kessenich140f3df2015-06-26 16:58:36 -06005355 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005356 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005357 break;
5358 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005359 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005360 break;
5361 case glslang::EOpTranspose:
5362 unaryOp = spv::OpTranspose;
5363 break;
5364
5365 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005366 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005367 break;
5368 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005369 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005370 break;
5371 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005372 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005373 break;
5374 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005375 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005376 break;
5377 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005378 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005379 break;
5380 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005381 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005382 break;
5383 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005384 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005385 break;
5386 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005387 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005388 break;
5389
5390 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005391 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005392 break;
5393 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005394 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005395 break;
5396 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005397 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005398 break;
5399 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005400 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005401 break;
5402 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005403 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005404 break;
5405 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005406 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005407 break;
5408
5409 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005410 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005411 break;
5412 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005413 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005414 break;
5415
5416 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005417 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005418 break;
5419 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005420 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005421 break;
5422 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005423 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005424 break;
5425 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005426 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005427 break;
5428 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005429 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005430 break;
5431 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005432 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005433 break;
5434
5435 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005436 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005437 break;
5438 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005439 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005440 break;
5441 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005442 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005443 break;
5444 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005445 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005446 break;
5447 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005448 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005449 break;
5450 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005451 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005452 break;
5453
5454 case glslang::EOpIsNan:
5455 unaryOp = spv::OpIsNan;
5456 break;
5457 case glslang::EOpIsInf:
5458 unaryOp = spv::OpIsInf;
5459 break;
LoopDawg592860c2016-06-09 08:57:35 -06005460 case glslang::EOpIsFinite:
5461 unaryOp = spv::OpIsFinite;
5462 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005463
Rex Xucbc426e2015-12-15 16:03:10 +08005464 case glslang::EOpFloatBitsToInt:
5465 case glslang::EOpFloatBitsToUint:
5466 case glslang::EOpIntBitsToFloat:
5467 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005468 case glslang::EOpDoubleBitsToInt64:
5469 case glslang::EOpDoubleBitsToUint64:
5470 case glslang::EOpInt64BitsToDouble:
5471 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005472 case glslang::EOpFloat16BitsToInt16:
5473 case glslang::EOpFloat16BitsToUint16:
5474 case glslang::EOpInt16BitsToFloat16:
5475 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005476 unaryOp = spv::OpBitcast;
5477 break;
5478
John Kessenich140f3df2015-06-26 16:58:36 -06005479 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005480 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005481 break;
5482 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005483 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005484 break;
5485 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005486 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005487 break;
5488 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005489 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005490 break;
5491 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005492 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005493 break;
5494 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005495 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005496 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005497 case glslang::EOpPackSnorm4x8:
5498 libCall = spv::GLSLstd450PackSnorm4x8;
5499 break;
5500 case glslang::EOpUnpackSnorm4x8:
5501 libCall = spv::GLSLstd450UnpackSnorm4x8;
5502 break;
5503 case glslang::EOpPackUnorm4x8:
5504 libCall = spv::GLSLstd450PackUnorm4x8;
5505 break;
5506 case glslang::EOpUnpackUnorm4x8:
5507 libCall = spv::GLSLstd450UnpackUnorm4x8;
5508 break;
5509 case glslang::EOpPackDouble2x32:
5510 libCall = spv::GLSLstd450PackDouble2x32;
5511 break;
5512 case glslang::EOpUnpackDouble2x32:
5513 libCall = spv::GLSLstd450UnpackDouble2x32;
5514 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005515
Rex Xu8ff43de2016-04-22 16:51:45 +08005516 case glslang::EOpPackInt2x32:
5517 case glslang::EOpUnpackInt2x32:
5518 case glslang::EOpPackUint2x32:
5519 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005520 case glslang::EOpPack16:
5521 case glslang::EOpPack32:
5522 case glslang::EOpPack64:
5523 case glslang::EOpUnpack32:
5524 case glslang::EOpUnpack16:
5525 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005526 case glslang::EOpPackInt2x16:
5527 case glslang::EOpUnpackInt2x16:
5528 case glslang::EOpPackUint2x16:
5529 case glslang::EOpUnpackUint2x16:
5530 case glslang::EOpPackInt4x16:
5531 case glslang::EOpUnpackInt4x16:
5532 case glslang::EOpPackUint4x16:
5533 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005534 case glslang::EOpPackFloat2x16:
5535 case glslang::EOpUnpackFloat2x16:
5536 unaryOp = spv::OpBitcast;
5537 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005538
John Kessenich140f3df2015-06-26 16:58:36 -06005539 case glslang::EOpDPdx:
5540 unaryOp = spv::OpDPdx;
5541 break;
5542 case glslang::EOpDPdy:
5543 unaryOp = spv::OpDPdy;
5544 break;
5545 case glslang::EOpFwidth:
5546 unaryOp = spv::OpFwidth;
5547 break;
5548 case glslang::EOpDPdxFine:
5549 unaryOp = spv::OpDPdxFine;
5550 break;
5551 case glslang::EOpDPdyFine:
5552 unaryOp = spv::OpDPdyFine;
5553 break;
5554 case glslang::EOpFwidthFine:
5555 unaryOp = spv::OpFwidthFine;
5556 break;
5557 case glslang::EOpDPdxCoarse:
5558 unaryOp = spv::OpDPdxCoarse;
5559 break;
5560 case glslang::EOpDPdyCoarse:
5561 unaryOp = spv::OpDPdyCoarse;
5562 break;
5563 case glslang::EOpFwidthCoarse:
5564 unaryOp = spv::OpFwidthCoarse;
5565 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005566 case glslang::EOpInterpolateAtCentroid:
Rex Xub4a2a6c2018-05-17 13:51:28 +08005567#ifdef AMD_EXTENSIONS
5568 if (typeProxy == glslang::EbtFloat16)
5569 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5570#endif
Rex Xu7a26c172015-12-08 17:12:09 +08005571 libCall = spv::GLSLstd450InterpolateAtCentroid;
5572 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005573 case glslang::EOpAny:
5574 unaryOp = spv::OpAny;
5575 break;
5576 case glslang::EOpAll:
5577 unaryOp = spv::OpAll;
5578 break;
5579
5580 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005581 if (isFloat)
5582 libCall = spv::GLSLstd450FAbs;
5583 else
5584 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005585 break;
5586 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005587 if (isFloat)
5588 libCall = spv::GLSLstd450FSign;
5589 else
5590 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005591 break;
5592
John Kessenichfc51d282015-08-19 13:34:18 -06005593 case glslang::EOpAtomicCounterIncrement:
5594 case glslang::EOpAtomicCounterDecrement:
5595 case glslang::EOpAtomicCounter:
5596 {
5597 // Handle all of the atomics in one place, in createAtomicOperation()
5598 std::vector<spv::Id> operands;
5599 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005600 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06005601 }
5602
John Kessenichfc51d282015-08-19 13:34:18 -06005603 case glslang::EOpBitFieldReverse:
5604 unaryOp = spv::OpBitReverse;
5605 break;
5606 case glslang::EOpBitCount:
5607 unaryOp = spv::OpBitCount;
5608 break;
5609 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005610 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005611 break;
5612 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005613 if (isUnsigned)
5614 libCall = spv::GLSLstd450FindUMsb;
5615 else
5616 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005617 break;
5618
Rex Xu574ab042016-04-14 16:53:07 +08005619 case glslang::EOpBallot:
5620 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005621 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005622 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005623 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005624#ifdef AMD_EXTENSIONS
5625 case glslang::EOpMinInvocations:
5626 case glslang::EOpMaxInvocations:
5627 case glslang::EOpAddInvocations:
5628 case glslang::EOpMinInvocationsNonUniform:
5629 case glslang::EOpMaxInvocationsNonUniform:
5630 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005631 case glslang::EOpMinInvocationsInclusiveScan:
5632 case glslang::EOpMaxInvocationsInclusiveScan:
5633 case glslang::EOpAddInvocationsInclusiveScan:
5634 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5635 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5636 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5637 case glslang::EOpMinInvocationsExclusiveScan:
5638 case glslang::EOpMaxInvocationsExclusiveScan:
5639 case glslang::EOpAddInvocationsExclusiveScan:
5640 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5641 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5642 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08005643#endif
Rex Xu51596642016-09-21 18:56:12 +08005644 {
5645 std::vector<spv::Id> operands;
5646 operands.push_back(operand);
5647 return createInvocationsOperation(op, typeId, operands, typeProxy);
5648 }
John Kessenich66011cb2018-03-06 16:12:04 -07005649 case glslang::EOpSubgroupAll:
5650 case glslang::EOpSubgroupAny:
5651 case glslang::EOpSubgroupAllEqual:
5652 case glslang::EOpSubgroupBroadcastFirst:
5653 case glslang::EOpSubgroupBallot:
5654 case glslang::EOpSubgroupInverseBallot:
5655 case glslang::EOpSubgroupBallotBitCount:
5656 case glslang::EOpSubgroupBallotInclusiveBitCount:
5657 case glslang::EOpSubgroupBallotExclusiveBitCount:
5658 case glslang::EOpSubgroupBallotFindLSB:
5659 case glslang::EOpSubgroupBallotFindMSB:
5660 case glslang::EOpSubgroupAdd:
5661 case glslang::EOpSubgroupMul:
5662 case glslang::EOpSubgroupMin:
5663 case glslang::EOpSubgroupMax:
5664 case glslang::EOpSubgroupAnd:
5665 case glslang::EOpSubgroupOr:
5666 case glslang::EOpSubgroupXor:
5667 case glslang::EOpSubgroupInclusiveAdd:
5668 case glslang::EOpSubgroupInclusiveMul:
5669 case glslang::EOpSubgroupInclusiveMin:
5670 case glslang::EOpSubgroupInclusiveMax:
5671 case glslang::EOpSubgroupInclusiveAnd:
5672 case glslang::EOpSubgroupInclusiveOr:
5673 case glslang::EOpSubgroupInclusiveXor:
5674 case glslang::EOpSubgroupExclusiveAdd:
5675 case glslang::EOpSubgroupExclusiveMul:
5676 case glslang::EOpSubgroupExclusiveMin:
5677 case glslang::EOpSubgroupExclusiveMax:
5678 case glslang::EOpSubgroupExclusiveAnd:
5679 case glslang::EOpSubgroupExclusiveOr:
5680 case glslang::EOpSubgroupExclusiveXor:
5681 case glslang::EOpSubgroupQuadSwapHorizontal:
5682 case glslang::EOpSubgroupQuadSwapVertical:
5683 case glslang::EOpSubgroupQuadSwapDiagonal: {
5684 std::vector<spv::Id> operands;
5685 operands.push_back(operand);
5686 return createSubgroupOperation(op, typeId, operands, typeProxy);
5687 }
Rex Xu9d93a232016-05-05 12:30:44 +08005688#ifdef AMD_EXTENSIONS
5689 case glslang::EOpMbcnt:
5690 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5691 libCall = spv::MbcntAMD;
5692 break;
5693
5694 case glslang::EOpCubeFaceIndex:
5695 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5696 libCall = spv::CubeFaceIndexAMD;
5697 break;
5698
5699 case glslang::EOpCubeFaceCoord:
5700 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5701 libCall = spv::CubeFaceCoordAMD;
5702 break;
5703#endif
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005704#ifdef NV_EXTENSIONS
5705 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005706 unaryOp = spv::OpGroupNonUniformPartitionNV;
5707 break;
5708#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005709 case glslang::EOpConstructReference:
5710 unaryOp = spv::OpBitcast;
5711 break;
Jeff Bolz88220d52019-05-08 10:24:46 -05005712
5713 case glslang::EOpCopyObject:
5714 unaryOp = spv::OpCopyObject;
5715 break;
5716
John Kessenich140f3df2015-06-26 16:58:36 -06005717 default:
5718 return 0;
5719 }
5720
5721 spv::Id id;
5722 if (libCall >= 0) {
5723 std::vector<spv::Id> args;
5724 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005725 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005726 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005727 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005728 }
John Kessenich140f3df2015-06-26 16:58:36 -06005729
John Kessenichead86222018-03-28 18:01:20 -06005730 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005731 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005732 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005733}
5734
John Kessenich7a53f762016-01-20 11:19:27 -07005735// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005736spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5737 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005738{
5739 // Handle unary operations vector by vector.
5740 // The result type is the same type as the original type.
5741 // The algorithm is to:
5742 // - break the matrix into vectors
5743 // - apply the operation to each vector
5744 // - make a matrix out the vector results
5745
5746 // get the types sorted out
5747 int numCols = builder.getNumColumns(operand);
5748 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005749 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5750 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005751 std::vector<spv::Id> results;
5752
5753 // do each vector op
5754 for (int c = 0; c < numCols; ++c) {
5755 std::vector<unsigned int> indexes;
5756 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005757 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5758 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06005759 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005760 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005761 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005762 }
5763
5764 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005765 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005766 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005767 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005768}
5769
John Kessenichad7645f2018-06-04 19:11:25 -06005770// For converting integers where both the bitwidth and the signedness could
5771// change, but only do the width change here. The caller is still responsible
5772// for the signedness conversion.
5773spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005774{
John Kessenichad7645f2018-06-04 19:11:25 -06005775 // Get the result type width, based on the type to convert to.
5776 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005777 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005778 case glslang::EOpConvInt16ToUint8:
5779 case glslang::EOpConvIntToUint8:
5780 case glslang::EOpConvInt64ToUint8:
5781 case glslang::EOpConvUint16ToInt8:
5782 case glslang::EOpConvUintToInt8:
5783 case glslang::EOpConvUint64ToInt8:
5784 width = 8;
5785 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005786 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005787 case glslang::EOpConvIntToUint16:
5788 case glslang::EOpConvInt64ToUint16:
5789 case glslang::EOpConvUint8ToInt16:
5790 case glslang::EOpConvUintToInt16:
5791 case glslang::EOpConvUint64ToInt16:
5792 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005793 break;
5794 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005795 case glslang::EOpConvInt16ToUint:
5796 case glslang::EOpConvInt64ToUint:
5797 case glslang::EOpConvUint8ToInt:
5798 case glslang::EOpConvUint16ToInt:
5799 case glslang::EOpConvUint64ToInt:
5800 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005801 break;
5802 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005803 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005804 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005805 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005806 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005807 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005808 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005809 break;
5810
5811 default:
5812 assert(false && "Default missing");
5813 break;
5814 }
5815
John Kessenichad7645f2018-06-04 19:11:25 -06005816 // Get the conversion operation and result type,
5817 // based on the target width, but the source type.
5818 spv::Id type = spv::NoType;
5819 spv::Op convOp = spv::OpNop;
5820 switch(op) {
5821 case glslang::EOpConvInt8ToUint16:
5822 case glslang::EOpConvInt8ToUint:
5823 case glslang::EOpConvInt8ToUint64:
5824 case glslang::EOpConvInt16ToUint8:
5825 case glslang::EOpConvInt16ToUint:
5826 case glslang::EOpConvInt16ToUint64:
5827 case glslang::EOpConvIntToUint8:
5828 case glslang::EOpConvIntToUint16:
5829 case glslang::EOpConvIntToUint64:
5830 case glslang::EOpConvInt64ToUint8:
5831 case glslang::EOpConvInt64ToUint16:
5832 case glslang::EOpConvInt64ToUint:
5833 convOp = spv::OpSConvert;
5834 type = builder.makeIntType(width);
5835 break;
5836 default:
5837 convOp = spv::OpUConvert;
5838 type = builder.makeUintType(width);
5839 break;
5840 }
5841
John Kessenich66011cb2018-03-06 16:12:04 -07005842 if (vectorSize > 0)
5843 type = builder.makeVectorType(type, vectorSize);
5844
John Kessenichad7645f2018-06-04 19:11:25 -06005845 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005846}
5847
John Kessenichead86222018-03-28 18:01:20 -06005848spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5849 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005850{
5851 spv::Op convOp = spv::OpNop;
5852 spv::Id zero = 0;
5853 spv::Id one = 0;
5854
5855 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5856
5857 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005858 case glslang::EOpConvInt8ToBool:
5859 case glslang::EOpConvUint8ToBool:
5860 zero = builder.makeUint8Constant(0);
5861 zero = makeSmearedConstant(zero, vectorSize);
5862 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08005863 case glslang::EOpConvInt16ToBool:
5864 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07005865 zero = builder.makeUint16Constant(0);
5866 zero = makeSmearedConstant(zero, vectorSize);
5867 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5868 case glslang::EOpConvIntToBool:
5869 case glslang::EOpConvUintToBool:
5870 zero = builder.makeUintConstant(0);
5871 zero = makeSmearedConstant(zero, vectorSize);
5872 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5873 case glslang::EOpConvInt64ToBool:
5874 case glslang::EOpConvUint64ToBool:
5875 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005876 zero = makeSmearedConstant(zero, vectorSize);
5877 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5878
5879 case glslang::EOpConvFloatToBool:
5880 zero = builder.makeFloatConstant(0.0F);
5881 zero = makeSmearedConstant(zero, vectorSize);
5882 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5883
5884 case glslang::EOpConvDoubleToBool:
5885 zero = builder.makeDoubleConstant(0.0);
5886 zero = makeSmearedConstant(zero, vectorSize);
5887 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5888
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005889 case glslang::EOpConvFloat16ToBool:
5890 zero = builder.makeFloat16Constant(0.0F);
5891 zero = makeSmearedConstant(zero, vectorSize);
5892 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005893
John Kessenich140f3df2015-06-26 16:58:36 -06005894 case glslang::EOpConvBoolToFloat:
5895 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005896 zero = builder.makeFloatConstant(0.0F);
5897 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06005898 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005899
John Kessenich140f3df2015-06-26 16:58:36 -06005900 case glslang::EOpConvBoolToDouble:
5901 convOp = spv::OpSelect;
5902 zero = builder.makeDoubleConstant(0.0);
5903 one = builder.makeDoubleConstant(1.0);
5904 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005905
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005906 case glslang::EOpConvBoolToFloat16:
5907 convOp = spv::OpSelect;
5908 zero = builder.makeFloat16Constant(0.0F);
5909 one = builder.makeFloat16Constant(1.0F);
5910 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005911
5912 case glslang::EOpConvBoolToInt8:
5913 zero = builder.makeInt8Constant(0);
5914 one = builder.makeInt8Constant(1);
5915 convOp = spv::OpSelect;
5916 break;
5917
5918 case glslang::EOpConvBoolToUint8:
5919 zero = builder.makeUint8Constant(0);
5920 one = builder.makeUint8Constant(1);
5921 convOp = spv::OpSelect;
5922 break;
5923
5924 case glslang::EOpConvBoolToInt16:
5925 zero = builder.makeInt16Constant(0);
5926 one = builder.makeInt16Constant(1);
5927 convOp = spv::OpSelect;
5928 break;
5929
5930 case glslang::EOpConvBoolToUint16:
5931 zero = builder.makeUint16Constant(0);
5932 one = builder.makeUint16Constant(1);
5933 convOp = spv::OpSelect;
5934 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005935
John Kessenich140f3df2015-06-26 16:58:36 -06005936 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005937 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005938 if (op == glslang::EOpConvBoolToInt64)
5939 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005940 else
5941 zero = builder.makeIntConstant(0);
5942
5943 if (op == glslang::EOpConvBoolToInt64)
5944 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005945 else
5946 one = builder.makeIntConstant(1);
5947
John Kessenich140f3df2015-06-26 16:58:36 -06005948 convOp = spv::OpSelect;
5949 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005950
John Kessenich140f3df2015-06-26 16:58:36 -06005951 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005952 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08005953 if (op == glslang::EOpConvBoolToUint64)
5954 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005955 else
5956 zero = builder.makeUintConstant(0);
5957
5958 if (op == glslang::EOpConvBoolToUint64)
5959 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005960 else
5961 one = builder.makeUintConstant(1);
5962
John Kessenich140f3df2015-06-26 16:58:36 -06005963 convOp = spv::OpSelect;
5964 break;
5965
John Kessenich66011cb2018-03-06 16:12:04 -07005966 case glslang::EOpConvInt8ToFloat16:
5967 case glslang::EOpConvInt8ToFloat:
5968 case glslang::EOpConvInt8ToDouble:
5969 case glslang::EOpConvInt16ToFloat16:
5970 case glslang::EOpConvInt16ToFloat:
5971 case glslang::EOpConvInt16ToDouble:
5972 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005973 case glslang::EOpConvIntToFloat:
5974 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005975 case glslang::EOpConvInt64ToFloat:
5976 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005977 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005978 convOp = spv::OpConvertSToF;
5979 break;
5980
John Kessenich66011cb2018-03-06 16:12:04 -07005981 case glslang::EOpConvUint8ToFloat16:
5982 case glslang::EOpConvUint8ToFloat:
5983 case glslang::EOpConvUint8ToDouble:
5984 case glslang::EOpConvUint16ToFloat16:
5985 case glslang::EOpConvUint16ToFloat:
5986 case glslang::EOpConvUint16ToDouble:
5987 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005988 case glslang::EOpConvUintToFloat:
5989 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005990 case glslang::EOpConvUint64ToFloat:
5991 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005992 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005993 convOp = spv::OpConvertUToF;
5994 break;
5995
5996 case glslang::EOpConvDoubleToFloat:
5997 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005998 case glslang::EOpConvDoubleToFloat16:
5999 case glslang::EOpConvFloat16ToDouble:
6000 case glslang::EOpConvFloatToFloat16:
6001 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06006002 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08006003 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06006004 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06006005 break;
6006
John Kessenich66011cb2018-03-06 16:12:04 -07006007 case glslang::EOpConvFloat16ToInt8:
6008 case glslang::EOpConvFloatToInt8:
6009 case glslang::EOpConvDoubleToInt8:
6010 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006011 case glslang::EOpConvFloatToInt16:
6012 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006013 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006014 case glslang::EOpConvFloatToInt:
6015 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006016 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006017 case glslang::EOpConvFloatToInt64:
6018 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006019 convOp = spv::OpConvertFToS;
6020 break;
6021
John Kessenich66011cb2018-03-06 16:12:04 -07006022 case glslang::EOpConvUint8ToInt8:
6023 case glslang::EOpConvInt8ToUint8:
6024 case glslang::EOpConvUint16ToInt16:
6025 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006026 case glslang::EOpConvUintToInt:
6027 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006028 case glslang::EOpConvUint64ToInt64:
6029 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006030 if (builder.isInSpecConstCodeGenMode()) {
6031 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006032 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6033 zero = builder.makeUint8Constant(0);
6034 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006035 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006036 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6037 zero = builder.makeUint64Constant(0);
6038 } else {
Rex Xucabbb782017-03-24 13:41:14 +08006039 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006040 }
qining189b2032016-04-12 23:16:20 -04006041 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006042 // Use OpIAdd, instead of OpBitcast to do the conversion when
6043 // generating for OpSpecConstantOp instruction.
6044 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6045 }
6046 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006047 convOp = spv::OpBitcast;
6048 break;
6049
John Kessenich66011cb2018-03-06 16:12:04 -07006050 case glslang::EOpConvFloat16ToUint8:
6051 case glslang::EOpConvFloatToUint8:
6052 case glslang::EOpConvDoubleToUint8:
6053 case glslang::EOpConvFloat16ToUint16:
6054 case glslang::EOpConvFloatToUint16:
6055 case glslang::EOpConvDoubleToUint16:
6056 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006057 case glslang::EOpConvFloatToUint:
6058 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006059 case glslang::EOpConvFloatToUint64:
6060 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006061 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006062 convOp = spv::OpConvertFToU;
6063 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006064
John Kessenich66011cb2018-03-06 16:12:04 -07006065 case glslang::EOpConvInt8ToInt16:
6066 case glslang::EOpConvInt8ToInt:
6067 case glslang::EOpConvInt8ToInt64:
6068 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006069 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006070 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006071 case glslang::EOpConvIntToInt8:
6072 case glslang::EOpConvIntToInt16:
6073 case glslang::EOpConvIntToInt64:
6074 case glslang::EOpConvInt64ToInt8:
6075 case glslang::EOpConvInt64ToInt16:
6076 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006077 convOp = spv::OpSConvert;
6078 break;
6079
John Kessenich66011cb2018-03-06 16:12:04 -07006080 case glslang::EOpConvUint8ToUint16:
6081 case glslang::EOpConvUint8ToUint:
6082 case glslang::EOpConvUint8ToUint64:
6083 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006084 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006085 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006086 case glslang::EOpConvUintToUint8:
6087 case glslang::EOpConvUintToUint16:
6088 case glslang::EOpConvUintToUint64:
6089 case glslang::EOpConvUint64ToUint8:
6090 case glslang::EOpConvUint64ToUint16:
6091 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006092 convOp = spv::OpUConvert;
6093 break;
6094
John Kessenich66011cb2018-03-06 16:12:04 -07006095 case glslang::EOpConvInt8ToUint16:
6096 case glslang::EOpConvInt8ToUint:
6097 case glslang::EOpConvInt8ToUint64:
6098 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006099 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006100 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006101 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006102 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006103 case glslang::EOpConvIntToUint64:
6104 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006105 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006106 case glslang::EOpConvInt64ToUint:
6107 case glslang::EOpConvUint8ToInt16:
6108 case glslang::EOpConvUint8ToInt:
6109 case glslang::EOpConvUint8ToInt64:
6110 case glslang::EOpConvUint16ToInt8:
6111 case glslang::EOpConvUint16ToInt:
6112 case glslang::EOpConvUint16ToInt64:
6113 case glslang::EOpConvUintToInt8:
6114 case glslang::EOpConvUintToInt16:
6115 case glslang::EOpConvUintToInt64:
6116 case glslang::EOpConvUint64ToInt8:
6117 case glslang::EOpConvUint64ToInt16:
6118 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006119 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006120 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006121
6122 if (builder.isInSpecConstCodeGenMode()) {
6123 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006124 switch(op) {
6125 case glslang::EOpConvInt16ToUint8:
6126 case glslang::EOpConvIntToUint8:
6127 case glslang::EOpConvInt64ToUint8:
6128 case glslang::EOpConvUint16ToInt8:
6129 case glslang::EOpConvUintToInt8:
6130 case glslang::EOpConvUint64ToInt8:
6131 zero = builder.makeUint8Constant(0);
6132 break;
6133 case glslang::EOpConvInt8ToUint16:
6134 case glslang::EOpConvIntToUint16:
6135 case glslang::EOpConvInt64ToUint16:
6136 case glslang::EOpConvUint8ToInt16:
6137 case glslang::EOpConvUintToInt16:
6138 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006139 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006140 break;
6141 case glslang::EOpConvInt8ToUint:
6142 case glslang::EOpConvInt16ToUint:
6143 case glslang::EOpConvInt64ToUint:
6144 case glslang::EOpConvUint8ToInt:
6145 case glslang::EOpConvUint16ToInt:
6146 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006147 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006148 break;
6149 case glslang::EOpConvInt8ToUint64:
6150 case glslang::EOpConvInt16ToUint64:
6151 case glslang::EOpConvIntToUint64:
6152 case glslang::EOpConvUint8ToInt64:
6153 case glslang::EOpConvUint16ToInt64:
6154 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006155 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006156 break;
6157 default:
6158 assert(false && "Default missing");
6159 break;
6160 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006161 zero = makeSmearedConstant(zero, vectorSize);
6162 // Use OpIAdd, instead of OpBitcast to do the conversion when
6163 // generating for OpSpecConstantOp instruction.
6164 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6165 }
6166 // For normal run-time conversion instruction, use OpBitcast.
6167 convOp = spv::OpBitcast;
6168 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006169 case glslang::EOpConvUint64ToPtr:
6170 convOp = spv::OpConvertUToPtr;
6171 break;
6172 case glslang::EOpConvPtrToUint64:
6173 convOp = spv::OpConvertPtrToU;
6174 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006175 default:
6176 break;
6177 }
6178
6179 spv::Id result = 0;
6180 if (convOp == spv::OpNop)
6181 return result;
6182
6183 if (convOp == spv::OpSelect) {
6184 zero = makeSmearedConstant(zero, vectorSize);
6185 one = makeSmearedConstant(one, vectorSize);
6186 result = builder.createTriOp(convOp, destType, operand, one, zero);
6187 } else
6188 result = builder.createUnaryOp(convOp, destType, operand);
6189
John Kessenichead86222018-03-28 18:01:20 -06006190 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06006191 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06006192 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006193}
6194
6195spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6196{
6197 if (vectorSize == 0)
6198 return constant;
6199
6200 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6201 std::vector<spv::Id> components;
6202 for (int c = 0; c < vectorSize; ++c)
6203 components.push_back(constant);
6204 return builder.makeCompositeConstant(vectorTypeId, components);
6205}
6206
John Kessenich426394d2015-07-23 10:22:48 -06006207// For glslang ops that map to SPV atomic opCodes
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006208spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich426394d2015-07-23 10:22:48 -06006209{
6210 spv::Op opCode = spv::OpNop;
6211
6212 switch (op) {
6213 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006214 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006215 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006216 opCode = spv::OpAtomicIAdd;
6217 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006218 case glslang::EOpAtomicCounterSubtract:
6219 opCode = spv::OpAtomicISub;
6220 break;
John Kessenich426394d2015-07-23 10:22:48 -06006221 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006222 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006223 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08006224 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006225 break;
6226 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006227 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006228 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08006229 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006230 break;
6231 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006232 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006233 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006234 opCode = spv::OpAtomicAnd;
6235 break;
6236 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006237 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006238 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006239 opCode = spv::OpAtomicOr;
6240 break;
6241 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006242 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006243 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006244 opCode = spv::OpAtomicXor;
6245 break;
6246 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006247 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006248 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006249 opCode = spv::OpAtomicExchange;
6250 break;
6251 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006252 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006253 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006254 opCode = spv::OpAtomicCompareExchange;
6255 break;
6256 case glslang::EOpAtomicCounterIncrement:
6257 opCode = spv::OpAtomicIIncrement;
6258 break;
6259 case glslang::EOpAtomicCounterDecrement:
6260 opCode = spv::OpAtomicIDecrement;
6261 break;
6262 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006263 case glslang::EOpImageAtomicLoad:
6264 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006265 opCode = spv::OpAtomicLoad;
6266 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006267 case glslang::EOpAtomicStore:
6268 case glslang::EOpImageAtomicStore:
6269 opCode = spv::OpAtomicStore;
6270 break;
John Kessenich426394d2015-07-23 10:22:48 -06006271 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006272 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006273 break;
6274 }
6275
Rex Xue8fe8b02017-09-26 15:42:56 +08006276 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6277 builder.addCapability(spv::CapabilityInt64Atomics);
6278
John Kessenich426394d2015-07-23 10:22:48 -06006279 // Sort out the operands
6280 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006281 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006282 // - compare-exchange swaps the value and comparator
6283 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006284 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006285 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6286 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6287 spv::Id scopeId;
6288 if (glslangIntermediate->usingVulkanMemoryModel()) {
6289 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6290 } else {
6291 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6292 }
6293 // semantics default to relaxed
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006294 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.volatil ? spv::MemorySemanticsVolatileMask : spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006295 spv::Id semanticsId2 = semanticsId;
6296
6297 pointerId = operands[0];
6298 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6299 // no additional operands
6300 } else if (opCode == spv::OpAtomicCompareExchange) {
6301 compareId = operands[1];
6302 valueId = operands[2];
6303 if (operands.size() > 3) {
6304 scopeId = operands[3];
6305 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6306 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
6307 }
6308 } else if (opCode == spv::OpAtomicLoad) {
6309 if (operands.size() > 1) {
6310 scopeId = operands[1];
6311 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
6312 }
6313 } else {
6314 // atomic store or RMW
6315 valueId = operands[1];
6316 if (operands.size() > 2) {
6317 scopeId = operands[2];
6318 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
6319 }
Rex Xu04db3f52015-09-16 11:44:02 +08006320 }
John Kessenich426394d2015-07-23 10:22:48 -06006321
Jeff Bolz36831c92018-09-05 10:11:41 -05006322 // Check for capabilities
6323 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006324 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6325 spv::MemorySemanticsMakeVisibleKHRMask |
6326 spv::MemorySemanticsOutputMemoryKHRMask |
6327 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006328 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6329 }
John Kessenich426394d2015-07-23 10:22:48 -06006330
Jeff Bolz36831c92018-09-05 10:11:41 -05006331 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6332 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6333 }
John Kessenich48d6e792017-10-06 21:21:48 -06006334
Jeff Bolz36831c92018-09-05 10:11:41 -05006335 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6336 spvAtomicOperands.push_back(pointerId);
6337 spvAtomicOperands.push_back(scopeId);
6338 spvAtomicOperands.push_back(semanticsId);
6339 if (opCode == spv::OpAtomicCompareExchange) {
6340 spvAtomicOperands.push_back(semanticsId2);
6341 spvAtomicOperands.push_back(valueId);
6342 spvAtomicOperands.push_back(compareId);
6343 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6344 spvAtomicOperands.push_back(valueId);
6345 }
John Kessenich48d6e792017-10-06 21:21:48 -06006346
Jeff Bolz36831c92018-09-05 10:11:41 -05006347 if (opCode == spv::OpAtomicStore) {
6348 builder.createNoResultOp(opCode, spvAtomicOperands);
6349 return 0;
6350 } else {
6351 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6352
6353 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6354 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6355 if (op == glslang::EOpAtomicCounterDecrement)
6356 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6357
6358 return resultId;
6359 }
John Kessenich426394d2015-07-23 10:22:48 -06006360}
6361
John Kessenich91cef522016-05-05 16:45:40 -06006362// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08006363spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006364{
Corentin Walleze7061422018-08-08 15:20:15 +02006365#ifdef AMD_EXTENSIONS
John Kessenich66011cb2018-03-06 16:12:04 -07006366 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6367 bool isFloat = isTypeFloat(typeProxy);
Corentin Walleze7061422018-08-08 15:20:15 +02006368#endif
Rex Xu9d93a232016-05-05 12:30:44 +08006369
Rex Xu51596642016-09-21 18:56:12 +08006370 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006371 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006372 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6373
chaocf200da82016-12-20 12:44:35 -08006374 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6375 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006376 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6377 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006378 } else if (op == glslang::EOpAnyInvocation ||
6379 op == glslang::EOpAllInvocations ||
6380 op == glslang::EOpAllInvocationsEqual) {
6381 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6382 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006383 } else {
6384 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04006385#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08006386 if (op == glslang::EOpMinInvocationsNonUniform ||
6387 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006388 op == glslang::EOpAddInvocationsNonUniform ||
6389 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6390 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6391 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6392 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6393 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6394 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006395 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04006396#endif
Rex Xu51596642016-09-21 18:56:12 +08006397
Rex Xu9d93a232016-05-05 12:30:44 +08006398#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08006399 switch (op) {
6400 case glslang::EOpMinInvocations:
6401 case glslang::EOpMaxInvocations:
6402 case glslang::EOpAddInvocations:
6403 case glslang::EOpMinInvocationsNonUniform:
6404 case glslang::EOpMaxInvocationsNonUniform:
6405 case glslang::EOpAddInvocationsNonUniform:
6406 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006407 break;
6408 case glslang::EOpMinInvocationsInclusiveScan:
6409 case glslang::EOpMaxInvocationsInclusiveScan:
6410 case glslang::EOpAddInvocationsInclusiveScan:
6411 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6412 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6413 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6414 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006415 break;
6416 case glslang::EOpMinInvocationsExclusiveScan:
6417 case glslang::EOpMaxInvocationsExclusiveScan:
6418 case glslang::EOpAddInvocationsExclusiveScan:
6419 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6420 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6421 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6422 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006423 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006424 default:
6425 break;
Rex Xu430ef402016-10-14 17:22:23 +08006426 }
John Kessenich149afc32018-08-14 13:31:43 -06006427 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6428 spvGroupOperands.push_back(scope);
6429 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006430 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006431 spvGroupOperands.push_back(groupOp);
6432 }
Rex Xu9d93a232016-05-05 12:30:44 +08006433#endif
Rex Xu51596642016-09-21 18:56:12 +08006434 }
6435
John Kessenich149afc32018-08-14 13:31:43 -06006436 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6437 spv::IdImmediate op = { true, *opIt };
6438 spvGroupOperands.push_back(op);
6439 }
John Kessenich91cef522016-05-05 16:45:40 -06006440
6441 switch (op) {
6442 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006443 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006444 break;
John Kessenich91cef522016-05-05 16:45:40 -06006445 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006446 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006447 break;
John Kessenich91cef522016-05-05 16:45:40 -06006448 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006449 opCode = spv::OpSubgroupAllEqualKHR;
6450 break;
Rex Xu51596642016-09-21 18:56:12 +08006451 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006452 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006453 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006454 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006455 break;
6456 case glslang::EOpReadFirstInvocation:
6457 opCode = spv::OpSubgroupFirstInvocationKHR;
6458 break;
6459 case glslang::EOpBallot:
6460 {
6461 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6462 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6463 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6464 //
6465 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6466 //
6467 spv::Id uintType = builder.makeUintType(32);
6468 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6469 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6470
6471 std::vector<spv::Id> components;
6472 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6473 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6474
6475 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6476 return builder.createUnaryOp(spv::OpBitcast, typeId,
6477 builder.createCompositeConstruct(uvec2Type, components));
6478 }
6479
Rex Xu9d93a232016-05-05 12:30:44 +08006480#ifdef AMD_EXTENSIONS
6481 case glslang::EOpMinInvocations:
6482 case glslang::EOpMaxInvocations:
6483 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006484 case glslang::EOpMinInvocationsInclusiveScan:
6485 case glslang::EOpMaxInvocationsInclusiveScan:
6486 case glslang::EOpAddInvocationsInclusiveScan:
6487 case glslang::EOpMinInvocationsExclusiveScan:
6488 case glslang::EOpMaxInvocationsExclusiveScan:
6489 case glslang::EOpAddInvocationsExclusiveScan:
6490 if (op == glslang::EOpMinInvocations ||
6491 op == glslang::EOpMinInvocationsInclusiveScan ||
6492 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006493 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006494 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006495 else {
6496 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006497 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006498 else
Rex Xu51596642016-09-21 18:56:12 +08006499 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006500 }
Rex Xu430ef402016-10-14 17:22:23 +08006501 } else if (op == glslang::EOpMaxInvocations ||
6502 op == glslang::EOpMaxInvocationsInclusiveScan ||
6503 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006504 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006505 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006506 else {
6507 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006508 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006509 else
Rex Xu51596642016-09-21 18:56:12 +08006510 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006511 }
6512 } else {
6513 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006514 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006515 else
Rex Xu51596642016-09-21 18:56:12 +08006516 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006517 }
6518
Rex Xu2bbbe062016-08-23 15:41:05 +08006519 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006520 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006521
6522 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006523 case glslang::EOpMinInvocationsNonUniform:
6524 case glslang::EOpMaxInvocationsNonUniform:
6525 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006526 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6527 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6528 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6529 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6530 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6531 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6532 if (op == glslang::EOpMinInvocationsNonUniform ||
6533 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6534 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006535 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006536 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006537 else {
6538 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006539 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006540 else
Rex Xu51596642016-09-21 18:56:12 +08006541 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006542 }
6543 }
Rex Xu430ef402016-10-14 17:22:23 +08006544 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6545 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6546 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006547 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006548 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006549 else {
6550 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006551 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006552 else
Rex Xu51596642016-09-21 18:56:12 +08006553 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006554 }
6555 }
6556 else {
6557 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006558 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006559 else
Rex Xu51596642016-09-21 18:56:12 +08006560 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006561 }
6562
Rex Xu2bbbe062016-08-23 15:41:05 +08006563 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006564 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006565
6566 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006567#endif
John Kessenich91cef522016-05-05 16:45:40 -06006568 default:
6569 logger->missingFunctionality("invocation operation");
6570 return spv::NoResult;
6571 }
Rex Xu51596642016-09-21 18:56:12 +08006572
6573 assert(opCode != spv::OpNop);
6574 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006575}
6576
Rex Xu2bbbe062016-08-23 15:41:05 +08006577// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006578spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6579 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006580{
Rex Xub7072052016-09-26 15:53:40 +08006581#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08006582 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6583 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006584 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006585 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006586 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
6587 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
6588 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08006589#else
6590 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6591 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08006592 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
6593 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08006594#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08006595
6596 // Handle group invocation operations scalar by scalar.
6597 // The result type is the same type as the original type.
6598 // The algorithm is to:
6599 // - break the vector into scalars
6600 // - apply the operation to each scalar
6601 // - make a vector out the scalar results
6602
6603 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006604 int numComponents = builder.getNumComponents(operands[0]);
6605 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006606 std::vector<spv::Id> results;
6607
6608 // do each scalar op
6609 for (int comp = 0; comp < numComponents; ++comp) {
6610 std::vector<unsigned int> indexes;
6611 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006612 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6613 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006614 if (op == spv::OpSubgroupReadInvocationKHR) {
6615 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006616 spv::IdImmediate operand = { true, operands[1] };
6617 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006618 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006619 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6620 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006621 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006622 spv::IdImmediate operand = { true, operands[1] };
6623 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006624 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006625 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6626 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006627 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006628 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006629 spvGroupOperands.push_back(scalar);
6630 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006631
Rex Xub7072052016-09-26 15:53:40 +08006632 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006633 }
6634
6635 // put the pieces together
6636 return builder.createCompositeConstruct(typeId, results);
6637}
Rex Xu2bbbe062016-08-23 15:41:05 +08006638
John Kessenich66011cb2018-03-06 16:12:04 -07006639// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006640spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6641 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006642{
6643 // Add the required capabilities.
6644 switch (op) {
6645 case glslang::EOpSubgroupElect:
6646 builder.addCapability(spv::CapabilityGroupNonUniform);
6647 break;
6648 case glslang::EOpSubgroupAll:
6649 case glslang::EOpSubgroupAny:
6650 case glslang::EOpSubgroupAllEqual:
6651 builder.addCapability(spv::CapabilityGroupNonUniform);
6652 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6653 break;
6654 case glslang::EOpSubgroupBroadcast:
6655 case glslang::EOpSubgroupBroadcastFirst:
6656 case glslang::EOpSubgroupBallot:
6657 case glslang::EOpSubgroupInverseBallot:
6658 case glslang::EOpSubgroupBallotBitExtract:
6659 case glslang::EOpSubgroupBallotBitCount:
6660 case glslang::EOpSubgroupBallotInclusiveBitCount:
6661 case glslang::EOpSubgroupBallotExclusiveBitCount:
6662 case glslang::EOpSubgroupBallotFindLSB:
6663 case glslang::EOpSubgroupBallotFindMSB:
6664 builder.addCapability(spv::CapabilityGroupNonUniform);
6665 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6666 break;
6667 case glslang::EOpSubgroupShuffle:
6668 case glslang::EOpSubgroupShuffleXor:
6669 builder.addCapability(spv::CapabilityGroupNonUniform);
6670 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6671 break;
6672 case glslang::EOpSubgroupShuffleUp:
6673 case glslang::EOpSubgroupShuffleDown:
6674 builder.addCapability(spv::CapabilityGroupNonUniform);
6675 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6676 break;
6677 case glslang::EOpSubgroupAdd:
6678 case glslang::EOpSubgroupMul:
6679 case glslang::EOpSubgroupMin:
6680 case glslang::EOpSubgroupMax:
6681 case glslang::EOpSubgroupAnd:
6682 case glslang::EOpSubgroupOr:
6683 case glslang::EOpSubgroupXor:
6684 case glslang::EOpSubgroupInclusiveAdd:
6685 case glslang::EOpSubgroupInclusiveMul:
6686 case glslang::EOpSubgroupInclusiveMin:
6687 case glslang::EOpSubgroupInclusiveMax:
6688 case glslang::EOpSubgroupInclusiveAnd:
6689 case glslang::EOpSubgroupInclusiveOr:
6690 case glslang::EOpSubgroupInclusiveXor:
6691 case glslang::EOpSubgroupExclusiveAdd:
6692 case glslang::EOpSubgroupExclusiveMul:
6693 case glslang::EOpSubgroupExclusiveMin:
6694 case glslang::EOpSubgroupExclusiveMax:
6695 case glslang::EOpSubgroupExclusiveAnd:
6696 case glslang::EOpSubgroupExclusiveOr:
6697 case glslang::EOpSubgroupExclusiveXor:
6698 builder.addCapability(spv::CapabilityGroupNonUniform);
6699 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6700 break;
6701 case glslang::EOpSubgroupClusteredAdd:
6702 case glslang::EOpSubgroupClusteredMul:
6703 case glslang::EOpSubgroupClusteredMin:
6704 case glslang::EOpSubgroupClusteredMax:
6705 case glslang::EOpSubgroupClusteredAnd:
6706 case glslang::EOpSubgroupClusteredOr:
6707 case glslang::EOpSubgroupClusteredXor:
6708 builder.addCapability(spv::CapabilityGroupNonUniform);
6709 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6710 break;
6711 case glslang::EOpSubgroupQuadBroadcast:
6712 case glslang::EOpSubgroupQuadSwapHorizontal:
6713 case glslang::EOpSubgroupQuadSwapVertical:
6714 case glslang::EOpSubgroupQuadSwapDiagonal:
6715 builder.addCapability(spv::CapabilityGroupNonUniform);
6716 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6717 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006718#ifdef NV_EXTENSIONS
6719 case glslang::EOpSubgroupPartitionedAdd:
6720 case glslang::EOpSubgroupPartitionedMul:
6721 case glslang::EOpSubgroupPartitionedMin:
6722 case glslang::EOpSubgroupPartitionedMax:
6723 case glslang::EOpSubgroupPartitionedAnd:
6724 case glslang::EOpSubgroupPartitionedOr:
6725 case glslang::EOpSubgroupPartitionedXor:
6726 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6727 case glslang::EOpSubgroupPartitionedInclusiveMul:
6728 case glslang::EOpSubgroupPartitionedInclusiveMin:
6729 case glslang::EOpSubgroupPartitionedInclusiveMax:
6730 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6731 case glslang::EOpSubgroupPartitionedInclusiveOr:
6732 case glslang::EOpSubgroupPartitionedInclusiveXor:
6733 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6734 case glslang::EOpSubgroupPartitionedExclusiveMul:
6735 case glslang::EOpSubgroupPartitionedExclusiveMin:
6736 case glslang::EOpSubgroupPartitionedExclusiveMax:
6737 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6738 case glslang::EOpSubgroupPartitionedExclusiveOr:
6739 case glslang::EOpSubgroupPartitionedExclusiveXor:
6740 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6741 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6742 break;
6743#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006744 default: assert(0 && "Unhandled subgroup operation!");
6745 }
6746
6747 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
6748 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
6749 const bool isBool = typeProxy == glslang::EbtBool;
6750
6751 spv::Op opCode = spv::OpNop;
6752
6753 // Figure out which opcode to use.
6754 switch (op) {
6755 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6756 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6757 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6758 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6759 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6760 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6761 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6762 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6763 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6764 case glslang::EOpSubgroupBallotBitCount:
6765 case glslang::EOpSubgroupBallotInclusiveBitCount:
6766 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6767 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6768 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6769 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6770 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6771 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6772 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6773 case glslang::EOpSubgroupAdd:
6774 case glslang::EOpSubgroupInclusiveAdd:
6775 case glslang::EOpSubgroupExclusiveAdd:
6776 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006777#ifdef NV_EXTENSIONS
6778 case glslang::EOpSubgroupPartitionedAdd:
6779 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6780 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6781#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006782 if (isFloat) {
6783 opCode = spv::OpGroupNonUniformFAdd;
6784 } else {
6785 opCode = spv::OpGroupNonUniformIAdd;
6786 }
6787 break;
6788 case glslang::EOpSubgroupMul:
6789 case glslang::EOpSubgroupInclusiveMul:
6790 case glslang::EOpSubgroupExclusiveMul:
6791 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006792#ifdef NV_EXTENSIONS
6793 case glslang::EOpSubgroupPartitionedMul:
6794 case glslang::EOpSubgroupPartitionedInclusiveMul:
6795 case glslang::EOpSubgroupPartitionedExclusiveMul:
6796#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006797 if (isFloat) {
6798 opCode = spv::OpGroupNonUniformFMul;
6799 } else {
6800 opCode = spv::OpGroupNonUniformIMul;
6801 }
6802 break;
6803 case glslang::EOpSubgroupMin:
6804 case glslang::EOpSubgroupInclusiveMin:
6805 case glslang::EOpSubgroupExclusiveMin:
6806 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006807#ifdef NV_EXTENSIONS
6808 case glslang::EOpSubgroupPartitionedMin:
6809 case glslang::EOpSubgroupPartitionedInclusiveMin:
6810 case glslang::EOpSubgroupPartitionedExclusiveMin:
6811#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006812 if (isFloat) {
6813 opCode = spv::OpGroupNonUniformFMin;
6814 } else if (isUnsigned) {
6815 opCode = spv::OpGroupNonUniformUMin;
6816 } else {
6817 opCode = spv::OpGroupNonUniformSMin;
6818 }
6819 break;
6820 case glslang::EOpSubgroupMax:
6821 case glslang::EOpSubgroupInclusiveMax:
6822 case glslang::EOpSubgroupExclusiveMax:
6823 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006824#ifdef NV_EXTENSIONS
6825 case glslang::EOpSubgroupPartitionedMax:
6826 case glslang::EOpSubgroupPartitionedInclusiveMax:
6827 case glslang::EOpSubgroupPartitionedExclusiveMax:
6828#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006829 if (isFloat) {
6830 opCode = spv::OpGroupNonUniformFMax;
6831 } else if (isUnsigned) {
6832 opCode = spv::OpGroupNonUniformUMax;
6833 } else {
6834 opCode = spv::OpGroupNonUniformSMax;
6835 }
6836 break;
6837 case glslang::EOpSubgroupAnd:
6838 case glslang::EOpSubgroupInclusiveAnd:
6839 case glslang::EOpSubgroupExclusiveAnd:
6840 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006841#ifdef NV_EXTENSIONS
6842 case glslang::EOpSubgroupPartitionedAnd:
6843 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6844 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6845#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006846 if (isBool) {
6847 opCode = spv::OpGroupNonUniformLogicalAnd;
6848 } else {
6849 opCode = spv::OpGroupNonUniformBitwiseAnd;
6850 }
6851 break;
6852 case glslang::EOpSubgroupOr:
6853 case glslang::EOpSubgroupInclusiveOr:
6854 case glslang::EOpSubgroupExclusiveOr:
6855 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006856#ifdef NV_EXTENSIONS
6857 case glslang::EOpSubgroupPartitionedOr:
6858 case glslang::EOpSubgroupPartitionedInclusiveOr:
6859 case glslang::EOpSubgroupPartitionedExclusiveOr:
6860#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006861 if (isBool) {
6862 opCode = spv::OpGroupNonUniformLogicalOr;
6863 } else {
6864 opCode = spv::OpGroupNonUniformBitwiseOr;
6865 }
6866 break;
6867 case glslang::EOpSubgroupXor:
6868 case glslang::EOpSubgroupInclusiveXor:
6869 case glslang::EOpSubgroupExclusiveXor:
6870 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006871#ifdef NV_EXTENSIONS
6872 case glslang::EOpSubgroupPartitionedXor:
6873 case glslang::EOpSubgroupPartitionedInclusiveXor:
6874 case glslang::EOpSubgroupPartitionedExclusiveXor:
6875#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006876 if (isBool) {
6877 opCode = spv::OpGroupNonUniformLogicalXor;
6878 } else {
6879 opCode = spv::OpGroupNonUniformBitwiseXor;
6880 }
6881 break;
6882 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
6883 case glslang::EOpSubgroupQuadSwapHorizontal:
6884 case glslang::EOpSubgroupQuadSwapVertical:
6885 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
6886 default: assert(0 && "Unhandled subgroup operation!");
6887 }
6888
John Kessenich149afc32018-08-14 13:31:43 -06006889 // get the right Group Operation
6890 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07006891 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06006892 default:
6893 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006894 case glslang::EOpSubgroupBallotBitCount:
6895 case glslang::EOpSubgroupAdd:
6896 case glslang::EOpSubgroupMul:
6897 case glslang::EOpSubgroupMin:
6898 case glslang::EOpSubgroupMax:
6899 case glslang::EOpSubgroupAnd:
6900 case glslang::EOpSubgroupOr:
6901 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06006902 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006903 break;
6904 case glslang::EOpSubgroupBallotInclusiveBitCount:
6905 case glslang::EOpSubgroupInclusiveAdd:
6906 case glslang::EOpSubgroupInclusiveMul:
6907 case glslang::EOpSubgroupInclusiveMin:
6908 case glslang::EOpSubgroupInclusiveMax:
6909 case glslang::EOpSubgroupInclusiveAnd:
6910 case glslang::EOpSubgroupInclusiveOr:
6911 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006912 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006913 break;
6914 case glslang::EOpSubgroupBallotExclusiveBitCount:
6915 case glslang::EOpSubgroupExclusiveAdd:
6916 case glslang::EOpSubgroupExclusiveMul:
6917 case glslang::EOpSubgroupExclusiveMin:
6918 case glslang::EOpSubgroupExclusiveMax:
6919 case glslang::EOpSubgroupExclusiveAnd:
6920 case glslang::EOpSubgroupExclusiveOr:
6921 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006922 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006923 break;
6924 case glslang::EOpSubgroupClusteredAdd:
6925 case glslang::EOpSubgroupClusteredMul:
6926 case glslang::EOpSubgroupClusteredMin:
6927 case glslang::EOpSubgroupClusteredMax:
6928 case glslang::EOpSubgroupClusteredAnd:
6929 case glslang::EOpSubgroupClusteredOr:
6930 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06006931 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006932 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006933#ifdef NV_EXTENSIONS
6934 case glslang::EOpSubgroupPartitionedAdd:
6935 case glslang::EOpSubgroupPartitionedMul:
6936 case glslang::EOpSubgroupPartitionedMin:
6937 case glslang::EOpSubgroupPartitionedMax:
6938 case glslang::EOpSubgroupPartitionedAnd:
6939 case glslang::EOpSubgroupPartitionedOr:
6940 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06006941 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006942 break;
6943 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6944 case glslang::EOpSubgroupPartitionedInclusiveMul:
6945 case glslang::EOpSubgroupPartitionedInclusiveMin:
6946 case glslang::EOpSubgroupPartitionedInclusiveMax:
6947 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6948 case glslang::EOpSubgroupPartitionedInclusiveOr:
6949 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006950 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006951 break;
6952 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6953 case glslang::EOpSubgroupPartitionedExclusiveMul:
6954 case glslang::EOpSubgroupPartitionedExclusiveMin:
6955 case glslang::EOpSubgroupPartitionedExclusiveMax:
6956 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6957 case glslang::EOpSubgroupPartitionedExclusiveOr:
6958 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006959 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006960 break;
6961#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006962 }
6963
John Kessenich149afc32018-08-14 13:31:43 -06006964 // build the instruction
6965 std::vector<spv::IdImmediate> spvGroupOperands;
6966
6967 // Every operation begins with the Execution Scope operand.
6968 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6969 spvGroupOperands.push_back(executionScope);
6970
6971 // Next, for all operations that use a Group Operation, push that as an operand.
6972 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006973 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006974 spvGroupOperands.push_back(groupOperand);
6975 }
6976
John Kessenich66011cb2018-03-06 16:12:04 -07006977 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06006978 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
6979 spv::IdImmediate operand = { true, *opIt };
6980 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006981 }
6982
6983 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06006984 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07006985 switch (op) {
6986 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06006987 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
6988 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
6989 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
6990 }
6991 if (directionId != spv::NoResult) {
6992 spv::IdImmediate direction = { true, directionId };
6993 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07006994 }
6995
6996 return builder.createOp(opCode, typeId, spvGroupOperands);
6997}
6998
John Kessenich5e4b1242015-08-06 22:53:06 -06006999spv::Id TGlslangToSpvTraverser::createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06007000{
John Kessenich66011cb2018-03-06 16:12:04 -07007001 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7002 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007003
John Kessenich140f3df2015-06-26 16:58:36 -06007004 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007005 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007006 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007007 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007008 spv::Id typeId0 = 0;
7009 if (consumedOperands > 0)
7010 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007011 spv::Id typeId1 = 0;
7012 if (consumedOperands > 1)
7013 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007014 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007015
7016 switch (op) {
7017 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007018 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007019 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007020 else if (isUnsigned)
7021 libCall = spv::GLSLstd450UMin;
7022 else
7023 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007024 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007025 break;
7026 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007027 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007028 break;
7029 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007030 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007031 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007032 else if (isUnsigned)
7033 libCall = spv::GLSLstd450UMax;
7034 else
7035 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007036 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007037 break;
7038 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007039 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007040 break;
7041 case glslang::EOpDot:
7042 opCode = spv::OpDot;
7043 break;
7044 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007045 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007046 break;
7047
7048 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007049 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007050 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007051 else if (isUnsigned)
7052 libCall = spv::GLSLstd450UClamp;
7053 else
7054 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007055 builder.promoteScalar(precision, operands.front(), operands[1]);
7056 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007057 break;
7058 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007059 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7060 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007061 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007062 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007063 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007064 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007065 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007066 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007067 break;
7068 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007069 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007070 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007071 break;
7072 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007073 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007074 builder.promoteScalar(precision, operands[0], operands[2]);
7075 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007076 break;
7077
7078 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007079 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007080 break;
7081 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007082 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007083 break;
7084 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007085 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007086 break;
7087 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007088 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007089 break;
7090 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007091 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007092 break;
Rex Xu7a26c172015-12-08 17:12:09 +08007093 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007094#ifdef AMD_EXTENSIONS
7095 if (typeProxy == glslang::EbtFloat16)
7096 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
7097#endif
Rex Xu7a26c172015-12-08 17:12:09 +08007098 libCall = spv::GLSLstd450InterpolateAtSample;
7099 break;
7100 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007101#ifdef AMD_EXTENSIONS
7102 if (typeProxy == glslang::EbtFloat16)
7103 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
7104#endif
Rex Xu7a26c172015-12-08 17:12:09 +08007105 libCall = spv::GLSLstd450InterpolateAtOffset;
7106 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007107 case glslang::EOpAddCarry:
7108 opCode = spv::OpIAddCarry;
7109 typeId = builder.makeStructResultType(typeId0, typeId0);
7110 consumedOperands = 2;
7111 break;
7112 case glslang::EOpSubBorrow:
7113 opCode = spv::OpISubBorrow;
7114 typeId = builder.makeStructResultType(typeId0, typeId0);
7115 consumedOperands = 2;
7116 break;
7117 case glslang::EOpUMulExtended:
7118 opCode = spv::OpUMulExtended;
7119 typeId = builder.makeStructResultType(typeId0, typeId0);
7120 consumedOperands = 2;
7121 break;
7122 case glslang::EOpIMulExtended:
7123 opCode = spv::OpSMulExtended;
7124 typeId = builder.makeStructResultType(typeId0, typeId0);
7125 consumedOperands = 2;
7126 break;
7127 case glslang::EOpBitfieldExtract:
7128 if (isUnsigned)
7129 opCode = spv::OpBitFieldUExtract;
7130 else
7131 opCode = spv::OpBitFieldSExtract;
7132 break;
7133 case glslang::EOpBitfieldInsert:
7134 opCode = spv::OpBitFieldInsert;
7135 break;
7136
7137 case glslang::EOpFma:
7138 libCall = spv::GLSLstd450Fma;
7139 break;
7140 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007141 {
7142 libCall = spv::GLSLstd450FrexpStruct;
7143 assert(builder.isPointerType(typeId1));
7144 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007145 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007146#ifdef AMD_EXTENSIONS
7147 if (width == 16)
7148 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7149 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
7150#endif
Rex Xu470026f2017-03-29 17:12:40 +08007151 if (builder.getNumComponents(operands[0]) == 1)
7152 frexpIntType = builder.makeIntegerType(width, true);
7153 else
7154 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
7155 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7156 consumedOperands = 1;
7157 }
John Kessenich55e7d112015-11-15 21:33:39 -07007158 break;
7159 case glslang::EOpLdexp:
7160 libCall = spv::GLSLstd450Ldexp;
7161 break;
7162
Rex Xu574ab042016-04-14 16:53:07 +08007163 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007164 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007165
John Kessenich66011cb2018-03-06 16:12:04 -07007166 case glslang::EOpSubgroupBroadcast:
7167 case glslang::EOpSubgroupBallotBitExtract:
7168 case glslang::EOpSubgroupShuffle:
7169 case glslang::EOpSubgroupShuffleXor:
7170 case glslang::EOpSubgroupShuffleUp:
7171 case glslang::EOpSubgroupShuffleDown:
7172 case glslang::EOpSubgroupClusteredAdd:
7173 case glslang::EOpSubgroupClusteredMul:
7174 case glslang::EOpSubgroupClusteredMin:
7175 case glslang::EOpSubgroupClusteredMax:
7176 case glslang::EOpSubgroupClusteredAnd:
7177 case glslang::EOpSubgroupClusteredOr:
7178 case glslang::EOpSubgroupClusteredXor:
7179 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007180#ifdef NV_EXTENSIONS
7181 case glslang::EOpSubgroupPartitionedAdd:
7182 case glslang::EOpSubgroupPartitionedMul:
7183 case glslang::EOpSubgroupPartitionedMin:
7184 case glslang::EOpSubgroupPartitionedMax:
7185 case glslang::EOpSubgroupPartitionedAnd:
7186 case glslang::EOpSubgroupPartitionedOr:
7187 case glslang::EOpSubgroupPartitionedXor:
7188 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7189 case glslang::EOpSubgroupPartitionedInclusiveMul:
7190 case glslang::EOpSubgroupPartitionedInclusiveMin:
7191 case glslang::EOpSubgroupPartitionedInclusiveMax:
7192 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7193 case glslang::EOpSubgroupPartitionedInclusiveOr:
7194 case glslang::EOpSubgroupPartitionedInclusiveXor:
7195 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7196 case glslang::EOpSubgroupPartitionedExclusiveMul:
7197 case glslang::EOpSubgroupPartitionedExclusiveMin:
7198 case glslang::EOpSubgroupPartitionedExclusiveMax:
7199 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7200 case glslang::EOpSubgroupPartitionedExclusiveOr:
7201 case glslang::EOpSubgroupPartitionedExclusiveXor:
7202#endif
John Kessenich66011cb2018-03-06 16:12:04 -07007203 return createSubgroupOperation(op, typeId, operands, typeProxy);
7204
Rex Xu9d93a232016-05-05 12:30:44 +08007205#ifdef AMD_EXTENSIONS
7206 case glslang::EOpSwizzleInvocations:
7207 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7208 libCall = spv::SwizzleInvocationsAMD;
7209 break;
7210 case glslang::EOpSwizzleInvocationsMasked:
7211 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7212 libCall = spv::SwizzleInvocationsMaskedAMD;
7213 break;
7214 case glslang::EOpWriteInvocation:
7215 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7216 libCall = spv::WriteInvocationAMD;
7217 break;
7218
7219 case glslang::EOpMin3:
7220 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7221 if (isFloat)
7222 libCall = spv::FMin3AMD;
7223 else {
7224 if (isUnsigned)
7225 libCall = spv::UMin3AMD;
7226 else
7227 libCall = spv::SMin3AMD;
7228 }
7229 break;
7230 case glslang::EOpMax3:
7231 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7232 if (isFloat)
7233 libCall = spv::FMax3AMD;
7234 else {
7235 if (isUnsigned)
7236 libCall = spv::UMax3AMD;
7237 else
7238 libCall = spv::SMax3AMD;
7239 }
7240 break;
7241 case glslang::EOpMid3:
7242 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7243 if (isFloat)
7244 libCall = spv::FMid3AMD;
7245 else {
7246 if (isUnsigned)
7247 libCall = spv::UMid3AMD;
7248 else
7249 libCall = spv::SMid3AMD;
7250 }
7251 break;
7252
7253 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007254 if (typeProxy == glslang::EbtFloat16)
7255 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007256 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7257 libCall = spv::InterpolateAtVertexAMD;
7258 break;
7259#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05007260 case glslang::EOpBarrier:
7261 {
7262 // This is for the extended controlBarrier function, with four operands.
7263 // The unextended barrier() goes through createNoArgOperation.
7264 assert(operands.size() == 4);
7265 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7266 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7267 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
7268 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05007269 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7270 spv::MemorySemanticsMakeVisibleKHRMask |
7271 spv::MemorySemanticsOutputMemoryKHRMask |
7272 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007273 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7274 }
7275 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
7276 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7277 }
7278 return 0;
7279 }
7280 break;
7281 case glslang::EOpMemoryBarrier:
7282 {
7283 // This is for the extended memoryBarrier function, with three operands.
7284 // The unextended memoryBarrier() goes through createNoArgOperation.
7285 assert(operands.size() == 3);
7286 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7287 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7288 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05007289 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7290 spv::MemorySemanticsMakeVisibleKHRMask |
7291 spv::MemorySemanticsOutputMemoryKHRMask |
7292 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007293 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7294 }
7295 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7296 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7297 }
7298 return 0;
7299 }
7300 break;
Chao Chen3c366992018-09-19 11:41:59 -07007301
7302#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07007303 case glslang::EOpReportIntersectionNV:
7304 {
7305 typeId = builder.makeBoolType();
Ashwin Leleff1783d2018-10-22 16:41:44 -07007306 opCode = spv::OpReportIntersectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07007307 }
7308 break;
7309 case glslang::EOpTraceNV:
7310 {
Ashwin Leleff1783d2018-10-22 16:41:44 -07007311 builder.createNoResultOp(spv::OpTraceNV, operands);
7312 return 0;
7313 }
7314 break;
7315 case glslang::EOpExecuteCallableNV:
7316 {
7317 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007318 return 0;
7319 }
7320 break;
Chao Chen3c366992018-09-19 11:41:59 -07007321 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7322 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7323 return 0;
7324#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007325 case glslang::EOpCooperativeMatrixMulAdd:
7326 opCode = spv::OpCooperativeMatrixMulAddNV;
7327 break;
7328
John Kessenich140f3df2015-06-26 16:58:36 -06007329 default:
7330 return 0;
7331 }
7332
7333 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007334 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007335 // Use an extended instruction from the standard library.
7336 // Construct the call arguments, without modifying the original operands vector.
7337 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7338 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007339 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007340 } else if (opCode == spv::OpDot && !isFloat) {
7341 // int dot(int, int)
7342 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7343 const int componentCount = builder.getNumComponents(operands[0]);
7344 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7345 builder.setPrecision(mulOp, precision);
7346 id = builder.createCompositeExtract(mulOp, typeId, 0);
7347 for (int i = 1; i < componentCount; ++i) {
7348 builder.setPrecision(id, precision);
7349 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(operands[0], typeId, i));
7350 }
John Kessenich2359bd02015-12-06 19:29:11 -07007351 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007352 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007353 case 0:
7354 // should all be handled by visitAggregate and createNoArgOperation
7355 assert(0);
7356 return 0;
7357 case 1:
7358 // should all be handled by createUnaryOperation
7359 assert(0);
7360 return 0;
7361 case 2:
7362 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7363 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007364 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007365 // anything 3 or over doesn't have l-value operands, so all should be consumed
7366 assert(consumedOperands == operands.size());
7367 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007368 break;
7369 }
7370 }
7371
John Kessenich55e7d112015-11-15 21:33:39 -07007372 // Decode the return types that were structures
7373 switch (op) {
7374 case glslang::EOpAddCarry:
7375 case glslang::EOpSubBorrow:
7376 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7377 id = builder.createCompositeExtract(id, typeId0, 0);
7378 break;
7379 case glslang::EOpUMulExtended:
7380 case glslang::EOpIMulExtended:
7381 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7382 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7383 break;
7384 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007385 {
7386 assert(operands.size() == 2);
7387 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7388 // "exp" is floating-point type (from HLSL intrinsic)
7389 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7390 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7391 builder.createStore(member1, operands[1]);
7392 } else
7393 // "exp" is integer type (from GLSL built-in function)
7394 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7395 id = builder.createCompositeExtract(id, typeId0, 0);
7396 }
John Kessenich55e7d112015-11-15 21:33:39 -07007397 break;
7398 default:
7399 break;
7400 }
7401
John Kessenich32cfd492016-02-02 12:37:46 -07007402 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007403}
7404
Rex Xu9d93a232016-05-05 12:30:44 +08007405// Intrinsics with no arguments (or no return value, and no precision).
7406spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007407{
Jeff Bolz36831c92018-09-05 10:11:41 -05007408 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
7409 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007410
7411 switch (op) {
7412 case glslang::EOpEmitVertex:
7413 builder.createNoResultOp(spv::OpEmitVertex);
7414 return 0;
7415 case glslang::EOpEndPrimitive:
7416 builder.createNoResultOp(spv::OpEndPrimitive);
7417 return 0;
7418 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007419 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007420 if (glslangIntermediate->usingVulkanMemoryModel()) {
7421 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7422 spv::MemorySemanticsOutputMemoryKHRMask |
7423 spv::MemorySemanticsAcquireReleaseMask);
7424 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7425 } else {
7426 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7427 }
John Kessenich82979362017-12-11 04:02:24 -07007428 } else {
7429 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7430 spv::MemorySemanticsWorkgroupMemoryMask |
7431 spv::MemorySemanticsAcquireReleaseMask);
7432 }
John Kessenich140f3df2015-06-26 16:58:36 -06007433 return 0;
7434 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007435 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7436 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007437 return 0;
7438 case glslang::EOpMemoryBarrierAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05007439 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7440 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007441 return 0;
7442 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007443 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7444 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007445 return 0;
7446 case glslang::EOpMemoryBarrierImage:
Jeff Bolz36831c92018-09-05 10:11:41 -05007447 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7448 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007449 return 0;
7450 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007451 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7452 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007453 return 0;
7454 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007455 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7456 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007457 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007458 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007459 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007460 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007461 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007462 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007463 case glslang::EOpDeviceMemoryBarrier:
7464 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7465 spv::MemorySemanticsImageMemoryMask |
7466 spv::MemorySemanticsAcquireReleaseMask);
7467 return 0;
7468 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7469 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7470 spv::MemorySemanticsImageMemoryMask |
7471 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007472 return 0;
7473 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007474 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7475 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007476 return 0;
7477 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007478 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7479 spv::MemorySemanticsWorkgroupMemoryMask |
7480 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007481 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007482 case glslang::EOpSubgroupBarrier:
7483 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7484 spv::MemorySemanticsAcquireReleaseMask);
7485 return spv::NoResult;
7486 case glslang::EOpSubgroupMemoryBarrier:
7487 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7488 spv::MemorySemanticsAcquireReleaseMask);
7489 return spv::NoResult;
7490 case glslang::EOpSubgroupMemoryBarrierBuffer:
7491 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7492 spv::MemorySemanticsAcquireReleaseMask);
7493 return spv::NoResult;
7494 case glslang::EOpSubgroupMemoryBarrierImage:
7495 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7496 spv::MemorySemanticsAcquireReleaseMask);
7497 return spv::NoResult;
7498 case glslang::EOpSubgroupMemoryBarrierShared:
7499 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7500 spv::MemorySemanticsAcquireReleaseMask);
7501 return spv::NoResult;
7502 case glslang::EOpSubgroupElect: {
7503 std::vector<spv::Id> operands;
7504 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7505 }
Rex Xu9d93a232016-05-05 12:30:44 +08007506#ifdef AMD_EXTENSIONS
7507 case glslang::EOpTime:
7508 {
7509 std::vector<spv::Id> args; // Dummy arguments
7510 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7511 return builder.setPrecision(id, precision);
7512 }
7513#endif
Chao Chenb50c02e2018-09-19 11:42:24 -07007514#ifdef NV_EXTENSIONS
7515 case glslang::EOpIgnoreIntersectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007516 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007517 return 0;
7518 case glslang::EOpTerminateRayNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007519 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007520 return 0;
7521#endif
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05007522
7523 case glslang::EOpBeginInvocationInterlock:
7524 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
7525 return 0;
7526 case glslang::EOpEndInvocationInterlock:
7527 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
7528 return 0;
7529
John Kessenich140f3df2015-06-26 16:58:36 -06007530 default:
Lei Zhang17535f72016-05-04 15:55:59 -04007531 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06007532 return 0;
7533 }
7534}
7535
7536spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7537{
John Kessenich2f273362015-07-18 22:34:27 -06007538 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007539 spv::Id id;
7540 if (symbolValues.end() != iter) {
7541 id = iter->second;
7542 return id;
7543 }
7544
7545 // it was not found, create it
7546 id = createSpvVariable(symbol);
7547 symbolValues[symbol->getId()] = id;
7548
Rex Xuc884b4a2016-06-29 15:03:44 +08007549 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007550 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7551 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7552 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
Chao Chen3c366992018-09-19 11:41:59 -07007553#ifdef NV_EXTENSIONS
7554 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
7555#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007556 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007557 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06007558 if (symbol->getQualifier().hasIndex())
7559 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
7560 if (symbol->getQualifier().hasComponent())
7561 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06007562 // atomic counters use this:
7563 if (symbol->getQualifier().hasOffset())
7564 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007565 }
7566
scygan2c864272016-05-18 18:09:17 +02007567 if (symbol->getQualifier().hasLocation())
7568 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007569 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007570 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007571 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007572 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007573 }
John Kessenich140f3df2015-06-26 16:58:36 -06007574 if (symbol->getQualifier().hasSet())
7575 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007576 else if (IsDescriptorResource(symbol->getType())) {
7577 // default to 0
7578 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7579 }
John Kessenich140f3df2015-06-26 16:58:36 -06007580 if (symbol->getQualifier().hasBinding())
7581 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06007582 else if (IsDescriptorResource(symbol->getType())) {
7583 // default to 0
7584 builder.addDecoration(id, spv::DecorationBinding, 0);
7585 }
John Kessenich6c292d32016-02-15 20:58:50 -07007586 if (symbol->getQualifier().hasAttachment())
7587 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06007588 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007589 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07007590 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007591 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007592 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7593 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7594 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7595 }
7596 if (symbol->getQualifier().hasXfbOffset())
7597 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007598 }
7599
Rex Xu1da878f2016-02-21 20:59:01 +08007600 if (symbol->getType().isImage()) {
7601 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05007602 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007603 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007604 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007605 }
7606
John Kessenich140f3df2015-06-26 16:58:36 -06007607 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06007608 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06007609 if (builtIn != spv::BuiltInMax)
John Kessenich5d610ee2018-03-07 18:05:55 -07007610 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06007611
John Kessenich5611c6d2018-04-05 11:25:02 -06007612 // nonuniform
7613 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7614
John Kessenichecba76f2017-01-06 00:34:48 -07007615#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08007616 if (builtIn == spv::BuiltInSampleMask) {
7617 spv::Decoration decoration;
7618 // GL_NV_sample_mask_override_coverage extension
7619 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007620 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007621 else
7622 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007623 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007624 if (decoration != spv::DecorationMax) {
7625 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7626 }
7627 }
chaoc771d89f2017-01-13 01:10:53 -08007628 else if (builtIn == spv::BuiltInLayer) {
7629 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007630 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007631 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007632 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7633 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7634 }
John Kessenichb41bff62017-08-11 13:07:17 -06007635 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007636 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7637 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007638 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7639 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7640 }
7641 }
7642
chaoc6e5acae2016-12-20 13:28:52 -08007643 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007644 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007645 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007646 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7647 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007648 if (symbol->getQualifier().pervertexNV) {
7649 builder.addDecoration(id, spv::DecorationPerVertexNV);
7650 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7651 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7652 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007653#endif
7654
John Kessenich5d610ee2018-03-07 18:05:55 -07007655 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7656 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7657 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7658 symbol->getType().getQualifier().semanticName);
7659 }
7660
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007661 if (symbol->getBasicType() == glslang::EbtReference) {
7662 builder.addDecoration(id, symbol->getType().getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
7663 }
7664
John Kessenich140f3df2015-06-26 16:58:36 -06007665 return id;
7666}
7667
Chao Chen3c366992018-09-19 11:41:59 -07007668#ifdef NV_EXTENSIONS
7669// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7670void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7671{
7672 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07007673 if (qualifier.perPrimitiveNV) {
7674 // Need to add capability/extension for fragment shader.
7675 // Mesh shader already adds this by default.
7676 if (glslangIntermediate->getStage() == EShLangFragment) {
7677 builder.addCapability(spv::CapabilityMeshShadingNV);
7678 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7679 }
Chao Chen3c366992018-09-19 11:41:59 -07007680 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007681 }
Chao Chen3c366992018-09-19 11:41:59 -07007682 if (qualifier.perViewNV)
7683 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7684 if (qualifier.perTaskNV)
7685 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7686 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07007687 if (qualifier.perPrimitiveNV) {
7688 // Need to add capability/extension for fragment shader.
7689 // Mesh shader already adds this by default.
7690 if (glslangIntermediate->getStage() == EShLangFragment) {
7691 builder.addCapability(spv::CapabilityMeshShadingNV);
7692 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7693 }
Chao Chen3c366992018-09-19 11:41:59 -07007694 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007695 }
Chao Chen3c366992018-09-19 11:41:59 -07007696 if (qualifier.perViewNV)
7697 builder.addDecoration(id, spv::DecorationPerViewNV);
7698 if (qualifier.perTaskNV)
7699 builder.addDecoration(id, spv::DecorationPerTaskNV);
7700 }
7701}
7702#endif
7703
John Kessenich55e7d112015-11-15 21:33:39 -07007704// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07007705// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07007706//
7707// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7708//
7709// Recursively walk the nodes. The nodes form a tree whose leaves are
7710// regular constants, which themselves are trees that createSpvConstant()
7711// recursively walks. So, this function walks the "top" of the tree:
7712// - emit specialization constant-building instructions for specConstant
7713// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04007714spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07007715{
John Kessenich7cc0e282016-03-20 00:46:02 -06007716 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07007717
qining4f4bb812016-04-03 23:55:17 -04007718 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07007719 if (! node.getQualifier().specConstant) {
7720 // hand off to the non-spec-constant path
7721 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
7722 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04007723 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07007724 nextConst, false);
7725 }
7726
7727 // We now know we have a specialization constant to build
7728
John Kessenichd94c0032016-05-30 19:29:40 -06007729 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04007730 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
7731 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
7732 std::vector<spv::Id> dimConstId;
7733 for (int dim = 0; dim < 3; ++dim) {
7734 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
7735 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07007736 if (specConst) {
7737 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
7738 glslangIntermediate->getLocalSizeSpecId(dim));
7739 }
qining4f4bb812016-04-03 23:55:17 -04007740 }
7741 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
7742 }
7743
7744 // An AST node labelled as specialization constant should be a symbol node.
7745 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
7746 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007747 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04007748 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04007749 // Traverse the constant constructor sub tree like generating normal run-time instructions.
7750 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
7751 // will set the builder into spec constant op instruction generating mode.
7752 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007753 result = accessChainLoad(sub_tree->getType());
7754 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04007755 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007756 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05007757 } else {
7758 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05007759 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07007760 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007761 builder.addName(result, sn->getName().c_str());
7762 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07007763 }
qining4f4bb812016-04-03 23:55:17 -04007764
7765 // Neither a front-end constant node, nor a specialization constant node with constant union array or
7766 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04007767 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04007768 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07007769}
7770
John Kessenich140f3df2015-06-26 16:58:36 -06007771// Use 'consts' as the flattened glslang source of scalar constants to recursively
7772// build the aggregate SPIR-V constant.
7773//
7774// If there are not enough elements present in 'consts', 0 will be substituted;
7775// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
7776//
qining08408382016-03-21 09:51:37 -04007777spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06007778{
7779 // vector of constants for SPIR-V
7780 std::vector<spv::Id> spvConsts;
7781
7782 // Type is used for struct and array constants
7783 spv::Id typeId = convertGlslangToSpvType(glslangType);
7784
7785 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007786 glslang::TType elementType(glslangType, 0);
7787 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04007788 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007789 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007790 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06007791 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04007792 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007793 } else if (glslangType.isCoopMat()) {
7794 glslang::TType componentType(glslangType.getBasicType());
7795 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007796 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007797 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
7798 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04007799 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06007800 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06007801 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
7802 bool zero = nextConst >= consts.size();
7803 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007804 case glslang::EbtInt8:
7805 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
7806 break;
7807 case glslang::EbtUint8:
7808 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
7809 break;
7810 case glslang::EbtInt16:
7811 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
7812 break;
7813 case glslang::EbtUint16:
7814 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
7815 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007816 case glslang::EbtInt:
7817 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
7818 break;
7819 case glslang::EbtUint:
7820 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
7821 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007822 case glslang::EbtInt64:
7823 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
7824 break;
7825 case glslang::EbtUint64:
7826 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
7827 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007828 case glslang::EbtFloat:
7829 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7830 break;
7831 case glslang::EbtDouble:
7832 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
7833 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007834 case glslang::EbtFloat16:
7835 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7836 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007837 case glslang::EbtBool:
7838 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7839 break;
7840 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007841 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007842 break;
7843 }
7844 ++nextConst;
7845 }
7846 } else {
7847 // we have a non-aggregate (scalar) constant
7848 bool zero = nextConst >= consts.size();
7849 spv::Id scalar = 0;
7850 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007851 case glslang::EbtInt8:
7852 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
7853 break;
7854 case glslang::EbtUint8:
7855 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
7856 break;
7857 case glslang::EbtInt16:
7858 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
7859 break;
7860 case glslang::EbtUint16:
7861 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
7862 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007863 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07007864 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007865 break;
7866 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07007867 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007868 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007869 case glslang::EbtInt64:
7870 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
7871 break;
7872 case glslang::EbtUint64:
7873 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7874 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007875 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07007876 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007877 break;
7878 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07007879 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007880 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007881 case glslang::EbtFloat16:
7882 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7883 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007884 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07007885 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007886 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06007887 case glslang::EbtReference:
7888 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7889 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
7890 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007891 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007892 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007893 break;
7894 }
7895 ++nextConst;
7896 return scalar;
7897 }
7898
7899 return builder.makeCompositeConstant(typeId, spvConsts);
7900}
7901
John Kessenich7c1aa102015-10-15 13:29:11 -06007902// Return true if the node is a constant or symbol whose reading has no
7903// non-trivial observable cost or effect.
7904bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
7905{
7906 // don't know what this is
7907 if (node == nullptr)
7908 return false;
7909
7910 // a constant is safe
7911 if (node->getAsConstantUnion() != nullptr)
7912 return true;
7913
7914 // not a symbol means non-trivial
7915 if (node->getAsSymbolNode() == nullptr)
7916 return false;
7917
7918 // a symbol, depends on what's being read
7919 switch (node->getType().getQualifier().storage) {
7920 case glslang::EvqTemporary:
7921 case glslang::EvqGlobal:
7922 case glslang::EvqIn:
7923 case glslang::EvqInOut:
7924 case glslang::EvqConst:
7925 case glslang::EvqConstReadOnly:
7926 case glslang::EvqUniform:
7927 return true;
7928 default:
7929 return false;
7930 }
qining25262b32016-05-06 17:25:16 -04007931}
John Kessenich7c1aa102015-10-15 13:29:11 -06007932
7933// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06007934// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06007935// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06007936// Return true if trivial.
7937bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
7938{
7939 if (node == nullptr)
7940 return false;
7941
John Kessenich84cc15f2017-05-24 16:44:47 -06007942 // count non scalars as trivial, as well as anything coming from HLSL
7943 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06007944 return true;
7945
John Kessenich7c1aa102015-10-15 13:29:11 -06007946 // symbols and constants are trivial
7947 if (isTrivialLeaf(node))
7948 return true;
7949
7950 // otherwise, it needs to be a simple operation or one or two leaf nodes
7951
7952 // not a simple operation
7953 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
7954 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
7955 if (binaryNode == nullptr && unaryNode == nullptr)
7956 return false;
7957
7958 // not on leaf nodes
7959 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
7960 return false;
7961
7962 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
7963 return false;
7964 }
7965
7966 switch (node->getAsOperator()->getOp()) {
7967 case glslang::EOpLogicalNot:
7968 case glslang::EOpConvIntToBool:
7969 case glslang::EOpConvUintToBool:
7970 case glslang::EOpConvFloatToBool:
7971 case glslang::EOpConvDoubleToBool:
7972 case glslang::EOpEqual:
7973 case glslang::EOpNotEqual:
7974 case glslang::EOpLessThan:
7975 case glslang::EOpGreaterThan:
7976 case glslang::EOpLessThanEqual:
7977 case glslang::EOpGreaterThanEqual:
7978 case glslang::EOpIndexDirect:
7979 case glslang::EOpIndexDirectStruct:
7980 case glslang::EOpLogicalXor:
7981 case glslang::EOpAny:
7982 case glslang::EOpAll:
7983 return true;
7984 default:
7985 return false;
7986 }
7987}
7988
7989// Emit short-circuiting code, where 'right' is never evaluated unless
7990// the left side is true (for &&) or false (for ||).
7991spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
7992{
7993 spv::Id boolTypeId = builder.makeBoolType();
7994
7995 // emit left operand
7996 builder.clearAccessChain();
7997 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007998 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007999
8000 // Operands to accumulate OpPhi operands
8001 std::vector<spv::Id> phiOperands;
8002 // accumulate left operand's phi information
8003 phiOperands.push_back(leftId);
8004 phiOperands.push_back(builder.getBuildPoint()->getId());
8005
8006 // Make the two kinds of operation symmetric with a "!"
8007 // || => emit "if (! left) result = right"
8008 // && => emit "if ( left) result = right"
8009 //
8010 // TODO: this runtime "not" for || could be avoided by adding functionality
8011 // to 'builder' to have an "else" without an "then"
8012 if (op == glslang::EOpLogicalOr)
8013 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8014
8015 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008016 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008017
8018 // emit right operand as the "then" part of the "if"
8019 builder.clearAccessChain();
8020 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008021 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008022
8023 // accumulate left operand's phi information
8024 phiOperands.push_back(rightId);
8025 phiOperands.push_back(builder.getBuildPoint()->getId());
8026
8027 // finish the "if"
8028 ifBuilder.makeEndIf();
8029
8030 // phi together the two results
8031 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8032}
8033
Frank Henigman541f7bb2018-01-16 00:18:26 -05008034#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08008035// Return type Id of the imported set of extended instructions corresponds to the name.
8036// Import this set if it has not been imported yet.
8037spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8038{
8039 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8040 return extBuiltinMap[name];
8041 else {
Rex Xu51596642016-09-21 18:56:12 +08008042 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008043 spv::Id extBuiltins = builder.import(name);
8044 extBuiltinMap[name] = extBuiltins;
8045 return extBuiltins;
8046 }
8047}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008048#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008049
John Kessenich140f3df2015-06-26 16:58:36 -06008050}; // end anonymous namespace
8051
8052namespace glslang {
8053
John Kessenich68d78fd2015-07-12 19:28:10 -06008054void GetSpirvVersion(std::string& version)
8055{
John Kessenich9e55f632015-07-15 10:03:39 -06008056 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008057 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008058 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008059 version = buf;
8060}
8061
John Kessenicha372a3e2017-11-02 22:32:14 -06008062// For low-order part of the generator's magic number. Bump up
8063// when there is a change in the style (e.g., if SSA form changes,
8064// or a different instruction sequence to do something gets used).
8065int GetSpirvGeneratorVersion()
8066{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008067 // return 1; // start
8068 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008069 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008070 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008071 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008072 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8073 // versions 4 and 6 each generate OpArrayLength as it has long been done
8074 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06008075}
8076
John Kessenich140f3df2015-06-26 16:58:36 -06008077// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008078void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008079{
8080 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008081 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008082 if (out.fail())
8083 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008084 for (int i = 0; i < (int)spirv.size(); ++i) {
8085 unsigned int word = spirv[i];
8086 out.write((const char*)&word, 4);
8087 }
8088 out.close();
8089}
8090
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008091// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008092void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008093{
8094 std::ofstream out;
8095 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008096 if (out.fail())
8097 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07008098 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06008099 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07008100 std::endl;
Flavio15017db2017-02-15 14:29:33 -08008101 if (varName != nullptr) {
8102 out << "\t #pragma once" << std::endl;
8103 out << "const uint32_t " << varName << "[] = {" << std::endl;
8104 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008105 const int WORDS_PER_LINE = 8;
8106 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8107 out << "\t";
8108 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8109 const unsigned int word = spirv[i + j];
8110 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8111 if (i + j + 1 < (int)spirv.size()) {
8112 out << ",";
8113 }
8114 }
8115 out << std::endl;
8116 }
Flavio15017db2017-02-15 14:29:33 -08008117 if (varName != nullptr) {
8118 out << "};";
8119 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008120 out.close();
8121}
8122
John Kessenich140f3df2015-06-26 16:58:36 -06008123//
8124// Set up the glslang traversal
8125//
John Kessenich4e11b612018-08-30 16:56:59 -06008126void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008127{
Lei Zhang17535f72016-05-04 15:55:59 -04008128 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008129 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008130}
8131
John Kessenich4e11b612018-08-30 16:56:59 -06008132void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008133 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008134{
John Kessenich140f3df2015-06-26 16:58:36 -06008135 TIntermNode* root = intermediate.getTreeRoot();
8136
8137 if (root == 0)
8138 return;
8139
John Kessenich4e11b612018-08-30 16:56:59 -06008140 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008141 if (options == nullptr)
8142 options = &defaultOptions;
8143
John Kessenich4e11b612018-08-30 16:56:59 -06008144 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008145
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008146 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008147 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008148 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008149 it.dumpSpv(spirv);
8150
GregFfb03a552018-03-29 11:49:14 -06008151#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008152 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8153 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008154 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
8155 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer) {
John Kesseniche7df8e02018-08-22 17:12:46 -06008156 SpirvToolsLegalize(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008157 prelegalization = false;
8158 }
John Kessenich717c80a2018-08-23 15:17:10 -06008159
John Kessenich4e11b612018-08-30 16:56:59 -06008160 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008161 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008162
John Kessenich717c80a2018-08-23 15:17:10 -06008163 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008164 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008165
GregFcd1f1692017-09-21 18:40:22 -06008166#endif
8167
John Kessenich4e11b612018-08-30 16:56:59 -06008168 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008169}
8170
8171}; // end namespace glslang