blob: 3633c5b8230cb41f39564f07b8aca5c49a0c9929 [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:
3082 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003083 }
3084 }
Rex Xuf89ad982017-04-07 23:22:33 +08003085
John Kessenich312dcfb2018-07-03 13:19:51 -06003086 const bool contains8BitType = node->getType().containsBasicType(glslang::EbtInt8) ||
3087 node->getType().containsBasicType(glslang::EbtUint8);
3088 if (contains8BitType) {
3089 if (storageClass == spv::StorageClassPushConstant) {
3090 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3091 builder.addCapability(spv::CapabilityStoragePushConstant8);
3092 } else if (storageClass == spv::StorageClassUniform) {
3093 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3094 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003095 } else if (storageClass == spv::StorageClassStorageBuffer) {
3096 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3097 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
John Kessenich312dcfb2018-07-03 13:19:51 -06003098 }
3099 }
3100
John Kessenich140f3df2015-06-26 16:58:36 -06003101 const char* name = node->getName().c_str();
3102 if (glslang::IsAnonymous(name))
3103 name = "";
3104
3105 return builder.createVariable(storageClass, spvType, name);
3106}
3107
3108// Return type Id of the sampled type.
3109spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3110{
3111 switch (sampler.type) {
3112 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08003113#ifdef AMD_EXTENSIONS
3114 case glslang::EbtFloat16:
3115 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3116 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3117 return builder.makeFloatType(16);
3118#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003119 case glslang::EbtInt: return builder.makeIntType(32);
3120 case glslang::EbtUint: return builder.makeUintType(32);
3121 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003122 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003123 return builder.makeFloatType(32);
3124 }
3125}
3126
John Kessenich8c8505c2016-07-26 12:50:38 -06003127// If node is a swizzle operation, return the type that should be used if
3128// the swizzle base is first consumed by another operation, before the swizzle
3129// is applied.
3130spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3131{
John Kessenichecba76f2017-01-06 00:34:48 -07003132 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003133 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3134 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3135 else
3136 return spv::NoType;
3137}
3138
3139// When inverting a swizzle with a parent op, this function
3140// will apply the swizzle operation to a completed parent operation.
3141spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
3142{
3143 std::vector<unsigned> swizzle;
3144 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3145 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3146}
3147
John Kessenich8c8505c2016-07-26 12:50:38 -06003148// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3149void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3150{
3151 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3152 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3153 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3154}
3155
John Kessenich3ac051e2015-12-20 11:29:16 -07003156// Convert from a glslang type to an SPV type, by calling into a
3157// recursive version of this function. This establishes the inherited
3158// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003159spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003160{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003161 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003162}
3163
3164// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003165// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003166// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003167spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003168 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3169 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003170{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003171 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003172
3173 switch (type.getBasicType()) {
3174 case glslang::EbtVoid:
3175 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003176 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003177 break;
3178 case glslang::EbtFloat:
3179 spvType = builder.makeFloatType(32);
3180 break;
3181 case glslang::EbtDouble:
3182 spvType = builder.makeFloatType(64);
3183 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003184 case glslang::EbtFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003185 spvType = builder.makeFloatType(16);
3186 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003187 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003188 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3189 // a 32-bit int where non-0 means true.
3190 if (explicitLayout != glslang::ElpNone)
3191 spvType = builder.makeUintType(32);
3192 else
3193 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003194 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003195 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003196 spvType = builder.makeIntType(8);
3197 break;
3198 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003199 spvType = builder.makeUintType(8);
3200 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003201 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003202 spvType = builder.makeIntType(16);
3203 break;
3204 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003205 spvType = builder.makeUintType(16);
3206 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003207 case glslang::EbtInt:
3208 spvType = builder.makeIntType(32);
3209 break;
3210 case glslang::EbtUint:
3211 spvType = builder.makeUintType(32);
3212 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003213 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003214 spvType = builder.makeIntType(64);
3215 break;
3216 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003217 spvType = builder.makeUintType(64);
3218 break;
John Kessenich426394d2015-07-23 10:22:48 -06003219 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003220 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003221 spvType = builder.makeUintType(32);
3222 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003223#ifdef NV_EXTENSIONS
3224 case glslang::EbtAccStructNV:
3225 spvType = builder.makeAccelerationStructureNVType();
3226 break;
3227#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003228 case glslang::EbtSampler:
3229 {
3230 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07003231 if (sampler.sampler) {
3232 // pure sampler
3233 spvType = builder.makeSamplerType();
3234 } else {
3235 // an image is present, make its type
3236 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
3237 sampler.image ? 2 : 1, TranslateImageFormat(type));
3238 if (sampler.combined) {
3239 // already has both image and sampler, make the combined type
3240 spvType = builder.makeSampledImageType(spvType);
3241 }
John Kessenich55e7d112015-11-15 21:33:39 -07003242 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003243 }
John Kessenich140f3df2015-06-26 16:58:36 -06003244 break;
3245 case glslang::EbtStruct:
3246 case glslang::EbtBlock:
3247 {
3248 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003249 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003250
3251 // Try to share structs for different layouts, but not yet for other
3252 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003253 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003254 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003255 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003256 break;
3257
3258 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003259 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06003260 memberRemapper[glslangMembers].resize(glslangMembers->size());
3261 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003262 }
3263 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003264 case glslang::EbtReference:
3265 {
3266 // Make the forward pointer, then recurse to convert the structure type, then
3267 // patch up the forward pointer with a real pointer type.
3268 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3269 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3270 forwardPointers[type.getReferentType()] = forwardId;
3271 }
3272 spvType = forwardPointers[type.getReferentType()];
3273 if (!forwardReferenceOnly) {
3274 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3275 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3276 forwardPointers[type.getReferentType()],
3277 referentType);
3278 }
3279 }
3280 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003281 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003282 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003283 break;
3284 }
3285
3286 if (type.isMatrix())
3287 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3288 else {
3289 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3290 if (type.getVectorSize() > 1)
3291 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3292 }
3293
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003294 if (type.isCoopMat()) {
3295 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3296 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3297 if (type.getBasicType() == glslang::EbtFloat16)
3298 builder.addCapability(spv::CapabilityFloat16);
3299
3300 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3301 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3302 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3303
3304 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3305 }
3306
John Kessenich140f3df2015-06-26 16:58:36 -06003307 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003308 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3309
John Kessenichc9a80832015-09-12 12:17:44 -06003310 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003311 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003312 // We need to decorate array strides for types needing explicit layout, except blocks.
3313 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003314 // Use a dummy glslang type for querying internal strides of
3315 // arrays of arrays, but using just a one-dimensional array.
3316 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003317 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3318 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003319
3320 // Will compute the higher-order strides here, rather than making a whole
3321 // pile of types and doing repetitive recursion on their contents.
3322 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3323 }
John Kessenichf8842e52016-01-04 19:22:56 -07003324
3325 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003326 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003327 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003328 if (stride > 0)
3329 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003330 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003331 }
3332 } else {
3333 // single-dimensional array, and don't yet have stride
3334
John Kessenichf8842e52016-01-04 19:22:56 -07003335 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003336 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3337 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003338 }
John Kessenich31ed4832015-09-09 17:51:38 -06003339
John Kessenichead86222018-03-28 18:01:20 -06003340 // Do the outer dimension, which might not be known for a runtime-sized array.
3341 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3342 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003343 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003344 else {
3345 if (!lastBufferBlockMember) {
3346 builder.addExtension("SPV_EXT_descriptor_indexing");
3347 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3348 }
John Kessenichead86222018-03-28 18:01:20 -06003349 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003350 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003351 if (stride > 0)
3352 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003353 }
3354
3355 return spvType;
3356}
3357
John Kessenich0e737842017-03-24 18:38:16 -06003358// TODO: this functionality should exist at a higher level, in creating the AST
3359//
3360// Identify interface members that don't have their required extension turned on.
3361//
3362bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3363{
Chao Chen3c366992018-09-19 11:41:59 -07003364#ifdef NV_EXTENSIONS
John Kessenich0e737842017-03-24 18:38:16 -06003365 auto& extensions = glslangIntermediate->getRequestedExtensions();
3366
Rex Xubcf291a2017-03-29 23:01:36 +08003367 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3368 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3369 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003370 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3371 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3372 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003373
3374 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3375 if (member.getFieldName() == "gl_ViewportMask" &&
3376 extensions.find("GL_NV_viewport_array2") == extensions.end())
3377 return true;
3378 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3379 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3380 return true;
3381 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3382 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3383 return true;
3384 }
3385#endif
John Kessenich0e737842017-03-24 18:38:16 -06003386
3387 return false;
3388};
3389
John Kessenich6090df02016-06-30 21:18:02 -06003390// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3391// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3392// Mutually recursive with convertGlslangToSpvType().
3393spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3394 const glslang::TTypeList* glslangMembers,
3395 glslang::TLayoutPacking explicitLayout,
3396 const glslang::TQualifier& qualifier)
3397{
3398 // Create a vector of struct types for SPIR-V to consume
3399 std::vector<spv::Id> spvMembers;
3400 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 -06003401 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003402 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3403 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3404 if (glslangMember.hiddenMember()) {
3405 ++memberDelta;
3406 if (type.getBasicType() == glslang::EbtBlock)
3407 memberRemapper[glslangMembers][i] = -1;
3408 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003409 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003410 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003411 if (filterMember(glslangMember))
3412 continue;
3413 }
John Kessenich6090df02016-06-30 21:18:02 -06003414 // modify just this child's view of the qualifier
3415 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3416 InheritQualifiers(memberQualifier, qualifier);
3417
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003418 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003419 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003420 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003421
3422 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003423 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3424 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003425
3426 // Make forward pointers for any pointer members, and create a list of members to
3427 // convert to spirv types after creating the struct.
3428 if (glslangMember.getBasicType() == glslang::EbtReference) {
3429 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3430 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3431 }
3432 spvMembers.push_back(
3433 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, true));
3434 } else {
3435 spvMembers.push_back(
3436 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, false));
3437 }
John Kessenich6090df02016-06-30 21:18:02 -06003438 }
3439 }
3440
3441 // Make the SPIR-V type
3442 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003443 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003444 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3445
3446 // Decorate it
3447 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3448
John Kessenichd72f4882019-01-16 14:55:37 +07003449 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003450 auto it = deferredForwardPointers[i];
3451 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3452 }
3453
John Kessenich6090df02016-06-30 21:18:02 -06003454 return spvType;
3455}
3456
3457void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3458 const glslang::TTypeList* glslangMembers,
3459 glslang::TLayoutPacking explicitLayout,
3460 const glslang::TQualifier& qualifier,
3461 spv::Id spvType)
3462{
3463 // Name and decorate the non-hidden members
3464 int offset = -1;
3465 int locationOffset = 0; // for use within the members of this struct
3466 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3467 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3468 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003469 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003470 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06003471 if (filterMember(glslangMember))
3472 continue;
3473 }
John Kessenich6090df02016-06-30 21:18:02 -06003474
3475 // modify just this child's view of the qualifier
3476 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3477 InheritQualifiers(memberQualifier, qualifier);
3478
3479 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003480 if (member < 0)
3481 continue;
3482
3483 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3484 builder.addMemberDecoration(spvType, member,
3485 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3486 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3487 // Add interpolation and auxiliary storage decorations only to
3488 // top-level members of Input and Output storage classes
3489 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3490 type.getQualifier().storage == glslang::EvqVaryingOut) {
3491 if (type.getBasicType() == glslang::EbtBlock ||
3492 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3493 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3494 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
Chao Chen3c366992018-09-19 11:41:59 -07003495#ifdef NV_EXTENSIONS
3496 addMeshNVDecoration(spvType, member, memberQualifier);
3497#endif
John Kessenich6090df02016-06-30 21:18:02 -06003498 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003499 }
3500 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003501
John Kessenich5d610ee2018-03-07 18:05:55 -07003502 if (type.getBasicType() == glslang::EbtBlock &&
3503 qualifier.storage == glslang::EvqBuffer) {
3504 // Add memory decorations only to top-level members of shader storage block
3505 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003506 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003507 for (unsigned int i = 0; i < memory.size(); ++i)
3508 builder.addMemberDecoration(spvType, member, memory[i]);
3509 }
John Kessenich6090df02016-06-30 21:18:02 -06003510
John Kessenich5d610ee2018-03-07 18:05:55 -07003511 // Location assignment was already completed correctly by the front end,
3512 // just track whether a member needs to be decorated.
3513 // Ignore member locations if the container is an array, as that's
3514 // ill-specified and decisions have been made to not allow this.
3515 if (! type.isArray() && memberQualifier.hasLocation())
3516 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003517
John Kessenich5d610ee2018-03-07 18:05:55 -07003518 if (qualifier.hasLocation()) // track for upcoming inheritance
3519 locationOffset += glslangIntermediate->computeTypeLocationSize(
3520 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003521
John Kessenich5d610ee2018-03-07 18:05:55 -07003522 // component, XFB, others
3523 if (glslangMember.getQualifier().hasComponent())
3524 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3525 glslangMember.getQualifier().layoutComponent);
3526 if (glslangMember.getQualifier().hasXfbOffset())
3527 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3528 glslangMember.getQualifier().layoutXfbOffset);
3529 else if (explicitLayout != glslang::ElpNone) {
3530 // figure out what to do with offset, which is accumulating
3531 int nextOffset;
3532 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3533 if (offset >= 0)
3534 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3535 offset = nextOffset;
3536 }
John Kessenich6090df02016-06-30 21:18:02 -06003537
John Kessenich5d610ee2018-03-07 18:05:55 -07003538 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3539 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3540 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003541
John Kessenich5d610ee2018-03-07 18:05:55 -07003542 // built-in variable decorations
3543 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3544 if (builtIn != spv::BuiltInMax)
3545 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003546
John Kessenich5611c6d2018-04-05 11:25:02 -06003547 // nonuniform
3548 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3549
John Kessenichead86222018-03-28 18:01:20 -06003550 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3551 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3552 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3553 memberQualifier.semanticName);
3554 }
3555
chaoc771d89f2017-01-13 01:10:53 -08003556#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07003557 if (builtIn == spv::BuiltInLayer) {
3558 // SPV_NV_viewport_array2 extension
3559 if (glslangMember.getQualifier().layoutViewportRelative){
3560 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3561 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3562 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003563 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003564 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3565 builder.addMemberDecoration(spvType, member,
3566 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3567 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3568 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3569 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003570 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003571 }
3572 if (glslangMember.getQualifier().layoutPassthrough) {
3573 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3574 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3575 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3576 }
chaoc771d89f2017-01-13 01:10:53 -08003577#endif
John Kessenich6090df02016-06-30 21:18:02 -06003578 }
3579
3580 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003581 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3582 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003583}
3584
John Kessenich6c292d32016-02-15 20:58:50 -07003585// Turn the expression forming the array size into an id.
3586// This is not quite trivial, because of specialization constants.
3587// Sometimes, a raw constant is turned into an Id, and sometimes
3588// a specialization constant expression is.
3589spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3590{
3591 // First, see if this is sized with a node, meaning a specialization constant:
3592 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3593 if (specNode != nullptr) {
3594 builder.clearAccessChain();
3595 specNode->traverse(this);
3596 return accessChainLoad(specNode->getAsTyped()->getType());
3597 }
qining25262b32016-05-06 17:25:16 -04003598
John Kessenich6c292d32016-02-15 20:58:50 -07003599 // Otherwise, need a compile-time (front end) size, get it:
3600 int size = arraySizes.getDimSize(dim);
3601 assert(size > 0);
3602 return builder.makeUintConstant(size);
3603}
3604
John Kessenich103bef92016-02-08 21:38:15 -07003605// Wrap the builder's accessChainLoad to:
3606// - localize handling of RelaxedPrecision
3607// - use the SPIR-V inferred type instead of another conversion of the glslang type
3608// (avoids unnecessary work and possible type punning for structures)
3609// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003610spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3611{
John Kessenich103bef92016-02-08 21:38:15 -07003612 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003613
3614 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3615 coherentFlags |= TranslateCoherent(type);
3616
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003617 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003618 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003619
John Kessenich5611c6d2018-04-05 11:25:02 -06003620 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003621 TranslateNonUniformDecoration(type.getQualifier()),
3622 nominalTypeId,
3623 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003624 TranslateMemoryScope(coherentFlags),
3625 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07003626
3627 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003628 if (type.getBasicType() == glslang::EbtBool) {
3629 if (builder.isScalarType(nominalTypeId)) {
3630 // Conversion for bool
3631 spv::Id boolType = builder.makeBoolType();
3632 if (nominalTypeId != boolType)
3633 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3634 } else if (builder.isVectorType(nominalTypeId)) {
3635 // Conversion for bvec
3636 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3637 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3638 if (nominalTypeId != bvecType)
3639 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3640 }
3641 }
John Kessenich103bef92016-02-08 21:38:15 -07003642
3643 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003644}
3645
Rex Xu27253232016-02-23 17:51:09 +08003646// Wrap the builder's accessChainStore to:
3647// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003648//
3649// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003650void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3651{
3652 // Need to convert to abstract types when necessary
3653 if (type.getBasicType() == glslang::EbtBool) {
3654 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3655
3656 if (builder.isScalarType(nominalTypeId)) {
3657 // Conversion for bool
3658 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003659 if (nominalTypeId != boolType) {
3660 // keep these outside arguments, for determinant order-of-evaluation
3661 spv::Id one = builder.makeUintConstant(1);
3662 spv::Id zero = builder.makeUintConstant(0);
3663 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3664 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003665 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003666 } else if (builder.isVectorType(nominalTypeId)) {
3667 // Conversion for bvec
3668 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3669 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003670 if (nominalTypeId != bvecType) {
3671 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003672 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3673 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3674 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003675 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003676 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3677 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003678 }
3679 }
3680
Jeff Bolz36831c92018-09-05 10:11:41 -05003681 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3682 coherentFlags |= TranslateCoherent(type);
3683
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003684 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003685 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003686
Jeff Bolz36831c92018-09-05 10:11:41 -05003687 builder.accessChainStore(rvalue,
3688 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003689 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08003690}
3691
John Kessenich4bf71552016-09-02 11:20:21 -06003692// For storing when types match at the glslang level, but not might match at the
3693// SPIR-V level.
3694//
3695// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003696// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003697// as in a member-decorated way.
3698//
3699// NOTE: This function can handle any store request; if it's not special it
3700// simplifies to a simple OpStore.
3701//
3702// Implicitly uses the existing builder.accessChain as the storage target.
3703void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3704{
John Kessenichb3e24e42016-09-11 12:33:43 -06003705 // we only do the complex path here if it's an aggregate
3706 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003707 accessChainStore(type, rValue);
3708 return;
3709 }
3710
John Kessenichb3e24e42016-09-11 12:33:43 -06003711 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003712 spv::Id rType = builder.getTypeId(rValue);
3713 spv::Id lValue = builder.accessChainGetLValue();
3714 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3715 if (lType == rType) {
3716 accessChainStore(type, rValue);
3717 return;
3718 }
3719
John Kessenichb3e24e42016-09-11 12:33:43 -06003720 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003721 // where the two types were the same type in GLSL. This requires member
3722 // by member copy, recursively.
3723
John Kessenichfbb6bdf2019-01-15 21:48:27 +07003724 // SPIR-V 1.4 added an instruction to do help do this.
3725 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
3726 // However, bool in uniform space is changed to int, so
3727 // OpCopyLogical does not work for that.
3728 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
3729 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
3730 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
3731 if (lBool == rBool) {
3732 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
3733 accessChainStore(type, logicalCopy);
3734 return;
3735 }
3736 }
3737
John Kessenichb3e24e42016-09-11 12:33:43 -06003738 // If an array, copy element by element.
3739 if (type.isArray()) {
3740 glslang::TType glslangElementType(type, 0);
3741 spv::Id elementRType = builder.getContainedTypeId(rType);
3742 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3743 // get the source member
3744 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003745
John Kessenichb3e24e42016-09-11 12:33:43 -06003746 // set up the target storage
3747 builder.clearAccessChain();
3748 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003749 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06003750
John Kessenichb3e24e42016-09-11 12:33:43 -06003751 // store the member
3752 multiTypeStore(glslangElementType, elementRValue);
3753 }
3754 } else {
3755 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003756
John Kessenichb3e24e42016-09-11 12:33:43 -06003757 // loop over structure members
3758 const glslang::TTypeList& members = *type.getStruct();
3759 for (int m = 0; m < (int)members.size(); ++m) {
3760 const glslang::TType& glslangMemberType = *members[m].type;
3761
3762 // get the source member
3763 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3764 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3765
3766 // set up the target storage
3767 builder.clearAccessChain();
3768 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003769 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06003770
3771 // store the member
3772 multiTypeStore(glslangMemberType, memberRValue);
3773 }
John Kessenich4bf71552016-09-02 11:20:21 -06003774 }
3775}
3776
John Kessenichf85e8062015-12-19 13:57:10 -07003777// Decide whether or not this type should be
3778// decorated with offsets and strides, and if so
3779// whether std140 or std430 rules should be applied.
3780glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003781{
John Kessenichf85e8062015-12-19 13:57:10 -07003782 // has to be a block
3783 if (type.getBasicType() != glslang::EbtBlock)
3784 return glslang::ElpNone;
3785
Chao Chen3c366992018-09-19 11:41:59 -07003786 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07003787 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07003788 type.getQualifier().storage != glslang::EvqBuffer &&
3789 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07003790 return glslang::ElpNone;
3791
3792 // return the layout to use
3793 switch (type.getQualifier().layoutPacking) {
3794 case glslang::ElpStd140:
3795 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003796 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07003797 return type.getQualifier().layoutPacking;
3798 default:
3799 return glslang::ElpNone;
3800 }
John Kessenich31ed4832015-09-09 17:51:38 -06003801}
3802
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003803// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003804int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003805{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003806 int size;
John Kessenich49987892015-12-29 17:11:44 -07003807 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003808 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003809
3810 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003811}
3812
John Kessenich49987892015-12-29 17:11:44 -07003813// 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 -07003814// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003815int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003816{
John Kessenich49987892015-12-29 17:11:44 -07003817 glslang::TType elementType;
3818 elementType.shallowCopy(matrixType);
3819 elementType.clearArraySizes();
3820
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003821 int size;
John Kessenich49987892015-12-29 17:11:44 -07003822 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003823 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07003824
3825 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003826}
3827
John Kessenich5e4b1242015-08-06 22:53:06 -06003828// Given a member type of a struct, realign the current offset for it, and compute
3829// the next (not yet aligned) offset for the next member, which will get aligned
3830// on the next call.
3831// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3832// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3833// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003834void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003835 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003836{
3837 // this will get a positive value when deemed necessary
3838 nextOffset = -1;
3839
John Kessenich5e4b1242015-08-06 22:53:06 -06003840 // override anything in currentOffset with user-set offset
3841 if (memberType.getQualifier().hasOffset())
3842 currentOffset = memberType.getQualifier().layoutOffset;
3843
3844 // It could be that current linker usage in glslang updated all the layoutOffset,
3845 // in which case the following code does not matter. But, that's not quite right
3846 // once cross-compilation unit GLSL validation is done, as the original user
3847 // settings are needed in layoutOffset, and then the following will come into play.
3848
John Kessenichf85e8062015-12-19 13:57:10 -07003849 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003850 if (! memberType.getQualifier().hasOffset())
3851 currentOffset = -1;
3852
3853 return;
3854 }
3855
John Kessenichf85e8062015-12-19 13:57:10 -07003856 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003857 if (currentOffset < 0)
3858 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003859
John Kessenich5e4b1242015-08-06 22:53:06 -06003860 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3861 // but possibly not yet correctly aligned.
3862
3863 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003864 int dummyStride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003865 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003866
3867 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003868 // TODO: make this consistent in early phases of code:
3869 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3870 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3871 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06003872 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06003873 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06003874 int dummySize;
3875 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
3876 if (componentAlignment <= 4)
3877 memberAlignment = componentAlignment;
3878 }
3879
3880 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06003881 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06003882
3883 // Bump up to vec4 if there is a bad straddle
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003884 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06003885 glslang::RoundToPow2(currentOffset, 16);
3886
John Kessenich5e4b1242015-08-06 22:53:06 -06003887 nextOffset = currentOffset + memberSize;
3888}
3889
David Netoa901ffe2016-06-08 14:11:40 +01003890void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06003891{
David Netoa901ffe2016-06-08 14:11:40 +01003892 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3893 switch (glslangBuiltIn)
3894 {
3895 case glslang::EbvClipDistance:
3896 case glslang::EbvCullDistance:
3897 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003898#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003899 case glslang::EbvViewportMaskNV:
3900 case glslang::EbvSecondaryPositionNV:
3901 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003902 case glslang::EbvPositionPerViewNV:
3903 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07003904 case glslang::EbvTaskCountNV:
3905 case glslang::EbvPrimitiveCountNV:
3906 case glslang::EbvPrimitiveIndicesNV:
3907 case glslang::EbvClipDistancePerViewNV:
3908 case glslang::EbvCullDistancePerViewNV:
3909 case glslang::EbvLayerPerViewNV:
3910 case glslang::EbvMeshViewCountNV:
3911 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08003912#endif
David Netoa901ffe2016-06-08 14:11:40 +01003913 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
3914 // Alternately, we could just call this for any glslang built-in, since the
3915 // capability already guards against duplicates.
3916 TranslateBuiltInDecoration(glslangBuiltIn, false);
3917 break;
3918 default:
3919 // Capabilities were already generated when the struct was declared.
3920 break;
3921 }
John Kessenichebb50532016-05-16 19:22:05 -06003922}
3923
John Kessenich6fccb3c2016-09-19 16:01:41 -06003924bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06003925{
John Kessenicheee9d532016-09-19 18:09:30 -06003926 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003927}
3928
John Kessenichd41993d2017-09-10 15:21:05 -06003929// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07003930// Assumes called after originalParam(), which filters out block/buffer/opaque-based
3931// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06003932bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06003933{
John Kessenich6a14f782017-12-04 02:48:10 -07003934 assert(qualifier == glslang::EvqIn ||
3935 qualifier == glslang::EvqOut ||
3936 qualifier == glslang::EvqInOut ||
3937 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06003938 return qualifier != glslang::EvqConstReadOnly;
3939}
3940
3941// Is parameter pass-by-original?
3942bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3943 bool implicitThisParam)
3944{
3945 if (implicitThisParam) // implicit this
3946 return true;
3947 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003948 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003949 return paramType.containsOpaque() || // sampler, etc.
3950 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3951}
3952
John Kessenich140f3df2015-06-26 16:58:36 -06003953// Make all the functions, skeletally, without actually visiting their bodies.
3954void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3955{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003956 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06003957 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3958 if (paramPrecision != spv::NoPrecision)
3959 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05003960 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003961 if (type.getBasicType() == glslang::EbtReference) {
3962 // Original and non-writable params pass the pointer directly and
3963 // use restrict/aliased, others are stored to a pointer in Function
3964 // memory and use RestrictPointer/AliasedPointer.
3965 if (originalParam(type.getQualifier().storage, type, false) ||
3966 !writableParam(type.getQualifier().storage)) {
3967 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrict : spv::DecorationAliased);
3968 } else {
3969 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
3970 }
3971 }
John Kessenichfad62972017-07-18 02:35:46 -06003972 };
3973
John Kessenich140f3df2015-06-26 16:58:36 -06003974 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3975 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003976 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003977 continue;
3978
3979 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003980 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003981 //
qining25262b32016-05-06 17:25:16 -04003982 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003983 // function. What it is an address of varies:
3984 //
John Kessenich4bf71552016-09-02 11:20:21 -06003985 // - "in" parameters not marked as "const" can be written to without modifying the calling
3986 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003987 //
3988 // - "const in" parameters can just be the r-value, as no writes need occur.
3989 //
John Kessenich4bf71552016-09-02 11:20:21 -06003990 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3991 // 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 -06003992
3993 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003994 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003995 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3996
John Kessenichfad62972017-07-18 02:35:46 -06003997 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3998 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003999
John Kessenichfad62972017-07-18 02:35:46 -06004000 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004001 for (int p = 0; p < (int)parameters.size(); ++p) {
4002 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4003 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004004 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004005 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004006 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004007 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4008 else
John Kessenich4bf71552016-09-02 11:20:21 -06004009 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004010 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004011 paramTypes.push_back(typeId);
4012 }
4013
4014 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004015 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4016 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004017 glslFunction->getName().c_str(), paramTypes,
4018 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004019 if (implicitThis)
4020 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004021
4022 // Track function to emit/call later
4023 functionMap[glslFunction->getName().c_str()] = function;
4024
4025 // Set the parameter id's
4026 for (int p = 0; p < (int)parameters.size(); ++p) {
4027 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4028 // give a name too
4029 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
4030 }
4031 }
4032}
4033
4034// Process all the initializers, while skipping the functions and link objects
4035void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4036{
4037 builder.setBuildPoint(shaderEntry->getLastBlock());
4038 for (int i = 0; i < (int)initializers.size(); ++i) {
4039 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
4040 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
4041
4042 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004043 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004044 initializer->traverse(this);
4045 }
4046 }
4047}
4048
4049// Process all the functions, while skipping initializers.
4050void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4051{
4052 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4053 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004054 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004055 node->traverse(this);
4056 }
4057}
4058
4059void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4060{
qining25262b32016-05-06 17:25:16 -04004061 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004062 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004063 currentFunction = functionMap[node->getName().c_str()];
4064 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004065 builder.setBuildPoint(functionBlock);
4066}
4067
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004068void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments, spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004069{
Rex Xufc618912015-09-09 16:42:49 +08004070 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004071
4072 glslang::TSampler sampler = {};
4073 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004074#ifdef AMD_EXTENSIONS
4075 bool f16ShadowCompare = false;
4076#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004077 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004078 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4079 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004080#ifdef AMD_EXTENSIONS
4081 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
4082#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004083 }
4084
John Kessenich140f3df2015-06-26 16:58:36 -06004085 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4086 builder.clearAccessChain();
4087 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004088
4089 // Special case l-value operands
4090 bool lvalue = false;
4091 switch (node.getOp()) {
4092 case glslang::EOpImageAtomicAdd:
4093 case glslang::EOpImageAtomicMin:
4094 case glslang::EOpImageAtomicMax:
4095 case glslang::EOpImageAtomicAnd:
4096 case glslang::EOpImageAtomicOr:
4097 case glslang::EOpImageAtomicXor:
4098 case glslang::EOpImageAtomicExchange:
4099 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004100 case glslang::EOpImageAtomicLoad:
4101 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004102 if (i == 0)
4103 lvalue = true;
4104 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004105 case glslang::EOpSparseImageLoad:
4106 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4107 lvalue = true;
4108 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004109#ifdef AMD_EXTENSIONS
4110 case glslang::EOpSparseTexture:
4111 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4112 lvalue = true;
4113 break;
4114 case glslang::EOpSparseTextureClamp:
4115 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4116 lvalue = true;
4117 break;
4118 case glslang::EOpSparseTextureLod:
4119 case glslang::EOpSparseTextureOffset:
4120 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4121 lvalue = true;
4122 break;
4123#else
Rex Xu48edadf2015-12-31 16:11:41 +08004124 case glslang::EOpSparseTexture:
4125 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
4126 lvalue = true;
4127 break;
4128 case glslang::EOpSparseTextureClamp:
4129 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
4130 lvalue = true;
4131 break;
4132 case glslang::EOpSparseTextureLod:
4133 case glslang::EOpSparseTextureOffset:
4134 if (i == 3)
4135 lvalue = true;
4136 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004137#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004138 case glslang::EOpSparseTextureFetch:
4139 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4140 lvalue = true;
4141 break;
4142 case glslang::EOpSparseTextureFetchOffset:
4143 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4144 lvalue = true;
4145 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004146#ifdef AMD_EXTENSIONS
4147 case glslang::EOpSparseTextureLodOffset:
4148 case glslang::EOpSparseTextureGrad:
4149 case glslang::EOpSparseTextureOffsetClamp:
4150 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4151 lvalue = true;
4152 break;
4153 case glslang::EOpSparseTextureGradOffset:
4154 case glslang::EOpSparseTextureGradClamp:
4155 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4156 lvalue = true;
4157 break;
4158 case glslang::EOpSparseTextureGradOffsetClamp:
4159 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4160 lvalue = true;
4161 break;
4162#else
Rex Xu48edadf2015-12-31 16:11:41 +08004163 case glslang::EOpSparseTextureLodOffset:
4164 case glslang::EOpSparseTextureGrad:
4165 case glslang::EOpSparseTextureOffsetClamp:
4166 if (i == 4)
4167 lvalue = true;
4168 break;
4169 case glslang::EOpSparseTextureGradOffset:
4170 case glslang::EOpSparseTextureGradClamp:
4171 if (i == 5)
4172 lvalue = true;
4173 break;
4174 case glslang::EOpSparseTextureGradOffsetClamp:
4175 if (i == 6)
4176 lvalue = true;
4177 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004178#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004179 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004180 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4181 lvalue = true;
4182 break;
4183 case glslang::EOpSparseTextureGatherOffset:
4184 case glslang::EOpSparseTextureGatherOffsets:
4185 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4186 lvalue = true;
4187 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004188#ifdef AMD_EXTENSIONS
4189 case glslang::EOpSparseTextureGatherLod:
4190 if (i == 3)
4191 lvalue = true;
4192 break;
4193 case glslang::EOpSparseTextureGatherLodOffset:
4194 case glslang::EOpSparseTextureGatherLodOffsets:
4195 if (i == 4)
4196 lvalue = true;
4197 break;
Rex Xu129799a2017-07-05 17:23:28 +08004198 case glslang::EOpSparseImageLoadLod:
4199 if (i == 3)
4200 lvalue = true;
4201 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004202#endif
Chao Chen3a137962018-09-19 11:41:27 -07004203#ifdef NV_EXTENSIONS
4204 case glslang::EOpImageSampleFootprintNV:
4205 if (i == 4)
4206 lvalue = true;
4207 break;
4208 case glslang::EOpImageSampleFootprintClampNV:
4209 case glslang::EOpImageSampleFootprintLodNV:
4210 if (i == 5)
4211 lvalue = true;
4212 break;
4213 case glslang::EOpImageSampleFootprintGradNV:
4214 if (i == 6)
4215 lvalue = true;
4216 break;
4217 case glslang::EOpImageSampleFootprintGradClampNV:
4218 if (i == 7)
4219 lvalue = true;
4220 break;
4221#endif
Rex Xufc618912015-09-09 16:42:49 +08004222 default:
4223 break;
4224 }
4225
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004226 if (lvalue) {
Rex Xufc618912015-09-09 16:42:49 +08004227 arguments.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004228 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
4229 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4230 } else
John Kessenich32cfd492016-02-02 12:37:46 -07004231 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004232 }
4233}
4234
John Kessenichfc51d282015-08-19 13:34:18 -06004235void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004236{
John Kessenichfc51d282015-08-19 13:34:18 -06004237 builder.clearAccessChain();
4238 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004239 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004240}
John Kessenich140f3df2015-06-26 16:58:36 -06004241
John Kessenichfc51d282015-08-19 13:34:18 -06004242spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4243{
John Kesseniche485c7a2017-05-31 18:50:53 -06004244 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004245 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004246
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004247 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004248
John Kessenichfc51d282015-08-19 13:34:18 -06004249 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004250
John Kessenichf43c7392019-03-31 10:51:57 -06004251 const glslang::TType &imageType = node->getAsAggregate()
4252 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4253 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004254 const glslang::TSampler sampler = imageType.getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08004255#ifdef AMD_EXTENSIONS
4256 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004257 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4258 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004259#endif
4260
John Kessenichf43c7392019-03-31 10:51:57 -06004261 const auto signExtensionMask = [&]() {
4262 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4263 if (sampler.type == glslang::EbtUint)
4264 return spv::ImageOperandsZeroExtendMask;
4265 else if (sampler.type == glslang::EbtInt)
4266 return spv::ImageOperandsSignExtendMask;
4267 }
4268 return spv::ImageOperandsMaskNone;
4269 };
4270
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004271 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4272
John Kessenichfc51d282015-08-19 13:34:18 -06004273 std::vector<spv::Id> arguments;
4274 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004275 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004276 else
4277 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004278 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004279
4280 spv::Builder::TextureParameters params = { };
4281 params.sampler = arguments[0];
4282
Rex Xu04db3f52015-09-16 11:44:02 +08004283 glslang::TCrackedTextureOp cracked;
4284 node->crackTexture(sampler, cracked);
4285
amhagan05506bb2017-06-13 16:53:02 -04004286 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004287
John Kessenichfc51d282015-08-19 13:34:18 -06004288 // Check for queries
4289 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004290 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4291 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004292 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004293
John Kessenichfc51d282015-08-19 13:34:18 -06004294 switch (node->getOp()) {
4295 case glslang::EOpImageQuerySize:
4296 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004297 if (arguments.size() > 1) {
4298 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004299 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004300 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004301 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004302 case glslang::EOpImageQuerySamples:
4303 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004304 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004305 case glslang::EOpTextureQueryLod:
4306 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004307 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004308 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004309 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004310 case glslang::EOpSparseTexelsResident:
4311 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06004312 default:
4313 assert(0);
4314 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004315 }
John Kessenich140f3df2015-06-26 16:58:36 -06004316 }
4317
LoopDawg4425f242018-02-18 11:40:01 -07004318 int components = node->getType().getVectorSize();
4319
4320 if (node->getOp() == glslang::EOpTextureFetch) {
4321 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4322 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4323 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4324 // here around e.g. which ones return scalars or other types.
4325 components = 4;
4326 }
4327
4328 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4329
4330 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4331
Rex Xufc618912015-09-09 16:42:49 +08004332 // Check for image functions other than queries
4333 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004334 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004335 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004336 spv::IdImmediate image = { true, *(opIt++) };
4337 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004338
4339 // Handle subpass operations
4340 // TODO: GLSL should change to have the "MS" only on the type rather than the
4341 // built-in function.
4342 if (cracked.subpass) {
4343 // add on the (0,0) coordinate
4344 spv::Id zero = builder.makeIntConstant(0);
4345 std::vector<spv::Id> comps;
4346 comps.push_back(zero);
4347 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004348 spv::IdImmediate coord = { true,
4349 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4350 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004351 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4352 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich6c292d32016-02-15 20:58:50 -07004353 if (sampler.ms) {
John Kessenichf43c7392019-03-31 10:51:57 -06004354 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4355 }
4356 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004357 operands.push_back(imageOperands);
John Kessenichf43c7392019-03-31 10:51:57 -06004358 if (sampler.ms) {
4359 spv::IdImmediate imageOperand = { true, *(opIt++) };
4360 operands.push_back(imageOperand);
4361 }
John Kessenich6c292d32016-02-15 20:58:50 -07004362 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004363 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4364 builder.setPrecision(result, precision);
4365 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004366 }
4367
John Kessenich149afc32018-08-14 13:31:43 -06004368 spv::IdImmediate coord = { true, *(opIt++) };
4369 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004370#ifdef AMD_EXTENSIONS
4371 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
4372#else
John Kessenich56bab042015-09-16 10:54:31 -06004373 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004374#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004375 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich55e7d112015-11-15 21:33:39 -07004376 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004377 mask = mask | spv::ImageOperandsSampleMask;
4378 }
Rex Xu129799a2017-07-05 17:23:28 +08004379#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004380 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004381 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4382 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004383 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004384 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004385#endif
4386 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4387 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004388 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004389 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004390 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4391 operands.push_back(imageOperands);
4392 }
4393 if (mask & spv::ImageOperandsSampleMask) {
4394 spv::IdImmediate imageOperand = { true, *opIt++ };
4395 operands.push_back(imageOperand);
4396 }
4397#ifdef AMD_EXTENSIONS
4398 if (mask & spv::ImageOperandsLodMask) {
4399 spv::IdImmediate imageOperand = { true, *opIt++ };
4400 operands.push_back(imageOperand);
4401 }
4402#endif
4403 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004404 spv::IdImmediate imageOperand = { true,
4405 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004406 operands.push_back(imageOperand);
4407 }
4408
John Kessenich149afc32018-08-14 13:31:43 -06004409 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004410 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004411
John Kessenich149afc32018-08-14 13:31:43 -06004412 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004413 builder.setPrecision(result[0], precision);
4414
4415 // If needed, add a conversion constructor to the proper size.
4416 if (components != node->getType().getVectorSize())
4417 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4418
4419 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004420#ifdef AMD_EXTENSIONS
4421 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
4422#else
John Kessenich56bab042015-09-16 10:54:31 -06004423 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08004424#endif
Rex Xu129799a2017-07-05 17:23:28 +08004425
Jeff Bolz36831c92018-09-05 10:11:41 -05004426 // Push the texel value before the operands
4427#ifdef AMD_EXTENSIONS
4428 if (sampler.ms || cracked.lod) {
4429#else
4430 if (sampler.ms) {
4431#endif
John Kessenich149afc32018-08-14 13:31:43 -06004432 spv::IdImmediate texel = { true, *(opIt + 1) };
4433 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004434 } else {
4435 spv::IdImmediate texel = { true, *opIt };
4436 operands.push_back(texel);
4437 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004438
4439 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
4440 if (sampler.ms) {
4441 mask = mask | spv::ImageOperandsSampleMask;
4442 }
4443#ifdef AMD_EXTENSIONS
4444 if (cracked.lod) {
4445 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4446 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4447 mask = mask | spv::ImageOperandsLodMask;
4448 }
4449#endif
4450 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4451 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004452 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004453 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004454 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4455 operands.push_back(imageOperands);
4456 }
4457 if (mask & spv::ImageOperandsSampleMask) {
4458 spv::IdImmediate imageOperand = { true, *opIt++ };
4459 operands.push_back(imageOperand);
4460 }
4461#ifdef AMD_EXTENSIONS
4462 if (mask & spv::ImageOperandsLodMask) {
4463 spv::IdImmediate imageOperand = { true, *opIt++ };
4464 operands.push_back(imageOperand);
4465 }
4466#endif
4467 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004468 spv::IdImmediate imageOperand = { true,
4469 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004470 operands.push_back(imageOperand);
4471 }
4472
John Kessenich56bab042015-09-16 10:54:31 -06004473 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004474 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004475 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004476 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08004477#ifdef AMD_EXTENSIONS
John Kessenichf43c7392019-03-31 10:51:57 -06004478 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4479 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004480#else
Rex Xu5eafa472016-02-19 22:24:03 +08004481 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004482#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004483 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004484 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004485 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4486
Jeff Bolz36831c92018-09-05 10:11:41 -05004487 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
Rex Xu5eafa472016-02-19 22:24:03 +08004488 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004489 mask = mask | spv::ImageOperandsSampleMask;
4490 }
Rex Xu129799a2017-07-05 17:23:28 +08004491#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004492 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004493 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4494 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4495
Jeff Bolz36831c92018-09-05 10:11:41 -05004496 mask = mask | spv::ImageOperandsLodMask;
4497 }
4498#endif
4499 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4500 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004501 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004502 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004503 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004504 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004505 }
4506 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004507 spv::IdImmediate imageOperand = { true, *opIt++ };
4508 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004509 }
4510#ifdef AMD_EXTENSIONS
4511 if (mask & spv::ImageOperandsLodMask) {
4512 spv::IdImmediate imageOperand = { true, *opIt++ };
4513 operands.push_back(imageOperand);
4514 }
Rex Xu129799a2017-07-05 17:23:28 +08004515#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004516 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4517 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4518 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004519 }
4520
4521 // Create the return type that was a special structure
4522 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004523 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004524 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4525 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4526
4527 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4528
4529 // Decode the return type
4530 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4531 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004532 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004533 // Process image atomic operations
4534
4535 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4536 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004537 // For non-MS, the sample value should be 0
4538 spv::IdImmediate sample = { true, sampler.ms ? *(opIt++) : builder.makeUintConstant(0) };
4539 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004540
Jeff Bolz36831c92018-09-05 10:11:41 -05004541 spv::Id resultTypeId;
4542 // imageAtomicStore has a void return type so base the pointer type on
4543 // the type of the value operand.
4544 if (node->getOp() == glslang::EOpImageAtomicStore) {
4545 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
4546 } else {
4547 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4548 }
John Kessenich56bab042015-09-16 10:54:31 -06004549 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08004550
4551 std::vector<spv::Id> operands;
4552 operands.push_back(pointer);
4553 for (; opIt != arguments.end(); ++opIt)
4554 operands.push_back(*opIt);
4555
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004556 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(), lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08004557 }
4558 }
4559
amhagan05506bb2017-06-13 16:53:02 -04004560#ifdef AMD_EXTENSIONS
4561 // Check for fragment mask functions other than queries
4562 if (cracked.fragMask) {
4563 assert(sampler.ms);
4564
4565 auto opIt = arguments.begin();
4566 std::vector<spv::Id> operands;
4567
4568 // Extract the image if necessary
4569 if (builder.isSampledImage(params.sampler))
4570 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4571
4572 operands.push_back(params.sampler);
4573 ++opIt;
4574
4575 if (sampler.isSubpass()) {
4576 // add on the (0,0) coordinate
4577 spv::Id zero = builder.makeIntConstant(0);
4578 std::vector<spv::Id> comps;
4579 comps.push_back(zero);
4580 comps.push_back(zero);
4581 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
4582 }
4583
4584 for (; opIt != arguments.end(); ++opIt)
4585 operands.push_back(*opIt);
4586
4587 spv::Op fragMaskOp = spv::OpNop;
4588 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4589 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4590 else if (node->getOp() == glslang::EOpFragmentFetch)
4591 fragMaskOp = spv::OpFragmentFetchAMD;
4592
4593 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4594 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4595 return builder.createOp(fragMaskOp, resultType(), operands);
4596 }
4597#endif
4598
Rex Xufc618912015-09-09 16:42:49 +08004599 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004600 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004601#ifdef NV_EXTENSIONS
4602 bool imageFootprint = node->isImageFootprint();
4603#endif
4604
Rex Xu71519fe2015-11-11 15:35:47 +08004605 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
4606
John Kessenichfc51d282015-08-19 13:34:18 -06004607 // check for bias argument
4608 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004609#ifdef AMD_EXTENSIONS
4610 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
4611#else
Rex Xu71519fe2015-11-11 15:35:47 +08004612 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08004613#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004614 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004615#ifdef AMD_EXTENSIONS
4616 if (cracked.gather)
4617 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004618
4619 if (f16ShadowCompare)
4620 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004621#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004622 if (cracked.offset)
4623 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004624#ifdef AMD_EXTENSIONS
4625 else if (cracked.offsets)
4626 ++nonBiasArgCount;
4627#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004628 if (cracked.grad)
4629 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004630 if (cracked.lodClamp)
4631 ++nonBiasArgCount;
4632 if (sparse)
4633 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004634#ifdef NV_EXTENSIONS
4635 if (imageFootprint)
4636 //Following three extra arguments
4637 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4638 nonBiasArgCount += 3;
4639#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004640 if ((int)arguments.size() > nonBiasArgCount)
4641 bias = true;
4642 }
4643
John Kessenicha5c33d62016-06-02 23:45:21 -06004644 // See if the sampler param should really be just the SPV image part
4645 if (cracked.fetch) {
4646 // a fetch needs to have the image extracted first
4647 if (builder.isSampledImage(params.sampler))
4648 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4649 }
4650
Rex Xu225e0fc2016-11-17 17:47:59 +08004651#ifdef AMD_EXTENSIONS
4652 if (cracked.gather) {
4653 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4654 if (bias || cracked.lod ||
4655 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4656 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004657 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004658 }
4659 }
4660#endif
4661
John Kessenichfc51d282015-08-19 13:34:18 -06004662 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004663
John Kessenichfc51d282015-08-19 13:34:18 -06004664 params.coords = arguments[1];
4665 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004666 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004667
4668 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004669#ifdef AMD_EXTENSIONS
4670 if (cubeCompare || f16ShadowCompare) {
4671#else
Rex Xu48edadf2015-12-31 16:11:41 +08004672 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08004673#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004674 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004675 ++extraArgs;
4676 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004677 params.Dref = arguments[2];
4678 ++extraArgs;
4679 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004680 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004681 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004682 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004683 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004684 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004685 dRefComp = builder.getNumComponents(params.coords) - 1;
4686 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004687 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4688 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004689
4690 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004691 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004692 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004693 ++extraArgs;
Chao Chenbeae2252018-09-19 11:40:45 -07004694 } else if (glslangIntermediate->getStage() != EShLangFragment
4695#ifdef NV_EXTENSIONS
4696 // NV_compute_shader_derivatives layout qualifiers allow for implicit LODs
4697 && !(glslangIntermediate->getStage() == EShLangCompute &&
4698 (glslangIntermediate->getLayoutDerivativeModeNone() != glslang::LayoutDerivativeNone))
4699#endif
4700 ) {
John Kessenich019f08f2016-02-15 15:40:42 -07004701 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4702 noImplicitLod = true;
4703 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004704
4705 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07004706 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004707 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004708 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004709 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004710
4711 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004712 if (cracked.grad) {
4713 params.gradX = arguments[2 + extraArgs];
4714 params.gradY = arguments[3 + extraArgs];
4715 extraArgs += 2;
4716 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004717
4718 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004719 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004720 params.offset = arguments[2 + extraArgs];
4721 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004722 } else if (cracked.offsets) {
4723 params.offsets = arguments[2 + extraArgs];
4724 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004725 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004726
4727 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004728 if (cracked.lodClamp) {
4729 params.lodClamp = arguments[2 + extraArgs];
4730 ++extraArgs;
4731 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004732 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004733 if (sparse) {
4734 params.texelOut = arguments[2 + extraArgs];
4735 ++extraArgs;
4736 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004737
John Kessenich76d4dfc2016-06-16 12:43:23 -06004738 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004739 if (cracked.gather && ! sampler.shadow) {
4740 // default component is 0, if missing, otherwise an argument
4741 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004742 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004743 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004744 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004745 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004746 }
Chao Chen3a137962018-09-19 11:41:27 -07004747#ifdef NV_EXTENSIONS
4748 spv::Id resultStruct = spv::NoResult;
4749 if (imageFootprint) {
4750 //Following three extra arguments
4751 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4752 params.granularity = arguments[2 + extraArgs];
4753 params.coarse = arguments[3 + extraArgs];
4754 resultStruct = arguments[4 + extraArgs];
4755 extraArgs += 3;
4756 }
4757#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004758 // bias
4759 if (bias) {
4760 params.bias = arguments[2 + extraArgs];
4761 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004762 }
John Kessenichfc51d282015-08-19 13:34:18 -06004763
Chao Chen3a137962018-09-19 11:41:27 -07004764#ifdef NV_EXTENSIONS
4765 if (imageFootprint) {
4766 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
4767 builder.addCapability(spv::CapabilityImageFootprintNV);
4768
4769
4770 //resultStructType(OpenGL type) contains 5 elements:
4771 //struct gl_TextureFootprint2DNV {
4772 // uvec2 anchor;
4773 // uvec2 offset;
4774 // uvec2 mask;
4775 // uint lod;
4776 // uint granularity;
4777 //};
4778 //or
4779 //struct gl_TextureFootprint3DNV {
4780 // uvec3 anchor;
4781 // uvec3 offset;
4782 // uvec2 mask;
4783 // uint lod;
4784 // uint granularity;
4785 //};
4786 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
4787 assert(builder.isStructType(resultStructType));
4788
4789 //resType (SPIR-V type) contains 6 elements:
4790 //Member 0 must be a Boolean type scalar(LOD),
4791 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
4792 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
4793 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
4794 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
4795 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
4796 std::vector<spv::Id> members;
4797 members.push_back(resultType());
4798 for (int i = 0; i < 5; i++) {
4799 members.push_back(builder.getContainedTypeId(resultStructType, i));
4800 }
4801 spv::Id resType = builder.makeStructType(members, "ResType");
4802
4803 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06004804 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
4805 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07004806
4807 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
4808 for (int i = 0; i < 5; i++) {
4809 builder.clearAccessChain();
4810 builder.setAccessChainLValue(resultStruct);
4811
4812 //Accessing to a struct we created, no coherent flag is set
4813 spv::Builder::AccessChain::CoherentFlags flags;
4814 flags.clear();
4815
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004816 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
Chao Chen3a137962018-09-19 11:41:27 -07004817 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1), i+1));
4818 }
4819 return builder.createCompositeExtract(res, resultType(), 0);
4820 }
4821#endif
4822
John Kessenich65336482016-06-16 14:06:26 -06004823 // projective component (might not to move)
4824 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4825 // are divided by the last component of P."
4826 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4827 // unused components will appear after all used components."
4828 if (cracked.proj) {
4829 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4830 int projTargetComp;
4831 switch (sampler.dim) {
4832 case glslang::Esd1D: projTargetComp = 1; break;
4833 case glslang::Esd2D: projTargetComp = 2; break;
4834 case glslang::EsdRect: projTargetComp = 2; break;
4835 default: projTargetComp = projSourceComp; break;
4836 }
4837 // copy the projective coordinate if we have to
4838 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004839 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004840 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4841 projSourceComp);
4842 params.coords = builder.createCompositeInsert(projComp, params.coords,
4843 builder.getTypeId(params.coords), projTargetComp);
4844 }
4845 }
4846
Jeff Bolz36831c92018-09-05 10:11:41 -05004847 // nonprivate
4848 if (imageType.getQualifier().nonprivate) {
4849 params.nonprivate = true;
4850 }
4851
4852 // volatile
4853 if (imageType.getQualifier().volatil) {
4854 params.volatil = true;
4855 }
4856
St0fFa1184dd2018-04-09 21:08:14 +02004857 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06004858 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
4859 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02004860 );
LoopDawg4425f242018-02-18 11:40:01 -07004861
4862 if (components != node->getType().getVectorSize())
4863 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4864
4865 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06004866}
4867
4868spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
4869{
4870 // Grab the function's pointer from the previously created function
4871 spv::Function* function = functionMap[node->getName().c_str()];
4872 if (! function)
4873 return 0;
4874
4875 const glslang::TIntermSequence& glslangArgs = node->getSequence();
4876 const glslang::TQualifierList& qualifiers = node->getQualifierList();
4877
4878 // See comments in makeFunctions() for details about the semantics for parameter passing.
4879 //
4880 // These imply we need a four step process:
4881 // 1. Evaluate the arguments
4882 // 2. Allocate and make copies of in, out, and inout arguments
4883 // 3. Make the call
4884 // 4. Copy back the results
4885
John Kessenichd3ed90b2018-05-04 11:43:03 -06004886 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06004887 std::vector<spv::Builder::AccessChain> lValues;
4888 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07004889 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06004890 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004891 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06004892 // build l-value
4893 builder.clearAccessChain();
4894 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06004895 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06004896 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07004897 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004898 // save l-value
4899 lValues.push_back(builder.getAccessChain());
4900 } else {
4901 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07004902 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06004903 }
4904 }
4905
4906 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
4907 // copy the original into that space.
4908 //
4909 // Also, build up the list of actual arguments to pass in for the call
4910 int lValueCount = 0;
4911 int rValueCount = 0;
4912 std::vector<spv::Id> spvArgs;
4913 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
4914 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06004915 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07004916 builder.setAccessChain(lValues[lValueCount]);
4917 arg = builder.accessChainGetLValue();
4918 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06004919 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004920 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06004921 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06004922 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
4923 // need to copy the input into output space
4924 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07004925 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06004926 builder.clearAccessChain();
4927 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004928 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004929 }
4930 ++lValueCount;
4931 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004932 // process r-value, which involves a copy for a type mismatch
4933 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
4934 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
4935 builder.clearAccessChain();
4936 builder.setAccessChainLValue(argCopy);
4937 multiTypeStore(*argTypes[a], rValues[rValueCount]);
4938 arg = builder.createLoad(argCopy);
4939 } else
4940 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06004941 ++rValueCount;
4942 }
4943 spvArgs.push_back(arg);
4944 }
4945
4946 // 3. Make the call.
4947 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07004948 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004949
4950 // 4. Copy back out an "out" arguments.
4951 lValueCount = 0;
4952 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004953 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06004954 ++lValueCount;
4955 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004956 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
4957 spv::Id copy = builder.createLoad(spvArgs[a]);
4958 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004959 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004960 }
4961 ++lValueCount;
4962 }
4963 }
4964
4965 return result;
4966}
4967
4968// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06004969spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06004970 spv::Id typeId, spv::Id left, spv::Id right,
4971 glslang::TBasicType typeProxy, bool reduceComparison)
4972{
John Kessenich66011cb2018-03-06 16:12:04 -07004973 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4974 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08004975 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06004976
4977 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06004978 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06004979 bool comparison = false;
4980
4981 switch (op) {
4982 case glslang::EOpAdd:
4983 case glslang::EOpAddAssign:
4984 if (isFloat)
4985 binOp = spv::OpFAdd;
4986 else
4987 binOp = spv::OpIAdd;
4988 break;
4989 case glslang::EOpSub:
4990 case glslang::EOpSubAssign:
4991 if (isFloat)
4992 binOp = spv::OpFSub;
4993 else
4994 binOp = spv::OpISub;
4995 break;
4996 case glslang::EOpMul:
4997 case glslang::EOpMulAssign:
4998 if (isFloat)
4999 binOp = spv::OpFMul;
5000 else
5001 binOp = spv::OpIMul;
5002 break;
5003 case glslang::EOpVectorTimesScalar:
5004 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005005 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005006 if (builder.isVector(right))
5007 std::swap(left, right);
5008 assert(builder.isScalar(right));
5009 needMatchingVectors = false;
5010 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005011 } else if (isFloat)
5012 binOp = spv::OpFMul;
5013 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005014 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005015 break;
5016 case glslang::EOpVectorTimesMatrix:
5017 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005018 binOp = spv::OpVectorTimesMatrix;
5019 break;
5020 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005021 binOp = spv::OpMatrixTimesVector;
5022 break;
5023 case glslang::EOpMatrixTimesScalar:
5024 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005025 binOp = spv::OpMatrixTimesScalar;
5026 break;
5027 case glslang::EOpMatrixTimesMatrix:
5028 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005029 binOp = spv::OpMatrixTimesMatrix;
5030 break;
5031 case glslang::EOpOuterProduct:
5032 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005033 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005034 break;
5035
5036 case glslang::EOpDiv:
5037 case glslang::EOpDivAssign:
5038 if (isFloat)
5039 binOp = spv::OpFDiv;
5040 else if (isUnsigned)
5041 binOp = spv::OpUDiv;
5042 else
5043 binOp = spv::OpSDiv;
5044 break;
5045 case glslang::EOpMod:
5046 case glslang::EOpModAssign:
5047 if (isFloat)
5048 binOp = spv::OpFMod;
5049 else if (isUnsigned)
5050 binOp = spv::OpUMod;
5051 else
5052 binOp = spv::OpSMod;
5053 break;
5054 case glslang::EOpRightShift:
5055 case glslang::EOpRightShiftAssign:
5056 if (isUnsigned)
5057 binOp = spv::OpShiftRightLogical;
5058 else
5059 binOp = spv::OpShiftRightArithmetic;
5060 break;
5061 case glslang::EOpLeftShift:
5062 case glslang::EOpLeftShiftAssign:
5063 binOp = spv::OpShiftLeftLogical;
5064 break;
5065 case glslang::EOpAnd:
5066 case glslang::EOpAndAssign:
5067 binOp = spv::OpBitwiseAnd;
5068 break;
5069 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005070 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005071 binOp = spv::OpLogicalAnd;
5072 break;
5073 case glslang::EOpInclusiveOr:
5074 case glslang::EOpInclusiveOrAssign:
5075 binOp = spv::OpBitwiseOr;
5076 break;
5077 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005078 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005079 binOp = spv::OpLogicalOr;
5080 break;
5081 case glslang::EOpExclusiveOr:
5082 case glslang::EOpExclusiveOrAssign:
5083 binOp = spv::OpBitwiseXor;
5084 break;
5085 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005086 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005087 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005088 break;
5089
5090 case glslang::EOpLessThan:
5091 case glslang::EOpGreaterThan:
5092 case glslang::EOpLessThanEqual:
5093 case glslang::EOpGreaterThanEqual:
5094 case glslang::EOpEqual:
5095 case glslang::EOpNotEqual:
5096 case glslang::EOpVectorEqual:
5097 case glslang::EOpVectorNotEqual:
5098 comparison = true;
5099 break;
5100 default:
5101 break;
5102 }
5103
John Kessenich7c1aa102015-10-15 13:29:11 -06005104 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005105 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005106 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005107 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5108 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005109 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005110
5111 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005112 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005113 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005114
qining25262b32016-05-06 17:25:16 -04005115 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005116 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005117 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005118 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005119 }
5120
5121 if (! comparison)
5122 return 0;
5123
John Kessenich7c1aa102015-10-15 13:29:11 -06005124 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005125
John Kessenich4583b612016-08-07 19:14:22 -06005126 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005127 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5128 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06005129 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005130 return result;
5131 }
John Kessenich140f3df2015-06-26 16:58:36 -06005132
5133 switch (op) {
5134 case glslang::EOpLessThan:
5135 if (isFloat)
5136 binOp = spv::OpFOrdLessThan;
5137 else if (isUnsigned)
5138 binOp = spv::OpULessThan;
5139 else
5140 binOp = spv::OpSLessThan;
5141 break;
5142 case glslang::EOpGreaterThan:
5143 if (isFloat)
5144 binOp = spv::OpFOrdGreaterThan;
5145 else if (isUnsigned)
5146 binOp = spv::OpUGreaterThan;
5147 else
5148 binOp = spv::OpSGreaterThan;
5149 break;
5150 case glslang::EOpLessThanEqual:
5151 if (isFloat)
5152 binOp = spv::OpFOrdLessThanEqual;
5153 else if (isUnsigned)
5154 binOp = spv::OpULessThanEqual;
5155 else
5156 binOp = spv::OpSLessThanEqual;
5157 break;
5158 case glslang::EOpGreaterThanEqual:
5159 if (isFloat)
5160 binOp = spv::OpFOrdGreaterThanEqual;
5161 else if (isUnsigned)
5162 binOp = spv::OpUGreaterThanEqual;
5163 else
5164 binOp = spv::OpSGreaterThanEqual;
5165 break;
5166 case glslang::EOpEqual:
5167 case glslang::EOpVectorEqual:
5168 if (isFloat)
5169 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005170 else if (isBool)
5171 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005172 else
5173 binOp = spv::OpIEqual;
5174 break;
5175 case glslang::EOpNotEqual:
5176 case glslang::EOpVectorNotEqual:
5177 if (isFloat)
5178 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005179 else if (isBool)
5180 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005181 else
5182 binOp = spv::OpINotEqual;
5183 break;
5184 default:
5185 break;
5186 }
5187
qining25262b32016-05-06 17:25:16 -04005188 if (binOp != spv::OpNop) {
5189 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005190 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005191 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005192 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005193 }
John Kessenich140f3df2015-06-26 16:58:36 -06005194
5195 return 0;
5196}
5197
John Kessenich04bb8a02015-12-12 12:28:14 -07005198//
5199// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5200// These can be any of:
5201//
5202// matrix * scalar
5203// scalar * matrix
5204// matrix * matrix linear algebraic
5205// matrix * vector
5206// vector * matrix
5207// matrix * matrix componentwise
5208// matrix op matrix op in {+, -, /}
5209// matrix op scalar op in {+, -, /}
5210// scalar op matrix op in {+, -, /}
5211//
John Kessenichead86222018-03-28 18:01:20 -06005212spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5213 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005214{
5215 bool firstClass = true;
5216
5217 // First, handle first-class matrix operations (* and matrix/scalar)
5218 switch (op) {
5219 case spv::OpFDiv:
5220 if (builder.isMatrix(left) && builder.isScalar(right)) {
5221 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005222 spv::Id resultType = builder.getTypeId(right);
5223 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005224 op = spv::OpMatrixTimesScalar;
5225 } else
5226 firstClass = false;
5227 break;
5228 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005229 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005230 std::swap(left, right);
5231 assert(builder.isScalar(right));
5232 break;
5233 case spv::OpVectorTimesMatrix:
5234 assert(builder.isVector(left));
5235 assert(builder.isMatrix(right));
5236 break;
5237 case spv::OpMatrixTimesVector:
5238 assert(builder.isMatrix(left));
5239 assert(builder.isVector(right));
5240 break;
5241 case spv::OpMatrixTimesMatrix:
5242 assert(builder.isMatrix(left));
5243 assert(builder.isMatrix(right));
5244 break;
5245 default:
5246 firstClass = false;
5247 break;
5248 }
5249
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005250 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5251 firstClass = true;
5252
qining25262b32016-05-06 17:25:16 -04005253 if (firstClass) {
5254 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005255 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005256 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005257 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005258 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005259
LoopDawg592860c2016-06-09 08:57:35 -06005260 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005261 // The result type of all of them is the same type as the (a) matrix operand.
5262 // The algorithm is to:
5263 // - break the matrix(es) into vectors
5264 // - smear any scalar to a vector
5265 // - do vector operations
5266 // - make a matrix out the vector results
5267 switch (op) {
5268 case spv::OpFAdd:
5269 case spv::OpFSub:
5270 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005271 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005272 case spv::OpFMul:
5273 {
5274 // one time set up...
5275 bool leftMat = builder.isMatrix(left);
5276 bool rightMat = builder.isMatrix(right);
5277 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5278 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5279 spv::Id scalarType = builder.getScalarTypeId(typeId);
5280 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5281 std::vector<spv::Id> results;
5282 spv::Id smearVec = spv::NoResult;
5283 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005284 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005285 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005286 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005287
5288 // do each vector op
5289 for (unsigned int c = 0; c < numCols; ++c) {
5290 std::vector<unsigned int> indexes;
5291 indexes.push_back(c);
5292 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5293 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005294 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06005295 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005296 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005297 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005298 }
5299
5300 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005301 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005302 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005303 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005304 }
5305 default:
5306 assert(0);
5307 return spv::NoResult;
5308 }
5309}
5310
John Kessenichead86222018-03-28 18:01:20 -06005311spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005312 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005313{
5314 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005315 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005316 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005317 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5318 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005319
5320 switch (op) {
5321 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005322 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005323 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005324 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005325 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005326 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005327 unaryOp = spv::OpSNegate;
5328 break;
5329
5330 case glslang::EOpLogicalNot:
5331 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005332 unaryOp = spv::OpLogicalNot;
5333 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005334 case glslang::EOpBitwiseNot:
5335 unaryOp = spv::OpNot;
5336 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005337
John Kessenich140f3df2015-06-26 16:58:36 -06005338 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005339 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005340 break;
5341 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005342 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005343 break;
5344 case glslang::EOpTranspose:
5345 unaryOp = spv::OpTranspose;
5346 break;
5347
5348 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005349 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005350 break;
5351 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005352 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005353 break;
5354 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005355 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005356 break;
5357 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005358 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005359 break;
5360 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005361 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005362 break;
5363 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005364 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005365 break;
5366 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005367 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005368 break;
5369 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005370 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005371 break;
5372
5373 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005374 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005375 break;
5376 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005377 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005378 break;
5379 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005380 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005381 break;
5382 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005383 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005384 break;
5385 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005386 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005387 break;
5388 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005389 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005390 break;
5391
5392 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005393 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005394 break;
5395 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005396 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005397 break;
5398
5399 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005400 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005401 break;
5402 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005403 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005404 break;
5405 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005406 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005407 break;
5408 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005409 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005410 break;
5411 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005412 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005413 break;
5414 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005415 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005416 break;
5417
5418 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005419 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005420 break;
5421 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005422 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005423 break;
5424 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005425 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005426 break;
5427 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005428 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005429 break;
5430 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005431 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005432 break;
5433 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005434 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005435 break;
5436
5437 case glslang::EOpIsNan:
5438 unaryOp = spv::OpIsNan;
5439 break;
5440 case glslang::EOpIsInf:
5441 unaryOp = spv::OpIsInf;
5442 break;
LoopDawg592860c2016-06-09 08:57:35 -06005443 case glslang::EOpIsFinite:
5444 unaryOp = spv::OpIsFinite;
5445 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005446
Rex Xucbc426e2015-12-15 16:03:10 +08005447 case glslang::EOpFloatBitsToInt:
5448 case glslang::EOpFloatBitsToUint:
5449 case glslang::EOpIntBitsToFloat:
5450 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005451 case glslang::EOpDoubleBitsToInt64:
5452 case glslang::EOpDoubleBitsToUint64:
5453 case glslang::EOpInt64BitsToDouble:
5454 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005455 case glslang::EOpFloat16BitsToInt16:
5456 case glslang::EOpFloat16BitsToUint16:
5457 case glslang::EOpInt16BitsToFloat16:
5458 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005459 unaryOp = spv::OpBitcast;
5460 break;
5461
John Kessenich140f3df2015-06-26 16:58:36 -06005462 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005463 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005464 break;
5465 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005466 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005467 break;
5468 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005469 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005470 break;
5471 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005472 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005473 break;
5474 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005475 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005476 break;
5477 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005478 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005479 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005480 case glslang::EOpPackSnorm4x8:
5481 libCall = spv::GLSLstd450PackSnorm4x8;
5482 break;
5483 case glslang::EOpUnpackSnorm4x8:
5484 libCall = spv::GLSLstd450UnpackSnorm4x8;
5485 break;
5486 case glslang::EOpPackUnorm4x8:
5487 libCall = spv::GLSLstd450PackUnorm4x8;
5488 break;
5489 case glslang::EOpUnpackUnorm4x8:
5490 libCall = spv::GLSLstd450UnpackUnorm4x8;
5491 break;
5492 case glslang::EOpPackDouble2x32:
5493 libCall = spv::GLSLstd450PackDouble2x32;
5494 break;
5495 case glslang::EOpUnpackDouble2x32:
5496 libCall = spv::GLSLstd450UnpackDouble2x32;
5497 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005498
Rex Xu8ff43de2016-04-22 16:51:45 +08005499 case glslang::EOpPackInt2x32:
5500 case glslang::EOpUnpackInt2x32:
5501 case glslang::EOpPackUint2x32:
5502 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005503 case glslang::EOpPack16:
5504 case glslang::EOpPack32:
5505 case glslang::EOpPack64:
5506 case glslang::EOpUnpack32:
5507 case glslang::EOpUnpack16:
5508 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005509 case glslang::EOpPackInt2x16:
5510 case glslang::EOpUnpackInt2x16:
5511 case glslang::EOpPackUint2x16:
5512 case glslang::EOpUnpackUint2x16:
5513 case glslang::EOpPackInt4x16:
5514 case glslang::EOpUnpackInt4x16:
5515 case glslang::EOpPackUint4x16:
5516 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005517 case glslang::EOpPackFloat2x16:
5518 case glslang::EOpUnpackFloat2x16:
5519 unaryOp = spv::OpBitcast;
5520 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005521
John Kessenich140f3df2015-06-26 16:58:36 -06005522 case glslang::EOpDPdx:
5523 unaryOp = spv::OpDPdx;
5524 break;
5525 case glslang::EOpDPdy:
5526 unaryOp = spv::OpDPdy;
5527 break;
5528 case glslang::EOpFwidth:
5529 unaryOp = spv::OpFwidth;
5530 break;
5531 case glslang::EOpDPdxFine:
5532 unaryOp = spv::OpDPdxFine;
5533 break;
5534 case glslang::EOpDPdyFine:
5535 unaryOp = spv::OpDPdyFine;
5536 break;
5537 case glslang::EOpFwidthFine:
5538 unaryOp = spv::OpFwidthFine;
5539 break;
5540 case glslang::EOpDPdxCoarse:
5541 unaryOp = spv::OpDPdxCoarse;
5542 break;
5543 case glslang::EOpDPdyCoarse:
5544 unaryOp = spv::OpDPdyCoarse;
5545 break;
5546 case glslang::EOpFwidthCoarse:
5547 unaryOp = spv::OpFwidthCoarse;
5548 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005549 case glslang::EOpInterpolateAtCentroid:
Rex Xub4a2a6c2018-05-17 13:51:28 +08005550#ifdef AMD_EXTENSIONS
5551 if (typeProxy == glslang::EbtFloat16)
5552 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5553#endif
Rex Xu7a26c172015-12-08 17:12:09 +08005554 libCall = spv::GLSLstd450InterpolateAtCentroid;
5555 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005556 case glslang::EOpAny:
5557 unaryOp = spv::OpAny;
5558 break;
5559 case glslang::EOpAll:
5560 unaryOp = spv::OpAll;
5561 break;
5562
5563 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005564 if (isFloat)
5565 libCall = spv::GLSLstd450FAbs;
5566 else
5567 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005568 break;
5569 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005570 if (isFloat)
5571 libCall = spv::GLSLstd450FSign;
5572 else
5573 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005574 break;
5575
John Kessenichfc51d282015-08-19 13:34:18 -06005576 case glslang::EOpAtomicCounterIncrement:
5577 case glslang::EOpAtomicCounterDecrement:
5578 case glslang::EOpAtomicCounter:
5579 {
5580 // Handle all of the atomics in one place, in createAtomicOperation()
5581 std::vector<spv::Id> operands;
5582 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005583 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06005584 }
5585
John Kessenichfc51d282015-08-19 13:34:18 -06005586 case glslang::EOpBitFieldReverse:
5587 unaryOp = spv::OpBitReverse;
5588 break;
5589 case glslang::EOpBitCount:
5590 unaryOp = spv::OpBitCount;
5591 break;
5592 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005593 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005594 break;
5595 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005596 if (isUnsigned)
5597 libCall = spv::GLSLstd450FindUMsb;
5598 else
5599 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005600 break;
5601
Rex Xu574ab042016-04-14 16:53:07 +08005602 case glslang::EOpBallot:
5603 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005604 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005605 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005606 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005607#ifdef AMD_EXTENSIONS
5608 case glslang::EOpMinInvocations:
5609 case glslang::EOpMaxInvocations:
5610 case glslang::EOpAddInvocations:
5611 case glslang::EOpMinInvocationsNonUniform:
5612 case glslang::EOpMaxInvocationsNonUniform:
5613 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005614 case glslang::EOpMinInvocationsInclusiveScan:
5615 case glslang::EOpMaxInvocationsInclusiveScan:
5616 case glslang::EOpAddInvocationsInclusiveScan:
5617 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5618 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5619 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5620 case glslang::EOpMinInvocationsExclusiveScan:
5621 case glslang::EOpMaxInvocationsExclusiveScan:
5622 case glslang::EOpAddInvocationsExclusiveScan:
5623 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5624 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5625 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08005626#endif
Rex Xu51596642016-09-21 18:56:12 +08005627 {
5628 std::vector<spv::Id> operands;
5629 operands.push_back(operand);
5630 return createInvocationsOperation(op, typeId, operands, typeProxy);
5631 }
John Kessenich66011cb2018-03-06 16:12:04 -07005632 case glslang::EOpSubgroupAll:
5633 case glslang::EOpSubgroupAny:
5634 case glslang::EOpSubgroupAllEqual:
5635 case glslang::EOpSubgroupBroadcastFirst:
5636 case glslang::EOpSubgroupBallot:
5637 case glslang::EOpSubgroupInverseBallot:
5638 case glslang::EOpSubgroupBallotBitCount:
5639 case glslang::EOpSubgroupBallotInclusiveBitCount:
5640 case glslang::EOpSubgroupBallotExclusiveBitCount:
5641 case glslang::EOpSubgroupBallotFindLSB:
5642 case glslang::EOpSubgroupBallotFindMSB:
5643 case glslang::EOpSubgroupAdd:
5644 case glslang::EOpSubgroupMul:
5645 case glslang::EOpSubgroupMin:
5646 case glslang::EOpSubgroupMax:
5647 case glslang::EOpSubgroupAnd:
5648 case glslang::EOpSubgroupOr:
5649 case glslang::EOpSubgroupXor:
5650 case glslang::EOpSubgroupInclusiveAdd:
5651 case glslang::EOpSubgroupInclusiveMul:
5652 case glslang::EOpSubgroupInclusiveMin:
5653 case glslang::EOpSubgroupInclusiveMax:
5654 case glslang::EOpSubgroupInclusiveAnd:
5655 case glslang::EOpSubgroupInclusiveOr:
5656 case glslang::EOpSubgroupInclusiveXor:
5657 case glslang::EOpSubgroupExclusiveAdd:
5658 case glslang::EOpSubgroupExclusiveMul:
5659 case glslang::EOpSubgroupExclusiveMin:
5660 case glslang::EOpSubgroupExclusiveMax:
5661 case glslang::EOpSubgroupExclusiveAnd:
5662 case glslang::EOpSubgroupExclusiveOr:
5663 case glslang::EOpSubgroupExclusiveXor:
5664 case glslang::EOpSubgroupQuadSwapHorizontal:
5665 case glslang::EOpSubgroupQuadSwapVertical:
5666 case glslang::EOpSubgroupQuadSwapDiagonal: {
5667 std::vector<spv::Id> operands;
5668 operands.push_back(operand);
5669 return createSubgroupOperation(op, typeId, operands, typeProxy);
5670 }
Rex Xu9d93a232016-05-05 12:30:44 +08005671#ifdef AMD_EXTENSIONS
5672 case glslang::EOpMbcnt:
5673 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5674 libCall = spv::MbcntAMD;
5675 break;
5676
5677 case glslang::EOpCubeFaceIndex:
5678 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5679 libCall = spv::CubeFaceIndexAMD;
5680 break;
5681
5682 case glslang::EOpCubeFaceCoord:
5683 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5684 libCall = spv::CubeFaceCoordAMD;
5685 break;
5686#endif
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005687#ifdef NV_EXTENSIONS
5688 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005689 unaryOp = spv::OpGroupNonUniformPartitionNV;
5690 break;
5691#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005692 case glslang::EOpConstructReference:
5693 unaryOp = spv::OpBitcast;
5694 break;
Jeff Bolz88220d52019-05-08 10:24:46 -05005695
5696 case glslang::EOpCopyObject:
5697 unaryOp = spv::OpCopyObject;
5698 break;
5699
John Kessenich140f3df2015-06-26 16:58:36 -06005700 default:
5701 return 0;
5702 }
5703
5704 spv::Id id;
5705 if (libCall >= 0) {
5706 std::vector<spv::Id> args;
5707 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005708 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005709 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005710 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005711 }
John Kessenich140f3df2015-06-26 16:58:36 -06005712
John Kessenichead86222018-03-28 18:01:20 -06005713 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005714 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005715 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005716}
5717
John Kessenich7a53f762016-01-20 11:19:27 -07005718// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005719spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5720 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005721{
5722 // Handle unary operations vector by vector.
5723 // The result type is the same type as the original type.
5724 // The algorithm is to:
5725 // - break the matrix into vectors
5726 // - apply the operation to each vector
5727 // - make a matrix out the vector results
5728
5729 // get the types sorted out
5730 int numCols = builder.getNumColumns(operand);
5731 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005732 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5733 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005734 std::vector<spv::Id> results;
5735
5736 // do each vector op
5737 for (int c = 0; c < numCols; ++c) {
5738 std::vector<unsigned int> indexes;
5739 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005740 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5741 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06005742 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005743 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005744 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005745 }
5746
5747 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005748 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005749 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005750 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005751}
5752
John Kessenichad7645f2018-06-04 19:11:25 -06005753// For converting integers where both the bitwidth and the signedness could
5754// change, but only do the width change here. The caller is still responsible
5755// for the signedness conversion.
5756spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005757{
John Kessenichad7645f2018-06-04 19:11:25 -06005758 // Get the result type width, based on the type to convert to.
5759 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005760 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005761 case glslang::EOpConvInt16ToUint8:
5762 case glslang::EOpConvIntToUint8:
5763 case glslang::EOpConvInt64ToUint8:
5764 case glslang::EOpConvUint16ToInt8:
5765 case glslang::EOpConvUintToInt8:
5766 case glslang::EOpConvUint64ToInt8:
5767 width = 8;
5768 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005769 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005770 case glslang::EOpConvIntToUint16:
5771 case glslang::EOpConvInt64ToUint16:
5772 case glslang::EOpConvUint8ToInt16:
5773 case glslang::EOpConvUintToInt16:
5774 case glslang::EOpConvUint64ToInt16:
5775 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005776 break;
5777 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005778 case glslang::EOpConvInt16ToUint:
5779 case glslang::EOpConvInt64ToUint:
5780 case glslang::EOpConvUint8ToInt:
5781 case glslang::EOpConvUint16ToInt:
5782 case glslang::EOpConvUint64ToInt:
5783 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005784 break;
5785 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005786 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005787 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005788 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005789 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005790 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005791 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005792 break;
5793
5794 default:
5795 assert(false && "Default missing");
5796 break;
5797 }
5798
John Kessenichad7645f2018-06-04 19:11:25 -06005799 // Get the conversion operation and result type,
5800 // based on the target width, but the source type.
5801 spv::Id type = spv::NoType;
5802 spv::Op convOp = spv::OpNop;
5803 switch(op) {
5804 case glslang::EOpConvInt8ToUint16:
5805 case glslang::EOpConvInt8ToUint:
5806 case glslang::EOpConvInt8ToUint64:
5807 case glslang::EOpConvInt16ToUint8:
5808 case glslang::EOpConvInt16ToUint:
5809 case glslang::EOpConvInt16ToUint64:
5810 case glslang::EOpConvIntToUint8:
5811 case glslang::EOpConvIntToUint16:
5812 case glslang::EOpConvIntToUint64:
5813 case glslang::EOpConvInt64ToUint8:
5814 case glslang::EOpConvInt64ToUint16:
5815 case glslang::EOpConvInt64ToUint:
5816 convOp = spv::OpSConvert;
5817 type = builder.makeIntType(width);
5818 break;
5819 default:
5820 convOp = spv::OpUConvert;
5821 type = builder.makeUintType(width);
5822 break;
5823 }
5824
John Kessenich66011cb2018-03-06 16:12:04 -07005825 if (vectorSize > 0)
5826 type = builder.makeVectorType(type, vectorSize);
5827
John Kessenichad7645f2018-06-04 19:11:25 -06005828 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005829}
5830
John Kessenichead86222018-03-28 18:01:20 -06005831spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5832 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005833{
5834 spv::Op convOp = spv::OpNop;
5835 spv::Id zero = 0;
5836 spv::Id one = 0;
5837
5838 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5839
5840 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005841 case glslang::EOpConvInt8ToBool:
5842 case glslang::EOpConvUint8ToBool:
5843 zero = builder.makeUint8Constant(0);
5844 zero = makeSmearedConstant(zero, vectorSize);
5845 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08005846 case glslang::EOpConvInt16ToBool:
5847 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07005848 zero = builder.makeUint16Constant(0);
5849 zero = makeSmearedConstant(zero, vectorSize);
5850 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5851 case glslang::EOpConvIntToBool:
5852 case glslang::EOpConvUintToBool:
5853 zero = builder.makeUintConstant(0);
5854 zero = makeSmearedConstant(zero, vectorSize);
5855 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5856 case glslang::EOpConvInt64ToBool:
5857 case glslang::EOpConvUint64ToBool:
5858 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005859 zero = makeSmearedConstant(zero, vectorSize);
5860 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5861
5862 case glslang::EOpConvFloatToBool:
5863 zero = builder.makeFloatConstant(0.0F);
5864 zero = makeSmearedConstant(zero, vectorSize);
5865 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5866
5867 case glslang::EOpConvDoubleToBool:
5868 zero = builder.makeDoubleConstant(0.0);
5869 zero = makeSmearedConstant(zero, vectorSize);
5870 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5871
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005872 case glslang::EOpConvFloat16ToBool:
5873 zero = builder.makeFloat16Constant(0.0F);
5874 zero = makeSmearedConstant(zero, vectorSize);
5875 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005876
John Kessenich140f3df2015-06-26 16:58:36 -06005877 case glslang::EOpConvBoolToFloat:
5878 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005879 zero = builder.makeFloatConstant(0.0F);
5880 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06005881 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005882
John Kessenich140f3df2015-06-26 16:58:36 -06005883 case glslang::EOpConvBoolToDouble:
5884 convOp = spv::OpSelect;
5885 zero = builder.makeDoubleConstant(0.0);
5886 one = builder.makeDoubleConstant(1.0);
5887 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005888
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005889 case glslang::EOpConvBoolToFloat16:
5890 convOp = spv::OpSelect;
5891 zero = builder.makeFloat16Constant(0.0F);
5892 one = builder.makeFloat16Constant(1.0F);
5893 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005894
5895 case glslang::EOpConvBoolToInt8:
5896 zero = builder.makeInt8Constant(0);
5897 one = builder.makeInt8Constant(1);
5898 convOp = spv::OpSelect;
5899 break;
5900
5901 case glslang::EOpConvBoolToUint8:
5902 zero = builder.makeUint8Constant(0);
5903 one = builder.makeUint8Constant(1);
5904 convOp = spv::OpSelect;
5905 break;
5906
5907 case glslang::EOpConvBoolToInt16:
5908 zero = builder.makeInt16Constant(0);
5909 one = builder.makeInt16Constant(1);
5910 convOp = spv::OpSelect;
5911 break;
5912
5913 case glslang::EOpConvBoolToUint16:
5914 zero = builder.makeUint16Constant(0);
5915 one = builder.makeUint16Constant(1);
5916 convOp = spv::OpSelect;
5917 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005918
John Kessenich140f3df2015-06-26 16:58:36 -06005919 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005920 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005921 if (op == glslang::EOpConvBoolToInt64)
5922 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005923 else
5924 zero = builder.makeIntConstant(0);
5925
5926 if (op == glslang::EOpConvBoolToInt64)
5927 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005928 else
5929 one = builder.makeIntConstant(1);
5930
John Kessenich140f3df2015-06-26 16:58:36 -06005931 convOp = spv::OpSelect;
5932 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005933
John Kessenich140f3df2015-06-26 16:58:36 -06005934 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005935 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08005936 if (op == glslang::EOpConvBoolToUint64)
5937 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005938 else
5939 zero = builder.makeUintConstant(0);
5940
5941 if (op == glslang::EOpConvBoolToUint64)
5942 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005943 else
5944 one = builder.makeUintConstant(1);
5945
John Kessenich140f3df2015-06-26 16:58:36 -06005946 convOp = spv::OpSelect;
5947 break;
5948
John Kessenich66011cb2018-03-06 16:12:04 -07005949 case glslang::EOpConvInt8ToFloat16:
5950 case glslang::EOpConvInt8ToFloat:
5951 case glslang::EOpConvInt8ToDouble:
5952 case glslang::EOpConvInt16ToFloat16:
5953 case glslang::EOpConvInt16ToFloat:
5954 case glslang::EOpConvInt16ToDouble:
5955 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005956 case glslang::EOpConvIntToFloat:
5957 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005958 case glslang::EOpConvInt64ToFloat:
5959 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005960 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005961 convOp = spv::OpConvertSToF;
5962 break;
5963
John Kessenich66011cb2018-03-06 16:12:04 -07005964 case glslang::EOpConvUint8ToFloat16:
5965 case glslang::EOpConvUint8ToFloat:
5966 case glslang::EOpConvUint8ToDouble:
5967 case glslang::EOpConvUint16ToFloat16:
5968 case glslang::EOpConvUint16ToFloat:
5969 case glslang::EOpConvUint16ToDouble:
5970 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005971 case glslang::EOpConvUintToFloat:
5972 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005973 case glslang::EOpConvUint64ToFloat:
5974 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005975 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005976 convOp = spv::OpConvertUToF;
5977 break;
5978
5979 case glslang::EOpConvDoubleToFloat:
5980 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005981 case glslang::EOpConvDoubleToFloat16:
5982 case glslang::EOpConvFloat16ToDouble:
5983 case glslang::EOpConvFloatToFloat16:
5984 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06005985 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08005986 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06005987 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005988 break;
5989
John Kessenich66011cb2018-03-06 16:12:04 -07005990 case glslang::EOpConvFloat16ToInt8:
5991 case glslang::EOpConvFloatToInt8:
5992 case glslang::EOpConvDoubleToInt8:
5993 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005994 case glslang::EOpConvFloatToInt16:
5995 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005996 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07005997 case glslang::EOpConvFloatToInt:
5998 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005999 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006000 case glslang::EOpConvFloatToInt64:
6001 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006002 convOp = spv::OpConvertFToS;
6003 break;
6004
John Kessenich66011cb2018-03-06 16:12:04 -07006005 case glslang::EOpConvUint8ToInt8:
6006 case glslang::EOpConvInt8ToUint8:
6007 case glslang::EOpConvUint16ToInt16:
6008 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006009 case glslang::EOpConvUintToInt:
6010 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006011 case glslang::EOpConvUint64ToInt64:
6012 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006013 if (builder.isInSpecConstCodeGenMode()) {
6014 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006015 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6016 zero = builder.makeUint8Constant(0);
6017 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006018 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006019 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6020 zero = builder.makeUint64Constant(0);
6021 } else {
Rex Xucabbb782017-03-24 13:41:14 +08006022 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006023 }
qining189b2032016-04-12 23:16:20 -04006024 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006025 // Use OpIAdd, instead of OpBitcast to do the conversion when
6026 // generating for OpSpecConstantOp instruction.
6027 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6028 }
6029 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006030 convOp = spv::OpBitcast;
6031 break;
6032
John Kessenich66011cb2018-03-06 16:12:04 -07006033 case glslang::EOpConvFloat16ToUint8:
6034 case glslang::EOpConvFloatToUint8:
6035 case glslang::EOpConvDoubleToUint8:
6036 case glslang::EOpConvFloat16ToUint16:
6037 case glslang::EOpConvFloatToUint16:
6038 case glslang::EOpConvDoubleToUint16:
6039 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006040 case glslang::EOpConvFloatToUint:
6041 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006042 case glslang::EOpConvFloatToUint64:
6043 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006044 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006045 convOp = spv::OpConvertFToU;
6046 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006047
John Kessenich66011cb2018-03-06 16:12:04 -07006048 case glslang::EOpConvInt8ToInt16:
6049 case glslang::EOpConvInt8ToInt:
6050 case glslang::EOpConvInt8ToInt64:
6051 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006052 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006053 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006054 case glslang::EOpConvIntToInt8:
6055 case glslang::EOpConvIntToInt16:
6056 case glslang::EOpConvIntToInt64:
6057 case glslang::EOpConvInt64ToInt8:
6058 case glslang::EOpConvInt64ToInt16:
6059 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006060 convOp = spv::OpSConvert;
6061 break;
6062
John Kessenich66011cb2018-03-06 16:12:04 -07006063 case glslang::EOpConvUint8ToUint16:
6064 case glslang::EOpConvUint8ToUint:
6065 case glslang::EOpConvUint8ToUint64:
6066 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006067 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006068 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006069 case glslang::EOpConvUintToUint8:
6070 case glslang::EOpConvUintToUint16:
6071 case glslang::EOpConvUintToUint64:
6072 case glslang::EOpConvUint64ToUint8:
6073 case glslang::EOpConvUint64ToUint16:
6074 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006075 convOp = spv::OpUConvert;
6076 break;
6077
John Kessenich66011cb2018-03-06 16:12:04 -07006078 case glslang::EOpConvInt8ToUint16:
6079 case glslang::EOpConvInt8ToUint:
6080 case glslang::EOpConvInt8ToUint64:
6081 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006082 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006083 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006084 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006085 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006086 case glslang::EOpConvIntToUint64:
6087 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006088 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006089 case glslang::EOpConvInt64ToUint:
6090 case glslang::EOpConvUint8ToInt16:
6091 case glslang::EOpConvUint8ToInt:
6092 case glslang::EOpConvUint8ToInt64:
6093 case glslang::EOpConvUint16ToInt8:
6094 case glslang::EOpConvUint16ToInt:
6095 case glslang::EOpConvUint16ToInt64:
6096 case glslang::EOpConvUintToInt8:
6097 case glslang::EOpConvUintToInt16:
6098 case glslang::EOpConvUintToInt64:
6099 case glslang::EOpConvUint64ToInt8:
6100 case glslang::EOpConvUint64ToInt16:
6101 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006102 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006103 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006104
6105 if (builder.isInSpecConstCodeGenMode()) {
6106 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006107 switch(op) {
6108 case glslang::EOpConvInt16ToUint8:
6109 case glslang::EOpConvIntToUint8:
6110 case glslang::EOpConvInt64ToUint8:
6111 case glslang::EOpConvUint16ToInt8:
6112 case glslang::EOpConvUintToInt8:
6113 case glslang::EOpConvUint64ToInt8:
6114 zero = builder.makeUint8Constant(0);
6115 break;
6116 case glslang::EOpConvInt8ToUint16:
6117 case glslang::EOpConvIntToUint16:
6118 case glslang::EOpConvInt64ToUint16:
6119 case glslang::EOpConvUint8ToInt16:
6120 case glslang::EOpConvUintToInt16:
6121 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006122 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006123 break;
6124 case glslang::EOpConvInt8ToUint:
6125 case glslang::EOpConvInt16ToUint:
6126 case glslang::EOpConvInt64ToUint:
6127 case glslang::EOpConvUint8ToInt:
6128 case glslang::EOpConvUint16ToInt:
6129 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006130 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006131 break;
6132 case glslang::EOpConvInt8ToUint64:
6133 case glslang::EOpConvInt16ToUint64:
6134 case glslang::EOpConvIntToUint64:
6135 case glslang::EOpConvUint8ToInt64:
6136 case glslang::EOpConvUint16ToInt64:
6137 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006138 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006139 break;
6140 default:
6141 assert(false && "Default missing");
6142 break;
6143 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006144 zero = makeSmearedConstant(zero, vectorSize);
6145 // Use OpIAdd, instead of OpBitcast to do the conversion when
6146 // generating for OpSpecConstantOp instruction.
6147 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6148 }
6149 // For normal run-time conversion instruction, use OpBitcast.
6150 convOp = spv::OpBitcast;
6151 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006152 case glslang::EOpConvUint64ToPtr:
6153 convOp = spv::OpConvertUToPtr;
6154 break;
6155 case glslang::EOpConvPtrToUint64:
6156 convOp = spv::OpConvertPtrToU;
6157 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006158 default:
6159 break;
6160 }
6161
6162 spv::Id result = 0;
6163 if (convOp == spv::OpNop)
6164 return result;
6165
6166 if (convOp == spv::OpSelect) {
6167 zero = makeSmearedConstant(zero, vectorSize);
6168 one = makeSmearedConstant(one, vectorSize);
6169 result = builder.createTriOp(convOp, destType, operand, one, zero);
6170 } else
6171 result = builder.createUnaryOp(convOp, destType, operand);
6172
John Kessenichead86222018-03-28 18:01:20 -06006173 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06006174 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06006175 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006176}
6177
6178spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6179{
6180 if (vectorSize == 0)
6181 return constant;
6182
6183 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6184 std::vector<spv::Id> components;
6185 for (int c = 0; c < vectorSize; ++c)
6186 components.push_back(constant);
6187 return builder.makeCompositeConstant(vectorTypeId, components);
6188}
6189
John Kessenich426394d2015-07-23 10:22:48 -06006190// For glslang ops that map to SPV atomic opCodes
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006191spv::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 -06006192{
6193 spv::Op opCode = spv::OpNop;
6194
6195 switch (op) {
6196 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006197 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006198 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006199 opCode = spv::OpAtomicIAdd;
6200 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006201 case glslang::EOpAtomicCounterSubtract:
6202 opCode = spv::OpAtomicISub;
6203 break;
John Kessenich426394d2015-07-23 10:22:48 -06006204 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006205 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006206 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08006207 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006208 break;
6209 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006210 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006211 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08006212 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006213 break;
6214 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006215 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006216 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006217 opCode = spv::OpAtomicAnd;
6218 break;
6219 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006220 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006221 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006222 opCode = spv::OpAtomicOr;
6223 break;
6224 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006225 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006226 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006227 opCode = spv::OpAtomicXor;
6228 break;
6229 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006230 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006231 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006232 opCode = spv::OpAtomicExchange;
6233 break;
6234 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006235 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006236 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006237 opCode = spv::OpAtomicCompareExchange;
6238 break;
6239 case glslang::EOpAtomicCounterIncrement:
6240 opCode = spv::OpAtomicIIncrement;
6241 break;
6242 case glslang::EOpAtomicCounterDecrement:
6243 opCode = spv::OpAtomicIDecrement;
6244 break;
6245 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006246 case glslang::EOpImageAtomicLoad:
6247 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006248 opCode = spv::OpAtomicLoad;
6249 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006250 case glslang::EOpAtomicStore:
6251 case glslang::EOpImageAtomicStore:
6252 opCode = spv::OpAtomicStore;
6253 break;
John Kessenich426394d2015-07-23 10:22:48 -06006254 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006255 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006256 break;
6257 }
6258
Rex Xue8fe8b02017-09-26 15:42:56 +08006259 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6260 builder.addCapability(spv::CapabilityInt64Atomics);
6261
John Kessenich426394d2015-07-23 10:22:48 -06006262 // Sort out the operands
6263 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006264 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006265 // - compare-exchange swaps the value and comparator
6266 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006267 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006268 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6269 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6270 spv::Id scopeId;
6271 if (glslangIntermediate->usingVulkanMemoryModel()) {
6272 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6273 } else {
6274 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6275 }
6276 // semantics default to relaxed
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006277 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.volatil ? spv::MemorySemanticsVolatileMask : spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006278 spv::Id semanticsId2 = semanticsId;
6279
6280 pointerId = operands[0];
6281 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6282 // no additional operands
6283 } else if (opCode == spv::OpAtomicCompareExchange) {
6284 compareId = operands[1];
6285 valueId = operands[2];
6286 if (operands.size() > 3) {
6287 scopeId = operands[3];
6288 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6289 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
6290 }
6291 } else if (opCode == spv::OpAtomicLoad) {
6292 if (operands.size() > 1) {
6293 scopeId = operands[1];
6294 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
6295 }
6296 } else {
6297 // atomic store or RMW
6298 valueId = operands[1];
6299 if (operands.size() > 2) {
6300 scopeId = operands[2];
6301 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
6302 }
Rex Xu04db3f52015-09-16 11:44:02 +08006303 }
John Kessenich426394d2015-07-23 10:22:48 -06006304
Jeff Bolz36831c92018-09-05 10:11:41 -05006305 // Check for capabilities
6306 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006307 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6308 spv::MemorySemanticsMakeVisibleKHRMask |
6309 spv::MemorySemanticsOutputMemoryKHRMask |
6310 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006311 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6312 }
John Kessenich426394d2015-07-23 10:22:48 -06006313
Jeff Bolz36831c92018-09-05 10:11:41 -05006314 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6315 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6316 }
John Kessenich48d6e792017-10-06 21:21:48 -06006317
Jeff Bolz36831c92018-09-05 10:11:41 -05006318 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6319 spvAtomicOperands.push_back(pointerId);
6320 spvAtomicOperands.push_back(scopeId);
6321 spvAtomicOperands.push_back(semanticsId);
6322 if (opCode == spv::OpAtomicCompareExchange) {
6323 spvAtomicOperands.push_back(semanticsId2);
6324 spvAtomicOperands.push_back(valueId);
6325 spvAtomicOperands.push_back(compareId);
6326 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6327 spvAtomicOperands.push_back(valueId);
6328 }
John Kessenich48d6e792017-10-06 21:21:48 -06006329
Jeff Bolz36831c92018-09-05 10:11:41 -05006330 if (opCode == spv::OpAtomicStore) {
6331 builder.createNoResultOp(opCode, spvAtomicOperands);
6332 return 0;
6333 } else {
6334 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6335
6336 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6337 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6338 if (op == glslang::EOpAtomicCounterDecrement)
6339 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6340
6341 return resultId;
6342 }
John Kessenich426394d2015-07-23 10:22:48 -06006343}
6344
John Kessenich91cef522016-05-05 16:45:40 -06006345// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08006346spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006347{
Corentin Walleze7061422018-08-08 15:20:15 +02006348#ifdef AMD_EXTENSIONS
John Kessenich66011cb2018-03-06 16:12:04 -07006349 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6350 bool isFloat = isTypeFloat(typeProxy);
Corentin Walleze7061422018-08-08 15:20:15 +02006351#endif
Rex Xu9d93a232016-05-05 12:30:44 +08006352
Rex Xu51596642016-09-21 18:56:12 +08006353 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006354 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006355 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6356
chaocf200da82016-12-20 12:44:35 -08006357 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6358 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006359 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6360 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006361 } else if (op == glslang::EOpAnyInvocation ||
6362 op == glslang::EOpAllInvocations ||
6363 op == glslang::EOpAllInvocationsEqual) {
6364 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6365 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006366 } else {
6367 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04006368#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08006369 if (op == glslang::EOpMinInvocationsNonUniform ||
6370 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006371 op == glslang::EOpAddInvocationsNonUniform ||
6372 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6373 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6374 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6375 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6376 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6377 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006378 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04006379#endif
Rex Xu51596642016-09-21 18:56:12 +08006380
Rex Xu9d93a232016-05-05 12:30:44 +08006381#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08006382 switch (op) {
6383 case glslang::EOpMinInvocations:
6384 case glslang::EOpMaxInvocations:
6385 case glslang::EOpAddInvocations:
6386 case glslang::EOpMinInvocationsNonUniform:
6387 case glslang::EOpMaxInvocationsNonUniform:
6388 case glslang::EOpAddInvocationsNonUniform:
6389 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006390 break;
6391 case glslang::EOpMinInvocationsInclusiveScan:
6392 case glslang::EOpMaxInvocationsInclusiveScan:
6393 case glslang::EOpAddInvocationsInclusiveScan:
6394 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6395 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6396 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6397 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006398 break;
6399 case glslang::EOpMinInvocationsExclusiveScan:
6400 case glslang::EOpMaxInvocationsExclusiveScan:
6401 case glslang::EOpAddInvocationsExclusiveScan:
6402 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6403 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6404 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6405 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006406 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006407 default:
6408 break;
Rex Xu430ef402016-10-14 17:22:23 +08006409 }
John Kessenich149afc32018-08-14 13:31:43 -06006410 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6411 spvGroupOperands.push_back(scope);
6412 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006413 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006414 spvGroupOperands.push_back(groupOp);
6415 }
Rex Xu9d93a232016-05-05 12:30:44 +08006416#endif
Rex Xu51596642016-09-21 18:56:12 +08006417 }
6418
John Kessenich149afc32018-08-14 13:31:43 -06006419 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6420 spv::IdImmediate op = { true, *opIt };
6421 spvGroupOperands.push_back(op);
6422 }
John Kessenich91cef522016-05-05 16:45:40 -06006423
6424 switch (op) {
6425 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006426 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006427 break;
John Kessenich91cef522016-05-05 16:45:40 -06006428 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006429 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006430 break;
John Kessenich91cef522016-05-05 16:45:40 -06006431 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006432 opCode = spv::OpSubgroupAllEqualKHR;
6433 break;
Rex Xu51596642016-09-21 18:56:12 +08006434 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006435 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006436 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006437 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006438 break;
6439 case glslang::EOpReadFirstInvocation:
6440 opCode = spv::OpSubgroupFirstInvocationKHR;
6441 break;
6442 case glslang::EOpBallot:
6443 {
6444 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6445 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6446 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6447 //
6448 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6449 //
6450 spv::Id uintType = builder.makeUintType(32);
6451 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6452 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6453
6454 std::vector<spv::Id> components;
6455 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6456 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6457
6458 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6459 return builder.createUnaryOp(spv::OpBitcast, typeId,
6460 builder.createCompositeConstruct(uvec2Type, components));
6461 }
6462
Rex Xu9d93a232016-05-05 12:30:44 +08006463#ifdef AMD_EXTENSIONS
6464 case glslang::EOpMinInvocations:
6465 case glslang::EOpMaxInvocations:
6466 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006467 case glslang::EOpMinInvocationsInclusiveScan:
6468 case glslang::EOpMaxInvocationsInclusiveScan:
6469 case glslang::EOpAddInvocationsInclusiveScan:
6470 case glslang::EOpMinInvocationsExclusiveScan:
6471 case glslang::EOpMaxInvocationsExclusiveScan:
6472 case glslang::EOpAddInvocationsExclusiveScan:
6473 if (op == glslang::EOpMinInvocations ||
6474 op == glslang::EOpMinInvocationsInclusiveScan ||
6475 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006476 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006477 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006478 else {
6479 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006480 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006481 else
Rex Xu51596642016-09-21 18:56:12 +08006482 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006483 }
Rex Xu430ef402016-10-14 17:22:23 +08006484 } else if (op == glslang::EOpMaxInvocations ||
6485 op == glslang::EOpMaxInvocationsInclusiveScan ||
6486 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006487 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006488 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006489 else {
6490 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006491 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006492 else
Rex Xu51596642016-09-21 18:56:12 +08006493 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006494 }
6495 } else {
6496 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006497 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006498 else
Rex Xu51596642016-09-21 18:56:12 +08006499 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006500 }
6501
Rex Xu2bbbe062016-08-23 15:41:05 +08006502 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006503 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006504
6505 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006506 case glslang::EOpMinInvocationsNonUniform:
6507 case glslang::EOpMaxInvocationsNonUniform:
6508 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006509 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6510 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6511 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6512 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6513 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6514 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6515 if (op == glslang::EOpMinInvocationsNonUniform ||
6516 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6517 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006518 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006519 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006520 else {
6521 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006522 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006523 else
Rex Xu51596642016-09-21 18:56:12 +08006524 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006525 }
6526 }
Rex Xu430ef402016-10-14 17:22:23 +08006527 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6528 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6529 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006530 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006531 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006532 else {
6533 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006534 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006535 else
Rex Xu51596642016-09-21 18:56:12 +08006536 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006537 }
6538 }
6539 else {
6540 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006541 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006542 else
Rex Xu51596642016-09-21 18:56:12 +08006543 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006544 }
6545
Rex Xu2bbbe062016-08-23 15:41:05 +08006546 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006547 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006548
6549 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006550#endif
John Kessenich91cef522016-05-05 16:45:40 -06006551 default:
6552 logger->missingFunctionality("invocation operation");
6553 return spv::NoResult;
6554 }
Rex Xu51596642016-09-21 18:56:12 +08006555
6556 assert(opCode != spv::OpNop);
6557 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006558}
6559
Rex Xu2bbbe062016-08-23 15:41:05 +08006560// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006561spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6562 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006563{
Rex Xub7072052016-09-26 15:53:40 +08006564#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08006565 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6566 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006567 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006568 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006569 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
6570 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
6571 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08006572#else
6573 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6574 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08006575 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
6576 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08006577#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08006578
6579 // Handle group invocation operations scalar by scalar.
6580 // The result type is the same type as the original type.
6581 // The algorithm is to:
6582 // - break the vector into scalars
6583 // - apply the operation to each scalar
6584 // - make a vector out the scalar results
6585
6586 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006587 int numComponents = builder.getNumComponents(operands[0]);
6588 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006589 std::vector<spv::Id> results;
6590
6591 // do each scalar op
6592 for (int comp = 0; comp < numComponents; ++comp) {
6593 std::vector<unsigned int> indexes;
6594 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006595 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6596 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006597 if (op == spv::OpSubgroupReadInvocationKHR) {
6598 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006599 spv::IdImmediate operand = { true, operands[1] };
6600 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006601 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006602 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6603 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006604 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006605 spv::IdImmediate operand = { true, operands[1] };
6606 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006607 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006608 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6609 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006610 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006611 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006612 spvGroupOperands.push_back(scalar);
6613 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006614
Rex Xub7072052016-09-26 15:53:40 +08006615 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006616 }
6617
6618 // put the pieces together
6619 return builder.createCompositeConstruct(typeId, results);
6620}
Rex Xu2bbbe062016-08-23 15:41:05 +08006621
John Kessenich66011cb2018-03-06 16:12:04 -07006622// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006623spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6624 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006625{
6626 // Add the required capabilities.
6627 switch (op) {
6628 case glslang::EOpSubgroupElect:
6629 builder.addCapability(spv::CapabilityGroupNonUniform);
6630 break;
6631 case glslang::EOpSubgroupAll:
6632 case glslang::EOpSubgroupAny:
6633 case glslang::EOpSubgroupAllEqual:
6634 builder.addCapability(spv::CapabilityGroupNonUniform);
6635 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6636 break;
6637 case glslang::EOpSubgroupBroadcast:
6638 case glslang::EOpSubgroupBroadcastFirst:
6639 case glslang::EOpSubgroupBallot:
6640 case glslang::EOpSubgroupInverseBallot:
6641 case glslang::EOpSubgroupBallotBitExtract:
6642 case glslang::EOpSubgroupBallotBitCount:
6643 case glslang::EOpSubgroupBallotInclusiveBitCount:
6644 case glslang::EOpSubgroupBallotExclusiveBitCount:
6645 case glslang::EOpSubgroupBallotFindLSB:
6646 case glslang::EOpSubgroupBallotFindMSB:
6647 builder.addCapability(spv::CapabilityGroupNonUniform);
6648 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6649 break;
6650 case glslang::EOpSubgroupShuffle:
6651 case glslang::EOpSubgroupShuffleXor:
6652 builder.addCapability(spv::CapabilityGroupNonUniform);
6653 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6654 break;
6655 case glslang::EOpSubgroupShuffleUp:
6656 case glslang::EOpSubgroupShuffleDown:
6657 builder.addCapability(spv::CapabilityGroupNonUniform);
6658 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6659 break;
6660 case glslang::EOpSubgroupAdd:
6661 case glslang::EOpSubgroupMul:
6662 case glslang::EOpSubgroupMin:
6663 case glslang::EOpSubgroupMax:
6664 case glslang::EOpSubgroupAnd:
6665 case glslang::EOpSubgroupOr:
6666 case glslang::EOpSubgroupXor:
6667 case glslang::EOpSubgroupInclusiveAdd:
6668 case glslang::EOpSubgroupInclusiveMul:
6669 case glslang::EOpSubgroupInclusiveMin:
6670 case glslang::EOpSubgroupInclusiveMax:
6671 case glslang::EOpSubgroupInclusiveAnd:
6672 case glslang::EOpSubgroupInclusiveOr:
6673 case glslang::EOpSubgroupInclusiveXor:
6674 case glslang::EOpSubgroupExclusiveAdd:
6675 case glslang::EOpSubgroupExclusiveMul:
6676 case glslang::EOpSubgroupExclusiveMin:
6677 case glslang::EOpSubgroupExclusiveMax:
6678 case glslang::EOpSubgroupExclusiveAnd:
6679 case glslang::EOpSubgroupExclusiveOr:
6680 case glslang::EOpSubgroupExclusiveXor:
6681 builder.addCapability(spv::CapabilityGroupNonUniform);
6682 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6683 break;
6684 case glslang::EOpSubgroupClusteredAdd:
6685 case glslang::EOpSubgroupClusteredMul:
6686 case glslang::EOpSubgroupClusteredMin:
6687 case glslang::EOpSubgroupClusteredMax:
6688 case glslang::EOpSubgroupClusteredAnd:
6689 case glslang::EOpSubgroupClusteredOr:
6690 case glslang::EOpSubgroupClusteredXor:
6691 builder.addCapability(spv::CapabilityGroupNonUniform);
6692 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6693 break;
6694 case glslang::EOpSubgroupQuadBroadcast:
6695 case glslang::EOpSubgroupQuadSwapHorizontal:
6696 case glslang::EOpSubgroupQuadSwapVertical:
6697 case glslang::EOpSubgroupQuadSwapDiagonal:
6698 builder.addCapability(spv::CapabilityGroupNonUniform);
6699 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6700 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006701#ifdef NV_EXTENSIONS
6702 case glslang::EOpSubgroupPartitionedAdd:
6703 case glslang::EOpSubgroupPartitionedMul:
6704 case glslang::EOpSubgroupPartitionedMin:
6705 case glslang::EOpSubgroupPartitionedMax:
6706 case glslang::EOpSubgroupPartitionedAnd:
6707 case glslang::EOpSubgroupPartitionedOr:
6708 case glslang::EOpSubgroupPartitionedXor:
6709 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6710 case glslang::EOpSubgroupPartitionedInclusiveMul:
6711 case glslang::EOpSubgroupPartitionedInclusiveMin:
6712 case glslang::EOpSubgroupPartitionedInclusiveMax:
6713 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6714 case glslang::EOpSubgroupPartitionedInclusiveOr:
6715 case glslang::EOpSubgroupPartitionedInclusiveXor:
6716 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6717 case glslang::EOpSubgroupPartitionedExclusiveMul:
6718 case glslang::EOpSubgroupPartitionedExclusiveMin:
6719 case glslang::EOpSubgroupPartitionedExclusiveMax:
6720 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6721 case glslang::EOpSubgroupPartitionedExclusiveOr:
6722 case glslang::EOpSubgroupPartitionedExclusiveXor:
6723 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6724 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6725 break;
6726#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006727 default: assert(0 && "Unhandled subgroup operation!");
6728 }
6729
6730 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
6731 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
6732 const bool isBool = typeProxy == glslang::EbtBool;
6733
6734 spv::Op opCode = spv::OpNop;
6735
6736 // Figure out which opcode to use.
6737 switch (op) {
6738 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6739 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6740 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6741 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6742 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6743 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6744 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6745 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6746 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6747 case glslang::EOpSubgroupBallotBitCount:
6748 case glslang::EOpSubgroupBallotInclusiveBitCount:
6749 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6750 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6751 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6752 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6753 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6754 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6755 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6756 case glslang::EOpSubgroupAdd:
6757 case glslang::EOpSubgroupInclusiveAdd:
6758 case glslang::EOpSubgroupExclusiveAdd:
6759 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006760#ifdef NV_EXTENSIONS
6761 case glslang::EOpSubgroupPartitionedAdd:
6762 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6763 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6764#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006765 if (isFloat) {
6766 opCode = spv::OpGroupNonUniformFAdd;
6767 } else {
6768 opCode = spv::OpGroupNonUniformIAdd;
6769 }
6770 break;
6771 case glslang::EOpSubgroupMul:
6772 case glslang::EOpSubgroupInclusiveMul:
6773 case glslang::EOpSubgroupExclusiveMul:
6774 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006775#ifdef NV_EXTENSIONS
6776 case glslang::EOpSubgroupPartitionedMul:
6777 case glslang::EOpSubgroupPartitionedInclusiveMul:
6778 case glslang::EOpSubgroupPartitionedExclusiveMul:
6779#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006780 if (isFloat) {
6781 opCode = spv::OpGroupNonUniformFMul;
6782 } else {
6783 opCode = spv::OpGroupNonUniformIMul;
6784 }
6785 break;
6786 case glslang::EOpSubgroupMin:
6787 case glslang::EOpSubgroupInclusiveMin:
6788 case glslang::EOpSubgroupExclusiveMin:
6789 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006790#ifdef NV_EXTENSIONS
6791 case glslang::EOpSubgroupPartitionedMin:
6792 case glslang::EOpSubgroupPartitionedInclusiveMin:
6793 case glslang::EOpSubgroupPartitionedExclusiveMin:
6794#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006795 if (isFloat) {
6796 opCode = spv::OpGroupNonUniformFMin;
6797 } else if (isUnsigned) {
6798 opCode = spv::OpGroupNonUniformUMin;
6799 } else {
6800 opCode = spv::OpGroupNonUniformSMin;
6801 }
6802 break;
6803 case glslang::EOpSubgroupMax:
6804 case glslang::EOpSubgroupInclusiveMax:
6805 case glslang::EOpSubgroupExclusiveMax:
6806 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006807#ifdef NV_EXTENSIONS
6808 case glslang::EOpSubgroupPartitionedMax:
6809 case glslang::EOpSubgroupPartitionedInclusiveMax:
6810 case glslang::EOpSubgroupPartitionedExclusiveMax:
6811#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006812 if (isFloat) {
6813 opCode = spv::OpGroupNonUniformFMax;
6814 } else if (isUnsigned) {
6815 opCode = spv::OpGroupNonUniformUMax;
6816 } else {
6817 opCode = spv::OpGroupNonUniformSMax;
6818 }
6819 break;
6820 case glslang::EOpSubgroupAnd:
6821 case glslang::EOpSubgroupInclusiveAnd:
6822 case glslang::EOpSubgroupExclusiveAnd:
6823 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006824#ifdef NV_EXTENSIONS
6825 case glslang::EOpSubgroupPartitionedAnd:
6826 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6827 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6828#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006829 if (isBool) {
6830 opCode = spv::OpGroupNonUniformLogicalAnd;
6831 } else {
6832 opCode = spv::OpGroupNonUniformBitwiseAnd;
6833 }
6834 break;
6835 case glslang::EOpSubgroupOr:
6836 case glslang::EOpSubgroupInclusiveOr:
6837 case glslang::EOpSubgroupExclusiveOr:
6838 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006839#ifdef NV_EXTENSIONS
6840 case glslang::EOpSubgroupPartitionedOr:
6841 case glslang::EOpSubgroupPartitionedInclusiveOr:
6842 case glslang::EOpSubgroupPartitionedExclusiveOr:
6843#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006844 if (isBool) {
6845 opCode = spv::OpGroupNonUniformLogicalOr;
6846 } else {
6847 opCode = spv::OpGroupNonUniformBitwiseOr;
6848 }
6849 break;
6850 case glslang::EOpSubgroupXor:
6851 case glslang::EOpSubgroupInclusiveXor:
6852 case glslang::EOpSubgroupExclusiveXor:
6853 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006854#ifdef NV_EXTENSIONS
6855 case glslang::EOpSubgroupPartitionedXor:
6856 case glslang::EOpSubgroupPartitionedInclusiveXor:
6857 case glslang::EOpSubgroupPartitionedExclusiveXor:
6858#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006859 if (isBool) {
6860 opCode = spv::OpGroupNonUniformLogicalXor;
6861 } else {
6862 opCode = spv::OpGroupNonUniformBitwiseXor;
6863 }
6864 break;
6865 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
6866 case glslang::EOpSubgroupQuadSwapHorizontal:
6867 case glslang::EOpSubgroupQuadSwapVertical:
6868 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
6869 default: assert(0 && "Unhandled subgroup operation!");
6870 }
6871
John Kessenich149afc32018-08-14 13:31:43 -06006872 // get the right Group Operation
6873 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07006874 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06006875 default:
6876 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006877 case glslang::EOpSubgroupBallotBitCount:
6878 case glslang::EOpSubgroupAdd:
6879 case glslang::EOpSubgroupMul:
6880 case glslang::EOpSubgroupMin:
6881 case glslang::EOpSubgroupMax:
6882 case glslang::EOpSubgroupAnd:
6883 case glslang::EOpSubgroupOr:
6884 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06006885 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006886 break;
6887 case glslang::EOpSubgroupBallotInclusiveBitCount:
6888 case glslang::EOpSubgroupInclusiveAdd:
6889 case glslang::EOpSubgroupInclusiveMul:
6890 case glslang::EOpSubgroupInclusiveMin:
6891 case glslang::EOpSubgroupInclusiveMax:
6892 case glslang::EOpSubgroupInclusiveAnd:
6893 case glslang::EOpSubgroupInclusiveOr:
6894 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006895 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006896 break;
6897 case glslang::EOpSubgroupBallotExclusiveBitCount:
6898 case glslang::EOpSubgroupExclusiveAdd:
6899 case glslang::EOpSubgroupExclusiveMul:
6900 case glslang::EOpSubgroupExclusiveMin:
6901 case glslang::EOpSubgroupExclusiveMax:
6902 case glslang::EOpSubgroupExclusiveAnd:
6903 case glslang::EOpSubgroupExclusiveOr:
6904 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006905 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006906 break;
6907 case glslang::EOpSubgroupClusteredAdd:
6908 case glslang::EOpSubgroupClusteredMul:
6909 case glslang::EOpSubgroupClusteredMin:
6910 case glslang::EOpSubgroupClusteredMax:
6911 case glslang::EOpSubgroupClusteredAnd:
6912 case glslang::EOpSubgroupClusteredOr:
6913 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06006914 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006915 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006916#ifdef NV_EXTENSIONS
6917 case glslang::EOpSubgroupPartitionedAdd:
6918 case glslang::EOpSubgroupPartitionedMul:
6919 case glslang::EOpSubgroupPartitionedMin:
6920 case glslang::EOpSubgroupPartitionedMax:
6921 case glslang::EOpSubgroupPartitionedAnd:
6922 case glslang::EOpSubgroupPartitionedOr:
6923 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06006924 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006925 break;
6926 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6927 case glslang::EOpSubgroupPartitionedInclusiveMul:
6928 case glslang::EOpSubgroupPartitionedInclusiveMin:
6929 case glslang::EOpSubgroupPartitionedInclusiveMax:
6930 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6931 case glslang::EOpSubgroupPartitionedInclusiveOr:
6932 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006933 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006934 break;
6935 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6936 case glslang::EOpSubgroupPartitionedExclusiveMul:
6937 case glslang::EOpSubgroupPartitionedExclusiveMin:
6938 case glslang::EOpSubgroupPartitionedExclusiveMax:
6939 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6940 case glslang::EOpSubgroupPartitionedExclusiveOr:
6941 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006942 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006943 break;
6944#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006945 }
6946
John Kessenich149afc32018-08-14 13:31:43 -06006947 // build the instruction
6948 std::vector<spv::IdImmediate> spvGroupOperands;
6949
6950 // Every operation begins with the Execution Scope operand.
6951 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6952 spvGroupOperands.push_back(executionScope);
6953
6954 // Next, for all operations that use a Group Operation, push that as an operand.
6955 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006956 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006957 spvGroupOperands.push_back(groupOperand);
6958 }
6959
John Kessenich66011cb2018-03-06 16:12:04 -07006960 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06006961 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
6962 spv::IdImmediate operand = { true, *opIt };
6963 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006964 }
6965
6966 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06006967 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07006968 switch (op) {
6969 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06006970 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
6971 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
6972 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
6973 }
6974 if (directionId != spv::NoResult) {
6975 spv::IdImmediate direction = { true, directionId };
6976 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07006977 }
6978
6979 return builder.createOp(opCode, typeId, spvGroupOperands);
6980}
6981
John Kessenich5e4b1242015-08-06 22:53:06 -06006982spv::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 -06006983{
John Kessenich66011cb2018-03-06 16:12:04 -07006984 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6985 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06006986
John Kessenich140f3df2015-06-26 16:58:36 -06006987 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08006988 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06006989 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05006990 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07006991 spv::Id typeId0 = 0;
6992 if (consumedOperands > 0)
6993 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08006994 spv::Id typeId1 = 0;
6995 if (consumedOperands > 1)
6996 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07006997 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06006998
6999 switch (op) {
7000 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007001 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007002 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007003 else if (isUnsigned)
7004 libCall = spv::GLSLstd450UMin;
7005 else
7006 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007007 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007008 break;
7009 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007010 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007011 break;
7012 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007013 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007014 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007015 else if (isUnsigned)
7016 libCall = spv::GLSLstd450UMax;
7017 else
7018 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007019 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007020 break;
7021 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007022 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007023 break;
7024 case glslang::EOpDot:
7025 opCode = spv::OpDot;
7026 break;
7027 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007028 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007029 break;
7030
7031 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007032 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007033 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007034 else if (isUnsigned)
7035 libCall = spv::GLSLstd450UClamp;
7036 else
7037 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007038 builder.promoteScalar(precision, operands.front(), operands[1]);
7039 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007040 break;
7041 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007042 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7043 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007044 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007045 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007046 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007047 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007048 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007049 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007050 break;
7051 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007052 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007053 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007054 break;
7055 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007056 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007057 builder.promoteScalar(precision, operands[0], operands[2]);
7058 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007059 break;
7060
7061 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007062 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007063 break;
7064 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007065 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007066 break;
7067 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007068 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007069 break;
7070 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007071 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007072 break;
7073 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007074 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007075 break;
Rex Xu7a26c172015-12-08 17:12:09 +08007076 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007077#ifdef AMD_EXTENSIONS
7078 if (typeProxy == glslang::EbtFloat16)
7079 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
7080#endif
Rex Xu7a26c172015-12-08 17:12:09 +08007081 libCall = spv::GLSLstd450InterpolateAtSample;
7082 break;
7083 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007084#ifdef AMD_EXTENSIONS
7085 if (typeProxy == glslang::EbtFloat16)
7086 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
7087#endif
Rex Xu7a26c172015-12-08 17:12:09 +08007088 libCall = spv::GLSLstd450InterpolateAtOffset;
7089 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007090 case glslang::EOpAddCarry:
7091 opCode = spv::OpIAddCarry;
7092 typeId = builder.makeStructResultType(typeId0, typeId0);
7093 consumedOperands = 2;
7094 break;
7095 case glslang::EOpSubBorrow:
7096 opCode = spv::OpISubBorrow;
7097 typeId = builder.makeStructResultType(typeId0, typeId0);
7098 consumedOperands = 2;
7099 break;
7100 case glslang::EOpUMulExtended:
7101 opCode = spv::OpUMulExtended;
7102 typeId = builder.makeStructResultType(typeId0, typeId0);
7103 consumedOperands = 2;
7104 break;
7105 case glslang::EOpIMulExtended:
7106 opCode = spv::OpSMulExtended;
7107 typeId = builder.makeStructResultType(typeId0, typeId0);
7108 consumedOperands = 2;
7109 break;
7110 case glslang::EOpBitfieldExtract:
7111 if (isUnsigned)
7112 opCode = spv::OpBitFieldUExtract;
7113 else
7114 opCode = spv::OpBitFieldSExtract;
7115 break;
7116 case glslang::EOpBitfieldInsert:
7117 opCode = spv::OpBitFieldInsert;
7118 break;
7119
7120 case glslang::EOpFma:
7121 libCall = spv::GLSLstd450Fma;
7122 break;
7123 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007124 {
7125 libCall = spv::GLSLstd450FrexpStruct;
7126 assert(builder.isPointerType(typeId1));
7127 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007128 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007129#ifdef AMD_EXTENSIONS
7130 if (width == 16)
7131 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7132 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
7133#endif
Rex Xu470026f2017-03-29 17:12:40 +08007134 if (builder.getNumComponents(operands[0]) == 1)
7135 frexpIntType = builder.makeIntegerType(width, true);
7136 else
7137 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
7138 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7139 consumedOperands = 1;
7140 }
John Kessenich55e7d112015-11-15 21:33:39 -07007141 break;
7142 case glslang::EOpLdexp:
7143 libCall = spv::GLSLstd450Ldexp;
7144 break;
7145
Rex Xu574ab042016-04-14 16:53:07 +08007146 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007147 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007148
John Kessenich66011cb2018-03-06 16:12:04 -07007149 case glslang::EOpSubgroupBroadcast:
7150 case glslang::EOpSubgroupBallotBitExtract:
7151 case glslang::EOpSubgroupShuffle:
7152 case glslang::EOpSubgroupShuffleXor:
7153 case glslang::EOpSubgroupShuffleUp:
7154 case glslang::EOpSubgroupShuffleDown:
7155 case glslang::EOpSubgroupClusteredAdd:
7156 case glslang::EOpSubgroupClusteredMul:
7157 case glslang::EOpSubgroupClusteredMin:
7158 case glslang::EOpSubgroupClusteredMax:
7159 case glslang::EOpSubgroupClusteredAnd:
7160 case glslang::EOpSubgroupClusteredOr:
7161 case glslang::EOpSubgroupClusteredXor:
7162 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007163#ifdef NV_EXTENSIONS
7164 case glslang::EOpSubgroupPartitionedAdd:
7165 case glslang::EOpSubgroupPartitionedMul:
7166 case glslang::EOpSubgroupPartitionedMin:
7167 case glslang::EOpSubgroupPartitionedMax:
7168 case glslang::EOpSubgroupPartitionedAnd:
7169 case glslang::EOpSubgroupPartitionedOr:
7170 case glslang::EOpSubgroupPartitionedXor:
7171 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7172 case glslang::EOpSubgroupPartitionedInclusiveMul:
7173 case glslang::EOpSubgroupPartitionedInclusiveMin:
7174 case glslang::EOpSubgroupPartitionedInclusiveMax:
7175 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7176 case glslang::EOpSubgroupPartitionedInclusiveOr:
7177 case glslang::EOpSubgroupPartitionedInclusiveXor:
7178 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7179 case glslang::EOpSubgroupPartitionedExclusiveMul:
7180 case glslang::EOpSubgroupPartitionedExclusiveMin:
7181 case glslang::EOpSubgroupPartitionedExclusiveMax:
7182 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7183 case glslang::EOpSubgroupPartitionedExclusiveOr:
7184 case glslang::EOpSubgroupPartitionedExclusiveXor:
7185#endif
John Kessenich66011cb2018-03-06 16:12:04 -07007186 return createSubgroupOperation(op, typeId, operands, typeProxy);
7187
Rex Xu9d93a232016-05-05 12:30:44 +08007188#ifdef AMD_EXTENSIONS
7189 case glslang::EOpSwizzleInvocations:
7190 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7191 libCall = spv::SwizzleInvocationsAMD;
7192 break;
7193 case glslang::EOpSwizzleInvocationsMasked:
7194 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7195 libCall = spv::SwizzleInvocationsMaskedAMD;
7196 break;
7197 case glslang::EOpWriteInvocation:
7198 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7199 libCall = spv::WriteInvocationAMD;
7200 break;
7201
7202 case glslang::EOpMin3:
7203 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7204 if (isFloat)
7205 libCall = spv::FMin3AMD;
7206 else {
7207 if (isUnsigned)
7208 libCall = spv::UMin3AMD;
7209 else
7210 libCall = spv::SMin3AMD;
7211 }
7212 break;
7213 case glslang::EOpMax3:
7214 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7215 if (isFloat)
7216 libCall = spv::FMax3AMD;
7217 else {
7218 if (isUnsigned)
7219 libCall = spv::UMax3AMD;
7220 else
7221 libCall = spv::SMax3AMD;
7222 }
7223 break;
7224 case glslang::EOpMid3:
7225 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7226 if (isFloat)
7227 libCall = spv::FMid3AMD;
7228 else {
7229 if (isUnsigned)
7230 libCall = spv::UMid3AMD;
7231 else
7232 libCall = spv::SMid3AMD;
7233 }
7234 break;
7235
7236 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007237 if (typeProxy == glslang::EbtFloat16)
7238 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007239 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7240 libCall = spv::InterpolateAtVertexAMD;
7241 break;
7242#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05007243 case glslang::EOpBarrier:
7244 {
7245 // This is for the extended controlBarrier function, with four operands.
7246 // The unextended barrier() goes through createNoArgOperation.
7247 assert(operands.size() == 4);
7248 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7249 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7250 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
7251 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05007252 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7253 spv::MemorySemanticsMakeVisibleKHRMask |
7254 spv::MemorySemanticsOutputMemoryKHRMask |
7255 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007256 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7257 }
7258 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
7259 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7260 }
7261 return 0;
7262 }
7263 break;
7264 case glslang::EOpMemoryBarrier:
7265 {
7266 // This is for the extended memoryBarrier function, with three operands.
7267 // The unextended memoryBarrier() goes through createNoArgOperation.
7268 assert(operands.size() == 3);
7269 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7270 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7271 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05007272 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7273 spv::MemorySemanticsMakeVisibleKHRMask |
7274 spv::MemorySemanticsOutputMemoryKHRMask |
7275 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007276 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7277 }
7278 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7279 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7280 }
7281 return 0;
7282 }
7283 break;
Chao Chen3c366992018-09-19 11:41:59 -07007284
7285#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07007286 case glslang::EOpReportIntersectionNV:
7287 {
7288 typeId = builder.makeBoolType();
Ashwin Leleff1783d2018-10-22 16:41:44 -07007289 opCode = spv::OpReportIntersectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07007290 }
7291 break;
7292 case glslang::EOpTraceNV:
7293 {
Ashwin Leleff1783d2018-10-22 16:41:44 -07007294 builder.createNoResultOp(spv::OpTraceNV, operands);
7295 return 0;
7296 }
7297 break;
7298 case glslang::EOpExecuteCallableNV:
7299 {
7300 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007301 return 0;
7302 }
7303 break;
Chao Chen3c366992018-09-19 11:41:59 -07007304 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7305 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7306 return 0;
7307#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007308 case glslang::EOpCooperativeMatrixMulAdd:
7309 opCode = spv::OpCooperativeMatrixMulAddNV;
7310 break;
7311
John Kessenich140f3df2015-06-26 16:58:36 -06007312 default:
7313 return 0;
7314 }
7315
7316 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007317 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007318 // Use an extended instruction from the standard library.
7319 // Construct the call arguments, without modifying the original operands vector.
7320 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7321 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007322 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007323 } else if (opCode == spv::OpDot && !isFloat) {
7324 // int dot(int, int)
7325 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7326 const int componentCount = builder.getNumComponents(operands[0]);
7327 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7328 builder.setPrecision(mulOp, precision);
7329 id = builder.createCompositeExtract(mulOp, typeId, 0);
7330 for (int i = 1; i < componentCount; ++i) {
7331 builder.setPrecision(id, precision);
7332 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(operands[0], typeId, i));
7333 }
John Kessenich2359bd02015-12-06 19:29:11 -07007334 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007335 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007336 case 0:
7337 // should all be handled by visitAggregate and createNoArgOperation
7338 assert(0);
7339 return 0;
7340 case 1:
7341 // should all be handled by createUnaryOperation
7342 assert(0);
7343 return 0;
7344 case 2:
7345 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7346 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007347 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007348 // anything 3 or over doesn't have l-value operands, so all should be consumed
7349 assert(consumedOperands == operands.size());
7350 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007351 break;
7352 }
7353 }
7354
John Kessenich55e7d112015-11-15 21:33:39 -07007355 // Decode the return types that were structures
7356 switch (op) {
7357 case glslang::EOpAddCarry:
7358 case glslang::EOpSubBorrow:
7359 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7360 id = builder.createCompositeExtract(id, typeId0, 0);
7361 break;
7362 case glslang::EOpUMulExtended:
7363 case glslang::EOpIMulExtended:
7364 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7365 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7366 break;
7367 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007368 {
7369 assert(operands.size() == 2);
7370 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7371 // "exp" is floating-point type (from HLSL intrinsic)
7372 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7373 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7374 builder.createStore(member1, operands[1]);
7375 } else
7376 // "exp" is integer type (from GLSL built-in function)
7377 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7378 id = builder.createCompositeExtract(id, typeId0, 0);
7379 }
John Kessenich55e7d112015-11-15 21:33:39 -07007380 break;
7381 default:
7382 break;
7383 }
7384
John Kessenich32cfd492016-02-02 12:37:46 -07007385 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007386}
7387
Rex Xu9d93a232016-05-05 12:30:44 +08007388// Intrinsics with no arguments (or no return value, and no precision).
7389spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007390{
Jeff Bolz36831c92018-09-05 10:11:41 -05007391 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
7392 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007393
7394 switch (op) {
7395 case glslang::EOpEmitVertex:
7396 builder.createNoResultOp(spv::OpEmitVertex);
7397 return 0;
7398 case glslang::EOpEndPrimitive:
7399 builder.createNoResultOp(spv::OpEndPrimitive);
7400 return 0;
7401 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007402 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007403 if (glslangIntermediate->usingVulkanMemoryModel()) {
7404 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7405 spv::MemorySemanticsOutputMemoryKHRMask |
7406 spv::MemorySemanticsAcquireReleaseMask);
7407 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7408 } else {
7409 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7410 }
John Kessenich82979362017-12-11 04:02:24 -07007411 } else {
7412 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7413 spv::MemorySemanticsWorkgroupMemoryMask |
7414 spv::MemorySemanticsAcquireReleaseMask);
7415 }
John Kessenich140f3df2015-06-26 16:58:36 -06007416 return 0;
7417 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007418 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7419 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007420 return 0;
7421 case glslang::EOpMemoryBarrierAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05007422 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7423 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007424 return 0;
7425 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007426 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7427 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007428 return 0;
7429 case glslang::EOpMemoryBarrierImage:
Jeff Bolz36831c92018-09-05 10:11:41 -05007430 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7431 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007432 return 0;
7433 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007434 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7435 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007436 return 0;
7437 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007438 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7439 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007440 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007441 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007442 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007443 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007444 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007445 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007446 case glslang::EOpDeviceMemoryBarrier:
7447 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7448 spv::MemorySemanticsImageMemoryMask |
7449 spv::MemorySemanticsAcquireReleaseMask);
7450 return 0;
7451 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7452 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7453 spv::MemorySemanticsImageMemoryMask |
7454 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007455 return 0;
7456 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007457 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7458 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007459 return 0;
7460 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007461 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7462 spv::MemorySemanticsWorkgroupMemoryMask |
7463 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007464 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007465 case glslang::EOpSubgroupBarrier:
7466 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7467 spv::MemorySemanticsAcquireReleaseMask);
7468 return spv::NoResult;
7469 case glslang::EOpSubgroupMemoryBarrier:
7470 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7471 spv::MemorySemanticsAcquireReleaseMask);
7472 return spv::NoResult;
7473 case glslang::EOpSubgroupMemoryBarrierBuffer:
7474 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7475 spv::MemorySemanticsAcquireReleaseMask);
7476 return spv::NoResult;
7477 case glslang::EOpSubgroupMemoryBarrierImage:
7478 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7479 spv::MemorySemanticsAcquireReleaseMask);
7480 return spv::NoResult;
7481 case glslang::EOpSubgroupMemoryBarrierShared:
7482 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7483 spv::MemorySemanticsAcquireReleaseMask);
7484 return spv::NoResult;
7485 case glslang::EOpSubgroupElect: {
7486 std::vector<spv::Id> operands;
7487 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7488 }
Rex Xu9d93a232016-05-05 12:30:44 +08007489#ifdef AMD_EXTENSIONS
7490 case glslang::EOpTime:
7491 {
7492 std::vector<spv::Id> args; // Dummy arguments
7493 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7494 return builder.setPrecision(id, precision);
7495 }
7496#endif
Chao Chenb50c02e2018-09-19 11:42:24 -07007497#ifdef NV_EXTENSIONS
7498 case glslang::EOpIgnoreIntersectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007499 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007500 return 0;
7501 case glslang::EOpTerminateRayNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007502 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007503 return 0;
7504#endif
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05007505
7506 case glslang::EOpBeginInvocationInterlock:
7507 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
7508 return 0;
7509 case glslang::EOpEndInvocationInterlock:
7510 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
7511 return 0;
7512
John Kessenich140f3df2015-06-26 16:58:36 -06007513 default:
Lei Zhang17535f72016-05-04 15:55:59 -04007514 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06007515 return 0;
7516 }
7517}
7518
7519spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7520{
John Kessenich2f273362015-07-18 22:34:27 -06007521 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007522 spv::Id id;
7523 if (symbolValues.end() != iter) {
7524 id = iter->second;
7525 return id;
7526 }
7527
7528 // it was not found, create it
7529 id = createSpvVariable(symbol);
7530 symbolValues[symbol->getId()] = id;
7531
Rex Xuc884b4a2016-06-29 15:03:44 +08007532 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007533 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7534 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7535 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
Chao Chen3c366992018-09-19 11:41:59 -07007536#ifdef NV_EXTENSIONS
7537 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
7538#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007539 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007540 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06007541 if (symbol->getQualifier().hasIndex())
7542 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
7543 if (symbol->getQualifier().hasComponent())
7544 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06007545 // atomic counters use this:
7546 if (symbol->getQualifier().hasOffset())
7547 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007548 }
7549
scygan2c864272016-05-18 18:09:17 +02007550 if (symbol->getQualifier().hasLocation())
7551 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007552 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007553 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007554 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007555 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007556 }
John Kessenich140f3df2015-06-26 16:58:36 -06007557 if (symbol->getQualifier().hasSet())
7558 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007559 else if (IsDescriptorResource(symbol->getType())) {
7560 // default to 0
7561 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7562 }
John Kessenich140f3df2015-06-26 16:58:36 -06007563 if (symbol->getQualifier().hasBinding())
7564 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06007565 else if (IsDescriptorResource(symbol->getType())) {
7566 // default to 0
7567 builder.addDecoration(id, spv::DecorationBinding, 0);
7568 }
John Kessenich6c292d32016-02-15 20:58:50 -07007569 if (symbol->getQualifier().hasAttachment())
7570 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06007571 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007572 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07007573 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007574 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007575 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7576 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7577 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7578 }
7579 if (symbol->getQualifier().hasXfbOffset())
7580 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007581 }
7582
Rex Xu1da878f2016-02-21 20:59:01 +08007583 if (symbol->getType().isImage()) {
7584 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05007585 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007586 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007587 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007588 }
7589
John Kessenich140f3df2015-06-26 16:58:36 -06007590 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06007591 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06007592 if (builtIn != spv::BuiltInMax)
John Kessenich5d610ee2018-03-07 18:05:55 -07007593 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06007594
John Kessenich5611c6d2018-04-05 11:25:02 -06007595 // nonuniform
7596 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7597
John Kessenichecba76f2017-01-06 00:34:48 -07007598#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08007599 if (builtIn == spv::BuiltInSampleMask) {
7600 spv::Decoration decoration;
7601 // GL_NV_sample_mask_override_coverage extension
7602 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007603 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007604 else
7605 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007606 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007607 if (decoration != spv::DecorationMax) {
7608 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7609 }
7610 }
chaoc771d89f2017-01-13 01:10:53 -08007611 else if (builtIn == spv::BuiltInLayer) {
7612 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007613 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007614 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007615 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7616 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7617 }
John Kessenichb41bff62017-08-11 13:07:17 -06007618 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007619 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7620 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007621 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7622 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7623 }
7624 }
7625
chaoc6e5acae2016-12-20 13:28:52 -08007626 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007627 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007628 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007629 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7630 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007631 if (symbol->getQualifier().pervertexNV) {
7632 builder.addDecoration(id, spv::DecorationPerVertexNV);
7633 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7634 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7635 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007636#endif
7637
John Kessenich5d610ee2018-03-07 18:05:55 -07007638 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7639 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7640 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7641 symbol->getType().getQualifier().semanticName);
7642 }
7643
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007644 if (symbol->getBasicType() == glslang::EbtReference) {
7645 builder.addDecoration(id, symbol->getType().getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
7646 }
7647
John Kessenich140f3df2015-06-26 16:58:36 -06007648 return id;
7649}
7650
Chao Chen3c366992018-09-19 11:41:59 -07007651#ifdef NV_EXTENSIONS
7652// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7653void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7654{
7655 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07007656 if (qualifier.perPrimitiveNV) {
7657 // Need to add capability/extension for fragment shader.
7658 // Mesh shader already adds this by default.
7659 if (glslangIntermediate->getStage() == EShLangFragment) {
7660 builder.addCapability(spv::CapabilityMeshShadingNV);
7661 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7662 }
Chao Chen3c366992018-09-19 11:41:59 -07007663 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007664 }
Chao Chen3c366992018-09-19 11:41:59 -07007665 if (qualifier.perViewNV)
7666 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7667 if (qualifier.perTaskNV)
7668 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7669 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07007670 if (qualifier.perPrimitiveNV) {
7671 // Need to add capability/extension for fragment shader.
7672 // Mesh shader already adds this by default.
7673 if (glslangIntermediate->getStage() == EShLangFragment) {
7674 builder.addCapability(spv::CapabilityMeshShadingNV);
7675 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7676 }
Chao Chen3c366992018-09-19 11:41:59 -07007677 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007678 }
Chao Chen3c366992018-09-19 11:41:59 -07007679 if (qualifier.perViewNV)
7680 builder.addDecoration(id, spv::DecorationPerViewNV);
7681 if (qualifier.perTaskNV)
7682 builder.addDecoration(id, spv::DecorationPerTaskNV);
7683 }
7684}
7685#endif
7686
John Kessenich55e7d112015-11-15 21:33:39 -07007687// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07007688// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07007689//
7690// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7691//
7692// Recursively walk the nodes. The nodes form a tree whose leaves are
7693// regular constants, which themselves are trees that createSpvConstant()
7694// recursively walks. So, this function walks the "top" of the tree:
7695// - emit specialization constant-building instructions for specConstant
7696// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04007697spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07007698{
John Kessenich7cc0e282016-03-20 00:46:02 -06007699 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07007700
qining4f4bb812016-04-03 23:55:17 -04007701 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07007702 if (! node.getQualifier().specConstant) {
7703 // hand off to the non-spec-constant path
7704 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
7705 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04007706 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07007707 nextConst, false);
7708 }
7709
7710 // We now know we have a specialization constant to build
7711
John Kessenichd94c0032016-05-30 19:29:40 -06007712 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04007713 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
7714 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
7715 std::vector<spv::Id> dimConstId;
7716 for (int dim = 0; dim < 3; ++dim) {
7717 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
7718 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07007719 if (specConst) {
7720 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
7721 glslangIntermediate->getLocalSizeSpecId(dim));
7722 }
qining4f4bb812016-04-03 23:55:17 -04007723 }
7724 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
7725 }
7726
7727 // An AST node labelled as specialization constant should be a symbol node.
7728 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
7729 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007730 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04007731 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04007732 // Traverse the constant constructor sub tree like generating normal run-time instructions.
7733 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
7734 // will set the builder into spec constant op instruction generating mode.
7735 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007736 result = accessChainLoad(sub_tree->getType());
7737 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04007738 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007739 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05007740 } else {
7741 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05007742 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07007743 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007744 builder.addName(result, sn->getName().c_str());
7745 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07007746 }
qining4f4bb812016-04-03 23:55:17 -04007747
7748 // Neither a front-end constant node, nor a specialization constant node with constant union array or
7749 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04007750 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04007751 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07007752}
7753
John Kessenich140f3df2015-06-26 16:58:36 -06007754// Use 'consts' as the flattened glslang source of scalar constants to recursively
7755// build the aggregate SPIR-V constant.
7756//
7757// If there are not enough elements present in 'consts', 0 will be substituted;
7758// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
7759//
qining08408382016-03-21 09:51:37 -04007760spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06007761{
7762 // vector of constants for SPIR-V
7763 std::vector<spv::Id> spvConsts;
7764
7765 // Type is used for struct and array constants
7766 spv::Id typeId = convertGlslangToSpvType(glslangType);
7767
7768 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007769 glslang::TType elementType(glslangType, 0);
7770 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04007771 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007772 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007773 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06007774 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04007775 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007776 } else if (glslangType.isCoopMat()) {
7777 glslang::TType componentType(glslangType.getBasicType());
7778 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007779 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007780 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
7781 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04007782 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06007783 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06007784 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
7785 bool zero = nextConst >= consts.size();
7786 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007787 case glslang::EbtInt8:
7788 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
7789 break;
7790 case glslang::EbtUint8:
7791 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
7792 break;
7793 case glslang::EbtInt16:
7794 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
7795 break;
7796 case glslang::EbtUint16:
7797 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
7798 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007799 case glslang::EbtInt:
7800 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
7801 break;
7802 case glslang::EbtUint:
7803 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
7804 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007805 case glslang::EbtInt64:
7806 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
7807 break;
7808 case glslang::EbtUint64:
7809 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
7810 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007811 case glslang::EbtFloat:
7812 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7813 break;
7814 case glslang::EbtDouble:
7815 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
7816 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007817 case glslang::EbtFloat16:
7818 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7819 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007820 case glslang::EbtBool:
7821 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7822 break;
7823 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007824 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007825 break;
7826 }
7827 ++nextConst;
7828 }
7829 } else {
7830 // we have a non-aggregate (scalar) constant
7831 bool zero = nextConst >= consts.size();
7832 spv::Id scalar = 0;
7833 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007834 case glslang::EbtInt8:
7835 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
7836 break;
7837 case glslang::EbtUint8:
7838 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
7839 break;
7840 case glslang::EbtInt16:
7841 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
7842 break;
7843 case glslang::EbtUint16:
7844 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
7845 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007846 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07007847 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007848 break;
7849 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07007850 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007851 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007852 case glslang::EbtInt64:
7853 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
7854 break;
7855 case glslang::EbtUint64:
7856 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7857 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007858 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07007859 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007860 break;
7861 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07007862 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007863 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007864 case glslang::EbtFloat16:
7865 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7866 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007867 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07007868 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007869 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06007870 case glslang::EbtReference:
7871 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7872 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
7873 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007874 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007875 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007876 break;
7877 }
7878 ++nextConst;
7879 return scalar;
7880 }
7881
7882 return builder.makeCompositeConstant(typeId, spvConsts);
7883}
7884
John Kessenich7c1aa102015-10-15 13:29:11 -06007885// Return true if the node is a constant or symbol whose reading has no
7886// non-trivial observable cost or effect.
7887bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
7888{
7889 // don't know what this is
7890 if (node == nullptr)
7891 return false;
7892
7893 // a constant is safe
7894 if (node->getAsConstantUnion() != nullptr)
7895 return true;
7896
7897 // not a symbol means non-trivial
7898 if (node->getAsSymbolNode() == nullptr)
7899 return false;
7900
7901 // a symbol, depends on what's being read
7902 switch (node->getType().getQualifier().storage) {
7903 case glslang::EvqTemporary:
7904 case glslang::EvqGlobal:
7905 case glslang::EvqIn:
7906 case glslang::EvqInOut:
7907 case glslang::EvqConst:
7908 case glslang::EvqConstReadOnly:
7909 case glslang::EvqUniform:
7910 return true;
7911 default:
7912 return false;
7913 }
qining25262b32016-05-06 17:25:16 -04007914}
John Kessenich7c1aa102015-10-15 13:29:11 -06007915
7916// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06007917// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06007918// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06007919// Return true if trivial.
7920bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
7921{
7922 if (node == nullptr)
7923 return false;
7924
John Kessenich84cc15f2017-05-24 16:44:47 -06007925 // count non scalars as trivial, as well as anything coming from HLSL
7926 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06007927 return true;
7928
John Kessenich7c1aa102015-10-15 13:29:11 -06007929 // symbols and constants are trivial
7930 if (isTrivialLeaf(node))
7931 return true;
7932
7933 // otherwise, it needs to be a simple operation or one or two leaf nodes
7934
7935 // not a simple operation
7936 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
7937 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
7938 if (binaryNode == nullptr && unaryNode == nullptr)
7939 return false;
7940
7941 // not on leaf nodes
7942 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
7943 return false;
7944
7945 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
7946 return false;
7947 }
7948
7949 switch (node->getAsOperator()->getOp()) {
7950 case glslang::EOpLogicalNot:
7951 case glslang::EOpConvIntToBool:
7952 case glslang::EOpConvUintToBool:
7953 case glslang::EOpConvFloatToBool:
7954 case glslang::EOpConvDoubleToBool:
7955 case glslang::EOpEqual:
7956 case glslang::EOpNotEqual:
7957 case glslang::EOpLessThan:
7958 case glslang::EOpGreaterThan:
7959 case glslang::EOpLessThanEqual:
7960 case glslang::EOpGreaterThanEqual:
7961 case glslang::EOpIndexDirect:
7962 case glslang::EOpIndexDirectStruct:
7963 case glslang::EOpLogicalXor:
7964 case glslang::EOpAny:
7965 case glslang::EOpAll:
7966 return true;
7967 default:
7968 return false;
7969 }
7970}
7971
7972// Emit short-circuiting code, where 'right' is never evaluated unless
7973// the left side is true (for &&) or false (for ||).
7974spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
7975{
7976 spv::Id boolTypeId = builder.makeBoolType();
7977
7978 // emit left operand
7979 builder.clearAccessChain();
7980 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007981 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007982
7983 // Operands to accumulate OpPhi operands
7984 std::vector<spv::Id> phiOperands;
7985 // accumulate left operand's phi information
7986 phiOperands.push_back(leftId);
7987 phiOperands.push_back(builder.getBuildPoint()->getId());
7988
7989 // Make the two kinds of operation symmetric with a "!"
7990 // || => emit "if (! left) result = right"
7991 // && => emit "if ( left) result = right"
7992 //
7993 // TODO: this runtime "not" for || could be avoided by adding functionality
7994 // to 'builder' to have an "else" without an "then"
7995 if (op == glslang::EOpLogicalOr)
7996 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
7997
7998 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08007999 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008000
8001 // emit right operand as the "then" part of the "if"
8002 builder.clearAccessChain();
8003 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008004 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008005
8006 // accumulate left operand's phi information
8007 phiOperands.push_back(rightId);
8008 phiOperands.push_back(builder.getBuildPoint()->getId());
8009
8010 // finish the "if"
8011 ifBuilder.makeEndIf();
8012
8013 // phi together the two results
8014 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8015}
8016
Frank Henigman541f7bb2018-01-16 00:18:26 -05008017#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08008018// Return type Id of the imported set of extended instructions corresponds to the name.
8019// Import this set if it has not been imported yet.
8020spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8021{
8022 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8023 return extBuiltinMap[name];
8024 else {
Rex Xu51596642016-09-21 18:56:12 +08008025 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008026 spv::Id extBuiltins = builder.import(name);
8027 extBuiltinMap[name] = extBuiltins;
8028 return extBuiltins;
8029 }
8030}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008031#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008032
John Kessenich140f3df2015-06-26 16:58:36 -06008033}; // end anonymous namespace
8034
8035namespace glslang {
8036
John Kessenich68d78fd2015-07-12 19:28:10 -06008037void GetSpirvVersion(std::string& version)
8038{
John Kessenich9e55f632015-07-15 10:03:39 -06008039 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008040 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008041 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008042 version = buf;
8043}
8044
John Kessenicha372a3e2017-11-02 22:32:14 -06008045// For low-order part of the generator's magic number. Bump up
8046// when there is a change in the style (e.g., if SSA form changes,
8047// or a different instruction sequence to do something gets used).
8048int GetSpirvGeneratorVersion()
8049{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008050 // return 1; // start
8051 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008052 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008053 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008054 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008055 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8056 // versions 4 and 6 each generate OpArrayLength as it has long been done
8057 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06008058}
8059
John Kessenich140f3df2015-06-26 16:58:36 -06008060// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008061void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008062{
8063 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008064 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008065 if (out.fail())
8066 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008067 for (int i = 0; i < (int)spirv.size(); ++i) {
8068 unsigned int word = spirv[i];
8069 out.write((const char*)&word, 4);
8070 }
8071 out.close();
8072}
8073
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008074// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008075void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008076{
8077 std::ofstream out;
8078 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008079 if (out.fail())
8080 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07008081 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06008082 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07008083 std::endl;
Flavio15017db2017-02-15 14:29:33 -08008084 if (varName != nullptr) {
8085 out << "\t #pragma once" << std::endl;
8086 out << "const uint32_t " << varName << "[] = {" << std::endl;
8087 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008088 const int WORDS_PER_LINE = 8;
8089 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8090 out << "\t";
8091 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8092 const unsigned int word = spirv[i + j];
8093 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8094 if (i + j + 1 < (int)spirv.size()) {
8095 out << ",";
8096 }
8097 }
8098 out << std::endl;
8099 }
Flavio15017db2017-02-15 14:29:33 -08008100 if (varName != nullptr) {
8101 out << "};";
8102 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008103 out.close();
8104}
8105
John Kessenich140f3df2015-06-26 16:58:36 -06008106//
8107// Set up the glslang traversal
8108//
John Kessenich4e11b612018-08-30 16:56:59 -06008109void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008110{
Lei Zhang17535f72016-05-04 15:55:59 -04008111 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008112 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008113}
8114
John Kessenich4e11b612018-08-30 16:56:59 -06008115void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008116 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008117{
John Kessenich140f3df2015-06-26 16:58:36 -06008118 TIntermNode* root = intermediate.getTreeRoot();
8119
8120 if (root == 0)
8121 return;
8122
John Kessenich4e11b612018-08-30 16:56:59 -06008123 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008124 if (options == nullptr)
8125 options = &defaultOptions;
8126
John Kessenich4e11b612018-08-30 16:56:59 -06008127 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008128
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008129 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008130 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008131 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008132 it.dumpSpv(spirv);
8133
GregFfb03a552018-03-29 11:49:14 -06008134#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008135 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8136 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008137 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
8138 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer) {
John Kesseniche7df8e02018-08-22 17:12:46 -06008139 SpirvToolsLegalize(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008140 prelegalization = false;
8141 }
John Kessenich717c80a2018-08-23 15:17:10 -06008142
John Kessenich4e11b612018-08-30 16:56:59 -06008143 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008144 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008145
John Kessenich717c80a2018-08-23 15:17:10 -06008146 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008147 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008148
GregFcd1f1692017-09-21 18:40:22 -06008149#endif
8150
John Kessenich4e11b612018-08-30 16:56:59 -06008151 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008152}
8153
8154}; // end namespace glslang