blob: 745dd7f203fdc9de22f8e718bf5d5d81cd396fd1 [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 Xu51596642016-09-21 18:56:12 +080049 #include "GLSL.ext.AMD.h"
chaoc0ad6a4e2016-12-19 16:29:34 -080050 #include "GLSL.ext.NV.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060051}
John Kessenich140f3df2015-06-26 16:58:36 -060052
53// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020054#include "../glslang/MachineIndependent/localintermediate.h"
55#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060056#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050057#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060058
John Kessenich140f3df2015-06-26 16:58:36 -060059#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050060#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040061#include <list>
62#include <map>
63#include <stack>
64#include <string>
65#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060066
67namespace {
68
qining4c912612016-04-01 10:35:16 -040069namespace {
70class SpecConstantOpModeGuard {
71public:
72 SpecConstantOpModeGuard(spv::Builder* builder)
73 : builder_(builder) {
74 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040075 }
76 ~SpecConstantOpModeGuard() {
77 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
78 : builder_->setToNormalCodeGenMode();
79 }
qining40887662016-04-03 22:20:42 -040080 void turnOnSpecConstantOpMode() {
81 builder_->setToSpecConstCodeGenMode();
82 }
qining4c912612016-04-01 10:35:16 -040083
84private:
85 spv::Builder* builder_;
86 bool previous_flag_;
87};
John Kessenichead86222018-03-28 18:01:20 -060088
89struct OpDecorations {
John Kessenichb9197c82019-08-11 07:41:45 -060090 public:
91 OpDecorations(spv::Decoration precision, spv::Decoration noContraction, spv::Decoration nonUniform) :
92 precision(precision)
93#ifndef GLSLANG_WEB
94 ,
95 noContraction(noContraction),
96 nonUniform(nonUniform)
97#endif
98 { }
99
John Kessenichead86222018-03-28 18:01:20 -0600100 spv::Decoration precision;
John Kessenichb9197c82019-08-11 07:41:45 -0600101
102#ifdef GLSLANG_WEB
Ryan Harrison7c9accb2019-10-11 11:00:57 -0400103 void addNoContraction(spv::Builder&, spv::Id) const { }
104 void addNonUniform(spv::Builder&, spv::Id) const { }
John Kessenichb9197c82019-08-11 07:41:45 -0600105#else
Ryan Harrison7c9accb2019-10-11 11:00:57 -0400106 void addNoContraction(spv::Builder& builder, spv::Id t) { builder.addDecoration(t, noContraction); }
107 void addNonUniform(spv::Builder& builder, spv::Id t) { builder.addDecoration(t, nonUniform); }
John Kessenichb9197c82019-08-11 07:41:45 -0600108 protected:
109 spv::Decoration noContraction;
110 spv::Decoration nonUniform;
111#endif
112
John Kessenichead86222018-03-28 18:01:20 -0600113};
114
115} // namespace
qining4c912612016-04-01 10:35:16 -0400116
John Kessenich140f3df2015-06-26 16:58:36 -0600117//
118// The main holder of information for translating glslang to SPIR-V.
119//
120// Derives from the AST walking base class.
121//
122class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
123public:
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700124 TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger,
125 glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700126 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600127
128 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
129 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
130 void visitConstantUnion(glslang::TIntermConstantUnion*);
131 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
132 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
133 void visitSymbol(glslang::TIntermSymbol* symbol);
134 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
135 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
136 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
137
John Kessenichfca82622016-11-26 13:23:20 -0700138 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700139 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600140
141protected:
John Kessenich5d610ee2018-03-07 18:05:55 -0700142 TGlslangToSpvTraverser(TGlslangToSpvTraverser&);
143 TGlslangToSpvTraverser& operator=(TGlslangToSpvTraverser&);
144
Rex Xu17ff3432016-10-14 17:41:45 +0800145 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800146 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
John Kessenich5611c6d2018-04-05 11:25:02 -0600147 spv::Decoration TranslateNonUniformDecoration(const glslang::TQualifier& qualifier);
Jeff Bolz36831c92018-09-05 10:11:41 -0500148 spv::Builder::AccessChain::CoherentFlags TranslateCoherent(const glslang::TType& type);
149 spv::MemoryAccessMask TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
150 spv::ImageOperandsMask TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
151 spv::Scope TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
David Netoa901ffe2016-06-08 14:11:40 +0100152 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700153 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kesseniche18fd202018-01-30 11:01:39 -0700154 spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const;
155 spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const;
John Kessenich1f4d0462019-01-12 17:31:41 +0700156 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, std::vector<unsigned int>& operands) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600157 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich5611c6d2018-04-05 11:25:02 -0600158 void addIndirectionIndexCapabilities(const glslang::TType& baseType, const glslang::TType& indexType);
John Kessenich9c14f772019-06-17 08:38:35 -0600159 spv::Id createSpvVariable(const glslang::TIntermSymbol*, spv::Id forcedType);
John Kessenich140f3df2015-06-26 16:58:36 -0600160 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600161 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
162 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
163 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600164 spv::Id convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly = false);
John Kessenichead86222018-03-28 18:01:20 -0600165 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&,
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600166 bool lastBufferBlockMember, bool forwardReferenceOnly = false);
John Kessenich0e737842017-03-24 18:38:16 -0600167 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600168 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
169 glslang::TLayoutPacking, const glslang::TQualifier&);
170 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
171 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700172 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700173 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800174 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600175 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700176 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700177 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
178 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich5d610ee2018-03-07 18:05:55 -0700179 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset,
180 int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100181 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600182
John Kessenich6fccb3c2016-09-19 16:01:41 -0600183 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd3ed90b2018-05-04 11:43:03 -0600184 bool writableParam(glslang::TStorageQualifier) const;
John Kessenichd41993d2017-09-10 15:21:05 -0600185 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600186 void makeFunctions(const glslang::TIntermSequence&);
187 void makeGlobalInitializers(const glslang::TIntermSequence&);
188 void visitFunctions(const glslang::TIntermSequence&);
189 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Jeff Bolz38a52fc2019-06-14 09:56:28 -0500190 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments, spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -0600191 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
192 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600193 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
194
John Kessenichead86222018-03-28 18:01:20 -0600195 spv::Id createBinaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right,
196 glslang::TBasicType typeProxy, bool reduceComparison = true);
197 spv::Id createBinaryMatrixOperation(spv::Op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right);
198 spv::Id createUnaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id operand,
Jeff Bolz38a52fc2019-06-14 09:56:28 -0500199 glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -0600200 spv::Id createUnaryMatrixOperation(spv::Op op, OpDecorations&, spv::Id typeId, spv::Id operand,
201 glslang::TBasicType typeProxy);
202 spv::Id createConversion(glslang::TOperator op, OpDecorations&, spv::Id destTypeId, spv::Id operand,
203 glslang::TBasicType typeProxy);
John Kessenichad7645f2018-06-04 19:11:25 -0600204 spv::Id createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize);
John Kessenich140f3df2015-06-26 16:58:36 -0600205 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Jeff Bolz38a52fc2019-06-14 09:56:28 -0500206 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 +0800207 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800208 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich66011cb2018-03-06 16:12:04 -0700209 spv::Id createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -0600210 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 +0800211 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600212 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
Chao Chen3c366992018-09-19 11:41:59 -0700213 void addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier & qualifier);
qining08408382016-03-21 09:51:37 -0400214 spv::Id createSpvConstant(const glslang::TIntermTyped&);
215 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600216 bool isTrivialLeaf(const glslang::TIntermTyped* node);
217 bool isTrivial(const glslang::TIntermTyped* node);
218 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800219 spv::Id getExtBuiltins(const char* name);
John Kessenich9c14f772019-06-17 08:38:35 -0600220 std::pair<spv::Id, spv::Id> getForcedType(spv::BuiltIn, const glslang::TType&);
221 spv::Id translateForcedType(spv::Id object);
Jeff Bolz53134492019-06-25 13:31:10 -0500222 spv::Id createCompositeConstruct(spv::Id typeId, std::vector<spv::Id> constituents);
John Kessenich140f3df2015-06-26 16:58:36 -0600223
John Kessenich121853f2017-05-31 17:11:16 -0600224 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600225 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600226 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700227 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600228 int sequenceDepth;
229
Lei Zhang17535f72016-05-04 15:55:59 -0400230 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400231
John Kessenich140f3df2015-06-26 16:58:36 -0600232 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
233 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700234 bool inEntryPoint;
235 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700236 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 -0700237 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600238 const glslang::TIntermediate* glslangIntermediate;
John Kessenich605afc72019-06-17 23:33:09 -0600239 bool nanMinMaxClamp; // true if use NMin/NMax/NClamp instead of FMin/FMax/FClamp
John Kessenich140f3df2015-06-26 16:58:36 -0600240 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800241 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600242
John Kessenich2f273362015-07-18 22:34:27 -0600243 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600244 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600245 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700246 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700247 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
248 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper;
John Kessenich140f3df2015-06-26 16:58:36 -0600249 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700250 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600251 // Map pointee types for EbtReference to their forward pointers
252 std::map<const glslang::TType *, spv::Id> forwardPointers;
John Kessenich9c14f772019-06-17 08:38:35 -0600253 // Type forcing, for when SPIR-V wants a different type than the AST,
254 // requiring local translation to and from SPIR-V type on every access.
255 // Maps <builtin-variable-id -> AST-required-type-id>
256 std::unordered_map<spv::Id, spv::Id> forceType;
John Kessenich140f3df2015-06-26 16:58:36 -0600257};
258
259//
260// Helper functions for translating glslang representations to SPIR-V enumerants.
261//
262
263// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700264spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600265{
John Kessenich155d3512019-08-08 23:29:20 -0600266#ifdef GLSLANG_WEB
267 return spv::SourceLanguageESSL;
268#endif
269
John Kessenich66e2faf2016-03-12 18:34:36 -0700270 switch (source) {
271 case glslang::EShSourceGlsl:
272 switch (profile) {
273 case ENoProfile:
274 case ECoreProfile:
275 case ECompatibilityProfile:
276 return spv::SourceLanguageGLSL;
277 case EEsProfile:
278 return spv::SourceLanguageESSL;
279 default:
280 return spv::SourceLanguageUnknown;
281 }
282 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600283 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600284 default:
285 return spv::SourceLanguageUnknown;
286 }
287}
288
289// Translate glslang language (stage) to SPIR-V execution model.
290spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
291{
292 switch (stage) {
293 case EShLangVertex: return spv::ExecutionModelVertex;
John Kessenicha28f7a72019-08-06 07:00:58 -0600294 case EShLangFragment: return spv::ExecutionModelFragment;
John Kessenicha28f7a72019-08-06 07:00:58 -0600295 case EShLangCompute: return spv::ExecutionModelGLCompute;
John Kessenich51ed01c2019-10-10 11:40:11 -0600296#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -0600297 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
298 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
299 case EShLangGeometry: return spv::ExecutionModelGeometry;
Ashwin Leleff1783d2018-10-22 16:41:44 -0700300 case EShLangRayGenNV: return spv::ExecutionModelRayGenerationNV;
301 case EShLangIntersectNV: return spv::ExecutionModelIntersectionNV;
302 case EShLangAnyHitNV: return spv::ExecutionModelAnyHitNV;
303 case EShLangClosestHitNV: return spv::ExecutionModelClosestHitNV;
304 case EShLangMissNV: return spv::ExecutionModelMissNV;
305 case EShLangCallableNV: return spv::ExecutionModelCallableNV;
Chao Chen3c366992018-09-19 11:41:59 -0700306 case EShLangTaskNV: return spv::ExecutionModelTaskNV;
307 case EShLangMeshNV: return spv::ExecutionModelMeshNV;
308#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600309 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700310 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600311 return spv::ExecutionModelFragment;
312 }
313}
314
John Kessenich140f3df2015-06-26 16:58:36 -0600315// Translate glslang sampler type to SPIR-V dimensionality.
316spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
317{
318 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700319 case glslang::Esd1D: return spv::Dim1D;
320 case glslang::Esd2D: return spv::Dim2D;
321 case glslang::Esd3D: return spv::Dim3D;
322 case glslang::EsdCube: return spv::DimCube;
323 case glslang::EsdRect: return spv::DimRect;
324 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700325 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600326 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700327 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600328 return spv::Dim2D;
329 }
330}
331
John Kessenichf6640762016-08-01 19:44:00 -0600332// Translate glslang precision to SPIR-V precision decorations.
333spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600334{
John Kessenichf6640762016-08-01 19:44:00 -0600335 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700336 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600337 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600338 default:
339 return spv::NoPrecision;
340 }
341}
342
John Kessenichf6640762016-08-01 19:44:00 -0600343// Translate glslang type to SPIR-V precision decorations.
344spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
345{
346 return TranslatePrecisionDecoration(type.getQualifier().precision);
347}
348
John Kessenich140f3df2015-06-26 16:58:36 -0600349// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600350spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600351{
352 if (type.getBasicType() == glslang::EbtBlock) {
353 switch (type.getQualifier().storage) {
354 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600355 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600356 case glslang::EvqVaryingIn: return spv::DecorationBlock;
357 case glslang::EvqVaryingOut: return spv::DecorationBlock;
John Kessenicha28f7a72019-08-06 07:00:58 -0600358#ifndef GLSLANG_WEB
Chao Chenb50c02e2018-09-19 11:42:24 -0700359 case glslang::EvqPayloadNV: return spv::DecorationBlock;
360 case glslang::EvqPayloadInNV: return spv::DecorationBlock;
361 case glslang::EvqHitAttrNV: return spv::DecorationBlock;
Ashwin Leleff1783d2018-10-22 16:41:44 -0700362 case glslang::EvqCallableDataNV: return spv::DecorationBlock;
363 case glslang::EvqCallableDataInNV: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700364#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600365 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700366 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600367 break;
368 }
369 }
370
John Kessenich4016e382016-07-15 11:53:56 -0600371 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600372}
373
Rex Xu1da878f2016-02-21 20:59:01 +0800374// Translate glslang type to SPIR-V memory decorations.
Jeff Bolz36831c92018-09-05 10:11:41 -0500375void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory, bool useVulkanMemoryModel)
Rex Xu1da878f2016-02-21 20:59:01 +0800376{
Jeff Bolz36831c92018-09-05 10:11:41 -0500377 if (!useVulkanMemoryModel) {
John Kessenichf8d1d742019-10-21 06:55:11 -0600378 if (qualifier.isCoherent())
Jeff Bolz36831c92018-09-05 10:11:41 -0500379 memory.push_back(spv::DecorationCoherent);
John Kessenichf8d1d742019-10-21 06:55:11 -0600380 if (qualifier.isVolatile()) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500381 memory.push_back(spv::DecorationVolatile);
382 memory.push_back(spv::DecorationCoherent);
383 }
John Kessenich14b85d32018-06-04 15:36:03 -0600384 }
John Kessenichf8d1d742019-10-21 06:55:11 -0600385 if (qualifier.isRestrict())
Rex Xu1da878f2016-02-21 20:59:01 +0800386 memory.push_back(spv::DecorationRestrict);
John Kessenichdeec1932019-08-13 08:00:30 -0600387 if (qualifier.isReadOnly())
Rex Xu1da878f2016-02-21 20:59:01 +0800388 memory.push_back(spv::DecorationNonWritable);
John Kessenichdeec1932019-08-13 08:00:30 -0600389 if (qualifier.isWriteOnly())
Rex Xu1da878f2016-02-21 20:59:01 +0800390 memory.push_back(spv::DecorationNonReadable);
391}
392
John Kessenich140f3df2015-06-26 16:58:36 -0600393// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700394spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600395{
396 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700397 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600398 case glslang::ElmRowMajor:
399 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700400 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600401 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700402 default:
403 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600404 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600405 }
406 } else {
407 switch (type.getBasicType()) {
408 default:
John Kessenich4016e382016-07-15 11:53:56 -0600409 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600410 break;
411 case glslang::EbtBlock:
412 switch (type.getQualifier().storage) {
413 case glslang::EvqUniform:
414 case glslang::EvqBuffer:
415 switch (type.getQualifier().layoutPacking) {
416 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600417 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
418 default:
John Kessenich4016e382016-07-15 11:53:56 -0600419 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600420 }
421 case glslang::EvqVaryingIn:
422 case glslang::EvqVaryingOut:
Chao Chen3c366992018-09-19 11:41:59 -0700423 if (type.getQualifier().isTaskMemory()) {
424 switch (type.getQualifier().layoutPacking) {
425 case glslang::ElpShared: return spv::DecorationGLSLShared;
426 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
427 default: break;
428 }
429 } else {
430 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
431 }
John Kessenich4016e382016-07-15 11:53:56 -0600432 return spv::DecorationMax;
John Kessenicha28f7a72019-08-06 07:00:58 -0600433#ifndef GLSLANG_WEB
Chao Chenb50c02e2018-09-19 11:42:24 -0700434 case glslang::EvqPayloadNV:
435 case glslang::EvqPayloadInNV:
436 case glslang::EvqHitAttrNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700437 case glslang::EvqCallableDataNV:
438 case glslang::EvqCallableDataInNV:
Chao Chenb50c02e2018-09-19 11:42:24 -0700439 return spv::DecorationMax;
440#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600441 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700442 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600443 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600444 }
445 }
446 }
447}
448
449// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600450// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700451// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800452spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600453{
Rex Xubbceed72016-05-21 09:40:44 +0800454 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700455 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600456 return spv::DecorationMax;
John Kessenich7015bd62019-08-01 03:28:08 -0600457 else if (qualifier.isNonPerspective())
John Kessenich55e7d112015-11-15 21:33:39 -0700458 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700459 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600460 return spv::DecorationFlat;
John Kessenicha28f7a72019-08-06 07:00:58 -0600461 else if (qualifier.isExplicitInterpolation()) {
Rex Xu17ff3432016-10-14 17:41:45 +0800462 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800463 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800464 }
Rex Xubbceed72016-05-21 09:40:44 +0800465 else
John Kessenich4016e382016-07-15 11:53:56 -0600466 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800467}
468
469// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600470// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800471// should be applied.
472spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
473{
John Kessenichb9197c82019-08-11 07:41:45 -0600474 if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600475 return spv::DecorationCentroid;
John Kessenichb9197c82019-08-11 07:41:45 -0600476#ifndef GLSLANG_WEB
477 else if (qualifier.patch)
478 return spv::DecorationPatch;
John Kessenich5e801132016-02-15 11:09:46 -0700479 else if (qualifier.sample) {
480 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600481 return spv::DecorationSample;
John Kessenichb9197c82019-08-11 07:41:45 -0600482 }
483#endif
484
485 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600486}
487
John Kessenich92187592016-02-01 13:45:25 -0700488// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700489spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600490{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700491 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600492 return spv::DecorationInvariant;
493 else
John Kessenich4016e382016-07-15 11:53:56 -0600494 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600495}
496
qining9220dbb2016-05-04 17:34:38 -0400497// If glslang type is noContraction, return SPIR-V NoContraction decoration.
498spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
499{
John Kessenichb9197c82019-08-11 07:41:45 -0600500#ifndef GLSLANG_WEB
John Kessenicha28f7a72019-08-06 07:00:58 -0600501 if (qualifier.isNoContraction())
qining9220dbb2016-05-04 17:34:38 -0400502 return spv::DecorationNoContraction;
503 else
John Kessenichb9197c82019-08-11 07:41:45 -0600504#endif
John Kessenich4016e382016-07-15 11:53:56 -0600505 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400506}
507
John Kessenich5611c6d2018-04-05 11:25:02 -0600508// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
509spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
510{
John Kessenichb9197c82019-08-11 07:41:45 -0600511#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -0600512 if (qualifier.isNonUniform()) {
John Kessenich8317e6c2019-08-18 23:58:08 -0600513 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -0600514 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
515 return spv::DecorationNonUniformEXT;
516 } else
John Kessenichb9197c82019-08-11 07:41:45 -0600517#endif
John Kessenich5611c6d2018-04-05 11:25:02 -0600518 return spv::DecorationMax;
519}
520
John Kessenichb9197c82019-08-11 07:41:45 -0600521spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(
522 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500523{
Jeff Bolz36831c92018-09-05 10:11:41 -0500524 spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
John Kessenichb9197c82019-08-11 07:41:45 -0600525
526#ifndef GLSLANG_WEB
527 if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage)
528 return mask;
529
Jeff Bolz36831c92018-09-05 10:11:41 -0500530 if (coherentFlags.volatil ||
531 coherentFlags.coherent ||
532 coherentFlags.devicecoherent ||
533 coherentFlags.queuefamilycoherent ||
534 coherentFlags.workgroupcoherent ||
535 coherentFlags.subgroupcoherent) {
536 mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
537 spv::MemoryAccessMakePointerVisibleKHRMask;
538 }
539 if (coherentFlags.nonprivate) {
540 mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
541 }
542 if (coherentFlags.volatil) {
543 mask = mask | spv::MemoryAccessVolatileMask;
544 }
545 if (mask != spv::MemoryAccessMaskNone) {
546 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
547 }
John Kessenichb9197c82019-08-11 07:41:45 -0600548#endif
549
Jeff Bolz36831c92018-09-05 10:11:41 -0500550 return mask;
551}
552
John Kessenichb9197c82019-08-11 07:41:45 -0600553spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(
554 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500555{
Jeff Bolz36831c92018-09-05 10:11:41 -0500556 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenichb9197c82019-08-11 07:41:45 -0600557
558#ifndef GLSLANG_WEB
559 if (!glslangIntermediate->usingVulkanMemoryModel())
560 return mask;
561
Jeff Bolz36831c92018-09-05 10:11:41 -0500562 if (coherentFlags.volatil ||
563 coherentFlags.coherent ||
564 coherentFlags.devicecoherent ||
565 coherentFlags.queuefamilycoherent ||
566 coherentFlags.workgroupcoherent ||
567 coherentFlags.subgroupcoherent) {
568 mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
569 spv::ImageOperandsMakeTexelVisibleKHRMask;
570 }
571 if (coherentFlags.nonprivate) {
572 mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
573 }
574 if (coherentFlags.volatil) {
575 mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
576 }
577 if (mask != spv::ImageOperandsMaskNone) {
578 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
579 }
John Kessenichb9197c82019-08-11 07:41:45 -0600580#endif
581
Jeff Bolz36831c92018-09-05 10:11:41 -0500582 return mask;
583}
584
585spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
586{
John Kessenichb9197c82019-08-11 07:41:45 -0600587 spv::Builder::AccessChain::CoherentFlags flags = {};
588#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -0500589 flags.coherent = type.getQualifier().coherent;
590 flags.devicecoherent = type.getQualifier().devicecoherent;
591 flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
592 // shared variables are implicitly workgroupcoherent in GLSL.
593 flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
594 type.getQualifier().storage == glslang::EvqShared;
595 flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600596 flags.volatil = type.getQualifier().volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500597 // *coherent variables are implicitly nonprivate in GLSL
598 flags.nonprivate = type.getQualifier().nonprivate ||
Jeff Bolzab3c9652018-10-15 22:46:48 -0500599 flags.subgroupcoherent ||
600 flags.workgroupcoherent ||
601 flags.queuefamilycoherent ||
602 flags.devicecoherent ||
Jeff Bolz38cbad12019-03-05 14:40:07 -0600603 flags.coherent ||
604 flags.volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500605 flags.isImage = type.getBasicType() == glslang::EbtSampler;
John Kessenichb9197c82019-08-11 07:41:45 -0600606#endif
Jeff Bolz36831c92018-09-05 10:11:41 -0500607 return flags;
608}
609
John Kessenichb9197c82019-08-11 07:41:45 -0600610spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(
611 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500612{
John Kessenichb9197c82019-08-11 07:41:45 -0600613 spv::Scope scope = spv::ScopeMax;
614
615#ifndef GLSLANG_WEB
Jeff Bolz38cbad12019-03-05 14:40:07 -0600616 if (coherentFlags.volatil || coherentFlags.coherent) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500617 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
618 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
619 } else if (coherentFlags.devicecoherent) {
620 scope = spv::ScopeDevice;
621 } else if (coherentFlags.queuefamilycoherent) {
622 scope = spv::ScopeQueueFamilyKHR;
623 } else if (coherentFlags.workgroupcoherent) {
624 scope = spv::ScopeWorkgroup;
625 } else if (coherentFlags.subgroupcoherent) {
626 scope = spv::ScopeSubgroup;
Jeff Bolz36831c92018-09-05 10:11:41 -0500627 }
628 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
629 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
630 }
John Kessenichb9197c82019-08-11 07:41:45 -0600631#endif
632
Jeff Bolz36831c92018-09-05 10:11:41 -0500633 return scope;
634}
635
David Netoa901ffe2016-06-08 14:11:40 +0100636// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
637// associated capabilities when required. For some built-in variables, a capability
638// is generated only when using the variable in an executable instruction, but not when
639// just declaring a struct member variable with it. This is true for PointSize,
640// ClipDistance, and CullDistance.
641spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600642{
643 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700644 case glslang::EbvPointSize:
John Kessenich155d3512019-08-08 23:29:20 -0600645#ifndef GLSLANG_WEB
John Kessenich78a45572016-07-08 14:05:15 -0600646 // Defer adding the capability until the built-in is actually used.
647 if (! memberDeclaration) {
648 switch (glslangIntermediate->getStage()) {
649 case EShLangGeometry:
650 builder.addCapability(spv::CapabilityGeometryPointSize);
651 break;
652 case EShLangTessControl:
653 case EShLangTessEvaluation:
654 builder.addCapability(spv::CapabilityTessellationPointSize);
655 break;
656 default:
657 break;
658 }
John Kessenich92187592016-02-01 13:45:25 -0700659 }
John Kessenich155d3512019-08-08 23:29:20 -0600660#endif
John Kessenich92187592016-02-01 13:45:25 -0700661 return spv::BuiltInPointSize;
662
John Kessenicha28f7a72019-08-06 07:00:58 -0600663 case glslang::EbvPosition: return spv::BuiltInPosition;
664 case glslang::EbvVertexId: return spv::BuiltInVertexId;
665 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
666 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
667 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
668
669 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
670 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
671 case glslang::EbvFace: return spv::BuiltInFrontFacing;
672 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
673
John Kessenich3dd1ce52019-10-17 07:08:40 -0600674 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
675 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
676 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
677 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
678 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
679 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
680
John Kessenicha28f7a72019-08-06 07:00:58 -0600681#ifndef GLSLANG_WEB
John Kessenichebb50532016-05-16 19:22:05 -0600682 // These *Distance capabilities logically belong here, but if the member is declared and
683 // then never used, consumers of SPIR-V prefer the capability not be declared.
684 // They are now generated when used, rather than here when declared.
685 // Potentially, the specification should be more clear what the minimum
686 // use needed is to trigger the capability.
687 //
John Kessenich92187592016-02-01 13:45:25 -0700688 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100689 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800690 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700691 return spv::BuiltInClipDistance;
692
693 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100694 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800695 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700696 return spv::BuiltInCullDistance;
697
698 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600699 builder.addCapability(spv::CapabilityMultiViewport);
700 if (glslangIntermediate->getStage() == EShLangVertex ||
701 glslangIntermediate->getStage() == EShLangTessControl ||
702 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800703
John Kessenich8317e6c2019-08-18 23:58:08 -0600704 builder.addIncorporatedExtension(spv::E_SPV_EXT_shader_viewport_index_layer, spv::Spv_1_5);
John Kessenichba6a3c22017-09-13 13:22:50 -0600705 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800706 }
John Kessenich92187592016-02-01 13:45:25 -0700707 return spv::BuiltInViewportIndex;
708
John Kessenich5e801132016-02-15 11:09:46 -0700709 case glslang::EbvSampleId:
710 builder.addCapability(spv::CapabilitySampleRateShading);
711 return spv::BuiltInSampleId;
712
713 case glslang::EbvSamplePosition:
714 builder.addCapability(spv::CapabilitySampleRateShading);
715 return spv::BuiltInSamplePosition;
716
717 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700718 return spv::BuiltInSampleMask;
719
John Kessenich78a45572016-07-08 14:05:15 -0600720 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700721 if (glslangIntermediate->getStage() == EShLangMeshNV) {
722 return spv::BuiltInLayer;
723 }
John Kessenichba6a3c22017-09-13 13:22:50 -0600724 builder.addCapability(spv::CapabilityGeometry);
725 if (glslangIntermediate->getStage() == EShLangVertex ||
726 glslangIntermediate->getStage() == EShLangTessControl ||
727 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800728
John Kessenich8317e6c2019-08-18 23:58:08 -0600729 builder.addIncorporatedExtension(spv::E_SPV_EXT_shader_viewport_index_layer, spv::Spv_1_5);
John Kessenichba6a3c22017-09-13 13:22:50 -0600730 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800731 }
John Kessenich78a45572016-07-08 14:05:15 -0600732 return spv::BuiltInLayer;
733
John Kessenichda581a22015-10-14 14:10:30 -0600734 case glslang::EbvBaseVertex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600735 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800736 builder.addCapability(spv::CapabilityDrawParameters);
737 return spv::BuiltInBaseVertex;
738
John Kessenichda581a22015-10-14 14:10:30 -0600739 case glslang::EbvBaseInstance:
John Kessenich8317e6c2019-08-18 23:58:08 -0600740 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800741 builder.addCapability(spv::CapabilityDrawParameters);
742 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200743
John Kessenichda581a22015-10-14 14:10:30 -0600744 case glslang::EbvDrawId:
John Kessenich8317e6c2019-08-18 23:58:08 -0600745 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800746 builder.addCapability(spv::CapabilityDrawParameters);
747 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200748
749 case glslang::EbvPrimitiveId:
750 if (glslangIntermediate->getStage() == EShLangFragment)
751 builder.addCapability(spv::CapabilityGeometry);
752 return spv::BuiltInPrimitiveId;
753
Rex Xu37cdcee2017-06-29 17:46:34 +0800754 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800755 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
756 builder.addCapability(spv::CapabilityStencilExportEXT);
757 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800758
John Kessenich140f3df2015-06-26 16:58:36 -0600759 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600760 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
761 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
762 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
763 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
John Kessenich140f3df2015-06-26 16:58:36 -0600764 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
Rex Xu51596642016-09-21 18:56:12 +0800765
Rex Xu574ab042016-04-14 16:53:07 +0800766 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800767 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800768 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
769 return spv::BuiltInSubgroupSize;
770
Rex Xu574ab042016-04-14 16:53:07 +0800771 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800772 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800773 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
774 return spv::BuiltInSubgroupLocalInvocationId;
775
Rex Xu574ab042016-04-14 16:53:07 +0800776 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800777 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
778 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600779 return spv::BuiltInSubgroupEqMask;
Rex Xu51596642016-09-21 18:56:12 +0800780
Rex Xu574ab042016-04-14 16:53:07 +0800781 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800782 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
783 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600784 return spv::BuiltInSubgroupGeMask;
Rex Xu51596642016-09-21 18:56:12 +0800785
Rex Xu574ab042016-04-14 16:53:07 +0800786 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800787 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
788 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600789 return spv::BuiltInSubgroupGtMask;
Rex Xu51596642016-09-21 18:56:12 +0800790
Rex Xu574ab042016-04-14 16:53:07 +0800791 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800792 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
793 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600794 return spv::BuiltInSubgroupLeMask;
Rex Xu51596642016-09-21 18:56:12 +0800795
Rex Xu574ab042016-04-14 16:53:07 +0800796 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800797 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
798 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600799 return spv::BuiltInSubgroupLtMask;
Rex Xu51596642016-09-21 18:56:12 +0800800
John Kessenich66011cb2018-03-06 16:12:04 -0700801 case glslang::EbvNumSubgroups:
802 builder.addCapability(spv::CapabilityGroupNonUniform);
803 return spv::BuiltInNumSubgroups;
804
805 case glslang::EbvSubgroupID:
806 builder.addCapability(spv::CapabilityGroupNonUniform);
807 return spv::BuiltInSubgroupId;
808
809 case glslang::EbvSubgroupSize2:
810 builder.addCapability(spv::CapabilityGroupNonUniform);
811 return spv::BuiltInSubgroupSize;
812
813 case glslang::EbvSubgroupInvocation2:
814 builder.addCapability(spv::CapabilityGroupNonUniform);
815 return spv::BuiltInSubgroupLocalInvocationId;
816
817 case glslang::EbvSubgroupEqMask2:
818 builder.addCapability(spv::CapabilityGroupNonUniform);
819 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
820 return spv::BuiltInSubgroupEqMask;
821
822 case glslang::EbvSubgroupGeMask2:
823 builder.addCapability(spv::CapabilityGroupNonUniform);
824 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
825 return spv::BuiltInSubgroupGeMask;
826
827 case glslang::EbvSubgroupGtMask2:
828 builder.addCapability(spv::CapabilityGroupNonUniform);
829 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
830 return spv::BuiltInSubgroupGtMask;
831
832 case glslang::EbvSubgroupLeMask2:
833 builder.addCapability(spv::CapabilityGroupNonUniform);
834 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
835 return spv::BuiltInSubgroupLeMask;
836
837 case glslang::EbvSubgroupLtMask2:
838 builder.addCapability(spv::CapabilityGroupNonUniform);
839 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
840 return spv::BuiltInSubgroupLtMask;
John Kessenich9c14f772019-06-17 08:38:35 -0600841
Rex Xu17ff3432016-10-14 17:41:45 +0800842 case glslang::EbvBaryCoordNoPersp:
843 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
844 return spv::BuiltInBaryCoordNoPerspAMD;
845
846 case glslang::EbvBaryCoordNoPerspCentroid:
847 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
848 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
849
850 case glslang::EbvBaryCoordNoPerspSample:
851 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
852 return spv::BuiltInBaryCoordNoPerspSampleAMD;
853
854 case glslang::EbvBaryCoordSmooth:
855 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
856 return spv::BuiltInBaryCoordSmoothAMD;
857
858 case glslang::EbvBaryCoordSmoothCentroid:
859 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
860 return spv::BuiltInBaryCoordSmoothCentroidAMD;
861
862 case glslang::EbvBaryCoordSmoothSample:
863 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
864 return spv::BuiltInBaryCoordSmoothSampleAMD;
865
866 case glslang::EbvBaryCoordPullModel:
867 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
868 return spv::BuiltInBaryCoordPullModelAMD;
chaoc771d89f2017-01-13 01:10:53 -0800869
John Kessenich6c8aaac2017-02-27 01:20:51 -0700870 case glslang::EbvDeviceIndex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600871 builder.addIncorporatedExtension(spv::E_SPV_KHR_device_group, spv::Spv_1_3);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700872 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700873 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700874
875 case glslang::EbvViewIndex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600876 builder.addIncorporatedExtension(spv::E_SPV_KHR_multiview, spv::Spv_1_3);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700877 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700878 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700879
Daniel Koch5154db52018-11-26 10:01:58 -0500880 case glslang::EbvFragSizeEXT:
881 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
882 builder.addCapability(spv::CapabilityFragmentDensityEXT);
883 return spv::BuiltInFragSizeEXT;
884
885 case glslang::EbvFragInvocationCountEXT:
886 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
887 builder.addCapability(spv::CapabilityFragmentDensityEXT);
888 return spv::BuiltInFragInvocationCountEXT;
889
chaoc771d89f2017-01-13 01:10:53 -0800890 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800891 if (!memberDeclaration) {
892 builder.addExtension(spv::E_SPV_NV_viewport_array2);
893 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
894 }
chaoc771d89f2017-01-13 01:10:53 -0800895 return spv::BuiltInViewportMaskNV;
896 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800897 if (!memberDeclaration) {
898 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
899 builder.addCapability(spv::CapabilityShaderStereoViewNV);
900 }
chaoc771d89f2017-01-13 01:10:53 -0800901 return spv::BuiltInSecondaryPositionNV;
902 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800903 if (!memberDeclaration) {
904 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
905 builder.addCapability(spv::CapabilityShaderStereoViewNV);
906 }
chaoc771d89f2017-01-13 01:10:53 -0800907 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800908 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800909 if (!memberDeclaration) {
910 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
911 builder.addCapability(spv::CapabilityPerViewAttributesNV);
912 }
chaocdf3956c2017-02-14 14:52:34 -0800913 return spv::BuiltInPositionPerViewNV;
914 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800915 if (!memberDeclaration) {
916 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
917 builder.addCapability(spv::CapabilityPerViewAttributesNV);
918 }
chaocdf3956c2017-02-14 14:52:34 -0800919 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700920 case glslang::EbvFragFullyCoveredNV:
921 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
922 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
923 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700924 case glslang::EbvFragmentSizeNV:
925 builder.addExtension(spv::E_SPV_NV_shading_rate);
926 builder.addCapability(spv::CapabilityShadingRateNV);
927 return spv::BuiltInFragmentSizeNV;
928 case glslang::EbvInvocationsPerPixelNV:
929 builder.addExtension(spv::E_SPV_NV_shading_rate);
930 builder.addCapability(spv::CapabilityShadingRateNV);
931 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700932
Daniel Koch593a4e02019-05-27 16:46:31 -0400933 // ray tracing
Chao Chenb50c02e2018-09-19 11:42:24 -0700934 case glslang::EbvLaunchIdNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700935 return spv::BuiltInLaunchIdNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700936 case glslang::EbvLaunchSizeNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700937 return spv::BuiltInLaunchSizeNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700938 case glslang::EbvWorldRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700939 return spv::BuiltInWorldRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700940 case glslang::EbvWorldRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700941 return spv::BuiltInWorldRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700942 case glslang::EbvObjectRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700943 return spv::BuiltInObjectRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700944 case glslang::EbvObjectRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700945 return spv::BuiltInObjectRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700946 case glslang::EbvRayTminNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700947 return spv::BuiltInRayTminNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700948 case glslang::EbvRayTmaxNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700949 return spv::BuiltInRayTmaxNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700950 case glslang::EbvInstanceCustomIndexNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700951 return spv::BuiltInInstanceCustomIndexNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700952 case glslang::EbvHitTNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700953 return spv::BuiltInHitTNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700954 case glslang::EbvHitKindNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700955 return spv::BuiltInHitKindNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700956 case glslang::EbvObjectToWorldNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700957 return spv::BuiltInObjectToWorldNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700958 case glslang::EbvWorldToObjectNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700959 return spv::BuiltInWorldToObjectNV;
960 case glslang::EbvIncomingRayFlagsNV:
961 return spv::BuiltInIncomingRayFlagsNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400962
963 // barycentrics
Chao Chen9eada4b2018-09-19 11:39:56 -0700964 case glslang::EbvBaryCoordNV:
965 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
966 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
967 return spv::BuiltInBaryCoordNV;
968 case glslang::EbvBaryCoordNoPerspNV:
969 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
970 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
971 return spv::BuiltInBaryCoordNoPerspNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400972
973 // mesh shaders
974 case glslang::EbvTaskCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700975 return spv::BuiltInTaskCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400976 case glslang::EbvPrimitiveCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700977 return spv::BuiltInPrimitiveCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400978 case glslang::EbvPrimitiveIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -0700979 return spv::BuiltInPrimitiveIndicesNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400980 case glslang::EbvClipDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700981 return spv::BuiltInClipDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400982 case glslang::EbvCullDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700983 return spv::BuiltInCullDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400984 case glslang::EbvLayerPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700985 return spv::BuiltInLayerPerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400986 case glslang::EbvMeshViewCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700987 return spv::BuiltInMeshViewCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400988 case glslang::EbvMeshViewIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -0700989 return spv::BuiltInMeshViewIndicesNV;
Daniel Koch2cb2f192019-06-04 08:43:32 -0400990
991 // sm builtins
992 case glslang::EbvWarpsPerSM:
993 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
994 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
995 return spv::BuiltInWarpsPerSMNV;
996 case glslang::EbvSMCount:
997 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
998 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
999 return spv::BuiltInSMCountNV;
1000 case glslang::EbvWarpID:
1001 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1002 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1003 return spv::BuiltInWarpIDNV;
1004 case glslang::EbvSMID:
1005 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1006 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1007 return spv::BuiltInSMIDNV;
John Kessenicha28f7a72019-08-06 07:00:58 -06001008#endif
1009
Rex Xu3e783f92017-02-22 16:44:48 +08001010 default:
1011 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -06001012 }
1013}
1014
Rex Xufc618912015-09-09 16:42:49 +08001015// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -07001016spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +08001017{
1018 assert(type.getBasicType() == glslang::EbtSampler);
1019
John Kessenichb9197c82019-08-11 07:41:45 -06001020#ifdef GLSLANG_WEB
1021 return spv::ImageFormatUnknown;
1022#endif
1023
John Kessenich5d0fa972016-02-15 11:57:00 -07001024 // Check for capabilities
John Kessenich7015bd62019-08-01 03:28:08 -06001025 switch (type.getQualifier().getFormat()) {
John Kessenich5d0fa972016-02-15 11:57:00 -07001026 case glslang::ElfRg32f:
1027 case glslang::ElfRg16f:
1028 case glslang::ElfR11fG11fB10f:
1029 case glslang::ElfR16f:
1030 case glslang::ElfRgba16:
1031 case glslang::ElfRgb10A2:
1032 case glslang::ElfRg16:
1033 case glslang::ElfRg8:
1034 case glslang::ElfR16:
1035 case glslang::ElfR8:
1036 case glslang::ElfRgba16Snorm:
1037 case glslang::ElfRg16Snorm:
1038 case glslang::ElfRg8Snorm:
1039 case glslang::ElfR16Snorm:
1040 case glslang::ElfR8Snorm:
1041
1042 case glslang::ElfRg32i:
1043 case glslang::ElfRg16i:
1044 case glslang::ElfRg8i:
1045 case glslang::ElfR16i:
1046 case glslang::ElfR8i:
1047
1048 case glslang::ElfRgb10a2ui:
1049 case glslang::ElfRg32ui:
1050 case glslang::ElfRg16ui:
1051 case glslang::ElfRg8ui:
1052 case glslang::ElfR16ui:
1053 case glslang::ElfR8ui:
1054 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
1055 break;
1056
1057 default:
1058 break;
1059 }
1060
1061 // do the translation
John Kessenich7015bd62019-08-01 03:28:08 -06001062 switch (type.getQualifier().getFormat()) {
Rex Xufc618912015-09-09 16:42:49 +08001063 case glslang::ElfNone: return spv::ImageFormatUnknown;
1064 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
1065 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
1066 case glslang::ElfR32f: return spv::ImageFormatR32f;
1067 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
1068 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
1069 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1070 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1071 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1072 case glslang::ElfR16f: return spv::ImageFormatR16f;
1073 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1074 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1075 case glslang::ElfRg16: return spv::ImageFormatRg16;
1076 case glslang::ElfRg8: return spv::ImageFormatRg8;
1077 case glslang::ElfR16: return spv::ImageFormatR16;
1078 case glslang::ElfR8: return spv::ImageFormatR8;
1079 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1080 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1081 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1082 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1083 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1084 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1085 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1086 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1087 case glslang::ElfR32i: return spv::ImageFormatR32i;
1088 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1089 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1090 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1091 case glslang::ElfR16i: return spv::ImageFormatR16i;
1092 case glslang::ElfR8i: return spv::ImageFormatR8i;
1093 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1094 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1095 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1096 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1097 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1098 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1099 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1100 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1101 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1102 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001103 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001104 }
1105}
1106
John Kesseniche18fd202018-01-30 11:01:39 -07001107spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001108{
John Kesseniche18fd202018-01-30 11:01:39 -07001109 if (selectionNode.getFlatten())
1110 return spv::SelectionControlFlattenMask;
1111 if (selectionNode.getDontFlatten())
1112 return spv::SelectionControlDontFlattenMask;
1113 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001114}
1115
John Kesseniche18fd202018-01-30 11:01:39 -07001116spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -06001117{
John Kesseniche18fd202018-01-30 11:01:39 -07001118 if (switchNode.getFlatten())
1119 return spv::SelectionControlFlattenMask;
1120 if (switchNode.getDontFlatten())
1121 return spv::SelectionControlDontFlattenMask;
1122 return spv::SelectionControlMaskNone;
1123}
1124
John Kessenicha2858d92018-01-31 08:11:18 -07001125// return a non-0 dependency if the dependency argument must be set
1126spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
John Kessenich1f4d0462019-01-12 17:31:41 +07001127 std::vector<unsigned int>& operands) const
John Kesseniche18fd202018-01-30 11:01:39 -07001128{
1129 spv::LoopControlMask control = spv::LoopControlMaskNone;
1130
1131 if (loopNode.getDontUnroll())
1132 control = control | spv::LoopControlDontUnrollMask;
1133 if (loopNode.getUnroll())
1134 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001135 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001136 control = control | spv::LoopControlDependencyInfiniteMask;
1137 else if (loopNode.getLoopDependency() > 0) {
1138 control = control | spv::LoopControlDependencyLengthMask;
John Kessenich1f4d0462019-01-12 17:31:41 +07001139 operands.push_back((unsigned int)loopNode.getLoopDependency());
1140 }
1141 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
1142 if (loopNode.getMinIterations() > 0) {
1143 control = control | spv::LoopControlMinIterationsMask;
1144 operands.push_back(loopNode.getMinIterations());
1145 }
1146 if (loopNode.getMaxIterations() < glslang::TIntermLoop::iterationsInfinite) {
1147 control = control | spv::LoopControlMaxIterationsMask;
1148 operands.push_back(loopNode.getMaxIterations());
1149 }
1150 if (loopNode.getIterationMultiple() > 1) {
1151 control = control | spv::LoopControlIterationMultipleMask;
1152 operands.push_back(loopNode.getIterationMultiple());
1153 }
1154 if (loopNode.getPeelCount() > 0) {
1155 control = control | spv::LoopControlPeelCountMask;
1156 operands.push_back(loopNode.getPeelCount());
1157 }
1158 if (loopNode.getPartialCount() > 0) {
1159 control = control | spv::LoopControlPartialCountMask;
1160 operands.push_back(loopNode.getPartialCount());
1161 }
John Kessenicha2858d92018-01-31 08:11:18 -07001162 }
John Kesseniche18fd202018-01-30 11:01:39 -07001163
1164 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001165}
1166
John Kessenicha5c5fb62017-05-05 05:09:58 -06001167// Translate glslang type to SPIR-V storage class.
1168spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1169{
1170 if (type.getQualifier().isPipeInput())
1171 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001172 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001173 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001174
1175 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
John Kessenicha28f7a72019-08-06 07:00:58 -06001176 type.getQualifier().storage == glslang::EvqUniform) {
John Kessenichdeec1932019-08-13 08:00:30 -06001177 if (type.isAtomic())
John Kessenichbed4e4f2017-09-08 02:38:07 -06001178 return spv::StorageClassAtomicCounter;
1179 if (type.containsOpaque())
1180 return spv::StorageClassUniformConstant;
1181 }
1182
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001183 if (type.getQualifier().isUniformOrBuffer() &&
John Kessenichdeec1932019-08-13 08:00:30 -06001184 type.getQualifier().isShaderRecordNV()) {
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001185 return spv::StorageClassShaderRecordBufferNV;
1186 }
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001187
John Kessenichbed4e4f2017-09-08 02:38:07 -06001188 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001189 builder.addIncorporatedExtension(spv::E_SPV_KHR_storage_buffer_storage_class, spv::Spv_1_3);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001190 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001191 }
1192
1193 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich7015bd62019-08-01 03:28:08 -06001194 if (type.getQualifier().isPushConstant())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001195 return spv::StorageClassPushConstant;
1196 if (type.getBasicType() == glslang::EbtBlock)
1197 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001198 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001199 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001200
1201 switch (type.getQualifier().storage) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001202 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1203 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1204 case glslang::EvqTemporary: return spv::StorageClassFunction;
John Kessenichdeec1932019-08-13 08:00:30 -06001205 case glslang::EvqShared: return spv::StorageClassWorkgroup;
John Kessenich3dd1ce52019-10-17 07:08:40 -06001206#ifndef GLSLANG_WEB
Ashwin Leleff1783d2018-10-22 16:41:44 -07001207 case glslang::EvqPayloadNV: return spv::StorageClassRayPayloadNV;
1208 case glslang::EvqPayloadInNV: return spv::StorageClassIncomingRayPayloadNV;
1209 case glslang::EvqHitAttrNV: return spv::StorageClassHitAttributeNV;
1210 case glslang::EvqCallableDataNV: return spv::StorageClassCallableDataNV;
1211 case glslang::EvqCallableDataInNV: return spv::StorageClassIncomingCallableDataNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07001212#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001213 default:
1214 assert(0);
1215 break;
1216 }
1217
1218 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001219}
1220
John Kessenich5611c6d2018-04-05 11:25:02 -06001221// Add capabilities pertaining to how an array is indexed.
1222void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1223 const glslang::TType& indexType)
1224{
John Kessenichb9197c82019-08-11 07:41:45 -06001225#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06001226 if (indexType.getQualifier().isNonUniform()) {
1227 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001228 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001229 if (baseType.getBasicType() == glslang::EbtSampler) {
1230 if (baseType.getQualifier().hasAttachment())
1231 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001232 else if (baseType.isImage() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001233 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001234 else if (baseType.isTexture() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001235 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1236 else if (baseType.isImage())
1237 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1238 else if (baseType.isTexture())
1239 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1240 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1241 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1242 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1243 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1244 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1245 }
1246 } else {
1247 // assume a dynamically uniform index
1248 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001249 if (baseType.getQualifier().hasAttachment()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001250 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001251 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001252 } else if (baseType.isImage() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001253 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001254 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001255 } else if (baseType.isTexture() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001256 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001257 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001258 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001259 }
1260 }
John Kessenichb9197c82019-08-11 07:41:45 -06001261#endif
John Kessenich5611c6d2018-04-05 11:25:02 -06001262}
1263
qining25262b32016-05-06 17:25:16 -04001264// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001265// descriptor set.
1266bool IsDescriptorResource(const glslang::TType& type)
1267{
John Kessenichf7497e22016-03-08 21:36:22 -07001268 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001269 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001270 return type.getQualifier().isUniformOrBuffer() &&
John Kessenich7015bd62019-08-01 03:28:08 -06001271 ! type.getQualifier().isShaderRecordNV() &&
1272 ! type.getQualifier().isPushConstant();
John Kessenich6c292d32016-02-15 20:58:50 -07001273
1274 // non block...
1275 // basically samplerXXX/subpass/sampler/texture are all included
1276 // if they are the global-scope-class, not the function parameter
1277 // (or local, if they ever exist) class.
1278 if (type.getBasicType() == glslang::EbtSampler)
1279 return type.getQualifier().isUniformOrBuffer();
1280
1281 // None of the above.
1282 return false;
1283}
1284
John Kesseniche0b6cad2015-12-24 10:30:13 -07001285void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1286{
1287 if (child.layoutMatrix == glslang::ElmNone)
1288 child.layoutMatrix = parent.layoutMatrix;
1289
1290 if (parent.invariant)
1291 child.invariant = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001292 if (parent.flat)
1293 child.flat = true;
1294 if (parent.centroid)
1295 child.centroid = true;
John Kessenich7015bd62019-08-01 03:28:08 -06001296#ifndef GLSLANG_WEB
John Kesseniche0b6cad2015-12-24 10:30:13 -07001297 if (parent.nopersp)
1298 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001299 if (parent.explicitInterp)
1300 child.explicitInterp = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001301 if (parent.perPrimitiveNV)
1302 child.perPrimitiveNV = true;
1303 if (parent.perViewNV)
1304 child.perViewNV = true;
1305 if (parent.perTaskNV)
1306 child.perTaskNV = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001307 if (parent.patch)
1308 child.patch = true;
1309 if (parent.sample)
1310 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001311 if (parent.coherent)
1312 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001313 if (parent.devicecoherent)
1314 child.devicecoherent = true;
1315 if (parent.queuefamilycoherent)
1316 child.queuefamilycoherent = true;
1317 if (parent.workgroupcoherent)
1318 child.workgroupcoherent = true;
1319 if (parent.subgroupcoherent)
1320 child.subgroupcoherent = true;
1321 if (parent.nonprivate)
1322 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001323 if (parent.volatil)
1324 child.volatil = true;
1325 if (parent.restrict)
1326 child.restrict = true;
1327 if (parent.readonly)
1328 child.readonly = true;
1329 if (parent.writeonly)
1330 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001331#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001332}
1333
John Kessenichf2b7f332016-09-01 17:05:23 -06001334bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001335{
John Kessenich7b9fa252016-01-21 18:56:57 -07001336 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001337 // - struct members might inherit from a struct declaration
1338 // (note that non-block structs don't explicitly inherit,
1339 // only implicitly, meaning no decoration involved)
1340 // - affect decorations on the struct members
1341 // (note smooth does not, and expecting something like volatile
1342 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001343 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001344 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001345}
1346
John Kessenich140f3df2015-06-26 16:58:36 -06001347//
1348// Implement the TGlslangToSpvTraverser class.
1349//
1350
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001351TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001352 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1353 : TIntermTraverser(true, false, true),
1354 options(options),
1355 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001356 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001357 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001358 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich605afc72019-06-17 23:33:09 -06001359 glslangIntermediate(glslangIntermediate),
1360 nanMinMaxClamp(glslangIntermediate->getNanMinMaxClamp())
John Kessenich140f3df2015-06-26 16:58:36 -06001361{
1362 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1363
1364 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001365 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1366 glslangIntermediate->getVersion());
1367
John Kessenich121853f2017-05-31 17:11:16 -06001368 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001369 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001370 builder.setSourceFile(glslangIntermediate->getSourceFile());
1371
1372 // Set the source shader's text. If for SPV version 1.0, include
1373 // a preamble in comments stating the OpModuleProcessed instructions.
1374 // Otherwise, emit those as actual instructions.
1375 std::string text;
1376 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1377 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001378 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001379 text.append("// OpModuleProcessed ");
1380 text.append(processes[p]);
1381 text.append("\n");
1382 } else
1383 builder.addModuleProcessed(processes[p]);
1384 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001385 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001386 text.append("#line 1\n");
1387 text.append(glslangIntermediate->getSourceText());
1388 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001389 // Pass name and text for all included files
1390 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1391 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1392 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001393 }
John Kessenich140f3df2015-06-26 16:58:36 -06001394 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001395
1396 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1397 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1398
1399 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1400 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
John Kessenich1ff0c182019-10-10 12:01:13 -06001401 builder.addIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer, spv::Spv_1_5);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001402 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
1403 };
Jeff Bolz36831c92018-09-05 10:11:41 -05001404 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001405 memoryModel = spv::MemoryModelVulkanKHR;
1406 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
John Kessenich8317e6c2019-08-18 23:58:08 -06001407 builder.addIncorporatedExtension(spv::E_SPV_KHR_vulkan_memory_model, spv::Spv_1_5);
Jeff Bolz36831c92018-09-05 10:11:41 -05001408 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001409 builder.setMemoryModel(addressingModel, memoryModel);
1410
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001411 if (glslangIntermediate->usingVariablePointers()) {
1412 builder.addCapability(spv::CapabilityVariablePointers);
1413 }
1414
John Kessenicheee9d532016-09-19 18:09:30 -06001415 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1416 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001417
1418 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001419 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1420 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001421 builder.addSourceExtension(it->c_str());
1422
1423 // Add the top-level modes for this shader.
1424
John Kessenich92187592016-02-01 13:45:25 -07001425 if (glslangIntermediate->getXfbMode()) {
1426 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001427 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001428 }
John Kessenich140f3df2015-06-26 16:58:36 -06001429
1430 unsigned int mode;
1431 switch (glslangIntermediate->getStage()) {
1432 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001433 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001434 break;
1435
John Kessenicha28f7a72019-08-06 07:00:58 -06001436 case EShLangFragment:
1437 builder.addCapability(spv::CapabilityShader);
1438 if (glslangIntermediate->getPixelCenterInteger())
1439 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
1440
1441 if (glslangIntermediate->getOriginUpperLeft())
1442 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
1443 else
1444 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
1445
1446 if (glslangIntermediate->getEarlyFragmentTests())
1447 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1448
1449 if (glslangIntermediate->getPostDepthCoverage()) {
1450 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1451 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1452 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1453 }
1454
John Kessenichb9197c82019-08-11 07:41:45 -06001455 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1456 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
1457
1458#ifndef GLSLANG_WEB
John Kessenicha28f7a72019-08-06 07:00:58 -06001459 switch(glslangIntermediate->getDepth()) {
1460 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1461 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
1462 default: mode = spv::ExecutionModeMax; break;
1463 }
1464 if (mode != spv::ExecutionModeMax)
1465 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kessenicha28f7a72019-08-06 07:00:58 -06001466 switch (glslangIntermediate->getInterlockOrdering()) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001467 case glslang::EioPixelInterlockOrdered: mode = spv::ExecutionModePixelInterlockOrderedEXT;
1468 break;
1469 case glslang::EioPixelInterlockUnordered: mode = spv::ExecutionModePixelInterlockUnorderedEXT;
1470 break;
1471 case glslang::EioSampleInterlockOrdered: mode = spv::ExecutionModeSampleInterlockOrderedEXT;
1472 break;
1473 case glslang::EioSampleInterlockUnordered: mode = spv::ExecutionModeSampleInterlockUnorderedEXT;
1474 break;
1475 case glslang::EioShadingRateInterlockOrdered: mode = spv::ExecutionModeShadingRateInterlockOrderedEXT;
1476 break;
1477 case glslang::EioShadingRateInterlockUnordered: mode = spv::ExecutionModeShadingRateInterlockUnorderedEXT;
1478 break;
1479 default: mode = spv::ExecutionModeMax;
1480 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06001481 }
1482 if (mode != spv::ExecutionModeMax) {
1483 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1484 if (mode == spv::ExecutionModeShadingRateInterlockOrderedEXT ||
1485 mode == spv::ExecutionModeShadingRateInterlockUnorderedEXT) {
1486 builder.addCapability(spv::CapabilityFragmentShaderShadingRateInterlockEXT);
1487 } else if (mode == spv::ExecutionModePixelInterlockOrderedEXT ||
1488 mode == spv::ExecutionModePixelInterlockUnorderedEXT) {
1489 builder.addCapability(spv::CapabilityFragmentShaderPixelInterlockEXT);
1490 } else {
1491 builder.addCapability(spv::CapabilityFragmentShaderSampleInterlockEXT);
1492 }
1493 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
1494 }
John Kessenichb9197c82019-08-11 07:41:45 -06001495#endif
John Kessenicha28f7a72019-08-06 07:00:58 -06001496 break;
1497
John Kessenicha28f7a72019-08-06 07:00:58 -06001498 case EShLangCompute:
1499 builder.addCapability(spv::CapabilityShader);
1500 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1501 glslangIntermediate->getLocalSize(1),
1502 glslangIntermediate->getLocalSize(2));
1503 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1504 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1505 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1506 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1507 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1508 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1509 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1510 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1511 }
1512 break;
John Kessenich51ed01c2019-10-10 11:40:11 -06001513#ifndef GLSLANG_WEB
steve-lunarge7412492017-03-23 11:56:07 -06001514 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001515 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001516 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001517
steve-lunarge7412492017-03-23 11:56:07 -06001518 glslang::TLayoutGeometry primitive;
1519
1520 if (glslangIntermediate->getStage() == EShLangTessControl) {
1521 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1522 primitive = glslangIntermediate->getOutputPrimitive();
1523 } else {
1524 primitive = glslangIntermediate->getInputPrimitive();
1525 }
1526
1527 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001528 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1529 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1530 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001531 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001532 }
John Kessenich4016e382016-07-15 11:53:56 -06001533 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001534 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1535
John Kesseniche6903322015-10-13 16:29:02 -06001536 switch (glslangIntermediate->getVertexSpacing()) {
1537 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1538 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1539 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001540 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001541 }
John Kessenich4016e382016-07-15 11:53:56 -06001542 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001543 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1544
1545 switch (glslangIntermediate->getVertexOrder()) {
1546 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1547 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001548 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001549 }
John Kessenich4016e382016-07-15 11:53:56 -06001550 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001551 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1552
1553 if (glslangIntermediate->getPointMode())
1554 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001555 break;
1556
1557 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001558 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001559 switch (glslangIntermediate->getInputPrimitive()) {
1560 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1561 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1562 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001563 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001564 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001565 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001566 }
John Kessenich4016e382016-07-15 11:53:56 -06001567 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001568 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001569
John Kessenich140f3df2015-06-26 16:58:36 -06001570 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1571
1572 switch (glslangIntermediate->getOutputPrimitive()) {
1573 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1574 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1575 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001576 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001577 }
John Kessenich4016e382016-07-15 11:53:56 -06001578 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001579 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1580 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1581 break;
1582
Chao Chenb50c02e2018-09-19 11:42:24 -07001583 case EShLangRayGenNV:
1584 case EShLangIntersectNV:
1585 case EShLangAnyHitNV:
1586 case EShLangClosestHitNV:
1587 case EShLangMissNV:
1588 case EShLangCallableNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07001589 builder.addCapability(spv::CapabilityRayTracingNV);
1590 builder.addExtension("SPV_NV_ray_tracing");
Chao Chenb50c02e2018-09-19 11:42:24 -07001591 break;
Chao Chen3c366992018-09-19 11:41:59 -07001592 case EShLangTaskNV:
1593 case EShLangMeshNV:
1594 builder.addCapability(spv::CapabilityMeshShadingNV);
1595 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1596 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1597 glslangIntermediate->getLocalSize(1),
1598 glslangIntermediate->getLocalSize(2));
1599 if (glslangIntermediate->getStage() == EShLangMeshNV) {
1600 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1601 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV, glslangIntermediate->getPrimitives());
1602
1603 switch (glslangIntermediate->getOutputPrimitive()) {
1604 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1605 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1606 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1607 default: mode = spv::ExecutionModeMax; break;
1608 }
1609 if (mode != spv::ExecutionModeMax)
1610 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1611 }
1612 break;
1613#endif
1614
John Kessenich140f3df2015-06-26 16:58:36 -06001615 default:
1616 break;
1617 }
John Kessenich140f3df2015-06-26 16:58:36 -06001618}
1619
John Kessenichfca82622016-11-26 13:23:20 -07001620// Finish creating SPV, after the traversal is complete.
1621void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001622{
John Kessenichf04c51b2018-08-03 15:56:12 -06001623 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001624 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001625 builder.setBuildPoint(shaderEntry->getLastBlock());
1626 builder.leaveFunction();
1627 }
1628
John Kessenich7ba63412015-12-20 17:37:07 -07001629 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001630 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1631 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001632
David Neto8c3d5b42019-10-21 14:50:31 -04001633 // Add capabilities, extensions, remove unneeded decorations, etc.,
John Kessenichf04c51b2018-08-03 15:56:12 -06001634 // based on the resulting SPIR-V.
David Neto8c3d5b42019-10-21 14:50:31 -04001635 // Note: WebGPU code generation must have the opportunity to aggressively
1636 // prune unreachable merge blocks and continue targets.
John Kessenichf04c51b2018-08-03 15:56:12 -06001637 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001638}
1639
John Kessenichfca82622016-11-26 13:23:20 -07001640// Write the SPV into 'out'.
1641void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001642{
John Kessenichfca82622016-11-26 13:23:20 -07001643 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001644}
1645
1646//
1647// Implement the traversal functions.
1648//
1649// Return true from interior nodes to have the external traversal
1650// continue on to children. Return false if children were
1651// already processed.
1652//
1653
1654//
qining25262b32016-05-06 17:25:16 -04001655// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001656// - uniform/input reads
1657// - output writes
1658// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1659// - something simple that degenerates into the last bullet
1660//
1661void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1662{
qining75d1d802016-04-06 14:42:01 -04001663 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1664 if (symbol->getType().getQualifier().isSpecConstant())
1665 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1666
John Kessenich140f3df2015-06-26 16:58:36 -06001667 // getSymbolId() will set up all the IO decorations on the first call.
1668 // Formal function parameters were mapped during makeFunctions().
1669 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001670
John Kessenich7ba63412015-12-20 17:37:07 -07001671 if (builder.isPointer(id)) {
John Kessenich9c14f772019-06-17 08:38:35 -06001672 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
John Kessenich7c7731e2019-01-04 16:47:06 +07001673 // Consider adding to the OpEntryPoint interface list.
1674 // Only looking at structures if they have at least one member.
1675 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1676 spv::StorageClass sc = builder.getStorageClass(id);
1677 // Before SPIR-V 1.4, we only want to include Input and Output.
1678 // Starting with SPIR-V 1.4, we want all globals.
1679 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && sc != spv::StorageClassFunction) ||
1680 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
John Kessenich5f77d862017-09-19 11:09:59 -06001681 iOSet.insert(id);
John Kessenich7c7731e2019-01-04 16:47:06 +07001682 }
John Kessenich5f77d862017-09-19 11:09:59 -06001683 }
John Kessenich9c14f772019-06-17 08:38:35 -06001684
1685 // If the SPIR-V type is required to be different than the AST type,
1686 // translate now from the SPIR-V type to the AST type, for the consuming
1687 // operation.
1688 // Note this turns it from an l-value to an r-value.
1689 // Currently, all symbols needing this are inputs; avoid the map lookup when non-input.
1690 if (symbol->getType().getQualifier().storage == glslang::EvqVaryingIn)
1691 id = translateForcedType(id);
John Kessenich7ba63412015-12-20 17:37:07 -07001692 }
1693
1694 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001695 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001696 // Prepare to generate code for the access
1697
1698 // L-value chains will be computed left to right. We're on the symbol now,
1699 // which is the left-most part of the access chain, so now is "clear" time,
1700 // followed by setting the base.
1701 builder.clearAccessChain();
1702
1703 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001704 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001705 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001706 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001707 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001708 // These are also pure R-values.
John Kessenich9c14f772019-06-17 08:38:35 -06001709 // C) R-Values from type translation, see above call to translateForcedType()
John Kessenich6c292d32016-02-15 20:58:50 -07001710 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich9c14f772019-06-17 08:38:35 -06001711 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end() ||
1712 !builder.isPointerType(builder.getTypeId(id)))
John Kessenich140f3df2015-06-26 16:58:36 -06001713 builder.setAccessChainRValue(id);
1714 else
1715 builder.setAccessChainLValue(id);
1716 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001717
John Kessenichb9197c82019-08-11 07:41:45 -06001718#ifdef ENABLE_HLSL
John Kessenich5d610ee2018-03-07 18:05:55 -07001719 // Process linkage-only nodes for any special additional interface work.
1720 if (linkageOnly) {
1721 if (glslangIntermediate->getHlslFunctionality1()) {
1722 // Map implicit counter buffers to their originating buffers, which should have been
1723 // seen by now, given earlier pruning of unused counters, and preservation of order
1724 // of declaration.
1725 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1726 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1727 // Save possible originating buffers for counter buffers, keyed by
1728 // making the potential counter-buffer name.
1729 std::string keyName = symbol->getName().c_str();
1730 keyName = glslangIntermediate->addCounterBufferName(keyName);
1731 counterOriginator[keyName] = symbol;
1732 } else {
1733 // Handle a counter buffer, by finding the saved originating buffer.
1734 std::string keyName = symbol->getName().c_str();
1735 auto it = counterOriginator.find(keyName);
1736 if (it != counterOriginator.end()) {
1737 id = getSymbolId(it->second);
1738 if (id != spv::NoResult) {
1739 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001740 if (counterId != spv::NoResult) {
1741 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001742 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001743 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001744 }
1745 }
1746 }
1747 }
1748 }
1749 }
John Kessenich155d3512019-08-08 23:29:20 -06001750#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001751}
1752
1753bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1754{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001755 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001756
qining40887662016-04-03 22:20:42 -04001757 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1758 if (node->getType().getQualifier().isSpecConstant())
1759 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1760
John Kessenich140f3df2015-06-26 16:58:36 -06001761 // First, handle special cases
1762 switch (node->getOp()) {
1763 case glslang::EOpAssign:
1764 case glslang::EOpAddAssign:
1765 case glslang::EOpSubAssign:
1766 case glslang::EOpMulAssign:
1767 case glslang::EOpVectorTimesMatrixAssign:
1768 case glslang::EOpVectorTimesScalarAssign:
1769 case glslang::EOpMatrixTimesScalarAssign:
1770 case glslang::EOpMatrixTimesMatrixAssign:
1771 case glslang::EOpDivAssign:
1772 case glslang::EOpModAssign:
1773 case glslang::EOpAndAssign:
1774 case glslang::EOpInclusiveOrAssign:
1775 case glslang::EOpExclusiveOrAssign:
1776 case glslang::EOpLeftShiftAssign:
1777 case glslang::EOpRightShiftAssign:
1778 // A bin-op assign "a += b" means the same thing as "a = a + b"
1779 // where a is evaluated before b. For a simple assignment, GLSL
1780 // says to evaluate the left before the right. So, always, left
1781 // node then right node.
1782 {
1783 // get the left l-value, save it away
1784 builder.clearAccessChain();
1785 node->getLeft()->traverse(this);
1786 spv::Builder::AccessChain lValue = builder.getAccessChain();
1787
1788 // evaluate the right
1789 builder.clearAccessChain();
1790 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001791 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001792
1793 if (node->getOp() != glslang::EOpAssign) {
1794 // the left is also an r-value
1795 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001796 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001797
1798 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001799 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001800 TranslateNoContractionDecoration(node->getType().getQualifier()),
1801 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001802 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001803 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1804 node->getType().getBasicType());
1805
1806 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001807 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001808 }
1809
1810 // store the result
1811 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001812 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001813
1814 // assignments are expressions having an rValue after they are evaluated...
1815 builder.clearAccessChain();
1816 builder.setAccessChainRValue(rValue);
1817 }
1818 return false;
1819 case glslang::EOpIndexDirect:
1820 case glslang::EOpIndexDirectStruct:
1821 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001822 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001823 // Get the left part of the access chain.
1824 node->getLeft()->traverse(this);
1825
1826 // Add the next element in the chain
1827
David Netoa901ffe2016-06-08 14:11:40 +01001828 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001829 if (! node->getLeft()->getType().isArray() &&
1830 node->getLeft()->getType().isVector() &&
1831 node->getOp() == glslang::EOpIndexDirect) {
1832 // This is essentially a hard-coded vector swizzle of size 1,
1833 // so short circuit the access-chain stuff with a swizzle.
1834 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001835 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001836 int dummySize;
1837 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1838 TranslateCoherent(node->getLeft()->getType()),
1839 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001840 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001841
1842 // Load through a block reference is performed with a dot operator that
1843 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1844 // do a load and reset the access chain.
John Kessenich7015bd62019-08-01 03:28:08 -06001845 if (node->getLeft()->isReference() &&
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001846 !node->getLeft()->getType().isArray() &&
1847 node->getOp() == glslang::EOpIndexDirectStruct)
1848 {
1849 spv::Id left = accessChainLoad(node->getLeft()->getType());
1850 builder.clearAccessChain();
1851 builder.setAccessChainLValue(left);
1852 }
1853
David Netoa901ffe2016-06-08 14:11:40 +01001854 int spvIndex = glslangIndex;
1855 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1856 node->getOp() == glslang::EOpIndexDirectStruct)
1857 {
1858 // This may be, e.g., an anonymous block-member selection, which generally need
1859 // index remapping due to hidden members in anonymous blocks.
1860 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1861 assert(remapper.size() > 0);
1862 spvIndex = remapper[glslangIndex];
1863 }
John Kessenichebb50532016-05-16 19:22:05 -06001864
David Netoa901ffe2016-06-08 14:11:40 +01001865 // normal case for indexing array or structure or block
Jeff Bolz7895e472019-03-06 13:34:10 -06001866 builder.accessChainPush(builder.makeIntConstant(spvIndex), TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001867
1868 // Add capabilities here for accessing PointSize and clip/cull distance.
1869 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001870 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001871 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001872 }
1873 }
1874 return false;
1875 case glslang::EOpIndexIndirect:
1876 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001877 // Array, matrix, or vector indirection with variable index.
1878 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06001879 // matrices are arrays of vectors, so will also work for a matrix.
1880 // Will use the access chain's 'component' for variable index into a vector.
1881
1882 // This adapter is building access chains left to right.
1883 // Set up the access chain to the left.
1884 node->getLeft()->traverse(this);
1885
1886 // save it so that computing the right side doesn't trash it
1887 spv::Builder::AccessChain partial = builder.getAccessChain();
1888
1889 // compute the next index in the chain
1890 builder.clearAccessChain();
1891 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001892 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001893
John Kessenich5611c6d2018-04-05 11:25:02 -06001894 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1895
John Kessenich140f3df2015-06-26 16:58:36 -06001896 // restore the saved access chain
1897 builder.setAccessChain(partial);
1898
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001899 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1900 int dummySize;
1901 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1902 TranslateCoherent(node->getLeft()->getType()),
1903 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
1904 } else
Jeff Bolz7895e472019-03-06 13:34:10 -06001905 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001906 }
1907 return false;
1908 case glslang::EOpVectorSwizzle:
1909 {
1910 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001911 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001912 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001913 int dummySize;
1914 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1915 TranslateCoherent(node->getLeft()->getType()),
1916 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001917 }
1918 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001919 case glslang::EOpMatrixSwizzle:
1920 logger->missingFunctionality("matrix swizzle");
1921 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001922 case glslang::EOpLogicalOr:
1923 case glslang::EOpLogicalAnd:
1924 {
1925
1926 // These may require short circuiting, but can sometimes be done as straight
1927 // binary operations. The right operand must be short circuited if it has
1928 // side effects, and should probably be if it is complex.
1929 if (isTrivial(node->getRight()->getAsTyped()))
1930 break; // handle below as a normal binary operation
1931 // otherwise, we need to do dynamic short circuiting on the right operand
1932 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1933 builder.clearAccessChain();
1934 builder.setAccessChainRValue(result);
1935 }
1936 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001937 default:
1938 break;
1939 }
1940
1941 // Assume generic binary op...
1942
John Kessenich32cfd492016-02-02 12:37:46 -07001943 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001944 builder.clearAccessChain();
1945 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001946 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001947
John Kessenich32cfd492016-02-02 12:37:46 -07001948 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001949 builder.clearAccessChain();
1950 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001951 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001952
John Kessenich32cfd492016-02-02 12:37:46 -07001953 // get result
John Kessenichead86222018-03-28 18:01:20 -06001954 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001955 TranslateNoContractionDecoration(node->getType().getQualifier()),
1956 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001957 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001958 convertGlslangToSpvType(node->getType()), left, right,
1959 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001960
John Kessenich50e57562015-12-21 21:21:11 -07001961 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001962 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001963 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001964 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001965 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001966 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001967 return false;
1968 }
John Kessenich140f3df2015-06-26 16:58:36 -06001969}
1970
John Kessenich9c14f772019-06-17 08:38:35 -06001971// Figure out what, if any, type changes are needed when accessing a specific built-in.
1972// Returns <the type SPIR-V requires for declarion, the type to translate to on use>.
1973// Also see comment for 'forceType', regarding tracking SPIR-V-required types.
1974std::pair<spv::Id, spv::Id> TGlslangToSpvTraverser::getForcedType(spv::BuiltIn builtIn,
1975 const glslang::TType& glslangType)
1976{
1977 switch(builtIn)
1978 {
1979 case spv::BuiltInSubgroupEqMask:
1980 case spv::BuiltInSubgroupGeMask:
1981 case spv::BuiltInSubgroupGtMask:
1982 case spv::BuiltInSubgroupLeMask:
1983 case spv::BuiltInSubgroupLtMask: {
1984 // these require changing a 64-bit scaler -> a vector of 32-bit components
1985 if (glslangType.isVector())
1986 break;
1987 std::pair<spv::Id, spv::Id> ret(builder.makeVectorType(builder.makeUintType(32), 4),
1988 builder.makeUintType(64));
1989 return ret;
1990 }
1991 default:
1992 break;
1993 }
1994
1995 std::pair<spv::Id, spv::Id> ret(spv::NoType, spv::NoType);
1996 return ret;
1997}
1998
1999// For an object previously identified (see getForcedType() and forceType)
2000// as needing type translations, do the translation needed for a load, turning
2001// an L-value into in R-value.
2002spv::Id TGlslangToSpvTraverser::translateForcedType(spv::Id object)
2003{
2004 const auto forceIt = forceType.find(object);
2005 if (forceIt == forceType.end())
2006 return object;
2007
2008 spv::Id desiredTypeId = forceIt->second;
2009 spv::Id objectTypeId = builder.getTypeId(object);
2010 assert(builder.isPointerType(objectTypeId));
2011 objectTypeId = builder.getContainedTypeId(objectTypeId);
2012 if (builder.isVectorType(objectTypeId) &&
2013 builder.getScalarTypeWidth(builder.getContainedTypeId(objectTypeId)) == 32) {
2014 if (builder.getScalarTypeWidth(desiredTypeId) == 64) {
2015 // handle 32-bit v.xy* -> 64-bit
2016 builder.clearAccessChain();
2017 builder.setAccessChainLValue(object);
2018 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2019 std::vector<spv::Id> components;
2020 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 0));
2021 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 1));
2022
2023 spv::Id vecType = builder.makeVectorType(builder.getContainedTypeId(objectTypeId), 2);
2024 return builder.createUnaryOp(spv::OpBitcast, desiredTypeId,
2025 builder.createCompositeConstruct(vecType, components));
2026 } else {
2027 logger->missingFunctionality("forcing 32-bit vector type to non 64-bit scalar");
2028 }
2029 } else {
2030 logger->missingFunctionality("forcing non 32-bit vector type");
2031 }
2032
2033 return object;
2034}
2035
John Kessenich140f3df2015-06-26 16:58:36 -06002036bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
2037{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002038 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002039
qining40887662016-04-03 22:20:42 -04002040 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2041 if (node->getType().getQualifier().isSpecConstant())
2042 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2043
John Kessenichfc51d282015-08-19 13:34:18 -06002044 spv::Id result = spv::NoResult;
2045
2046 // try texturing first
2047 result = createImageTextureFunctionCall(node);
2048 if (result != spv::NoResult) {
2049 builder.clearAccessChain();
2050 builder.setAccessChainRValue(result);
2051
2052 return false; // done with this node
2053 }
2054
2055 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06002056
2057 if (node->getOp() == glslang::EOpArrayLength) {
2058 // Quite special; won't want to evaluate the operand.
2059
John Kessenich5611c6d2018-04-05 11:25:02 -06002060 // Currently, the front-end does not allow .length() on an array until it is sized,
2061 // except for the last block membeor of an SSBO.
2062 // TODO: If this changes, link-time sized arrays might show up here, and need their
2063 // size extracted.
2064
John Kessenichc9a80832015-09-12 12:17:44 -06002065 // Normal .length() would have been constant folded by the front-end.
2066 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06002067 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06002068
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002069 spv::Id length;
2070 if (node->getOperand()->getType().isCoopMat()) {
2071 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2072
2073 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
2074 assert(builder.isCooperativeMatrixType(typeId));
2075
2076 length = builder.createCooperativeMatrixLength(typeId);
2077 } else {
2078 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
2079 block->traverse(this);
2080 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
2081 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
2082 }
John Kessenichc9a80832015-09-12 12:17:44 -06002083
John Kessenich8c869672018-11-28 07:01:37 -07002084 // GLSL semantics say the result of .length() is an int, while SPIR-V says
2085 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
2086 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002087 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
2088 if (builder.isInSpecConstCodeGenMode()) {
2089 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
2090 } else {
2091 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
2092 }
2093 }
John Kessenich8c869672018-11-28 07:01:37 -07002094
John Kessenichc9a80832015-09-12 12:17:44 -06002095 builder.clearAccessChain();
2096 builder.setAccessChainRValue(length);
2097
2098 return false;
2099 }
2100
John Kessenichfc51d282015-08-19 13:34:18 -06002101 // Start by evaluating the operand
2102
John Kessenich8c8505c2016-07-26 12:50:38 -06002103 // Does it need a swizzle inversion? If so, evaluation is inverted;
2104 // operate first on the swizzle base, then apply the swizzle.
2105 spv::Id invertedType = spv::NoType;
2106 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
2107 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
2108 invertedType = getInvertedSwizzleType(*node->getOperand());
2109
John Kessenich140f3df2015-06-26 16:58:36 -06002110 builder.clearAccessChain();
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002111 TIntermNode *operandNode;
John Kessenich8c8505c2016-07-26 12:50:38 -06002112 if (invertedType != spv::NoType)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002113 operandNode = node->getOperand()->getAsBinaryNode()->getLeft();
John Kessenich8c8505c2016-07-26 12:50:38 -06002114 else
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002115 operandNode = node->getOperand();
2116
2117 operandNode->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08002118
Rex Xufc618912015-09-09 16:42:49 +08002119 spv::Id operand = spv::NoResult;
2120
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002121 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2122
John Kessenichfb4f2332019-08-09 03:49:15 -06002123#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08002124 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
2125 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08002126 node->getOp() == glslang::EOpAtomicCounter ||
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002127 node->getOp() == glslang::EOpInterpolateAtCentroid) {
Rex Xufc618912015-09-09 16:42:49 +08002128 operand = builder.accessChainGetLValue(); // Special case l-value operands
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002129 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2130 lvalueCoherentFlags |= TranslateCoherent(operandNode->getAsTyped()->getType());
2131 } else
John Kessenichfb4f2332019-08-09 03:49:15 -06002132#endif
2133 {
John Kessenich32cfd492016-02-02 12:37:46 -07002134 operand = accessChainLoad(node->getOperand()->getType());
John Kessenichfb4f2332019-08-09 03:49:15 -06002135 }
John Kessenich140f3df2015-06-26 16:58:36 -06002136
John Kessenichead86222018-03-28 18:01:20 -06002137 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002138 TranslateNoContractionDecoration(node->getType().getQualifier()),
2139 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06002140
2141 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06002142 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06002143 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002144
2145 // if not, then possibly an operation
2146 if (! result)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002147 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType(), lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002148
2149 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06002150 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06002151 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenichb9197c82019-08-11 07:41:45 -06002152 decorations.addNonUniform(builder, result);
John Kessenich5611c6d2018-04-05 11:25:02 -06002153 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002154
John Kessenich140f3df2015-06-26 16:58:36 -06002155 builder.clearAccessChain();
2156 builder.setAccessChainRValue(result);
2157
2158 return false; // done with this node
2159 }
2160
2161 // it must be a special case, check...
2162 switch (node->getOp()) {
2163 case glslang::EOpPostIncrement:
2164 case glslang::EOpPostDecrement:
2165 case glslang::EOpPreIncrement:
2166 case glslang::EOpPreDecrement:
2167 {
2168 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08002169 spv::Id one = 0;
2170 if (node->getBasicType() == glslang::EbtFloat)
2171 one = builder.makeFloatConstant(1.0F);
John Kessenich39697cd2019-08-08 10:35:51 -06002172#ifndef GLSLANG_WEB
Rex Xuce31aea2016-07-29 16:13:04 +08002173 else if (node->getBasicType() == glslang::EbtDouble)
2174 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002175 else if (node->getBasicType() == glslang::EbtFloat16)
2176 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07002177 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
2178 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08002179 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
2180 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002181 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2182 one = builder.makeInt64Constant(1);
John Kessenich39697cd2019-08-08 10:35:51 -06002183#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08002184 else
2185 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002186 glslang::TOperator op;
2187 if (node->getOp() == glslang::EOpPreIncrement ||
2188 node->getOp() == glslang::EOpPostIncrement)
2189 op = glslang::EOpAdd;
2190 else
2191 op = glslang::EOpSub;
2192
John Kessenichead86222018-03-28 18:01:20 -06002193 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002194 convertGlslangToSpvType(node->getType()), operand, one,
2195 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002196 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002197
2198 // The result of operation is always stored, but conditionally the
2199 // consumed result. The consumed result is always an r-value.
2200 builder.accessChainStore(result);
2201 builder.clearAccessChain();
2202 if (node->getOp() == glslang::EOpPreIncrement ||
2203 node->getOp() == glslang::EOpPreDecrement)
2204 builder.setAccessChainRValue(result);
2205 else
2206 builder.setAccessChainRValue(operand);
2207 }
2208
2209 return false;
2210
John Kessenich155d3512019-08-08 23:29:20 -06002211#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06002212 case glslang::EOpEmitStreamVertex:
2213 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2214 return false;
2215 case glslang::EOpEndStreamPrimitive:
2216 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2217 return false;
John Kessenich155d3512019-08-08 23:29:20 -06002218#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002219
2220 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002221 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002222 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002223 }
John Kessenich140f3df2015-06-26 16:58:36 -06002224}
2225
Jeff Bolz53134492019-06-25 13:31:10 -05002226// Construct a composite object, recursively copying members if their types don't match
2227spv::Id TGlslangToSpvTraverser::createCompositeConstruct(spv::Id resultTypeId, std::vector<spv::Id> constituents)
2228{
2229 for (int c = 0; c < (int)constituents.size(); ++c) {
2230 spv::Id& constituent = constituents[c];
2231 spv::Id lType = builder.getContainedTypeId(resultTypeId, c);
2232 spv::Id rType = builder.getTypeId(constituent);
2233 if (lType != rType) {
2234 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
2235 constituent = builder.createUnaryOp(spv::OpCopyLogical, lType, constituent);
2236 } else if (builder.isStructType(rType)) {
2237 std::vector<spv::Id> rTypeConstituents;
2238 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2239 for (int i = 0; i < numrTypeConstituents; ++i) {
2240 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, builder.getContainedTypeId(rType, i), i));
2241 }
2242 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2243 } else {
2244 assert(builder.isArrayType(rType));
2245 std::vector<spv::Id> rTypeConstituents;
2246 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2247
2248 spv::Id elementRType = builder.getContainedTypeId(rType);
2249 for (int i = 0; i < numrTypeConstituents; ++i) {
2250 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, elementRType, i));
2251 }
2252 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2253 }
2254 }
2255 }
2256 return builder.createCompositeConstruct(resultTypeId, constituents);
2257}
2258
John Kessenich140f3df2015-06-26 16:58:36 -06002259bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2260{
qining27e04a02016-04-14 16:40:20 -04002261 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2262 if (node->getType().getQualifier().isSpecConstant())
2263 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2264
John Kessenichfc51d282015-08-19 13:34:18 -06002265 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06002266 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2267 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002268
2269 // try texturing
2270 result = createImageTextureFunctionCall(node);
2271 if (result != spv::NoResult) {
2272 builder.clearAccessChain();
2273 builder.setAccessChainRValue(result);
2274
2275 return false;
John Kessenicha28f7a72019-08-06 07:00:58 -06002276 }
2277#ifndef GLSLANG_WEB
2278 else if (node->getOp() == glslang::EOpImageStore ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002279 node->getOp() == glslang::EOpImageStoreLod ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002280 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002281 // "imageStore" is a special case, which has no result
2282 return false;
2283 }
John Kessenicha28f7a72019-08-06 07:00:58 -06002284#endif
John Kessenichfc51d282015-08-19 13:34:18 -06002285
John Kessenich140f3df2015-06-26 16:58:36 -06002286 glslang::TOperator binOp = glslang::EOpNull;
2287 bool reduceComparison = true;
2288 bool isMatrix = false;
2289 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002290 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002291
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002292 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2293
John Kessenich140f3df2015-06-26 16:58:36 -06002294 assert(node->getOp());
2295
John Kessenichf6640762016-08-01 19:44:00 -06002296 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002297
2298 switch (node->getOp()) {
2299 case glslang::EOpSequence:
2300 {
2301 if (preVisit)
2302 ++sequenceDepth;
2303 else
2304 --sequenceDepth;
2305
2306 if (sequenceDepth == 1) {
2307 // If this is the parent node of all the functions, we want to see them
2308 // early, so all call points have actual SPIR-V functions to reference.
2309 // In all cases, still let the traverser visit the children for us.
2310 makeFunctions(node->getAsAggregate()->getSequence());
2311
John Kessenich6fccb3c2016-09-19 16:01:41 -06002312 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002313 // anything else gets there, so visit out of order, doing them all now.
2314 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2315
John Kessenich6a60c2f2016-12-08 21:01:59 -07002316 // 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 -06002317 // so do them manually.
2318 visitFunctions(node->getAsAggregate()->getSequence());
2319
2320 return false;
2321 }
2322
2323 return true;
2324 }
2325 case glslang::EOpLinkerObjects:
2326 {
2327 if (visit == glslang::EvPreVisit)
2328 linkageOnly = true;
2329 else
2330 linkageOnly = false;
2331
2332 return true;
2333 }
2334 case glslang::EOpComma:
2335 {
2336 // processing from left to right naturally leaves the right-most
2337 // lying around in the access chain
2338 glslang::TIntermSequence& glslangOperands = node->getSequence();
2339 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2340 glslangOperands[i]->traverse(this);
2341
2342 return false;
2343 }
2344 case glslang::EOpFunction:
2345 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002346 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002347 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002348 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002349 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002350 } else {
2351 handleFunctionEntry(node);
2352 }
2353 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002354 if (inEntryPoint)
2355 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002356 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002357 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002358 }
2359
2360 return true;
2361 case glslang::EOpParameters:
2362 // Parameters will have been consumed by EOpFunction processing, but not
2363 // the body, so we still visited the function node's children, making this
2364 // child redundant.
2365 return false;
2366 case glslang::EOpFunctionCall:
2367 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002368 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002369 if (node->isUserDefined())
2370 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07002371 // 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 -07002372 if (result) {
2373 builder.clearAccessChain();
2374 builder.setAccessChainRValue(result);
2375 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002376 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002377
2378 return false;
2379 }
2380 case glslang::EOpConstructMat2x2:
2381 case glslang::EOpConstructMat2x3:
2382 case glslang::EOpConstructMat2x4:
2383 case glslang::EOpConstructMat3x2:
2384 case glslang::EOpConstructMat3x3:
2385 case glslang::EOpConstructMat3x4:
2386 case glslang::EOpConstructMat4x2:
2387 case glslang::EOpConstructMat4x3:
2388 case glslang::EOpConstructMat4x4:
2389 case glslang::EOpConstructDMat2x2:
2390 case glslang::EOpConstructDMat2x3:
2391 case glslang::EOpConstructDMat2x4:
2392 case glslang::EOpConstructDMat3x2:
2393 case glslang::EOpConstructDMat3x3:
2394 case glslang::EOpConstructDMat3x4:
2395 case glslang::EOpConstructDMat4x2:
2396 case glslang::EOpConstructDMat4x3:
2397 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002398 case glslang::EOpConstructIMat2x2:
2399 case glslang::EOpConstructIMat2x3:
2400 case glslang::EOpConstructIMat2x4:
2401 case glslang::EOpConstructIMat3x2:
2402 case glslang::EOpConstructIMat3x3:
2403 case glslang::EOpConstructIMat3x4:
2404 case glslang::EOpConstructIMat4x2:
2405 case glslang::EOpConstructIMat4x3:
2406 case glslang::EOpConstructIMat4x4:
2407 case glslang::EOpConstructUMat2x2:
2408 case glslang::EOpConstructUMat2x3:
2409 case glslang::EOpConstructUMat2x4:
2410 case glslang::EOpConstructUMat3x2:
2411 case glslang::EOpConstructUMat3x3:
2412 case glslang::EOpConstructUMat3x4:
2413 case glslang::EOpConstructUMat4x2:
2414 case glslang::EOpConstructUMat4x3:
2415 case glslang::EOpConstructUMat4x4:
2416 case glslang::EOpConstructBMat2x2:
2417 case glslang::EOpConstructBMat2x3:
2418 case glslang::EOpConstructBMat2x4:
2419 case glslang::EOpConstructBMat3x2:
2420 case glslang::EOpConstructBMat3x3:
2421 case glslang::EOpConstructBMat3x4:
2422 case glslang::EOpConstructBMat4x2:
2423 case glslang::EOpConstructBMat4x3:
2424 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002425 case glslang::EOpConstructF16Mat2x2:
2426 case glslang::EOpConstructF16Mat2x3:
2427 case glslang::EOpConstructF16Mat2x4:
2428 case glslang::EOpConstructF16Mat3x2:
2429 case glslang::EOpConstructF16Mat3x3:
2430 case glslang::EOpConstructF16Mat3x4:
2431 case glslang::EOpConstructF16Mat4x2:
2432 case glslang::EOpConstructF16Mat4x3:
2433 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002434 isMatrix = true;
2435 // fall through
2436 case glslang::EOpConstructFloat:
2437 case glslang::EOpConstructVec2:
2438 case glslang::EOpConstructVec3:
2439 case glslang::EOpConstructVec4:
2440 case glslang::EOpConstructDouble:
2441 case glslang::EOpConstructDVec2:
2442 case glslang::EOpConstructDVec3:
2443 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002444 case glslang::EOpConstructFloat16:
2445 case glslang::EOpConstructF16Vec2:
2446 case glslang::EOpConstructF16Vec3:
2447 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002448 case glslang::EOpConstructBool:
2449 case glslang::EOpConstructBVec2:
2450 case glslang::EOpConstructBVec3:
2451 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002452 case glslang::EOpConstructInt8:
2453 case glslang::EOpConstructI8Vec2:
2454 case glslang::EOpConstructI8Vec3:
2455 case glslang::EOpConstructI8Vec4:
2456 case glslang::EOpConstructUint8:
2457 case glslang::EOpConstructU8Vec2:
2458 case glslang::EOpConstructU8Vec3:
2459 case glslang::EOpConstructU8Vec4:
2460 case glslang::EOpConstructInt16:
2461 case glslang::EOpConstructI16Vec2:
2462 case glslang::EOpConstructI16Vec3:
2463 case glslang::EOpConstructI16Vec4:
2464 case glslang::EOpConstructUint16:
2465 case glslang::EOpConstructU16Vec2:
2466 case glslang::EOpConstructU16Vec3:
2467 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002468 case glslang::EOpConstructInt:
2469 case glslang::EOpConstructIVec2:
2470 case glslang::EOpConstructIVec3:
2471 case glslang::EOpConstructIVec4:
2472 case glslang::EOpConstructUint:
2473 case glslang::EOpConstructUVec2:
2474 case glslang::EOpConstructUVec3:
2475 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002476 case glslang::EOpConstructInt64:
2477 case glslang::EOpConstructI64Vec2:
2478 case glslang::EOpConstructI64Vec3:
2479 case glslang::EOpConstructI64Vec4:
2480 case glslang::EOpConstructUint64:
2481 case glslang::EOpConstructU64Vec2:
2482 case glslang::EOpConstructU64Vec3:
2483 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002484 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002485 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002486 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002487 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002488 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002489 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002490 std::vector<spv::Id> arguments;
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002491 translateArguments(*node, arguments, lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002492 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002493 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002494 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002495 else if (node->getOp() == glslang::EOpConstructStruct ||
2496 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2497 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002498 std::vector<spv::Id> constituents;
2499 for (int c = 0; c < (int)arguments.size(); ++c)
2500 constituents.push_back(arguments[c]);
Jeff Bolz53134492019-06-25 13:31:10 -05002501 constructed = createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002502 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002503 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002504 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002505 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002506
2507 builder.clearAccessChain();
2508 builder.setAccessChainRValue(constructed);
2509
2510 return false;
2511 }
2512
2513 // These six are component-wise compares with component-wise results.
2514 // Forward on to createBinaryOperation(), requesting a vector result.
2515 case glslang::EOpLessThan:
2516 case glslang::EOpGreaterThan:
2517 case glslang::EOpLessThanEqual:
2518 case glslang::EOpGreaterThanEqual:
2519 case glslang::EOpVectorEqual:
2520 case glslang::EOpVectorNotEqual:
2521 {
2522 // Map the operation to a binary
2523 binOp = node->getOp();
2524 reduceComparison = false;
2525 switch (node->getOp()) {
2526 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2527 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2528 default: binOp = node->getOp(); break;
2529 }
2530
2531 break;
2532 }
2533 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002534 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002535 binOp = glslang::EOpMul;
2536 break;
2537 case glslang::EOpOuterProduct:
2538 // two vectors multiplied to make a matrix
2539 binOp = glslang::EOpOuterProduct;
2540 break;
2541 case glslang::EOpDot:
2542 {
qining25262b32016-05-06 17:25:16 -04002543 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002544 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002545 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002546 binOp = glslang::EOpMul;
2547 break;
2548 }
2549 case glslang::EOpMod:
2550 // when an aggregate, this is the floating-point mod built-in function,
2551 // which can be emitted by the one in createBinaryOperation()
2552 binOp = glslang::EOpMod;
2553 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002554
John Kessenich140f3df2015-06-26 16:58:36 -06002555 case glslang::EOpEmitVertex:
2556 case glslang::EOpEndPrimitive:
2557 case glslang::EOpBarrier:
2558 case glslang::EOpMemoryBarrier:
2559 case glslang::EOpMemoryBarrierAtomicCounter:
2560 case glslang::EOpMemoryBarrierBuffer:
2561 case glslang::EOpMemoryBarrierImage:
2562 case glslang::EOpMemoryBarrierShared:
2563 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002564 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002565 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002566 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002567 case glslang::EOpWorkgroupMemoryBarrier:
2568 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002569 case glslang::EOpSubgroupBarrier:
2570 case glslang::EOpSubgroupMemoryBarrier:
2571 case glslang::EOpSubgroupMemoryBarrierBuffer:
2572 case glslang::EOpSubgroupMemoryBarrierImage:
2573 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002574 noReturnValue = true;
2575 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2576 break;
2577
John Kessenich426394d2015-07-23 10:22:48 -06002578 case glslang::EOpAtomicAdd:
2579 case glslang::EOpAtomicMin:
2580 case glslang::EOpAtomicMax:
2581 case glslang::EOpAtomicAnd:
2582 case glslang::EOpAtomicOr:
2583 case glslang::EOpAtomicXor:
2584 case glslang::EOpAtomicExchange:
2585 case glslang::EOpAtomicCompSwap:
2586 atomic = true;
2587 break;
2588
John Kesseniche5eee8f2019-10-18 01:03:11 -06002589#ifndef GLSLANG_WEB
2590 case glslang::EOpAtomicStore:
2591 noReturnValue = true;
2592 // fallthrough
2593 case glslang::EOpAtomicLoad:
2594 atomic = true;
2595 break;
2596
John Kessenich0d0c6d32017-07-23 16:08:26 -06002597 case glslang::EOpAtomicCounterAdd:
2598 case glslang::EOpAtomicCounterSubtract:
2599 case glslang::EOpAtomicCounterMin:
2600 case glslang::EOpAtomicCounterMax:
2601 case glslang::EOpAtomicCounterAnd:
2602 case glslang::EOpAtomicCounterOr:
2603 case glslang::EOpAtomicCounterXor:
2604 case glslang::EOpAtomicCounterExchange:
2605 case glslang::EOpAtomicCounterCompSwap:
2606 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2607 builder.addCapability(spv::CapabilityAtomicStorageOps);
2608 atomic = true;
2609 break;
2610
Ian Romanickb3bd4022019-01-21 08:57:25 -08002611 case glslang::EOpAbsDifference:
2612 case glslang::EOpAddSaturate:
2613 case glslang::EOpSubSaturate:
2614 case glslang::EOpAverage:
2615 case glslang::EOpAverageRounded:
2616 case glslang::EOpMul32x16:
2617 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
2618 builder.addExtension("SPV_INTEL_shader_integer_functions2");
2619 binOp = node->getOp();
2620 break;
2621
Chao Chenb50c02e2018-09-19 11:42:24 -07002622 case glslang::EOpIgnoreIntersectionNV:
2623 case glslang::EOpTerminateRayNV:
2624 case glslang::EOpTraceNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07002625 case glslang::EOpExecuteCallableNV:
Chao Chen3c366992018-09-19 11:41:59 -07002626 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2627 noReturnValue = true;
2628 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002629 case glslang::EOpCooperativeMatrixLoad:
2630 case glslang::EOpCooperativeMatrixStore:
2631 noReturnValue = true;
2632 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002633 case glslang::EOpBeginInvocationInterlock:
2634 case glslang::EOpEndInvocationInterlock:
2635 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2636 noReturnValue = true;
2637 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002638#endif
Chao Chen3c366992018-09-19 11:41:59 -07002639
John Kessenich140f3df2015-06-26 16:58:36 -06002640 default:
2641 break;
2642 }
2643
2644 //
2645 // See if it maps to a regular operation.
2646 //
John Kessenich140f3df2015-06-26 16:58:36 -06002647 if (binOp != glslang::EOpNull) {
2648 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2649 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2650 assert(left && right);
2651
2652 builder.clearAccessChain();
2653 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002654 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002655
2656 builder.clearAccessChain();
2657 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002658 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002659
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002660 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002661 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002662 TranslateNoContractionDecoration(node->getType().getQualifier()),
2663 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002664 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002665 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002666 left->getType().getBasicType(), reduceComparison);
2667
2668 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002669 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002670 builder.clearAccessChain();
2671 builder.setAccessChainRValue(result);
2672
2673 return false;
2674 }
2675
John Kessenich426394d2015-07-23 10:22:48 -06002676 //
2677 // Create the list of operands.
2678 //
John Kessenich140f3df2015-06-26 16:58:36 -06002679 glslang::TIntermSequence& glslangOperands = node->getSequence();
2680 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002681 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002682 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002683 // special case l-value operands; there are just a few
2684 bool lvalue = false;
2685 switch (node->getOp()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002686 case glslang::EOpModf:
2687 if (arg == 1)
2688 lvalue = true;
2689 break;
John Kesseniche5eee8f2019-10-18 01:03:11 -06002690
2691 case glslang::EOpAtomicAdd:
2692 case glslang::EOpAtomicMin:
2693 case glslang::EOpAtomicMax:
2694 case glslang::EOpAtomicAnd:
2695 case glslang::EOpAtomicOr:
2696 case glslang::EOpAtomicXor:
2697 case glslang::EOpAtomicExchange:
2698 case glslang::EOpAtomicCompSwap:
2699 if (arg == 0)
2700 lvalue = true;
2701 break;
2702
John Kessenicha28f7a72019-08-06 07:00:58 -06002703#ifndef GLSLANG_WEB
2704 case glslang::EOpFrexp:
2705 if (arg == 1)
2706 lvalue = true;
2707 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002708 case glslang::EOpInterpolateAtSample:
2709 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002710 case glslang::EOpInterpolateAtVertex:
John Kessenich8c8505c2016-07-26 12:50:38 -06002711 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002712 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002713
2714 // Does it need a swizzle inversion? If so, evaluation is inverted;
2715 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002716 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002717 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2718 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2719 }
Rex Xu7a26c172015-12-08 17:12:09 +08002720 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05002721 case glslang::EOpAtomicLoad:
2722 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002723 case glslang::EOpAtomicCounterAdd:
2724 case glslang::EOpAtomicCounterSubtract:
2725 case glslang::EOpAtomicCounterMin:
2726 case glslang::EOpAtomicCounterMax:
2727 case glslang::EOpAtomicCounterAnd:
2728 case glslang::EOpAtomicCounterOr:
2729 case glslang::EOpAtomicCounterXor:
2730 case glslang::EOpAtomicCounterExchange:
2731 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002732 if (arg == 0)
2733 lvalue = true;
2734 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002735 case glslang::EOpAddCarry:
2736 case glslang::EOpSubBorrow:
2737 if (arg == 2)
2738 lvalue = true;
2739 break;
2740 case glslang::EOpUMulExtended:
2741 case glslang::EOpIMulExtended:
2742 if (arg >= 2)
2743 lvalue = true;
2744 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002745 case glslang::EOpCooperativeMatrixLoad:
2746 if (arg == 0 || arg == 1)
2747 lvalue = true;
2748 break;
2749 case glslang::EOpCooperativeMatrixStore:
2750 if (arg == 1)
2751 lvalue = true;
2752 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002753#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002754 default:
2755 break;
2756 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002757 builder.clearAccessChain();
2758 if (invertedType != spv::NoType && arg == 0)
2759 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2760 else
2761 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002762
John Kessenichb9197c82019-08-11 07:41:45 -06002763#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002764 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2765 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2766
2767 if (arg == 1) {
2768 // fold "element" parameter into the access chain
2769 spv::Builder::AccessChain save = builder.getAccessChain();
2770 builder.clearAccessChain();
2771 glslangOperands[2]->traverse(this);
2772
2773 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2774
2775 builder.setAccessChain(save);
2776
2777 // Point to the first element of the array.
2778 builder.accessChainPush(elementId, TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
Jeff Bolz7895e472019-03-06 13:34:10 -06002779 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002780
2781 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2782 unsigned int alignment = builder.getAccessChain().alignment;
2783
2784 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2785 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2786 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2787 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2788 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
2789 if (builder.getStorageClass(builder.getAccessChain().base) == spv::StorageClassPhysicalStorageBufferEXT) {
2790 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2791 }
2792
2793 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2794
2795 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2796 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2797 }
2798
2799 if (memoryAccess & (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2800 memoryAccessOperands.push_back(spv::IdImmediate(true, builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
2801 }
2802 } else if (arg == 2) {
2803 continue;
2804 }
2805 }
John Kessenichb9197c82019-08-11 07:41:45 -06002806#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002807
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002808 if (lvalue) {
John Kessenich140f3df2015-06-26 16:58:36 -06002809 operands.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002810 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2811 lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
2812 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002813 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich32cfd492016-02-02 12:37:46 -07002814 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002815 }
John Kessenich140f3df2015-06-26 16:58:36 -06002816 }
John Kessenich426394d2015-07-23 10:22:48 -06002817
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002818 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichb9197c82019-08-11 07:41:45 -06002819#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002820 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
2821 std::vector<spv::IdImmediate> idImmOps;
2822
2823 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2824 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2825 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2826 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2827 // get the pointee type
2828 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
2829 assert(builder.isCooperativeMatrixType(typeId));
2830 // do the op
2831 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
2832 // store the result to the pointer (out param 'm')
2833 builder.createStore(result, operands[0]);
2834 result = 0;
2835 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
2836 std::vector<spv::IdImmediate> idImmOps;
2837
2838 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2839 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
2840 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2841 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2842 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2843
2844 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
2845 result = 0;
John Kessenichb9197c82019-08-11 07:41:45 -06002846 } else
2847#endif
John Kesseniche5eee8f2019-10-18 01:03:11 -06002848 if (atomic) {
2849 // Handle all atomics
2850 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(), lvalueCoherentFlags);
2851 } else {
John Kessenich426394d2015-07-23 10:22:48 -06002852 // Pass through to generic operations.
2853 switch (glslangOperands.size()) {
2854 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002855 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002856 break;
2857 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002858 {
2859 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002860 TranslateNoContractionDecoration(node->getType().getQualifier()),
2861 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002862 result = createUnaryOperation(
2863 node->getOp(), decorations,
2864 resultType(), operands.front(),
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002865 glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -06002866 }
John Kessenich426394d2015-07-23 10:22:48 -06002867 break;
2868 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002869 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002870 break;
2871 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002872 if (invertedType)
2873 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002874 }
2875
2876 if (noReturnValue)
2877 return false;
2878
2879 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002880 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002881 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002882 } else {
2883 builder.clearAccessChain();
2884 builder.setAccessChainRValue(result);
2885 return false;
2886 }
2887}
2888
John Kessenich433e9ff2017-01-26 20:31:11 -07002889// This path handles both if-then-else and ?:
2890// The if-then-else has a node type of void, while
2891// ?: has either a void or a non-void node type
2892//
2893// Leaving the result, when not void:
2894// GLSL only has r-values as the result of a :?, but
2895// if we have an l-value, that can be more efficient if it will
2896// become the base of a complex r-value expression, because the
2897// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002898bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2899{
John Kessenich0c1e71a2019-01-10 18:23:06 +07002900 // see if OpSelect can handle it
2901 const auto isOpSelectable = [&]() {
2902 if (node->getBasicType() == glslang::EbtVoid)
2903 return false;
2904 // OpSelect can do all other types starting with SPV 1.4
2905 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
2906 // pre-1.4, only scalars and vectors can be handled
2907 if ((!node->getType().isScalar() && !node->getType().isVector()))
2908 return false;
2909 }
2910 return true;
2911 };
2912
John Kessenich4bee5312018-02-20 21:29:05 -07002913 // See if it simple and safe, or required, to execute both sides.
2914 // Crucially, side effects must be either semantically required or avoided,
2915 // and there are performance trade-offs.
2916 // Return true if required or a good idea (and safe) to execute both sides,
2917 // false otherwise.
2918 const auto bothSidesPolicy = [&]() -> bool {
2919 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002920 if (node->getTrueBlock() == nullptr ||
2921 node->getFalseBlock() == nullptr)
2922 return false;
2923
John Kessenich4bee5312018-02-20 21:29:05 -07002924 // required? (unless we write additional code to look for side effects
2925 // and make performance trade-offs if none are present)
2926 if (!node->getShortCircuit())
2927 return true;
2928
2929 // if not required to execute both, decide based on performance/practicality...
2930
John Kessenich0c1e71a2019-01-10 18:23:06 +07002931 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07002932 return false;
2933
John Kessenich433e9ff2017-01-26 20:31:11 -07002934 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2935 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2936
2937 // return true if a single operand to ? : is okay for OpSelect
2938 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002939 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002940 };
2941
2942 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2943 operandOkay(node->getFalseBlock()->getAsTyped());
2944 };
2945
John Kessenich4bee5312018-02-20 21:29:05 -07002946 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2947 // emit the condition before doing anything with selection
2948 node->getCondition()->traverse(this);
2949 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2950
2951 // Find a way of executing both sides and selecting the right result.
2952 const auto executeBothSides = [&]() -> void {
2953 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002954 node->getTrueBlock()->traverse(this);
2955 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2956 node->getFalseBlock()->traverse(this);
2957 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2958
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002959 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002960
John Kessenich4bee5312018-02-20 21:29:05 -07002961 // done if void
2962 if (node->getBasicType() == glslang::EbtVoid)
2963 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002964
John Kessenich4bee5312018-02-20 21:29:05 -07002965 // emit code to select between trueValue and falseValue
2966
2967 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07002968 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07002969 // Emit OpSelect for this selection.
2970
2971 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07002972 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
2973 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07002974 condition = builder.smearScalar(spv::NoPrecision, condition,
2975 builder.makeVectorType(builder.makeBoolType(),
2976 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07002977 }
John Kessenich4bee5312018-02-20 21:29:05 -07002978
2979 // OpSelect
2980 result = builder.createTriOp(spv::OpSelect,
2981 convertGlslangToSpvType(node->getType()), condition,
2982 trueValue, falseValue);
2983
2984 builder.clearAccessChain();
2985 builder.setAccessChainRValue(result);
2986 } else {
2987 // We need control flow to select the result.
2988 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2989 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2990
2991 // Selection control:
2992 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2993
2994 // make an "if" based on the value created by the condition
2995 spv::Builder::If ifBuilder(condition, control, builder);
2996
2997 // emit the "then" statement
2998 builder.createStore(trueValue, result);
2999 ifBuilder.makeBeginElse();
3000 // emit the "else" statement
3001 builder.createStore(falseValue, result);
3002
3003 // finish off the control flow
3004 ifBuilder.makeEndIf();
3005
3006 builder.clearAccessChain();
3007 builder.setAccessChainLValue(result);
3008 }
John Kessenich433e9ff2017-01-26 20:31:11 -07003009 };
3010
John Kessenich4bee5312018-02-20 21:29:05 -07003011 // Execute the one side needed, as per the condition
3012 const auto executeOneSide = [&]() {
3013 // Always emit control flow.
3014 if (node->getBasicType() != glslang::EbtVoid)
3015 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07003016
John Kessenich4bee5312018-02-20 21:29:05 -07003017 // Selection control:
3018 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3019
3020 // make an "if" based on the value created by the condition
3021 spv::Builder::If ifBuilder(condition, control, builder);
3022
3023 // emit the "then" statement
3024 if (node->getTrueBlock() != nullptr) {
3025 node->getTrueBlock()->traverse(this);
3026 if (result != spv::NoResult)
3027 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
3028 }
3029
3030 if (node->getFalseBlock() != nullptr) {
3031 ifBuilder.makeBeginElse();
3032 // emit the "else" statement
3033 node->getFalseBlock()->traverse(this);
3034 if (result != spv::NoResult)
3035 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
3036 }
3037
3038 // finish off the control flow
3039 ifBuilder.makeEndIf();
3040
3041 if (result != spv::NoResult) {
3042 builder.clearAccessChain();
3043 builder.setAccessChainLValue(result);
3044 }
3045 };
3046
3047 // Try for OpSelect (or a requirement to execute both sides)
3048 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003049 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
3050 if (node->getType().getQualifier().isSpecConstant())
3051 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07003052 executeBothSides();
3053 } else
3054 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06003055
3056 return false;
3057}
3058
3059bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
3060{
3061 // emit and get the condition before doing anything with switch
3062 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003063 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06003064
Rex Xu57e65922017-07-04 23:23:40 +08003065 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07003066 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08003067
John Kessenich140f3df2015-06-26 16:58:36 -06003068 // browse the children to sort out code segments
3069 int defaultSegment = -1;
3070 std::vector<TIntermNode*> codeSegments;
3071 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
3072 std::vector<int> caseValues;
3073 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
3074 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
3075 TIntermNode* child = *c;
3076 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02003077 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003078 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02003079 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003080 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
3081 } else
3082 codeSegments.push_back(child);
3083 }
3084
qining25262b32016-05-06 17:25:16 -04003085 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06003086 // statements between the last case and the end of the switch statement
3087 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
3088 (int)codeSegments.size() == defaultSegment)
3089 codeSegments.push_back(nullptr);
3090
3091 // make the switch statement
3092 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08003093 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06003094
3095 // emit all the code in the segments
3096 breakForLoop.push(false);
3097 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
3098 builder.nextSwitchSegment(segmentBlocks, s);
3099 if (codeSegments[s])
3100 codeSegments[s]->traverse(this);
3101 else
3102 builder.addSwitchBreak();
3103 }
3104 breakForLoop.pop();
3105
3106 builder.endSwitch(segmentBlocks);
3107
3108 return false;
3109}
3110
3111void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
3112{
3113 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003114 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06003115
3116 builder.clearAccessChain();
3117 builder.setAccessChainRValue(constant);
3118}
3119
3120bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
3121{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003122 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003123 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06003124
3125 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07003126 std::vector<unsigned int> operands;
3127 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06003128
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003129 // Spec requires back edges to target header blocks, and every header block
3130 // must dominate its merge block. Make a header block first to ensure these
3131 // conditions are met. By definition, it will contain OpLoopMerge, followed
3132 // by a block-ending branch. But we don't want to put any other body/test
3133 // instructions in it, since the body/test may have arbitrary instructions,
3134 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003135 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003136 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07003137 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003138 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003139 spv::Block& test = builder.makeNewBlock();
3140 builder.createBranch(&test);
3141
3142 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06003143 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06003144 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003145 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
3146
3147 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003148 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003149 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003150 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003151 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003152 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003153
3154 builder.setBuildPoint(&blocks.continue_target);
3155 if (node->getTerminal())
3156 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003157 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04003158 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003159 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003160 builder.createBranch(&blocks.body);
3161
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003162 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003163 builder.setBuildPoint(&blocks.body);
3164 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003165 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003166 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003167 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003168
3169 builder.setBuildPoint(&blocks.continue_target);
3170 if (node->getTerminal())
3171 node->getTerminal()->traverse(this);
3172 if (node->getTest()) {
3173 node->getTest()->traverse(this);
3174 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07003175 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003176 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003177 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05003178 // TODO: unless there was a break/return/discard instruction
3179 // somewhere in the body, this is an infinite loop, so we should
3180 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003181 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003182 }
John Kessenich140f3df2015-06-26 16:58:36 -06003183 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003184 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003185 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06003186 return false;
3187}
3188
3189bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
3190{
3191 if (node->getExpression())
3192 node->getExpression()->traverse(this);
3193
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003194 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003195
John Kessenich140f3df2015-06-26 16:58:36 -06003196 switch (node->getFlowOp()) {
3197 case glslang::EOpKill:
3198 builder.makeDiscard();
3199 break;
3200 case glslang::EOpBreak:
3201 if (breakForLoop.top())
3202 builder.createLoopExit();
3203 else
3204 builder.addSwitchBreak();
3205 break;
3206 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06003207 builder.createLoopContinue();
3208 break;
3209 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06003210 if (node->getExpression()) {
3211 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3212 spv::Id returnId = accessChainLoad(glslangReturnType);
3213 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
3214 builder.clearAccessChain();
3215 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
3216 builder.setAccessChainLValue(copyId);
3217 multiTypeStore(glslangReturnType, returnId);
3218 returnId = builder.createLoad(copyId);
3219 }
3220 builder.makeReturn(false, returnId);
3221 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003222 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003223
3224 builder.clearAccessChain();
3225 break;
3226
John Kessenichb9197c82019-08-11 07:41:45 -06003227#ifndef GLSLANG_WEB
Jeff Bolzba6170b2019-07-01 09:23:23 -05003228 case glslang::EOpDemote:
3229 builder.createNoResultOp(spv::OpDemoteToHelperInvocationEXT);
3230 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
3231 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
3232 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003233#endif
Jeff Bolzba6170b2019-07-01 09:23:23 -05003234
John Kessenich140f3df2015-06-26 16:58:36 -06003235 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003236 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003237 break;
3238 }
3239
3240 return false;
3241}
3242
John Kessenich9c14f772019-06-17 08:38:35 -06003243spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node, spv::Id forcedType)
John Kessenich140f3df2015-06-26 16:58:36 -06003244{
qining25262b32016-05-06 17:25:16 -04003245 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003246 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003247 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003248 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003249 spv::Id result = createSpvConstant(*node);
3250 if (result != spv::NoResult)
3251 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003252 }
3253
3254 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003255 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06003256 spv::Id spvType = forcedType == spv::NoType ? convertGlslangToSpvType(node->getType())
3257 : forcedType;
John Kessenich140f3df2015-06-26 16:58:36 -06003258
John Kessenichb9197c82019-08-11 07:41:45 -06003259 const bool contains16BitType = node->getType().contains16BitFloat() ||
3260 node->getType().contains16BitInt();
Rex Xuf89ad982017-04-07 23:22:33 +08003261 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003262 switch (storageClass) {
3263 case spv::StorageClassInput:
3264 case spv::StorageClassOutput:
John Kessenich8317e6c2019-08-18 23:58:08 -06003265 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003266 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003267 break;
John Kessenich18310872018-05-14 22:08:53 -06003268 case spv::StorageClassUniform:
John Kessenich8317e6c2019-08-18 23:58:08 -06003269 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003270 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3271 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003272 else
3273 builder.addCapability(spv::CapabilityStorageUniform16);
3274 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003275#ifndef GLSLANG_WEB
3276 case spv::StorageClassPushConstant:
John Kessenich8317e6c2019-08-18 23:58:08 -06003277 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenichb9197c82019-08-11 07:41:45 -06003278 builder.addCapability(spv::CapabilityStoragePushConstant16);
3279 break;
John Kessenich18310872018-05-14 22:08:53 -06003280 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003281 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich8317e6c2019-08-18 23:58:08 -06003282 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenich18310872018-05-14 22:08:53 -06003283 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3284 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003285#endif
John Kessenich18310872018-05-14 22:08:53 -06003286 default:
John Kessenichb9197c82019-08-11 07:41:45 -06003287 if (node->getType().contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003288 builder.addCapability(spv::CapabilityFloat16);
John Kessenichb9197c82019-08-11 07:41:45 -06003289 if (node->getType().contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003290 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06003291 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003292 }
3293 }
Rex Xuf89ad982017-04-07 23:22:33 +08003294
John Kessenichb9197c82019-08-11 07:41:45 -06003295 if (node->getType().contains8BitInt()) {
John Kessenich312dcfb2018-07-03 13:19:51 -06003296 if (storageClass == spv::StorageClassPushConstant) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003297 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003298 builder.addCapability(spv::CapabilityStoragePushConstant8);
3299 } else if (storageClass == spv::StorageClassUniform) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003300 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003301 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003302 } else if (storageClass == spv::StorageClassStorageBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003303 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
Neil Henningb6b01f02018-10-23 15:02:29 +01003304 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003305 } else {
3306 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06003307 }
3308 }
3309
John Kessenich140f3df2015-06-26 16:58:36 -06003310 const char* name = node->getName().c_str();
3311 if (glslang::IsAnonymous(name))
3312 name = "";
3313
3314 return builder.createVariable(storageClass, spvType, name);
3315}
3316
3317// Return type Id of the sampled type.
3318spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3319{
3320 switch (sampler.type) {
John Kessenicha28f7a72019-08-06 07:00:58 -06003321 case glslang::EbtInt: return builder.makeIntType(32);
3322 case glslang::EbtUint: return builder.makeUintType(32);
John Kessenich140f3df2015-06-26 16:58:36 -06003323 case glslang::EbtFloat: return builder.makeFloatType(32);
John Kessenicha28f7a72019-08-06 07:00:58 -06003324#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08003325 case glslang::EbtFloat16:
3326 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3327 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3328 return builder.makeFloatType(16);
3329#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003330 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003331 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003332 return builder.makeFloatType(32);
3333 }
3334}
3335
John Kessenich8c8505c2016-07-26 12:50:38 -06003336// If node is a swizzle operation, return the type that should be used if
3337// the swizzle base is first consumed by another operation, before the swizzle
3338// is applied.
3339spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3340{
John Kessenichecba76f2017-01-06 00:34:48 -07003341 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003342 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3343 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3344 else
3345 return spv::NoType;
3346}
3347
3348// When inverting a swizzle with a parent op, this function
3349// will apply the swizzle operation to a completed parent operation.
3350spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
3351{
3352 std::vector<unsigned> swizzle;
3353 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3354 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3355}
3356
John Kessenich8c8505c2016-07-26 12:50:38 -06003357// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3358void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3359{
3360 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3361 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3362 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3363}
3364
John Kessenich3ac051e2015-12-20 11:29:16 -07003365// Convert from a glslang type to an SPV type, by calling into a
3366// recursive version of this function. This establishes the inherited
3367// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003368spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003369{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003370 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003371}
3372
3373// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003374// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003375// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003376spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003377 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3378 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003379{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003380 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003381
3382 switch (type.getBasicType()) {
3383 case glslang::EbtVoid:
3384 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003385 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003386 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003387 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003388 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3389 // a 32-bit int where non-0 means true.
3390 if (explicitLayout != glslang::ElpNone)
3391 spvType = builder.makeUintType(32);
3392 else
3393 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003394 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003395 case glslang::EbtInt:
3396 spvType = builder.makeIntType(32);
3397 break;
3398 case glslang::EbtUint:
3399 spvType = builder.makeUintType(32);
3400 break;
3401 case glslang::EbtFloat:
3402 spvType = builder.makeFloatType(32);
3403 break;
3404#ifndef GLSLANG_WEB
3405 case glslang::EbtDouble:
3406 spvType = builder.makeFloatType(64);
3407 break;
3408 case glslang::EbtFloat16:
3409 spvType = builder.makeFloatType(16);
3410 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003411 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003412 spvType = builder.makeIntType(8);
3413 break;
3414 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003415 spvType = builder.makeUintType(8);
3416 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003417 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003418 spvType = builder.makeIntType(16);
3419 break;
3420 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003421 spvType = builder.makeUintType(16);
3422 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003423 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003424 spvType = builder.makeIntType(64);
3425 break;
3426 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003427 spvType = builder.makeUintType(64);
3428 break;
John Kessenich426394d2015-07-23 10:22:48 -06003429 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003430 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003431 spvType = builder.makeUintType(32);
3432 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003433 case glslang::EbtAccStructNV:
3434 spvType = builder.makeAccelerationStructureNVType();
3435 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003436 case glslang::EbtReference:
3437 {
3438 // Make the forward pointer, then recurse to convert the structure type, then
3439 // patch up the forward pointer with a real pointer type.
3440 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3441 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3442 forwardPointers[type.getReferentType()] = forwardId;
3443 }
3444 spvType = forwardPointers[type.getReferentType()];
3445 if (!forwardReferenceOnly) {
3446 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3447 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3448 forwardPointers[type.getReferentType()],
3449 referentType);
3450 }
3451 }
3452 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003453#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003454 case glslang::EbtSampler:
3455 {
3456 const glslang::TSampler& sampler = type.getSampler();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003457 if (sampler.isPureSampler()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003458 spvType = builder.makeSamplerType();
3459 } else {
3460 // an image is present, make its type
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003461 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler),
3462 sampler.isShadow(), sampler.isArrayed(), sampler.isMultiSample(),
3463 sampler.isImageClass() ? 2 : 1, TranslateImageFormat(type));
3464 if (sampler.isCombined()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003465 // already has both image and sampler, make the combined type
3466 spvType = builder.makeSampledImageType(spvType);
3467 }
John Kessenich55e7d112015-11-15 21:33:39 -07003468 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003469 }
John Kessenich140f3df2015-06-26 16:58:36 -06003470 break;
3471 case glslang::EbtStruct:
3472 case glslang::EbtBlock:
3473 {
3474 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003475 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003476
3477 // Try to share structs for different layouts, but not yet for other
3478 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003479 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003480 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003481 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003482 break;
3483
3484 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003485 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06003486 memberRemapper[glslangMembers].resize(glslangMembers->size());
3487 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003488 }
3489 break;
3490 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003491 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003492 break;
3493 }
3494
3495 if (type.isMatrix())
3496 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3497 else {
3498 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3499 if (type.getVectorSize() > 1)
3500 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3501 }
3502
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003503 if (type.isCoopMat()) {
3504 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3505 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3506 if (type.getBasicType() == glslang::EbtFloat16)
3507 builder.addCapability(spv::CapabilityFloat16);
Jeff Bolz387657e2019-08-22 20:28:00 -05003508 if (type.getBasicType() == glslang::EbtUint8 ||
3509 type.getBasicType() == glslang::EbtInt8) {
3510 builder.addCapability(spv::CapabilityInt8);
3511 }
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003512
3513 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3514 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3515 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3516
3517 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3518 }
3519
John Kessenich140f3df2015-06-26 16:58:36 -06003520 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003521 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3522
John Kessenichc9a80832015-09-12 12:17:44 -06003523 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003524 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003525 // We need to decorate array strides for types needing explicit layout, except blocks.
3526 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003527 // Use a dummy glslang type for querying internal strides of
3528 // arrays of arrays, but using just a one-dimensional array.
3529 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003530 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3531 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003532
3533 // Will compute the higher-order strides here, rather than making a whole
3534 // pile of types and doing repetitive recursion on their contents.
3535 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3536 }
John Kessenichf8842e52016-01-04 19:22:56 -07003537
3538 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003539 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003540 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003541 if (stride > 0)
3542 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003543 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003544 }
3545 } else {
3546 // single-dimensional array, and don't yet have stride
3547
John Kessenichf8842e52016-01-04 19:22:56 -07003548 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003549 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3550 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003551 }
John Kessenich31ed4832015-09-09 17:51:38 -06003552
John Kessenichead86222018-03-28 18:01:20 -06003553 // Do the outer dimension, which might not be known for a runtime-sized array.
3554 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3555 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003556 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003557 else {
John Kessenichb9197c82019-08-11 07:41:45 -06003558#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003559 if (!lastBufferBlockMember) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003560 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06003561 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3562 }
John Kessenichb9197c82019-08-11 07:41:45 -06003563#endif
John Kessenich3dd1ce52019-10-17 07:08:40 -06003564 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003565 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003566 if (stride > 0)
3567 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003568 }
3569
3570 return spvType;
3571}
3572
John Kessenich0e737842017-03-24 18:38:16 -06003573// TODO: this functionality should exist at a higher level, in creating the AST
3574//
3575// Identify interface members that don't have their required extension turned on.
3576//
3577bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3578{
John Kessenicha28f7a72019-08-06 07:00:58 -06003579#ifndef GLSLANG_WEB
John Kessenich0e737842017-03-24 18:38:16 -06003580 auto& extensions = glslangIntermediate->getRequestedExtensions();
3581
Rex Xubcf291a2017-03-29 23:01:36 +08003582 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3583 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3584 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003585 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3586 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3587 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003588
3589 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3590 if (member.getFieldName() == "gl_ViewportMask" &&
3591 extensions.find("GL_NV_viewport_array2") == extensions.end())
3592 return true;
3593 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3594 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3595 return true;
3596 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3597 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3598 return true;
3599 }
3600#endif
John Kessenich0e737842017-03-24 18:38:16 -06003601
3602 return false;
3603};
3604
John Kessenich6090df02016-06-30 21:18:02 -06003605// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3606// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3607// Mutually recursive with convertGlslangToSpvType().
3608spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3609 const glslang::TTypeList* glslangMembers,
3610 glslang::TLayoutPacking explicitLayout,
3611 const glslang::TQualifier& qualifier)
3612{
3613 // Create a vector of struct types for SPIR-V to consume
3614 std::vector<spv::Id> spvMembers;
3615 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 -06003616 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003617 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3618 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3619 if (glslangMember.hiddenMember()) {
3620 ++memberDelta;
3621 if (type.getBasicType() == glslang::EbtBlock)
3622 memberRemapper[glslangMembers][i] = -1;
3623 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003624 if (type.getBasicType() == glslang::EbtBlock) {
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003625 if (filterMember(glslangMember)) {
3626 memberDelta++;
3627 memberRemapper[glslangMembers][i] = -1;
John Kessenich0e737842017-03-24 18:38:16 -06003628 continue;
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003629 }
3630 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003631 }
John Kessenich6090df02016-06-30 21:18:02 -06003632 // modify just this child's view of the qualifier
3633 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3634 InheritQualifiers(memberQualifier, qualifier);
3635
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003636 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003637 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003638 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003639
3640 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003641 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3642 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003643
3644 // Make forward pointers for any pointer members, and create a list of members to
3645 // convert to spirv types after creating the struct.
John Kessenich7015bd62019-08-01 03:28:08 -06003646 if (glslangMember.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003647 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3648 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3649 }
3650 spvMembers.push_back(
3651 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, true));
3652 } else {
3653 spvMembers.push_back(
3654 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, false));
3655 }
John Kessenich6090df02016-06-30 21:18:02 -06003656 }
3657 }
3658
3659 // Make the SPIR-V type
3660 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003661 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003662 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3663
3664 // Decorate it
3665 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3666
John Kessenichd72f4882019-01-16 14:55:37 +07003667 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003668 auto it = deferredForwardPointers[i];
3669 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3670 }
3671
John Kessenich6090df02016-06-30 21:18:02 -06003672 return spvType;
3673}
3674
3675void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3676 const glslang::TTypeList* glslangMembers,
3677 glslang::TLayoutPacking explicitLayout,
3678 const glslang::TQualifier& qualifier,
3679 spv::Id spvType)
3680{
3681 // Name and decorate the non-hidden members
3682 int offset = -1;
3683 int locationOffset = 0; // for use within the members of this struct
3684 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3685 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3686 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003687 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003688 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06003689 if (filterMember(glslangMember))
3690 continue;
3691 }
John Kessenich6090df02016-06-30 21:18:02 -06003692
3693 // modify just this child's view of the qualifier
3694 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3695 InheritQualifiers(memberQualifier, qualifier);
3696
3697 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003698 if (member < 0)
3699 continue;
3700
3701 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3702 builder.addMemberDecoration(spvType, member,
3703 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3704 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3705 // Add interpolation and auxiliary storage decorations only to
3706 // top-level members of Input and Output storage classes
3707 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3708 type.getQualifier().storage == glslang::EvqVaryingOut) {
3709 if (type.getBasicType() == glslang::EbtBlock ||
3710 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3711 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3712 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenicha28f7a72019-08-06 07:00:58 -06003713#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07003714 addMeshNVDecoration(spvType, member, memberQualifier);
3715#endif
John Kessenich6090df02016-06-30 21:18:02 -06003716 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003717 }
3718 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003719
John Kessenichb9197c82019-08-11 07:41:45 -06003720#ifndef GLSLANG_WEB
John Kessenich5d610ee2018-03-07 18:05:55 -07003721 if (type.getBasicType() == glslang::EbtBlock &&
3722 qualifier.storage == glslang::EvqBuffer) {
3723 // Add memory decorations only to top-level members of shader storage block
3724 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003725 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003726 for (unsigned int i = 0; i < memory.size(); ++i)
3727 builder.addMemberDecoration(spvType, member, memory[i]);
3728 }
John Kessenichf8d1d742019-10-21 06:55:11 -06003729
John Kessenichb9197c82019-08-11 07:41:45 -06003730#endif
John Kessenich6090df02016-06-30 21:18:02 -06003731
John Kessenich5d610ee2018-03-07 18:05:55 -07003732 // Location assignment was already completed correctly by the front end,
3733 // just track whether a member needs to be decorated.
3734 // Ignore member locations if the container is an array, as that's
3735 // ill-specified and decisions have been made to not allow this.
3736 if (! type.isArray() && memberQualifier.hasLocation())
3737 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003738
John Kessenich5d610ee2018-03-07 18:05:55 -07003739 if (qualifier.hasLocation()) // track for upcoming inheritance
3740 locationOffset += glslangIntermediate->computeTypeLocationSize(
3741 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003742
John Kessenich5d610ee2018-03-07 18:05:55 -07003743 // component, XFB, others
3744 if (glslangMember.getQualifier().hasComponent())
3745 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3746 glslangMember.getQualifier().layoutComponent);
3747 if (glslangMember.getQualifier().hasXfbOffset())
3748 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3749 glslangMember.getQualifier().layoutXfbOffset);
3750 else if (explicitLayout != glslang::ElpNone) {
3751 // figure out what to do with offset, which is accumulating
3752 int nextOffset;
3753 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3754 if (offset >= 0)
3755 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3756 offset = nextOffset;
3757 }
John Kessenich6090df02016-06-30 21:18:02 -06003758
John Kessenich5d610ee2018-03-07 18:05:55 -07003759 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3760 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3761 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003762
John Kessenich5d610ee2018-03-07 18:05:55 -07003763 // built-in variable decorations
3764 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3765 if (builtIn != spv::BuiltInMax)
3766 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003767
John Kessenichb9197c82019-08-11 07:41:45 -06003768#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003769 // nonuniform
3770 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3771
John Kessenichead86222018-03-28 18:01:20 -06003772 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3773 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3774 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3775 memberQualifier.semanticName);
3776 }
3777
John Kessenich5d610ee2018-03-07 18:05:55 -07003778 if (builtIn == spv::BuiltInLayer) {
3779 // SPV_NV_viewport_array2 extension
3780 if (glslangMember.getQualifier().layoutViewportRelative){
3781 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3782 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3783 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003784 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003785 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3786 builder.addMemberDecoration(spvType, member,
3787 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3788 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3789 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3790 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003791 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003792 }
3793 if (glslangMember.getQualifier().layoutPassthrough) {
3794 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3795 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3796 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3797 }
chaoc771d89f2017-01-13 01:10:53 -08003798#endif
John Kessenich6090df02016-06-30 21:18:02 -06003799 }
3800
3801 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003802 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3803 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003804}
3805
John Kessenich6c292d32016-02-15 20:58:50 -07003806// Turn the expression forming the array size into an id.
3807// This is not quite trivial, because of specialization constants.
3808// Sometimes, a raw constant is turned into an Id, and sometimes
3809// a specialization constant expression is.
3810spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3811{
3812 // First, see if this is sized with a node, meaning a specialization constant:
3813 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3814 if (specNode != nullptr) {
3815 builder.clearAccessChain();
3816 specNode->traverse(this);
3817 return accessChainLoad(specNode->getAsTyped()->getType());
3818 }
qining25262b32016-05-06 17:25:16 -04003819
John Kessenich6c292d32016-02-15 20:58:50 -07003820 // Otherwise, need a compile-time (front end) size, get it:
3821 int size = arraySizes.getDimSize(dim);
3822 assert(size > 0);
3823 return builder.makeUintConstant(size);
3824}
3825
John Kessenich103bef92016-02-08 21:38:15 -07003826// Wrap the builder's accessChainLoad to:
3827// - localize handling of RelaxedPrecision
3828// - use the SPIR-V inferred type instead of another conversion of the glslang type
3829// (avoids unnecessary work and possible type punning for structures)
3830// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003831spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3832{
John Kessenich103bef92016-02-08 21:38:15 -07003833 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003834
3835 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3836 coherentFlags |= TranslateCoherent(type);
3837
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003838 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003839 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003840
John Kessenich5611c6d2018-04-05 11:25:02 -06003841 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003842 TranslateNonUniformDecoration(type.getQualifier()),
3843 nominalTypeId,
3844 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003845 TranslateMemoryScope(coherentFlags),
3846 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07003847
3848 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003849 if (type.getBasicType() == glslang::EbtBool) {
3850 if (builder.isScalarType(nominalTypeId)) {
3851 // Conversion for bool
3852 spv::Id boolType = builder.makeBoolType();
3853 if (nominalTypeId != boolType)
3854 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3855 } else if (builder.isVectorType(nominalTypeId)) {
3856 // Conversion for bvec
3857 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3858 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3859 if (nominalTypeId != bvecType)
3860 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3861 }
3862 }
John Kessenich103bef92016-02-08 21:38:15 -07003863
3864 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003865}
3866
Rex Xu27253232016-02-23 17:51:09 +08003867// Wrap the builder's accessChainStore to:
3868// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003869//
3870// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003871void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3872{
3873 // Need to convert to abstract types when necessary
3874 if (type.getBasicType() == glslang::EbtBool) {
3875 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3876
3877 if (builder.isScalarType(nominalTypeId)) {
3878 // Conversion for bool
3879 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003880 if (nominalTypeId != boolType) {
3881 // keep these outside arguments, for determinant order-of-evaluation
3882 spv::Id one = builder.makeUintConstant(1);
3883 spv::Id zero = builder.makeUintConstant(0);
3884 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3885 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003886 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003887 } else if (builder.isVectorType(nominalTypeId)) {
3888 // Conversion for bvec
3889 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3890 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003891 if (nominalTypeId != bvecType) {
3892 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003893 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3894 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3895 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003896 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003897 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3898 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003899 }
3900 }
3901
Jeff Bolz36831c92018-09-05 10:11:41 -05003902 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3903 coherentFlags |= TranslateCoherent(type);
3904
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003905 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003906 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003907
Jeff Bolz36831c92018-09-05 10:11:41 -05003908 builder.accessChainStore(rvalue,
3909 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003910 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08003911}
3912
John Kessenich4bf71552016-09-02 11:20:21 -06003913// For storing when types match at the glslang level, but not might match at the
3914// SPIR-V level.
3915//
3916// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003917// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003918// as in a member-decorated way.
3919//
3920// NOTE: This function can handle any store request; if it's not special it
3921// simplifies to a simple OpStore.
3922//
3923// Implicitly uses the existing builder.accessChain as the storage target.
3924void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3925{
John Kessenichb3e24e42016-09-11 12:33:43 -06003926 // we only do the complex path here if it's an aggregate
3927 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003928 accessChainStore(type, rValue);
3929 return;
3930 }
3931
John Kessenichb3e24e42016-09-11 12:33:43 -06003932 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003933 spv::Id rType = builder.getTypeId(rValue);
3934 spv::Id lValue = builder.accessChainGetLValue();
3935 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3936 if (lType == rType) {
3937 accessChainStore(type, rValue);
3938 return;
3939 }
3940
John Kessenichb3e24e42016-09-11 12:33:43 -06003941 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003942 // where the two types were the same type in GLSL. This requires member
3943 // by member copy, recursively.
3944
John Kessenichfbb6bdf2019-01-15 21:48:27 +07003945 // SPIR-V 1.4 added an instruction to do help do this.
3946 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
3947 // However, bool in uniform space is changed to int, so
3948 // OpCopyLogical does not work for that.
3949 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
3950 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
3951 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
3952 if (lBool == rBool) {
3953 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
3954 accessChainStore(type, logicalCopy);
3955 return;
3956 }
3957 }
3958
John Kessenichb3e24e42016-09-11 12:33:43 -06003959 // If an array, copy element by element.
3960 if (type.isArray()) {
3961 glslang::TType glslangElementType(type, 0);
3962 spv::Id elementRType = builder.getContainedTypeId(rType);
3963 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3964 // get the source member
3965 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003966
John Kessenichb3e24e42016-09-11 12:33:43 -06003967 // set up the target storage
3968 builder.clearAccessChain();
3969 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003970 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06003971
John Kessenichb3e24e42016-09-11 12:33:43 -06003972 // store the member
3973 multiTypeStore(glslangElementType, elementRValue);
3974 }
3975 } else {
3976 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003977
John Kessenichb3e24e42016-09-11 12:33:43 -06003978 // loop over structure members
3979 const glslang::TTypeList& members = *type.getStruct();
3980 for (int m = 0; m < (int)members.size(); ++m) {
3981 const glslang::TType& glslangMemberType = *members[m].type;
3982
3983 // get the source member
3984 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3985 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3986
3987 // set up the target storage
3988 builder.clearAccessChain();
3989 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003990 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06003991
3992 // store the member
3993 multiTypeStore(glslangMemberType, memberRValue);
3994 }
John Kessenich4bf71552016-09-02 11:20:21 -06003995 }
3996}
3997
John Kessenichf85e8062015-12-19 13:57:10 -07003998// Decide whether or not this type should be
3999// decorated with offsets and strides, and if so
4000// whether std140 or std430 rules should be applied.
4001glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06004002{
John Kessenichf85e8062015-12-19 13:57:10 -07004003 // has to be a block
4004 if (type.getBasicType() != glslang::EbtBlock)
4005 return glslang::ElpNone;
4006
Chao Chen3c366992018-09-19 11:41:59 -07004007 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07004008 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07004009 type.getQualifier().storage != glslang::EvqBuffer &&
4010 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07004011 return glslang::ElpNone;
4012
4013 // return the layout to use
4014 switch (type.getQualifier().layoutPacking) {
4015 case glslang::ElpStd140:
4016 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004017 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07004018 return type.getQualifier().layoutPacking;
4019 default:
4020 return glslang::ElpNone;
4021 }
John Kessenich31ed4832015-09-09 17:51:38 -06004022}
4023
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004024// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07004025int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004026{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004027 int size;
John Kessenich49987892015-12-29 17:11:44 -07004028 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004029 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07004030
4031 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004032}
4033
John Kessenich49987892015-12-29 17:11:44 -07004034// 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 -07004035// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07004036int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004037{
John Kessenich49987892015-12-29 17:11:44 -07004038 glslang::TType elementType;
4039 elementType.shallowCopy(matrixType);
4040 elementType.clearArraySizes();
4041
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004042 int size;
John Kessenich49987892015-12-29 17:11:44 -07004043 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004044 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07004045
4046 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004047}
4048
John Kessenich5e4b1242015-08-06 22:53:06 -06004049// Given a member type of a struct, realign the current offset for it, and compute
4050// the next (not yet aligned) offset for the next member, which will get aligned
4051// on the next call.
4052// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
4053// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
4054// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06004055void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07004056 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06004057{
4058 // this will get a positive value when deemed necessary
4059 nextOffset = -1;
4060
John Kessenich5e4b1242015-08-06 22:53:06 -06004061 // override anything in currentOffset with user-set offset
4062 if (memberType.getQualifier().hasOffset())
4063 currentOffset = memberType.getQualifier().layoutOffset;
4064
4065 // It could be that current linker usage in glslang updated all the layoutOffset,
4066 // in which case the following code does not matter. But, that's not quite right
4067 // once cross-compilation unit GLSL validation is done, as the original user
4068 // settings are needed in layoutOffset, and then the following will come into play.
4069
John Kessenichf85e8062015-12-19 13:57:10 -07004070 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06004071 if (! memberType.getQualifier().hasOffset())
4072 currentOffset = -1;
4073
4074 return;
4075 }
4076
John Kessenichf85e8062015-12-19 13:57:10 -07004077 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06004078 if (currentOffset < 0)
4079 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04004080
John Kessenich5e4b1242015-08-06 22:53:06 -06004081 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
4082 // but possibly not yet correctly aligned.
4083
4084 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07004085 int dummyStride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004086 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06004087
4088 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06004089 // TODO: make this consistent in early phases of code:
4090 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
4091 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
4092 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06004093 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06004094 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06004095 int dummySize;
4096 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
4097 if (componentAlignment <= 4)
4098 memberAlignment = componentAlignment;
4099 }
4100
4101 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06004102 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06004103
4104 // Bump up to vec4 if there is a bad straddle
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004105 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06004106 glslang::RoundToPow2(currentOffset, 16);
4107
John Kessenich5e4b1242015-08-06 22:53:06 -06004108 nextOffset = currentOffset + memberSize;
4109}
4110
David Netoa901ffe2016-06-08 14:11:40 +01004111void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06004112{
David Netoa901ffe2016-06-08 14:11:40 +01004113 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
4114 switch (glslangBuiltIn)
4115 {
John Kessenicha28f7a72019-08-06 07:00:58 -06004116 case glslang::EbvPointSize:
4117#ifndef GLSLANG_WEB
David Netoa901ffe2016-06-08 14:11:40 +01004118 case glslang::EbvClipDistance:
4119 case glslang::EbvCullDistance:
chaoc771d89f2017-01-13 01:10:53 -08004120 case glslang::EbvViewportMaskNV:
4121 case glslang::EbvSecondaryPositionNV:
4122 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08004123 case glslang::EbvPositionPerViewNV:
4124 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07004125 case glslang::EbvTaskCountNV:
4126 case glslang::EbvPrimitiveCountNV:
4127 case glslang::EbvPrimitiveIndicesNV:
4128 case glslang::EbvClipDistancePerViewNV:
4129 case glslang::EbvCullDistancePerViewNV:
4130 case glslang::EbvLayerPerViewNV:
4131 case glslang::EbvMeshViewCountNV:
4132 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004133#endif
David Netoa901ffe2016-06-08 14:11:40 +01004134 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4135 // Alternately, we could just call this for any glslang built-in, since the
4136 // capability already guards against duplicates.
4137 TranslateBuiltInDecoration(glslangBuiltIn, false);
4138 break;
4139 default:
4140 // Capabilities were already generated when the struct was declared.
4141 break;
4142 }
John Kessenichebb50532016-05-16 19:22:05 -06004143}
4144
John Kessenich6fccb3c2016-09-19 16:01:41 -06004145bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004146{
John Kessenicheee9d532016-09-19 18:09:30 -06004147 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004148}
4149
John Kessenichd41993d2017-09-10 15:21:05 -06004150// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004151// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4152// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004153bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004154{
John Kessenich6a14f782017-12-04 02:48:10 -07004155 assert(qualifier == glslang::EvqIn ||
4156 qualifier == glslang::EvqOut ||
4157 qualifier == glslang::EvqInOut ||
4158 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06004159 return qualifier != glslang::EvqConstReadOnly;
4160}
4161
4162// Is parameter pass-by-original?
4163bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4164 bool implicitThisParam)
4165{
4166 if (implicitThisParam) // implicit this
4167 return true;
4168 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004169 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004170 return paramType.containsOpaque() || // sampler, etc.
4171 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4172}
4173
John Kessenich140f3df2015-06-26 16:58:36 -06004174// Make all the functions, skeletally, without actually visiting their bodies.
4175void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4176{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004177 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004178 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4179 if (paramPrecision != spv::NoPrecision)
4180 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004181 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenich7015bd62019-08-01 03:28:08 -06004182 if (type.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004183 // Original and non-writable params pass the pointer directly and
4184 // use restrict/aliased, others are stored to a pointer in Function
4185 // memory and use RestrictPointer/AliasedPointer.
4186 if (originalParam(type.getQualifier().storage, type, false) ||
4187 !writableParam(type.getQualifier().storage)) {
John Kessenichf8d1d742019-10-21 06:55:11 -06004188 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrict :
4189 spv::DecorationAliased);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004190 } else {
John Kessenichf8d1d742019-10-21 06:55:11 -06004191 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrictPointerEXT :
4192 spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004193 }
4194 }
John Kessenichfad62972017-07-18 02:35:46 -06004195 };
4196
John Kessenich140f3df2015-06-26 16:58:36 -06004197 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4198 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004199 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004200 continue;
4201
4202 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004203 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004204 //
qining25262b32016-05-06 17:25:16 -04004205 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004206 // function. What it is an address of varies:
4207 //
John Kessenich4bf71552016-09-02 11:20:21 -06004208 // - "in" parameters not marked as "const" can be written to without modifying the calling
4209 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004210 //
4211 // - "const in" parameters can just be the r-value, as no writes need occur.
4212 //
John Kessenich4bf71552016-09-02 11:20:21 -06004213 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4214 // 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 -06004215
4216 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004217 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004218 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4219
John Kessenich155d3512019-08-08 23:29:20 -06004220#ifdef ENABLE_HLSL
John Kessenichfad62972017-07-18 02:35:46 -06004221 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4222 glslangIntermediate->implicitThisName;
John Kessenich155d3512019-08-08 23:29:20 -06004223#else
4224 bool implicitThis = false;
4225#endif
John Kessenich37789792017-03-21 23:56:40 -06004226
John Kessenichfad62972017-07-18 02:35:46 -06004227 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004228 for (int p = 0; p < (int)parameters.size(); ++p) {
4229 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4230 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004231 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004232 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004233 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004234 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4235 else
John Kessenich4bf71552016-09-02 11:20:21 -06004236 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004237 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004238 paramTypes.push_back(typeId);
4239 }
4240
4241 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004242 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4243 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004244 glslFunction->getName().c_str(), paramTypes,
4245 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004246 if (implicitThis)
4247 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004248
4249 // Track function to emit/call later
4250 functionMap[glslFunction->getName().c_str()] = function;
4251
4252 // Set the parameter id's
4253 for (int p = 0; p < (int)parameters.size(); ++p) {
4254 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4255 // give a name too
4256 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004257
4258 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
John Kessenichb9197c82019-08-11 07:41:45 -06004259 if (paramType.contains8BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004260 builder.addCapability(spv::CapabilityInt8);
John Kessenichb9197c82019-08-11 07:41:45 -06004261 if (paramType.contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004262 builder.addCapability(spv::CapabilityInt16);
John Kessenichb9197c82019-08-11 07:41:45 -06004263 if (paramType.contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004264 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004265 }
4266 }
4267}
4268
4269// Process all the initializers, while skipping the functions and link objects
4270void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4271{
4272 builder.setBuildPoint(shaderEntry->getLastBlock());
4273 for (int i = 0; i < (int)initializers.size(); ++i) {
4274 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
4275 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
4276
4277 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004278 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004279 initializer->traverse(this);
4280 }
4281 }
4282}
4283
4284// Process all the functions, while skipping initializers.
4285void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4286{
4287 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4288 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004289 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004290 node->traverse(this);
4291 }
4292}
4293
4294void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4295{
qining25262b32016-05-06 17:25:16 -04004296 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004297 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004298 currentFunction = functionMap[node->getName().c_str()];
4299 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004300 builder.setBuildPoint(functionBlock);
4301}
4302
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004303void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments, spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004304{
Rex Xufc618912015-09-09 16:42:49 +08004305 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004306
4307 glslang::TSampler sampler = {};
4308 bool cubeCompare = false;
John Kessenicha28f7a72019-08-06 07:00:58 -06004309#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004310 bool f16ShadowCompare = false;
4311#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004312 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004313 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4314 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
John Kessenicha28f7a72019-08-06 07:00:58 -06004315#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004316 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
4317#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004318 }
4319
John Kessenich140f3df2015-06-26 16:58:36 -06004320 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4321 builder.clearAccessChain();
4322 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004323
John Kessenicha28f7a72019-08-06 07:00:58 -06004324#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08004325 // Special case l-value operands
4326 bool lvalue = false;
4327 switch (node.getOp()) {
4328 case glslang::EOpImageAtomicAdd:
4329 case glslang::EOpImageAtomicMin:
4330 case glslang::EOpImageAtomicMax:
4331 case glslang::EOpImageAtomicAnd:
4332 case glslang::EOpImageAtomicOr:
4333 case glslang::EOpImageAtomicXor:
4334 case glslang::EOpImageAtomicExchange:
4335 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004336 case glslang::EOpImageAtomicLoad:
4337 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004338 if (i == 0)
4339 lvalue = true;
4340 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004341 case glslang::EOpSparseImageLoad:
4342 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4343 lvalue = true;
4344 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004345 case glslang::EOpSparseTexture:
4346 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4347 lvalue = true;
4348 break;
4349 case glslang::EOpSparseTextureClamp:
4350 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4351 lvalue = true;
4352 break;
4353 case glslang::EOpSparseTextureLod:
4354 case glslang::EOpSparseTextureOffset:
4355 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4356 lvalue = true;
4357 break;
Rex Xu48edadf2015-12-31 16:11:41 +08004358 case glslang::EOpSparseTextureFetch:
4359 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4360 lvalue = true;
4361 break;
4362 case glslang::EOpSparseTextureFetchOffset:
4363 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4364 lvalue = true;
4365 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004366 case glslang::EOpSparseTextureLodOffset:
4367 case glslang::EOpSparseTextureGrad:
4368 case glslang::EOpSparseTextureOffsetClamp:
4369 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4370 lvalue = true;
4371 break;
4372 case glslang::EOpSparseTextureGradOffset:
4373 case glslang::EOpSparseTextureGradClamp:
4374 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4375 lvalue = true;
4376 break;
4377 case glslang::EOpSparseTextureGradOffsetClamp:
4378 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4379 lvalue = true;
4380 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004381 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004382 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4383 lvalue = true;
4384 break;
4385 case glslang::EOpSparseTextureGatherOffset:
4386 case glslang::EOpSparseTextureGatherOffsets:
4387 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4388 lvalue = true;
4389 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004390 case glslang::EOpSparseTextureGatherLod:
4391 if (i == 3)
4392 lvalue = true;
4393 break;
4394 case glslang::EOpSparseTextureGatherLodOffset:
4395 case glslang::EOpSparseTextureGatherLodOffsets:
4396 if (i == 4)
4397 lvalue = true;
4398 break;
Rex Xu129799a2017-07-05 17:23:28 +08004399 case glslang::EOpSparseImageLoadLod:
4400 if (i == 3)
4401 lvalue = true;
4402 break;
Chao Chen3a137962018-09-19 11:41:27 -07004403 case glslang::EOpImageSampleFootprintNV:
4404 if (i == 4)
4405 lvalue = true;
4406 break;
4407 case glslang::EOpImageSampleFootprintClampNV:
4408 case glslang::EOpImageSampleFootprintLodNV:
4409 if (i == 5)
4410 lvalue = true;
4411 break;
4412 case glslang::EOpImageSampleFootprintGradNV:
4413 if (i == 6)
4414 lvalue = true;
4415 break;
4416 case glslang::EOpImageSampleFootprintGradClampNV:
4417 if (i == 7)
4418 lvalue = true;
4419 break;
Rex Xufc618912015-09-09 16:42:49 +08004420 default:
4421 break;
4422 }
4423
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004424 if (lvalue) {
Rex Xufc618912015-09-09 16:42:49 +08004425 arguments.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004426 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
4427 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4428 } else
John Kessenicha28f7a72019-08-06 07:00:58 -06004429#endif
John Kessenich32cfd492016-02-02 12:37:46 -07004430 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004431 }
4432}
4433
John Kessenichfc51d282015-08-19 13:34:18 -06004434void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004435{
John Kessenichfc51d282015-08-19 13:34:18 -06004436 builder.clearAccessChain();
4437 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004438 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004439}
John Kessenich140f3df2015-06-26 16:58:36 -06004440
John Kessenichfc51d282015-08-19 13:34:18 -06004441spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4442{
John Kesseniche485c7a2017-05-31 18:50:53 -06004443 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004444 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004445
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004446 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004447
John Kessenichfc51d282015-08-19 13:34:18 -06004448 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004449
John Kessenichf43c7392019-03-31 10:51:57 -06004450 const glslang::TType &imageType = node->getAsAggregate()
4451 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4452 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004453 const glslang::TSampler sampler = imageType.getSampler();
John Kessenicha28f7a72019-08-06 07:00:58 -06004454#ifdef GLSLANG_WEB
4455 const bool f16ShadowCompare = false;
4456#else
Rex Xu1e5d7b02016-11-29 17:36:31 +08004457 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004458 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4459 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004460#endif
4461
John Kessenichf43c7392019-03-31 10:51:57 -06004462 const auto signExtensionMask = [&]() {
4463 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4464 if (sampler.type == glslang::EbtUint)
4465 return spv::ImageOperandsZeroExtendMask;
4466 else if (sampler.type == glslang::EbtInt)
4467 return spv::ImageOperandsSignExtendMask;
4468 }
4469 return spv::ImageOperandsMaskNone;
4470 };
4471
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004472 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4473
John Kessenichfc51d282015-08-19 13:34:18 -06004474 std::vector<spv::Id> arguments;
4475 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004476 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004477 else
4478 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004479 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004480
4481 spv::Builder::TextureParameters params = { };
4482 params.sampler = arguments[0];
4483
Rex Xu04db3f52015-09-16 11:44:02 +08004484 glslang::TCrackedTextureOp cracked;
4485 node->crackTexture(sampler, cracked);
4486
amhagan05506bb2017-06-13 16:53:02 -04004487 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004488
John Kessenichfc51d282015-08-19 13:34:18 -06004489 // Check for queries
4490 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004491 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4492 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004493 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004494
John Kessenichfc51d282015-08-19 13:34:18 -06004495 switch (node->getOp()) {
4496 case glslang::EOpImageQuerySize:
4497 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004498 if (arguments.size() > 1) {
4499 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004500 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004501 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004502 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenicha28f7a72019-08-06 07:00:58 -06004503#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06004504 case glslang::EOpImageQuerySamples:
4505 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004506 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004507 case glslang::EOpTextureQueryLod:
4508 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004509 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004510 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004511 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004512 case glslang::EOpSparseTexelsResident:
4513 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenicha28f7a72019-08-06 07:00:58 -06004514#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004515 default:
4516 assert(0);
4517 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004518 }
John Kessenich140f3df2015-06-26 16:58:36 -06004519 }
4520
LoopDawg4425f242018-02-18 11:40:01 -07004521 int components = node->getType().getVectorSize();
4522
4523 if (node->getOp() == glslang::EOpTextureFetch) {
4524 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4525 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4526 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4527 // here around e.g. which ones return scalars or other types.
4528 components = 4;
4529 }
4530
4531 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4532
4533 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4534
Rex Xufc618912015-09-09 16:42:49 +08004535 // Check for image functions other than queries
4536 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004537 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004538 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004539 spv::IdImmediate image = { true, *(opIt++) };
4540 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004541
4542 // Handle subpass operations
4543 // TODO: GLSL should change to have the "MS" only on the type rather than the
4544 // built-in function.
4545 if (cracked.subpass) {
4546 // add on the (0,0) coordinate
4547 spv::Id zero = builder.makeIntConstant(0);
4548 std::vector<spv::Id> comps;
4549 comps.push_back(zero);
4550 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004551 spv::IdImmediate coord = { true,
4552 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4553 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004554 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4555 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004556 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004557 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4558 }
4559 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004560 operands.push_back(imageOperands);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004561 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004562 spv::IdImmediate imageOperand = { true, *(opIt++) };
4563 operands.push_back(imageOperand);
4564 }
John Kessenich6c292d32016-02-15 20:58:50 -07004565 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004566 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4567 builder.setPrecision(result, precision);
4568 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004569 }
4570
John Kessenich149afc32018-08-14 13:31:43 -06004571 spv::IdImmediate coord = { true, *(opIt++) };
4572 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004573 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004574 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004575 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004576 mask = mask | spv::ImageOperandsSampleMask;
4577 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004578 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004579 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4580 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004581 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004582 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004583 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4584 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004585 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004586 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004587 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4588 operands.push_back(imageOperands);
4589 }
4590 if (mask & spv::ImageOperandsSampleMask) {
4591 spv::IdImmediate imageOperand = { true, *opIt++ };
4592 operands.push_back(imageOperand);
4593 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004594 if (mask & spv::ImageOperandsLodMask) {
4595 spv::IdImmediate imageOperand = { true, *opIt++ };
4596 operands.push_back(imageOperand);
4597 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004598 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004599 spv::IdImmediate imageOperand = { true,
4600 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004601 operands.push_back(imageOperand);
4602 }
4603
John Kessenich149afc32018-08-14 13:31:43 -06004604 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004605 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004606
John Kessenich149afc32018-08-14 13:31:43 -06004607 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004608 builder.setPrecision(result[0], precision);
4609
4610 // If needed, add a conversion constructor to the proper size.
4611 if (components != node->getType().getVectorSize())
4612 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4613
4614 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004615 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004616
Jeff Bolz36831c92018-09-05 10:11:41 -05004617 // Push the texel value before the operands
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004618 if (sampler.isMultiSample() || cracked.lod) {
John Kessenich149afc32018-08-14 13:31:43 -06004619 spv::IdImmediate texel = { true, *(opIt + 1) };
4620 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004621 } else {
4622 spv::IdImmediate texel = { true, *opIt };
4623 operands.push_back(texel);
4624 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004625
4626 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004627 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004628 mask = mask | spv::ImageOperandsSampleMask;
4629 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004630 if (cracked.lod) {
4631 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4632 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4633 mask = mask | spv::ImageOperandsLodMask;
4634 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004635 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4636 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004637 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004638 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004639 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4640 operands.push_back(imageOperands);
4641 }
4642 if (mask & spv::ImageOperandsSampleMask) {
4643 spv::IdImmediate imageOperand = { true, *opIt++ };
4644 operands.push_back(imageOperand);
4645 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004646 if (mask & spv::ImageOperandsLodMask) {
4647 spv::IdImmediate imageOperand = { true, *opIt++ };
4648 operands.push_back(imageOperand);
4649 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004650 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004651 spv::IdImmediate imageOperand = { true,
4652 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004653 operands.push_back(imageOperand);
4654 }
4655
John Kessenich56bab042015-09-16 10:54:31 -06004656 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004657 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004658 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004659 return spv::NoResult;
John Kessenichf43c7392019-03-31 10:51:57 -06004660 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4661 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu5eafa472016-02-19 22:24:03 +08004662 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004663 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004664 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4665
Jeff Bolz36831c92018-09-05 10:11:41 -05004666 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004667 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004668 mask = mask | spv::ImageOperandsSampleMask;
4669 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004670 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004671 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4672 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4673
Jeff Bolz36831c92018-09-05 10:11:41 -05004674 mask = mask | spv::ImageOperandsLodMask;
4675 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004676 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4677 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004678 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004679 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004680 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004681 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004682 }
4683 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004684 spv::IdImmediate imageOperand = { true, *opIt++ };
4685 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004686 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004687 if (mask & spv::ImageOperandsLodMask) {
4688 spv::IdImmediate imageOperand = { true, *opIt++ };
4689 operands.push_back(imageOperand);
4690 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004691 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4692 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4693 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004694 }
4695
4696 // Create the return type that was a special structure
4697 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004698 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004699 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4700 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4701
4702 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4703
4704 // Decode the return type
4705 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4706 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004707 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004708 // Process image atomic operations
4709
4710 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4711 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004712 // For non-MS, the sample value should be 0
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004713 spv::IdImmediate sample = { true, sampler.isMultiSample() ? *(opIt++) : builder.makeUintConstant(0) };
John Kessenich149afc32018-08-14 13:31:43 -06004714 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004715
Jeff Bolz36831c92018-09-05 10:11:41 -05004716 spv::Id resultTypeId;
4717 // imageAtomicStore has a void return type so base the pointer type on
4718 // the type of the value operand.
4719 if (node->getOp() == glslang::EOpImageAtomicStore) {
4720 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
4721 } else {
4722 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4723 }
John Kessenich56bab042015-09-16 10:54:31 -06004724 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08004725
4726 std::vector<spv::Id> operands;
4727 operands.push_back(pointer);
4728 for (; opIt != arguments.end(); ++opIt)
4729 operands.push_back(*opIt);
4730
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004731 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(), lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08004732 }
4733 }
4734
John Kessenicha28f7a72019-08-06 07:00:58 -06004735#ifndef GLSLANG_WEB
amhagan05506bb2017-06-13 16:53:02 -04004736 // Check for fragment mask functions other than queries
4737 if (cracked.fragMask) {
4738 assert(sampler.ms);
4739
4740 auto opIt = arguments.begin();
4741 std::vector<spv::Id> operands;
4742
4743 // Extract the image if necessary
4744 if (builder.isSampledImage(params.sampler))
4745 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4746
4747 operands.push_back(params.sampler);
4748 ++opIt;
4749
4750 if (sampler.isSubpass()) {
4751 // add on the (0,0) coordinate
4752 spv::Id zero = builder.makeIntConstant(0);
4753 std::vector<spv::Id> comps;
4754 comps.push_back(zero);
4755 comps.push_back(zero);
4756 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
4757 }
4758
4759 for (; opIt != arguments.end(); ++opIt)
4760 operands.push_back(*opIt);
4761
4762 spv::Op fragMaskOp = spv::OpNop;
4763 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4764 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4765 else if (node->getOp() == glslang::EOpFragmentFetch)
4766 fragMaskOp = spv::OpFragmentFetchAMD;
4767
4768 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4769 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4770 return builder.createOp(fragMaskOp, resultType(), operands);
4771 }
4772#endif
4773
Rex Xufc618912015-09-09 16:42:49 +08004774 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004775 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004776 bool imageFootprint = node->isImageFootprint();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004777 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.isArrayed() && sampler.isShadow();
Rex Xu71519fe2015-11-11 15:35:47 +08004778
John Kessenichfc51d282015-08-19 13:34:18 -06004779 // check for bias argument
4780 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004781 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06004782 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004783 if (cracked.gather)
4784 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004785
4786 if (f16ShadowCompare)
4787 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06004788 if (cracked.offset)
4789 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004790 else if (cracked.offsets)
4791 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06004792 if (cracked.grad)
4793 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004794 if (cracked.lodClamp)
4795 ++nonBiasArgCount;
4796 if (sparse)
4797 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004798 if (imageFootprint)
4799 //Following three extra arguments
4800 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4801 nonBiasArgCount += 3;
John Kessenichfc51d282015-08-19 13:34:18 -06004802 if ((int)arguments.size() > nonBiasArgCount)
4803 bias = true;
4804 }
4805
John Kessenicha5c33d62016-06-02 23:45:21 -06004806 // See if the sampler param should really be just the SPV image part
4807 if (cracked.fetch) {
4808 // a fetch needs to have the image extracted first
4809 if (builder.isSampledImage(params.sampler))
4810 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4811 }
4812
John Kessenicha28f7a72019-08-06 07:00:58 -06004813#ifndef GLSLANG_WEB
Rex Xu225e0fc2016-11-17 17:47:59 +08004814 if (cracked.gather) {
4815 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4816 if (bias || cracked.lod ||
4817 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4818 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004819 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004820 }
4821 }
4822#endif
4823
John Kessenichfc51d282015-08-19 13:34:18 -06004824 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004825
John Kessenichfc51d282015-08-19 13:34:18 -06004826 params.coords = arguments[1];
4827 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004828 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004829
4830 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004831 if (cubeCompare || f16ShadowCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06004832 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004833 ++extraArgs;
4834 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004835 params.Dref = arguments[2];
4836 ++extraArgs;
4837 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004838 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004839 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004840 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004841 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004842 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004843 dRefComp = builder.getNumComponents(params.coords) - 1;
4844 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004845 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4846 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004847
4848 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004849 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004850 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004851 ++extraArgs;
John Kessenichb9197c82019-08-11 07:41:45 -06004852 } else if (glslangIntermediate->getStage() != EShLangFragment &&
4853 !(glslangIntermediate->getStage() == EShLangCompute &&
4854 glslangIntermediate->hasLayoutDerivativeModeNone())) {
John Kessenich019f08f2016-02-15 15:40:42 -07004855 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4856 noImplicitLod = true;
4857 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004858
4859 // multisample
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004860 if (sampler.isMultiSample()) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004861 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004862 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004863 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004864
4865 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004866 if (cracked.grad) {
4867 params.gradX = arguments[2 + extraArgs];
4868 params.gradY = arguments[3 + extraArgs];
4869 extraArgs += 2;
4870 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004871
4872 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004873 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004874 params.offset = arguments[2 + extraArgs];
4875 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004876 } else if (cracked.offsets) {
4877 params.offsets = arguments[2 + extraArgs];
4878 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004879 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004880
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004881#ifndef GLSLANG_WEB
John Kessenich76d4dfc2016-06-16 12:43:23 -06004882 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004883 if (cracked.lodClamp) {
4884 params.lodClamp = arguments[2 + extraArgs];
4885 ++extraArgs;
4886 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004887 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004888 if (sparse) {
4889 params.texelOut = arguments[2 + extraArgs];
4890 ++extraArgs;
4891 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004892 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004893 if (cracked.gather && ! sampler.shadow) {
4894 // default component is 0, if missing, otherwise an argument
4895 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004896 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004897 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004898 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004899 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004900 }
Chao Chen3a137962018-09-19 11:41:27 -07004901 spv::Id resultStruct = spv::NoResult;
4902 if (imageFootprint) {
4903 //Following three extra arguments
4904 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4905 params.granularity = arguments[2 + extraArgs];
4906 params.coarse = arguments[3 + extraArgs];
4907 resultStruct = arguments[4 + extraArgs];
4908 extraArgs += 3;
4909 }
4910#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004911 // bias
4912 if (bias) {
4913 params.bias = arguments[2 + extraArgs];
4914 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004915 }
John Kessenichfc51d282015-08-19 13:34:18 -06004916
John Kessenicha28f7a72019-08-06 07:00:58 -06004917#ifndef GLSLANG_WEB
Chao Chen3a137962018-09-19 11:41:27 -07004918 if (imageFootprint) {
4919 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
4920 builder.addCapability(spv::CapabilityImageFootprintNV);
4921
4922
4923 //resultStructType(OpenGL type) contains 5 elements:
4924 //struct gl_TextureFootprint2DNV {
4925 // uvec2 anchor;
4926 // uvec2 offset;
4927 // uvec2 mask;
4928 // uint lod;
4929 // uint granularity;
4930 //};
4931 //or
4932 //struct gl_TextureFootprint3DNV {
4933 // uvec3 anchor;
4934 // uvec3 offset;
4935 // uvec2 mask;
4936 // uint lod;
4937 // uint granularity;
4938 //};
4939 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
4940 assert(builder.isStructType(resultStructType));
4941
4942 //resType (SPIR-V type) contains 6 elements:
4943 //Member 0 must be a Boolean type scalar(LOD),
4944 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
4945 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
4946 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
4947 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
4948 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
4949 std::vector<spv::Id> members;
4950 members.push_back(resultType());
4951 for (int i = 0; i < 5; i++) {
4952 members.push_back(builder.getContainedTypeId(resultStructType, i));
4953 }
4954 spv::Id resType = builder.makeStructType(members, "ResType");
4955
4956 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06004957 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
4958 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07004959
4960 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
4961 for (int i = 0; i < 5; i++) {
4962 builder.clearAccessChain();
4963 builder.setAccessChainLValue(resultStruct);
4964
4965 //Accessing to a struct we created, no coherent flag is set
4966 spv::Builder::AccessChain::CoherentFlags flags;
4967 flags.clear();
4968
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004969 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
Chao Chen3a137962018-09-19 11:41:27 -07004970 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1), i+1));
4971 }
4972 return builder.createCompositeExtract(res, resultType(), 0);
4973 }
4974#endif
4975
John Kessenich65336482016-06-16 14:06:26 -06004976 // projective component (might not to move)
4977 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4978 // are divided by the last component of P."
4979 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4980 // unused components will appear after all used components."
4981 if (cracked.proj) {
4982 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4983 int projTargetComp;
4984 switch (sampler.dim) {
4985 case glslang::Esd1D: projTargetComp = 1; break;
4986 case glslang::Esd2D: projTargetComp = 2; break;
4987 case glslang::EsdRect: projTargetComp = 2; break;
4988 default: projTargetComp = projSourceComp; break;
4989 }
4990 // copy the projective coordinate if we have to
4991 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004992 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004993 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4994 projSourceComp);
4995 params.coords = builder.createCompositeInsert(projComp, params.coords,
4996 builder.getTypeId(params.coords), projTargetComp);
4997 }
4998 }
4999
John Kessenichf8d1d742019-10-21 06:55:11 -06005000#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -05005001 // nonprivate
5002 if (imageType.getQualifier().nonprivate) {
5003 params.nonprivate = true;
5004 }
5005
5006 // volatile
5007 if (imageType.getQualifier().volatil) {
5008 params.volatil = true;
5009 }
John Kessenichf8d1d742019-10-21 06:55:11 -06005010#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05005011
St0fFa1184dd2018-04-09 21:08:14 +02005012 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06005013 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
5014 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02005015 );
LoopDawg4425f242018-02-18 11:40:01 -07005016
5017 if (components != node->getType().getVectorSize())
5018 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
5019
5020 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06005021}
5022
5023spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
5024{
5025 // Grab the function's pointer from the previously created function
5026 spv::Function* function = functionMap[node->getName().c_str()];
5027 if (! function)
5028 return 0;
5029
5030 const glslang::TIntermSequence& glslangArgs = node->getSequence();
5031 const glslang::TQualifierList& qualifiers = node->getQualifierList();
5032
5033 // See comments in makeFunctions() for details about the semantics for parameter passing.
5034 //
5035 // These imply we need a four step process:
5036 // 1. Evaluate the arguments
5037 // 2. Allocate and make copies of in, out, and inout arguments
5038 // 3. Make the call
5039 // 4. Copy back the results
5040
John Kessenichd3ed90b2018-05-04 11:43:03 -06005041 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06005042 std::vector<spv::Builder::AccessChain> lValues;
5043 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07005044 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06005045 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005046 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06005047 // build l-value
5048 builder.clearAccessChain();
5049 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06005050 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06005051 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07005052 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005053 // save l-value
5054 lValues.push_back(builder.getAccessChain());
5055 } else {
5056 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07005057 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06005058 }
5059 }
5060
5061 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
5062 // copy the original into that space.
5063 //
5064 // Also, build up the list of actual arguments to pass in for the call
5065 int lValueCount = 0;
5066 int rValueCount = 0;
5067 std::vector<spv::Id> spvArgs;
5068 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
5069 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06005070 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07005071 builder.setAccessChain(lValues[lValueCount]);
5072 arg = builder.accessChainGetLValue();
5073 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06005074 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005075 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06005076 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06005077 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
5078 // need to copy the input into output space
5079 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07005080 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06005081 builder.clearAccessChain();
5082 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005083 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005084 }
5085 ++lValueCount;
5086 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005087 // process r-value, which involves a copy for a type mismatch
5088 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
5089 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
5090 builder.clearAccessChain();
5091 builder.setAccessChainLValue(argCopy);
5092 multiTypeStore(*argTypes[a], rValues[rValueCount]);
5093 arg = builder.createLoad(argCopy);
5094 } else
5095 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005096 ++rValueCount;
5097 }
5098 spvArgs.push_back(arg);
5099 }
5100
5101 // 3. Make the call.
5102 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005103 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06005104
5105 // 4. Copy back out an "out" arguments.
5106 lValueCount = 0;
5107 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005108 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005109 ++lValueCount;
5110 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005111 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
5112 spv::Id copy = builder.createLoad(spvArgs[a]);
5113 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005114 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005115 }
5116 ++lValueCount;
5117 }
5118 }
5119
5120 return result;
5121}
5122
5123// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005124spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005125 spv::Id typeId, spv::Id left, spv::Id right,
5126 glslang::TBasicType typeProxy, bool reduceComparison)
5127{
John Kessenich66011cb2018-03-06 16:12:04 -07005128 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5129 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005130 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005131
5132 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005133 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005134 bool comparison = false;
5135
5136 switch (op) {
5137 case glslang::EOpAdd:
5138 case glslang::EOpAddAssign:
5139 if (isFloat)
5140 binOp = spv::OpFAdd;
5141 else
5142 binOp = spv::OpIAdd;
5143 break;
5144 case glslang::EOpSub:
5145 case glslang::EOpSubAssign:
5146 if (isFloat)
5147 binOp = spv::OpFSub;
5148 else
5149 binOp = spv::OpISub;
5150 break;
5151 case glslang::EOpMul:
5152 case glslang::EOpMulAssign:
5153 if (isFloat)
5154 binOp = spv::OpFMul;
5155 else
5156 binOp = spv::OpIMul;
5157 break;
5158 case glslang::EOpVectorTimesScalar:
5159 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005160 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005161 if (builder.isVector(right))
5162 std::swap(left, right);
5163 assert(builder.isScalar(right));
5164 needMatchingVectors = false;
5165 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005166 } else if (isFloat)
5167 binOp = spv::OpFMul;
5168 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005169 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005170 break;
5171 case glslang::EOpVectorTimesMatrix:
5172 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005173 binOp = spv::OpVectorTimesMatrix;
5174 break;
5175 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005176 binOp = spv::OpMatrixTimesVector;
5177 break;
5178 case glslang::EOpMatrixTimesScalar:
5179 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005180 binOp = spv::OpMatrixTimesScalar;
5181 break;
5182 case glslang::EOpMatrixTimesMatrix:
5183 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005184 binOp = spv::OpMatrixTimesMatrix;
5185 break;
5186 case glslang::EOpOuterProduct:
5187 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005188 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005189 break;
5190
5191 case glslang::EOpDiv:
5192 case glslang::EOpDivAssign:
5193 if (isFloat)
5194 binOp = spv::OpFDiv;
5195 else if (isUnsigned)
5196 binOp = spv::OpUDiv;
5197 else
5198 binOp = spv::OpSDiv;
5199 break;
5200 case glslang::EOpMod:
5201 case glslang::EOpModAssign:
5202 if (isFloat)
5203 binOp = spv::OpFMod;
5204 else if (isUnsigned)
5205 binOp = spv::OpUMod;
5206 else
5207 binOp = spv::OpSMod;
5208 break;
5209 case glslang::EOpRightShift:
5210 case glslang::EOpRightShiftAssign:
5211 if (isUnsigned)
5212 binOp = spv::OpShiftRightLogical;
5213 else
5214 binOp = spv::OpShiftRightArithmetic;
5215 break;
5216 case glslang::EOpLeftShift:
5217 case glslang::EOpLeftShiftAssign:
5218 binOp = spv::OpShiftLeftLogical;
5219 break;
5220 case glslang::EOpAnd:
5221 case glslang::EOpAndAssign:
5222 binOp = spv::OpBitwiseAnd;
5223 break;
5224 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005225 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005226 binOp = spv::OpLogicalAnd;
5227 break;
5228 case glslang::EOpInclusiveOr:
5229 case glslang::EOpInclusiveOrAssign:
5230 binOp = spv::OpBitwiseOr;
5231 break;
5232 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005233 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005234 binOp = spv::OpLogicalOr;
5235 break;
5236 case glslang::EOpExclusiveOr:
5237 case glslang::EOpExclusiveOrAssign:
5238 binOp = spv::OpBitwiseXor;
5239 break;
5240 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005241 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005242 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005243 break;
5244
Ian Romanickb3bd4022019-01-21 08:57:25 -08005245 case glslang::EOpAbsDifference:
5246 binOp = isUnsigned ? spv::OpAbsUSubINTEL : spv::OpAbsISubINTEL;
5247 break;
5248
5249 case glslang::EOpAddSaturate:
5250 binOp = isUnsigned ? spv::OpUAddSatINTEL : spv::OpIAddSatINTEL;
5251 break;
5252
5253 case glslang::EOpSubSaturate:
5254 binOp = isUnsigned ? spv::OpUSubSatINTEL : spv::OpISubSatINTEL;
5255 break;
5256
5257 case glslang::EOpAverage:
5258 binOp = isUnsigned ? spv::OpUAverageINTEL : spv::OpIAverageINTEL;
5259 break;
5260
5261 case glslang::EOpAverageRounded:
5262 binOp = isUnsigned ? spv::OpUAverageRoundedINTEL : spv::OpIAverageRoundedINTEL;
5263 break;
5264
5265 case glslang::EOpMul32x16:
5266 binOp = isUnsigned ? spv::OpUMul32x16INTEL : spv::OpIMul32x16INTEL;
5267 break;
5268
John Kessenich140f3df2015-06-26 16:58:36 -06005269 case glslang::EOpLessThan:
5270 case glslang::EOpGreaterThan:
5271 case glslang::EOpLessThanEqual:
5272 case glslang::EOpGreaterThanEqual:
5273 case glslang::EOpEqual:
5274 case glslang::EOpNotEqual:
5275 case glslang::EOpVectorEqual:
5276 case glslang::EOpVectorNotEqual:
5277 comparison = true;
5278 break;
5279 default:
5280 break;
5281 }
5282
John Kessenich7c1aa102015-10-15 13:29:11 -06005283 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005284 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005285 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005286 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5287 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005288 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005289
5290 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005291 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005292 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005293
qining25262b32016-05-06 17:25:16 -04005294 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005295 decorations.addNoContraction(builder, result);
5296 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005297 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005298 }
5299
5300 if (! comparison)
5301 return 0;
5302
John Kessenich7c1aa102015-10-15 13:29:11 -06005303 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005304
John Kessenich4583b612016-08-07 19:14:22 -06005305 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005306 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5307 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenichb9197c82019-08-11 07:41:45 -06005308 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005309 return result;
5310 }
John Kessenich140f3df2015-06-26 16:58:36 -06005311
5312 switch (op) {
5313 case glslang::EOpLessThan:
5314 if (isFloat)
5315 binOp = spv::OpFOrdLessThan;
5316 else if (isUnsigned)
5317 binOp = spv::OpULessThan;
5318 else
5319 binOp = spv::OpSLessThan;
5320 break;
5321 case glslang::EOpGreaterThan:
5322 if (isFloat)
5323 binOp = spv::OpFOrdGreaterThan;
5324 else if (isUnsigned)
5325 binOp = spv::OpUGreaterThan;
5326 else
5327 binOp = spv::OpSGreaterThan;
5328 break;
5329 case glslang::EOpLessThanEqual:
5330 if (isFloat)
5331 binOp = spv::OpFOrdLessThanEqual;
5332 else if (isUnsigned)
5333 binOp = spv::OpULessThanEqual;
5334 else
5335 binOp = spv::OpSLessThanEqual;
5336 break;
5337 case glslang::EOpGreaterThanEqual:
5338 if (isFloat)
5339 binOp = spv::OpFOrdGreaterThanEqual;
5340 else if (isUnsigned)
5341 binOp = spv::OpUGreaterThanEqual;
5342 else
5343 binOp = spv::OpSGreaterThanEqual;
5344 break;
5345 case glslang::EOpEqual:
5346 case glslang::EOpVectorEqual:
5347 if (isFloat)
5348 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005349 else if (isBool)
5350 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005351 else
5352 binOp = spv::OpIEqual;
5353 break;
5354 case glslang::EOpNotEqual:
5355 case glslang::EOpVectorNotEqual:
5356 if (isFloat)
5357 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005358 else if (isBool)
5359 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005360 else
5361 binOp = spv::OpINotEqual;
5362 break;
5363 default:
5364 break;
5365 }
5366
qining25262b32016-05-06 17:25:16 -04005367 if (binOp != spv::OpNop) {
5368 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005369 decorations.addNoContraction(builder, result);
5370 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005371 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005372 }
John Kessenich140f3df2015-06-26 16:58:36 -06005373
5374 return 0;
5375}
5376
John Kessenich04bb8a02015-12-12 12:28:14 -07005377//
5378// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5379// These can be any of:
5380//
5381// matrix * scalar
5382// scalar * matrix
5383// matrix * matrix linear algebraic
5384// matrix * vector
5385// vector * matrix
5386// matrix * matrix componentwise
5387// matrix op matrix op in {+, -, /}
5388// matrix op scalar op in {+, -, /}
5389// scalar op matrix op in {+, -, /}
5390//
John Kessenichead86222018-03-28 18:01:20 -06005391spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5392 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005393{
5394 bool firstClass = true;
5395
5396 // First, handle first-class matrix operations (* and matrix/scalar)
5397 switch (op) {
5398 case spv::OpFDiv:
5399 if (builder.isMatrix(left) && builder.isScalar(right)) {
5400 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005401 spv::Id resultType = builder.getTypeId(right);
5402 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005403 op = spv::OpMatrixTimesScalar;
5404 } else
5405 firstClass = false;
5406 break;
5407 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005408 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005409 std::swap(left, right);
5410 assert(builder.isScalar(right));
5411 break;
5412 case spv::OpVectorTimesMatrix:
5413 assert(builder.isVector(left));
5414 assert(builder.isMatrix(right));
5415 break;
5416 case spv::OpMatrixTimesVector:
5417 assert(builder.isMatrix(left));
5418 assert(builder.isVector(right));
5419 break;
5420 case spv::OpMatrixTimesMatrix:
5421 assert(builder.isMatrix(left));
5422 assert(builder.isMatrix(right));
5423 break;
5424 default:
5425 firstClass = false;
5426 break;
5427 }
5428
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005429 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5430 firstClass = true;
5431
qining25262b32016-05-06 17:25:16 -04005432 if (firstClass) {
5433 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005434 decorations.addNoContraction(builder, result);
5435 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005436 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005437 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005438
LoopDawg592860c2016-06-09 08:57:35 -06005439 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005440 // The result type of all of them is the same type as the (a) matrix operand.
5441 // The algorithm is to:
5442 // - break the matrix(es) into vectors
5443 // - smear any scalar to a vector
5444 // - do vector operations
5445 // - make a matrix out the vector results
5446 switch (op) {
5447 case spv::OpFAdd:
5448 case spv::OpFSub:
5449 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005450 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005451 case spv::OpFMul:
5452 {
5453 // one time set up...
5454 bool leftMat = builder.isMatrix(left);
5455 bool rightMat = builder.isMatrix(right);
5456 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5457 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5458 spv::Id scalarType = builder.getScalarTypeId(typeId);
5459 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5460 std::vector<spv::Id> results;
5461 spv::Id smearVec = spv::NoResult;
5462 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005463 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005464 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005465 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005466
5467 // do each vector op
5468 for (unsigned int c = 0; c < numCols; ++c) {
5469 std::vector<unsigned int> indexes;
5470 indexes.push_back(c);
5471 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5472 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005473 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005474 decorations.addNoContraction(builder, result);
5475 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005476 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005477 }
5478
5479 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005480 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005481 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005482 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005483 }
5484 default:
5485 assert(0);
5486 return spv::NoResult;
5487 }
5488}
5489
John Kessenichead86222018-03-28 18:01:20 -06005490spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005491 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005492{
5493 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005494 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005495 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005496 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5497 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005498
5499 switch (op) {
5500 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005501 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005502 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005503 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005504 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005505 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005506 unaryOp = spv::OpSNegate;
5507 break;
5508
5509 case glslang::EOpLogicalNot:
5510 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005511 unaryOp = spv::OpLogicalNot;
5512 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005513 case glslang::EOpBitwiseNot:
5514 unaryOp = spv::OpNot;
5515 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005516
John Kessenich140f3df2015-06-26 16:58:36 -06005517 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005518 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005519 break;
5520 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005521 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005522 break;
5523 case glslang::EOpTranspose:
5524 unaryOp = spv::OpTranspose;
5525 break;
5526
5527 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005528 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005529 break;
5530 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005531 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005532 break;
5533 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005534 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005535 break;
5536 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005537 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005538 break;
5539 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005540 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005541 break;
5542 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005543 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005544 break;
5545 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005546 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005547 break;
5548 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005549 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005550 break;
5551
5552 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005553 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005554 break;
5555 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005556 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005557 break;
5558 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005559 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005560 break;
5561 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005562 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005563 break;
5564 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005565 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005566 break;
5567 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005568 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005569 break;
5570
5571 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005572 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005573 break;
5574 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005575 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005576 break;
5577
5578 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005579 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005580 break;
5581 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005582 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005583 break;
5584 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005585 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005586 break;
5587 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005588 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005589 break;
5590 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005591 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005592 break;
5593 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005594 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005595 break;
5596
5597 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005598 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005599 break;
5600 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005601 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005602 break;
5603 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005604 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005605 break;
5606 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005607 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005608 break;
5609 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005610 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005611 break;
5612 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005613 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005614 break;
5615
5616 case glslang::EOpIsNan:
5617 unaryOp = spv::OpIsNan;
5618 break;
5619 case glslang::EOpIsInf:
5620 unaryOp = spv::OpIsInf;
5621 break;
LoopDawg592860c2016-06-09 08:57:35 -06005622 case glslang::EOpIsFinite:
5623 unaryOp = spv::OpIsFinite;
5624 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005625
Rex Xucbc426e2015-12-15 16:03:10 +08005626 case glslang::EOpFloatBitsToInt:
5627 case glslang::EOpFloatBitsToUint:
5628 case glslang::EOpIntBitsToFloat:
5629 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005630 case glslang::EOpDoubleBitsToInt64:
5631 case glslang::EOpDoubleBitsToUint64:
5632 case glslang::EOpInt64BitsToDouble:
5633 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005634 case glslang::EOpFloat16BitsToInt16:
5635 case glslang::EOpFloat16BitsToUint16:
5636 case glslang::EOpInt16BitsToFloat16:
5637 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005638 unaryOp = spv::OpBitcast;
5639 break;
5640
John Kessenich140f3df2015-06-26 16:58:36 -06005641 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005642 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005643 break;
5644 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005645 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005646 break;
5647 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005648 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005649 break;
5650 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005651 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005652 break;
5653 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005654 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005655 break;
5656 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005657 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005658 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005659#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06005660 case glslang::EOpPackSnorm4x8:
5661 libCall = spv::GLSLstd450PackSnorm4x8;
5662 break;
5663 case glslang::EOpUnpackSnorm4x8:
5664 libCall = spv::GLSLstd450UnpackSnorm4x8;
5665 break;
5666 case glslang::EOpPackUnorm4x8:
5667 libCall = spv::GLSLstd450PackUnorm4x8;
5668 break;
5669 case glslang::EOpUnpackUnorm4x8:
5670 libCall = spv::GLSLstd450UnpackUnorm4x8;
5671 break;
5672 case glslang::EOpPackDouble2x32:
5673 libCall = spv::GLSLstd450PackDouble2x32;
5674 break;
5675 case glslang::EOpUnpackDouble2x32:
5676 libCall = spv::GLSLstd450UnpackDouble2x32;
5677 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005678#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005679
Rex Xu8ff43de2016-04-22 16:51:45 +08005680 case glslang::EOpPackInt2x32:
5681 case glslang::EOpUnpackInt2x32:
5682 case glslang::EOpPackUint2x32:
5683 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005684 case glslang::EOpPack16:
5685 case glslang::EOpPack32:
5686 case glslang::EOpPack64:
5687 case glslang::EOpUnpack32:
5688 case glslang::EOpUnpack16:
5689 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005690 case glslang::EOpPackInt2x16:
5691 case glslang::EOpUnpackInt2x16:
5692 case glslang::EOpPackUint2x16:
5693 case glslang::EOpUnpackUint2x16:
5694 case glslang::EOpPackInt4x16:
5695 case glslang::EOpUnpackInt4x16:
5696 case glslang::EOpPackUint4x16:
5697 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005698 case glslang::EOpPackFloat2x16:
5699 case glslang::EOpUnpackFloat2x16:
5700 unaryOp = spv::OpBitcast;
5701 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005702
John Kessenich140f3df2015-06-26 16:58:36 -06005703 case glslang::EOpDPdx:
5704 unaryOp = spv::OpDPdx;
5705 break;
5706 case glslang::EOpDPdy:
5707 unaryOp = spv::OpDPdy;
5708 break;
5709 case glslang::EOpFwidth:
5710 unaryOp = spv::OpFwidth;
5711 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005712
John Kessenich140f3df2015-06-26 16:58:36 -06005713 case glslang::EOpAny:
5714 unaryOp = spv::OpAny;
5715 break;
5716 case glslang::EOpAll:
5717 unaryOp = spv::OpAll;
5718 break;
5719
5720 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005721 if (isFloat)
5722 libCall = spv::GLSLstd450FAbs;
5723 else
5724 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005725 break;
5726 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005727 if (isFloat)
5728 libCall = spv::GLSLstd450FSign;
5729 else
5730 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005731 break;
5732
John Kessenicha28f7a72019-08-06 07:00:58 -06005733#ifndef GLSLANG_WEB
5734 case glslang::EOpDPdxFine:
5735 unaryOp = spv::OpDPdxFine;
5736 break;
5737 case glslang::EOpDPdyFine:
5738 unaryOp = spv::OpDPdyFine;
5739 break;
5740 case glslang::EOpFwidthFine:
5741 unaryOp = spv::OpFwidthFine;
5742 break;
5743 case glslang::EOpDPdxCoarse:
5744 unaryOp = spv::OpDPdxCoarse;
5745 break;
5746 case glslang::EOpDPdyCoarse:
5747 unaryOp = spv::OpDPdyCoarse;
5748 break;
5749 case glslang::EOpFwidthCoarse:
5750 unaryOp = spv::OpFwidthCoarse;
5751 break;
5752 case glslang::EOpInterpolateAtCentroid:
5753 if (typeProxy == glslang::EbtFloat16)
5754 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5755 libCall = spv::GLSLstd450InterpolateAtCentroid;
5756 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005757 case glslang::EOpAtomicCounterIncrement:
5758 case glslang::EOpAtomicCounterDecrement:
5759 case glslang::EOpAtomicCounter:
5760 {
5761 // Handle all of the atomics in one place, in createAtomicOperation()
5762 std::vector<spv::Id> operands;
5763 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005764 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06005765 }
5766
John Kessenichfc51d282015-08-19 13:34:18 -06005767 case glslang::EOpBitFieldReverse:
5768 unaryOp = spv::OpBitReverse;
5769 break;
5770 case glslang::EOpBitCount:
5771 unaryOp = spv::OpBitCount;
5772 break;
5773 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005774 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005775 break;
5776 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005777 if (isUnsigned)
5778 libCall = spv::GLSLstd450FindUMsb;
5779 else
5780 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005781 break;
5782
Ian Romanickb3bd4022019-01-21 08:57:25 -08005783 case glslang::EOpCountLeadingZeros:
5784 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
5785 builder.addExtension("SPV_INTEL_shader_integer_functions2");
5786 unaryOp = spv::OpUCountLeadingZerosINTEL;
5787 break;
5788
5789 case glslang::EOpCountTrailingZeros:
5790 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
5791 builder.addExtension("SPV_INTEL_shader_integer_functions2");
5792 unaryOp = spv::OpUCountTrailingZerosINTEL;
5793 break;
5794
Rex Xu574ab042016-04-14 16:53:07 +08005795 case glslang::EOpBallot:
5796 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005797 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005798 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005799 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005800 case glslang::EOpMinInvocations:
5801 case glslang::EOpMaxInvocations:
5802 case glslang::EOpAddInvocations:
5803 case glslang::EOpMinInvocationsNonUniform:
5804 case glslang::EOpMaxInvocationsNonUniform:
5805 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005806 case glslang::EOpMinInvocationsInclusiveScan:
5807 case glslang::EOpMaxInvocationsInclusiveScan:
5808 case glslang::EOpAddInvocationsInclusiveScan:
5809 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5810 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5811 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5812 case glslang::EOpMinInvocationsExclusiveScan:
5813 case glslang::EOpMaxInvocationsExclusiveScan:
5814 case glslang::EOpAddInvocationsExclusiveScan:
5815 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5816 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5817 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu51596642016-09-21 18:56:12 +08005818 {
5819 std::vector<spv::Id> operands;
5820 operands.push_back(operand);
5821 return createInvocationsOperation(op, typeId, operands, typeProxy);
5822 }
John Kessenich66011cb2018-03-06 16:12:04 -07005823 case glslang::EOpSubgroupAll:
5824 case glslang::EOpSubgroupAny:
5825 case glslang::EOpSubgroupAllEqual:
5826 case glslang::EOpSubgroupBroadcastFirst:
5827 case glslang::EOpSubgroupBallot:
5828 case glslang::EOpSubgroupInverseBallot:
5829 case glslang::EOpSubgroupBallotBitCount:
5830 case glslang::EOpSubgroupBallotInclusiveBitCount:
5831 case glslang::EOpSubgroupBallotExclusiveBitCount:
5832 case glslang::EOpSubgroupBallotFindLSB:
5833 case glslang::EOpSubgroupBallotFindMSB:
5834 case glslang::EOpSubgroupAdd:
5835 case glslang::EOpSubgroupMul:
5836 case glslang::EOpSubgroupMin:
5837 case glslang::EOpSubgroupMax:
5838 case glslang::EOpSubgroupAnd:
5839 case glslang::EOpSubgroupOr:
5840 case glslang::EOpSubgroupXor:
5841 case glslang::EOpSubgroupInclusiveAdd:
5842 case glslang::EOpSubgroupInclusiveMul:
5843 case glslang::EOpSubgroupInclusiveMin:
5844 case glslang::EOpSubgroupInclusiveMax:
5845 case glslang::EOpSubgroupInclusiveAnd:
5846 case glslang::EOpSubgroupInclusiveOr:
5847 case glslang::EOpSubgroupInclusiveXor:
5848 case glslang::EOpSubgroupExclusiveAdd:
5849 case glslang::EOpSubgroupExclusiveMul:
5850 case glslang::EOpSubgroupExclusiveMin:
5851 case glslang::EOpSubgroupExclusiveMax:
5852 case glslang::EOpSubgroupExclusiveAnd:
5853 case glslang::EOpSubgroupExclusiveOr:
5854 case glslang::EOpSubgroupExclusiveXor:
5855 case glslang::EOpSubgroupQuadSwapHorizontal:
5856 case glslang::EOpSubgroupQuadSwapVertical:
5857 case glslang::EOpSubgroupQuadSwapDiagonal: {
5858 std::vector<spv::Id> operands;
5859 operands.push_back(operand);
5860 return createSubgroupOperation(op, typeId, operands, typeProxy);
5861 }
Rex Xu9d93a232016-05-05 12:30:44 +08005862 case glslang::EOpMbcnt:
5863 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5864 libCall = spv::MbcntAMD;
5865 break;
5866
5867 case glslang::EOpCubeFaceIndex:
5868 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5869 libCall = spv::CubeFaceIndexAMD;
5870 break;
5871
5872 case glslang::EOpCubeFaceCoord:
5873 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5874 libCall = spv::CubeFaceCoordAMD;
5875 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005876 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005877 unaryOp = spv::OpGroupNonUniformPartitionNV;
5878 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005879 case glslang::EOpConstructReference:
5880 unaryOp = spv::OpBitcast;
5881 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005882#endif
Jeff Bolz88220d52019-05-08 10:24:46 -05005883
5884 case glslang::EOpCopyObject:
5885 unaryOp = spv::OpCopyObject;
5886 break;
5887
John Kessenich140f3df2015-06-26 16:58:36 -06005888 default:
5889 return 0;
5890 }
5891
5892 spv::Id id;
5893 if (libCall >= 0) {
5894 std::vector<spv::Id> args;
5895 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005896 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005897 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005898 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005899 }
John Kessenich140f3df2015-06-26 16:58:36 -06005900
John Kessenichb9197c82019-08-11 07:41:45 -06005901 decorations.addNoContraction(builder, id);
5902 decorations.addNonUniform(builder, id);
John Kessenichead86222018-03-28 18:01:20 -06005903 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005904}
5905
John Kessenich7a53f762016-01-20 11:19:27 -07005906// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005907spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5908 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005909{
5910 // Handle unary operations vector by vector.
5911 // The result type is the same type as the original type.
5912 // The algorithm is to:
5913 // - break the matrix into vectors
5914 // - apply the operation to each vector
5915 // - make a matrix out the vector results
5916
5917 // get the types sorted out
5918 int numCols = builder.getNumColumns(operand);
5919 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005920 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5921 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005922 std::vector<spv::Id> results;
5923
5924 // do each vector op
5925 for (int c = 0; c < numCols; ++c) {
5926 std::vector<unsigned int> indexes;
5927 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005928 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5929 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005930 decorations.addNoContraction(builder, destVec);
5931 decorations.addNonUniform(builder, destVec);
John Kessenichead86222018-03-28 18:01:20 -06005932 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005933 }
5934
5935 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005936 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005937 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005938 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005939}
5940
John Kessenichad7645f2018-06-04 19:11:25 -06005941// For converting integers where both the bitwidth and the signedness could
5942// change, but only do the width change here. The caller is still responsible
5943// for the signedness conversion.
5944spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005945{
John Kessenichad7645f2018-06-04 19:11:25 -06005946 // Get the result type width, based on the type to convert to.
5947 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005948 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005949 case glslang::EOpConvInt16ToUint8:
5950 case glslang::EOpConvIntToUint8:
5951 case glslang::EOpConvInt64ToUint8:
5952 case glslang::EOpConvUint16ToInt8:
5953 case glslang::EOpConvUintToInt8:
5954 case glslang::EOpConvUint64ToInt8:
5955 width = 8;
5956 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005957 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005958 case glslang::EOpConvIntToUint16:
5959 case glslang::EOpConvInt64ToUint16:
5960 case glslang::EOpConvUint8ToInt16:
5961 case glslang::EOpConvUintToInt16:
5962 case glslang::EOpConvUint64ToInt16:
5963 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005964 break;
5965 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005966 case glslang::EOpConvInt16ToUint:
5967 case glslang::EOpConvInt64ToUint:
5968 case glslang::EOpConvUint8ToInt:
5969 case glslang::EOpConvUint16ToInt:
5970 case glslang::EOpConvUint64ToInt:
5971 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005972 break;
5973 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005974 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005975 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005976 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005977 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005978 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005979 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005980 break;
5981
5982 default:
5983 assert(false && "Default missing");
5984 break;
5985 }
5986
John Kessenichad7645f2018-06-04 19:11:25 -06005987 // Get the conversion operation and result type,
5988 // based on the target width, but the source type.
5989 spv::Id type = spv::NoType;
5990 spv::Op convOp = spv::OpNop;
5991 switch(op) {
5992 case glslang::EOpConvInt8ToUint16:
5993 case glslang::EOpConvInt8ToUint:
5994 case glslang::EOpConvInt8ToUint64:
5995 case glslang::EOpConvInt16ToUint8:
5996 case glslang::EOpConvInt16ToUint:
5997 case glslang::EOpConvInt16ToUint64:
5998 case glslang::EOpConvIntToUint8:
5999 case glslang::EOpConvIntToUint16:
6000 case glslang::EOpConvIntToUint64:
6001 case glslang::EOpConvInt64ToUint8:
6002 case glslang::EOpConvInt64ToUint16:
6003 case glslang::EOpConvInt64ToUint:
6004 convOp = spv::OpSConvert;
6005 type = builder.makeIntType(width);
6006 break;
6007 default:
6008 convOp = spv::OpUConvert;
6009 type = builder.makeUintType(width);
6010 break;
6011 }
6012
John Kessenich66011cb2018-03-06 16:12:04 -07006013 if (vectorSize > 0)
6014 type = builder.makeVectorType(type, vectorSize);
6015
John Kessenichad7645f2018-06-04 19:11:25 -06006016 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006017}
6018
John Kessenichead86222018-03-28 18:01:20 -06006019spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
6020 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06006021{
6022 spv::Op convOp = spv::OpNop;
6023 spv::Id zero = 0;
6024 spv::Id one = 0;
6025
6026 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
6027
6028 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07006029 case glslang::EOpConvIntToBool:
6030 case glslang::EOpConvUintToBool:
6031 zero = builder.makeUintConstant(0);
6032 zero = makeSmearedConstant(zero, vectorSize);
6033 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006034 case glslang::EOpConvFloatToBool:
6035 zero = builder.makeFloatConstant(0.0F);
6036 zero = makeSmearedConstant(zero, vectorSize);
6037 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006038 case glslang::EOpConvBoolToFloat:
6039 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006040 zero = builder.makeFloatConstant(0.0F);
6041 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06006042 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006043
John Kessenich140f3df2015-06-26 16:58:36 -06006044 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006045 case glslang::EOpConvBoolToInt64:
John Kessenichb9197c82019-08-11 07:41:45 -06006046#ifndef GLSLANG_WEB
6047 if (op == glslang::EOpConvBoolToInt64) {
Rex Xucabbb782017-03-24 13:41:14 +08006048 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006049 one = builder.makeInt64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006050 } else
6051#endif
6052 {
6053 zero = builder.makeIntConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006054 one = builder.makeIntConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006055 }
Rex Xucabbb782017-03-24 13:41:14 +08006056
John Kessenich140f3df2015-06-26 16:58:36 -06006057 convOp = spv::OpSelect;
6058 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006059
John Kessenich140f3df2015-06-26 16:58:36 -06006060 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006061 case glslang::EOpConvBoolToUint64:
John Kessenichb9197c82019-08-11 07:41:45 -06006062#ifndef GLSLANG_WEB
6063 if (op == glslang::EOpConvBoolToUint64) {
Rex Xucabbb782017-03-24 13:41:14 +08006064 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006065 one = builder.makeUint64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006066 } else
6067#endif
6068 {
6069 zero = builder.makeUintConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006070 one = builder.makeUintConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006071 }
Rex Xucabbb782017-03-24 13:41:14 +08006072
John Kessenich140f3df2015-06-26 16:58:36 -06006073 convOp = spv::OpSelect;
6074 break;
6075
John Kessenich66011cb2018-03-06 16:12:04 -07006076 case glslang::EOpConvInt8ToFloat16:
6077 case glslang::EOpConvInt8ToFloat:
6078 case glslang::EOpConvInt8ToDouble:
6079 case glslang::EOpConvInt16ToFloat16:
6080 case glslang::EOpConvInt16ToFloat:
6081 case glslang::EOpConvInt16ToDouble:
6082 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006083 case glslang::EOpConvIntToFloat:
6084 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006085 case glslang::EOpConvInt64ToFloat:
6086 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006087 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006088 convOp = spv::OpConvertSToF;
6089 break;
6090
John Kessenich66011cb2018-03-06 16:12:04 -07006091 case glslang::EOpConvUint8ToFloat16:
6092 case glslang::EOpConvUint8ToFloat:
6093 case glslang::EOpConvUint8ToDouble:
6094 case glslang::EOpConvUint16ToFloat16:
6095 case glslang::EOpConvUint16ToFloat:
6096 case glslang::EOpConvUint16ToDouble:
6097 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006098 case glslang::EOpConvUintToFloat:
6099 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006100 case glslang::EOpConvUint64ToFloat:
6101 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006102 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006103 convOp = spv::OpConvertUToF;
6104 break;
6105
John Kessenich66011cb2018-03-06 16:12:04 -07006106 case glslang::EOpConvFloat16ToInt8:
6107 case glslang::EOpConvFloatToInt8:
6108 case glslang::EOpConvDoubleToInt8:
6109 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006110 case glslang::EOpConvFloatToInt16:
6111 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006112 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006113 case glslang::EOpConvFloatToInt:
6114 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006115 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006116 case glslang::EOpConvFloatToInt64:
6117 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006118 convOp = spv::OpConvertFToS;
6119 break;
6120
John Kessenich66011cb2018-03-06 16:12:04 -07006121 case glslang::EOpConvUint8ToInt8:
6122 case glslang::EOpConvInt8ToUint8:
6123 case glslang::EOpConvUint16ToInt16:
6124 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006125 case glslang::EOpConvUintToInt:
6126 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006127 case glslang::EOpConvUint64ToInt64:
6128 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006129 if (builder.isInSpecConstCodeGenMode()) {
6130 // Build zero scalar or vector for OpIAdd.
John Kessenich39697cd2019-08-08 10:35:51 -06006131#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07006132 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6133 zero = builder.makeUint8Constant(0);
6134 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006135 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006136 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6137 zero = builder.makeUint64Constant(0);
John Kessenich39697cd2019-08-08 10:35:51 -06006138 } else
6139#endif
6140 {
Rex Xucabbb782017-03-24 13:41:14 +08006141 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006142 }
qining189b2032016-04-12 23:16:20 -04006143 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006144 // Use OpIAdd, instead of OpBitcast to do the conversion when
6145 // generating for OpSpecConstantOp instruction.
6146 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6147 }
6148 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006149 convOp = spv::OpBitcast;
6150 break;
6151
John Kessenich66011cb2018-03-06 16:12:04 -07006152 case glslang::EOpConvFloat16ToUint8:
6153 case glslang::EOpConvFloatToUint8:
6154 case glslang::EOpConvDoubleToUint8:
6155 case glslang::EOpConvFloat16ToUint16:
6156 case glslang::EOpConvFloatToUint16:
6157 case glslang::EOpConvDoubleToUint16:
6158 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006159 case glslang::EOpConvFloatToUint:
6160 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006161 case glslang::EOpConvFloatToUint64:
6162 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006163 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006164 convOp = spv::OpConvertFToU;
6165 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006166
John Kessenich39697cd2019-08-08 10:35:51 -06006167#ifndef GLSLANG_WEB
6168 case glslang::EOpConvInt8ToBool:
6169 case glslang::EOpConvUint8ToBool:
6170 zero = builder.makeUint8Constant(0);
6171 zero = makeSmearedConstant(zero, vectorSize);
6172 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6173 case glslang::EOpConvInt16ToBool:
6174 case glslang::EOpConvUint16ToBool:
6175 zero = builder.makeUint16Constant(0);
6176 zero = makeSmearedConstant(zero, vectorSize);
6177 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6178 case glslang::EOpConvInt64ToBool:
6179 case glslang::EOpConvUint64ToBool:
6180 zero = builder.makeUint64Constant(0);
6181 zero = makeSmearedConstant(zero, vectorSize);
6182 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6183 case glslang::EOpConvDoubleToBool:
6184 zero = builder.makeDoubleConstant(0.0);
6185 zero = makeSmearedConstant(zero, vectorSize);
6186 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6187 case glslang::EOpConvFloat16ToBool:
6188 zero = builder.makeFloat16Constant(0.0F);
6189 zero = makeSmearedConstant(zero, vectorSize);
6190 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6191 case glslang::EOpConvBoolToDouble:
6192 convOp = spv::OpSelect;
6193 zero = builder.makeDoubleConstant(0.0);
6194 one = builder.makeDoubleConstant(1.0);
6195 break;
6196 case glslang::EOpConvBoolToFloat16:
6197 convOp = spv::OpSelect;
6198 zero = builder.makeFloat16Constant(0.0F);
6199 one = builder.makeFloat16Constant(1.0F);
6200 break;
6201 case glslang::EOpConvBoolToInt8:
6202 zero = builder.makeInt8Constant(0);
6203 one = builder.makeInt8Constant(1);
6204 convOp = spv::OpSelect;
6205 break;
6206 case glslang::EOpConvBoolToUint8:
6207 zero = builder.makeUint8Constant(0);
6208 one = builder.makeUint8Constant(1);
6209 convOp = spv::OpSelect;
6210 break;
6211 case glslang::EOpConvBoolToInt16:
6212 zero = builder.makeInt16Constant(0);
6213 one = builder.makeInt16Constant(1);
6214 convOp = spv::OpSelect;
6215 break;
6216 case glslang::EOpConvBoolToUint16:
6217 zero = builder.makeUint16Constant(0);
6218 one = builder.makeUint16Constant(1);
6219 convOp = spv::OpSelect;
6220 break;
6221 case glslang::EOpConvDoubleToFloat:
6222 case glslang::EOpConvFloatToDouble:
6223 case glslang::EOpConvDoubleToFloat16:
6224 case glslang::EOpConvFloat16ToDouble:
6225 case glslang::EOpConvFloatToFloat16:
6226 case glslang::EOpConvFloat16ToFloat:
6227 convOp = spv::OpFConvert;
6228 if (builder.isMatrixType(destType))
6229 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
6230 break;
6231
John Kessenich66011cb2018-03-06 16:12:04 -07006232 case glslang::EOpConvInt8ToInt16:
6233 case glslang::EOpConvInt8ToInt:
6234 case glslang::EOpConvInt8ToInt64:
6235 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006236 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006237 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006238 case glslang::EOpConvIntToInt8:
6239 case glslang::EOpConvIntToInt16:
6240 case glslang::EOpConvIntToInt64:
6241 case glslang::EOpConvInt64ToInt8:
6242 case glslang::EOpConvInt64ToInt16:
6243 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006244 convOp = spv::OpSConvert;
6245 break;
6246
John Kessenich66011cb2018-03-06 16:12:04 -07006247 case glslang::EOpConvUint8ToUint16:
6248 case glslang::EOpConvUint8ToUint:
6249 case glslang::EOpConvUint8ToUint64:
6250 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006251 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006252 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006253 case glslang::EOpConvUintToUint8:
6254 case glslang::EOpConvUintToUint16:
6255 case glslang::EOpConvUintToUint64:
6256 case glslang::EOpConvUint64ToUint8:
6257 case glslang::EOpConvUint64ToUint16:
6258 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006259 convOp = spv::OpUConvert;
6260 break;
6261
John Kessenich66011cb2018-03-06 16:12:04 -07006262 case glslang::EOpConvInt8ToUint16:
6263 case glslang::EOpConvInt8ToUint:
6264 case glslang::EOpConvInt8ToUint64:
6265 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006266 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006267 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006268 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006269 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006270 case glslang::EOpConvIntToUint64:
6271 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006272 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006273 case glslang::EOpConvInt64ToUint:
6274 case glslang::EOpConvUint8ToInt16:
6275 case glslang::EOpConvUint8ToInt:
6276 case glslang::EOpConvUint8ToInt64:
6277 case glslang::EOpConvUint16ToInt8:
6278 case glslang::EOpConvUint16ToInt:
6279 case glslang::EOpConvUint16ToInt64:
6280 case glslang::EOpConvUintToInt8:
6281 case glslang::EOpConvUintToInt16:
6282 case glslang::EOpConvUintToInt64:
6283 case glslang::EOpConvUint64ToInt8:
6284 case glslang::EOpConvUint64ToInt16:
6285 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006286 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006287 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006288
6289 if (builder.isInSpecConstCodeGenMode()) {
6290 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006291 switch(op) {
6292 case glslang::EOpConvInt16ToUint8:
6293 case glslang::EOpConvIntToUint8:
6294 case glslang::EOpConvInt64ToUint8:
6295 case glslang::EOpConvUint16ToInt8:
6296 case glslang::EOpConvUintToInt8:
6297 case glslang::EOpConvUint64ToInt8:
6298 zero = builder.makeUint8Constant(0);
6299 break;
6300 case glslang::EOpConvInt8ToUint16:
6301 case glslang::EOpConvIntToUint16:
6302 case glslang::EOpConvInt64ToUint16:
6303 case glslang::EOpConvUint8ToInt16:
6304 case glslang::EOpConvUintToInt16:
6305 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006306 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006307 break;
6308 case glslang::EOpConvInt8ToUint:
6309 case glslang::EOpConvInt16ToUint:
6310 case glslang::EOpConvInt64ToUint:
6311 case glslang::EOpConvUint8ToInt:
6312 case glslang::EOpConvUint16ToInt:
6313 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006314 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006315 break;
6316 case glslang::EOpConvInt8ToUint64:
6317 case glslang::EOpConvInt16ToUint64:
6318 case glslang::EOpConvIntToUint64:
6319 case glslang::EOpConvUint8ToInt64:
6320 case glslang::EOpConvUint16ToInt64:
6321 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006322 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006323 break;
6324 default:
6325 assert(false && "Default missing");
6326 break;
6327 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006328 zero = makeSmearedConstant(zero, vectorSize);
6329 // Use OpIAdd, instead of OpBitcast to do the conversion when
6330 // generating for OpSpecConstantOp instruction.
6331 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6332 }
6333 // For normal run-time conversion instruction, use OpBitcast.
6334 convOp = spv::OpBitcast;
6335 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006336 case glslang::EOpConvUint64ToPtr:
6337 convOp = spv::OpConvertUToPtr;
6338 break;
6339 case glslang::EOpConvPtrToUint64:
6340 convOp = spv::OpConvertPtrToU;
6341 break;
John Kessenich90e402f2019-09-17 23:19:38 -06006342 case glslang::EOpConvPtrToUvec2:
6343 case glslang::EOpConvUvec2ToPtr:
John Kessenichee8e9c12019-10-10 20:54:21 -06006344 if (builder.isVector(operand))
6345 builder.promoteIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer,
6346 spv::E_SPV_KHR_physical_storage_buffer, spv::Spv_1_5);
John Kessenich90e402f2019-09-17 23:19:38 -06006347 convOp = spv::OpBitcast;
6348 break;
John Kessenich39697cd2019-08-08 10:35:51 -06006349#endif
6350
John Kessenich140f3df2015-06-26 16:58:36 -06006351 default:
6352 break;
6353 }
6354
6355 spv::Id result = 0;
6356 if (convOp == spv::OpNop)
6357 return result;
6358
6359 if (convOp == spv::OpSelect) {
6360 zero = makeSmearedConstant(zero, vectorSize);
6361 one = makeSmearedConstant(one, vectorSize);
6362 result = builder.createTriOp(convOp, destType, operand, one, zero);
6363 } else
6364 result = builder.createUnaryOp(convOp, destType, operand);
6365
John Kessenichead86222018-03-28 18:01:20 -06006366 result = builder.setPrecision(result, decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006367 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006368 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006369}
6370
6371spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6372{
6373 if (vectorSize == 0)
6374 return constant;
6375
6376 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6377 std::vector<spv::Id> components;
6378 for (int c = 0; c < vectorSize; ++c)
6379 components.push_back(constant);
6380 return builder.makeCompositeConstant(vectorTypeId, components);
6381}
6382
John Kessenich426394d2015-07-23 10:22:48 -06006383// For glslang ops that map to SPV atomic opCodes
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006384spv::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 -06006385{
6386 spv::Op opCode = spv::OpNop;
6387
6388 switch (op) {
6389 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006390 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006391 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006392 opCode = spv::OpAtomicIAdd;
6393 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006394 case glslang::EOpAtomicCounterSubtract:
6395 opCode = spv::OpAtomicISub;
6396 break;
John Kessenich426394d2015-07-23 10:22:48 -06006397 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006398 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006399 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08006400 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006401 break;
6402 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006403 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006404 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08006405 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006406 break;
6407 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006408 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006409 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006410 opCode = spv::OpAtomicAnd;
6411 break;
6412 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006413 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006414 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006415 opCode = spv::OpAtomicOr;
6416 break;
6417 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006418 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006419 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006420 opCode = spv::OpAtomicXor;
6421 break;
6422 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006423 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006424 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006425 opCode = spv::OpAtomicExchange;
6426 break;
6427 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006428 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006429 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006430 opCode = spv::OpAtomicCompareExchange;
6431 break;
6432 case glslang::EOpAtomicCounterIncrement:
6433 opCode = spv::OpAtomicIIncrement;
6434 break;
6435 case glslang::EOpAtomicCounterDecrement:
6436 opCode = spv::OpAtomicIDecrement;
6437 break;
6438 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006439 case glslang::EOpImageAtomicLoad:
6440 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006441 opCode = spv::OpAtomicLoad;
6442 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006443 case glslang::EOpAtomicStore:
6444 case glslang::EOpImageAtomicStore:
6445 opCode = spv::OpAtomicStore;
6446 break;
John Kessenich426394d2015-07-23 10:22:48 -06006447 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006448 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006449 break;
6450 }
6451
Rex Xue8fe8b02017-09-26 15:42:56 +08006452 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6453 builder.addCapability(spv::CapabilityInt64Atomics);
6454
John Kessenich426394d2015-07-23 10:22:48 -06006455 // Sort out the operands
6456 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006457 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006458 // - compare-exchange swaps the value and comparator
6459 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006460 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006461 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6462 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6463 spv::Id scopeId;
6464 if (glslangIntermediate->usingVulkanMemoryModel()) {
6465 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6466 } else {
6467 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6468 }
6469 // semantics default to relaxed
Jeff Bolz016ddee2019-10-17 11:22:57 -05006470 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.isVolatile() && glslangIntermediate->usingVulkanMemoryModel() ?
John Kessenichb9197c82019-08-11 07:41:45 -06006471 spv::MemorySemanticsVolatileMask :
6472 spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006473 spv::Id semanticsId2 = semanticsId;
6474
6475 pointerId = operands[0];
6476 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6477 // no additional operands
6478 } else if (opCode == spv::OpAtomicCompareExchange) {
6479 compareId = operands[1];
6480 valueId = operands[2];
6481 if (operands.size() > 3) {
6482 scopeId = operands[3];
6483 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6484 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
6485 }
6486 } else if (opCode == spv::OpAtomicLoad) {
6487 if (operands.size() > 1) {
6488 scopeId = operands[1];
6489 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
6490 }
6491 } else {
6492 // atomic store or RMW
6493 valueId = operands[1];
6494 if (operands.size() > 2) {
6495 scopeId = operands[2];
6496 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
6497 }
Rex Xu04db3f52015-09-16 11:44:02 +08006498 }
John Kessenich426394d2015-07-23 10:22:48 -06006499
Jeff Bolz36831c92018-09-05 10:11:41 -05006500 // Check for capabilities
6501 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006502 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6503 spv::MemorySemanticsMakeVisibleKHRMask |
6504 spv::MemorySemanticsOutputMemoryKHRMask |
6505 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006506 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6507 }
John Kessenich426394d2015-07-23 10:22:48 -06006508
Jeff Bolz36831c92018-09-05 10:11:41 -05006509 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6510 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6511 }
John Kessenich48d6e792017-10-06 21:21:48 -06006512
Jeff Bolz36831c92018-09-05 10:11:41 -05006513 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6514 spvAtomicOperands.push_back(pointerId);
6515 spvAtomicOperands.push_back(scopeId);
6516 spvAtomicOperands.push_back(semanticsId);
6517 if (opCode == spv::OpAtomicCompareExchange) {
6518 spvAtomicOperands.push_back(semanticsId2);
6519 spvAtomicOperands.push_back(valueId);
6520 spvAtomicOperands.push_back(compareId);
6521 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6522 spvAtomicOperands.push_back(valueId);
6523 }
John Kessenich48d6e792017-10-06 21:21:48 -06006524
Jeff Bolz36831c92018-09-05 10:11:41 -05006525 if (opCode == spv::OpAtomicStore) {
6526 builder.createNoResultOp(opCode, spvAtomicOperands);
6527 return 0;
6528 } else {
6529 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6530
6531 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6532 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6533 if (op == glslang::EOpAtomicCounterDecrement)
6534 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6535
6536 return resultId;
6537 }
John Kessenich426394d2015-07-23 10:22:48 -06006538}
6539
John Kessenich91cef522016-05-05 16:45:40 -06006540// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08006541spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006542{
John Kessenich66011cb2018-03-06 16:12:04 -07006543 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6544 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08006545
Rex Xu51596642016-09-21 18:56:12 +08006546 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006547 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006548 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6549
chaocf200da82016-12-20 12:44:35 -08006550 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6551 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006552 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6553 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006554 } else if (op == glslang::EOpAnyInvocation ||
6555 op == glslang::EOpAllInvocations ||
6556 op == glslang::EOpAllInvocationsEqual) {
6557 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6558 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006559 } else {
6560 builder.addCapability(spv::CapabilityGroups);
Rex Xu17ff3432016-10-14 17:41:45 +08006561 if (op == glslang::EOpMinInvocationsNonUniform ||
6562 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006563 op == glslang::EOpAddInvocationsNonUniform ||
6564 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6565 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6566 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6567 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6568 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6569 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006570 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +08006571
Rex Xu430ef402016-10-14 17:22:23 +08006572 switch (op) {
6573 case glslang::EOpMinInvocations:
6574 case glslang::EOpMaxInvocations:
6575 case glslang::EOpAddInvocations:
6576 case glslang::EOpMinInvocationsNonUniform:
6577 case glslang::EOpMaxInvocationsNonUniform:
6578 case glslang::EOpAddInvocationsNonUniform:
6579 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006580 break;
6581 case glslang::EOpMinInvocationsInclusiveScan:
6582 case glslang::EOpMaxInvocationsInclusiveScan:
6583 case glslang::EOpAddInvocationsInclusiveScan:
6584 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6585 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6586 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6587 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006588 break;
6589 case glslang::EOpMinInvocationsExclusiveScan:
6590 case glslang::EOpMaxInvocationsExclusiveScan:
6591 case glslang::EOpAddInvocationsExclusiveScan:
6592 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6593 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6594 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6595 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006596 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006597 default:
6598 break;
Rex Xu430ef402016-10-14 17:22:23 +08006599 }
John Kessenich149afc32018-08-14 13:31:43 -06006600 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6601 spvGroupOperands.push_back(scope);
6602 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006603 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006604 spvGroupOperands.push_back(groupOp);
6605 }
Rex Xu51596642016-09-21 18:56:12 +08006606 }
6607
John Kessenich149afc32018-08-14 13:31:43 -06006608 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6609 spv::IdImmediate op = { true, *opIt };
6610 spvGroupOperands.push_back(op);
6611 }
John Kessenich91cef522016-05-05 16:45:40 -06006612
6613 switch (op) {
6614 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006615 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006616 break;
John Kessenich91cef522016-05-05 16:45:40 -06006617 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006618 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006619 break;
John Kessenich91cef522016-05-05 16:45:40 -06006620 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006621 opCode = spv::OpSubgroupAllEqualKHR;
6622 break;
Rex Xu51596642016-09-21 18:56:12 +08006623 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006624 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006625 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006626 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006627 break;
6628 case glslang::EOpReadFirstInvocation:
6629 opCode = spv::OpSubgroupFirstInvocationKHR;
6630 break;
6631 case glslang::EOpBallot:
6632 {
6633 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6634 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6635 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6636 //
6637 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6638 //
6639 spv::Id uintType = builder.makeUintType(32);
6640 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6641 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6642
6643 std::vector<spv::Id> components;
6644 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6645 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6646
6647 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6648 return builder.createUnaryOp(spv::OpBitcast, typeId,
6649 builder.createCompositeConstruct(uvec2Type, components));
6650 }
6651
Rex Xu9d93a232016-05-05 12:30:44 +08006652 case glslang::EOpMinInvocations:
6653 case glslang::EOpMaxInvocations:
6654 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006655 case glslang::EOpMinInvocationsInclusiveScan:
6656 case glslang::EOpMaxInvocationsInclusiveScan:
6657 case glslang::EOpAddInvocationsInclusiveScan:
6658 case glslang::EOpMinInvocationsExclusiveScan:
6659 case glslang::EOpMaxInvocationsExclusiveScan:
6660 case glslang::EOpAddInvocationsExclusiveScan:
6661 if (op == glslang::EOpMinInvocations ||
6662 op == glslang::EOpMinInvocationsInclusiveScan ||
6663 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006664 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006665 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006666 else {
6667 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006668 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006669 else
Rex Xu51596642016-09-21 18:56:12 +08006670 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006671 }
Rex Xu430ef402016-10-14 17:22:23 +08006672 } else if (op == glslang::EOpMaxInvocations ||
6673 op == glslang::EOpMaxInvocationsInclusiveScan ||
6674 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006675 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006676 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006677 else {
6678 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006679 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006680 else
Rex Xu51596642016-09-21 18:56:12 +08006681 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006682 }
6683 } else {
6684 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006685 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006686 else
Rex Xu51596642016-09-21 18:56:12 +08006687 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006688 }
6689
Rex Xu2bbbe062016-08-23 15:41:05 +08006690 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006691 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006692
6693 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006694 case glslang::EOpMinInvocationsNonUniform:
6695 case glslang::EOpMaxInvocationsNonUniform:
6696 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006697 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6698 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6699 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6700 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6701 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6702 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6703 if (op == glslang::EOpMinInvocationsNonUniform ||
6704 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6705 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006706 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006707 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006708 else {
6709 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006710 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006711 else
Rex Xu51596642016-09-21 18:56:12 +08006712 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006713 }
6714 }
Rex Xu430ef402016-10-14 17:22:23 +08006715 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6716 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6717 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006718 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006719 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006720 else {
6721 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006722 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006723 else
Rex Xu51596642016-09-21 18:56:12 +08006724 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006725 }
6726 }
6727 else {
6728 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006729 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006730 else
Rex Xu51596642016-09-21 18:56:12 +08006731 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006732 }
6733
Rex Xu2bbbe062016-08-23 15:41:05 +08006734 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006735 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006736
6737 break;
John Kessenich91cef522016-05-05 16:45:40 -06006738 default:
6739 logger->missingFunctionality("invocation operation");
6740 return spv::NoResult;
6741 }
Rex Xu51596642016-09-21 18:56:12 +08006742
6743 assert(opCode != spv::OpNop);
6744 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006745}
6746
Rex Xu2bbbe062016-08-23 15:41:05 +08006747// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006748spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6749 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006750{
6751 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6752 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006753 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006754 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006755 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
6756 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
6757 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
6758
6759 // Handle group invocation operations scalar by scalar.
6760 // The result type is the same type as the original type.
6761 // The algorithm is to:
6762 // - break the vector into scalars
6763 // - apply the operation to each scalar
6764 // - make a vector out the scalar results
6765
6766 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006767 int numComponents = builder.getNumComponents(operands[0]);
6768 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006769 std::vector<spv::Id> results;
6770
6771 // do each scalar op
6772 for (int comp = 0; comp < numComponents; ++comp) {
6773 std::vector<unsigned int> indexes;
6774 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006775 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6776 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006777 if (op == spv::OpSubgroupReadInvocationKHR) {
6778 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006779 spv::IdImmediate operand = { true, operands[1] };
6780 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006781 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006782 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6783 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006784 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006785 spv::IdImmediate operand = { true, operands[1] };
6786 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006787 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006788 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6789 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006790 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006791 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006792 spvGroupOperands.push_back(scalar);
6793 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006794
Rex Xub7072052016-09-26 15:53:40 +08006795 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006796 }
6797
6798 // put the pieces together
6799 return builder.createCompositeConstruct(typeId, results);
6800}
Rex Xu2bbbe062016-08-23 15:41:05 +08006801
John Kessenich66011cb2018-03-06 16:12:04 -07006802// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006803spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6804 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006805{
6806 // Add the required capabilities.
6807 switch (op) {
6808 case glslang::EOpSubgroupElect:
6809 builder.addCapability(spv::CapabilityGroupNonUniform);
6810 break;
6811 case glslang::EOpSubgroupAll:
6812 case glslang::EOpSubgroupAny:
6813 case glslang::EOpSubgroupAllEqual:
6814 builder.addCapability(spv::CapabilityGroupNonUniform);
6815 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6816 break;
6817 case glslang::EOpSubgroupBroadcast:
6818 case glslang::EOpSubgroupBroadcastFirst:
6819 case glslang::EOpSubgroupBallot:
6820 case glslang::EOpSubgroupInverseBallot:
6821 case glslang::EOpSubgroupBallotBitExtract:
6822 case glslang::EOpSubgroupBallotBitCount:
6823 case glslang::EOpSubgroupBallotInclusiveBitCount:
6824 case glslang::EOpSubgroupBallotExclusiveBitCount:
6825 case glslang::EOpSubgroupBallotFindLSB:
6826 case glslang::EOpSubgroupBallotFindMSB:
6827 builder.addCapability(spv::CapabilityGroupNonUniform);
6828 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6829 break;
6830 case glslang::EOpSubgroupShuffle:
6831 case glslang::EOpSubgroupShuffleXor:
6832 builder.addCapability(spv::CapabilityGroupNonUniform);
6833 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6834 break;
6835 case glslang::EOpSubgroupShuffleUp:
6836 case glslang::EOpSubgroupShuffleDown:
6837 builder.addCapability(spv::CapabilityGroupNonUniform);
6838 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6839 break;
6840 case glslang::EOpSubgroupAdd:
6841 case glslang::EOpSubgroupMul:
6842 case glslang::EOpSubgroupMin:
6843 case glslang::EOpSubgroupMax:
6844 case glslang::EOpSubgroupAnd:
6845 case glslang::EOpSubgroupOr:
6846 case glslang::EOpSubgroupXor:
6847 case glslang::EOpSubgroupInclusiveAdd:
6848 case glslang::EOpSubgroupInclusiveMul:
6849 case glslang::EOpSubgroupInclusiveMin:
6850 case glslang::EOpSubgroupInclusiveMax:
6851 case glslang::EOpSubgroupInclusiveAnd:
6852 case glslang::EOpSubgroupInclusiveOr:
6853 case glslang::EOpSubgroupInclusiveXor:
6854 case glslang::EOpSubgroupExclusiveAdd:
6855 case glslang::EOpSubgroupExclusiveMul:
6856 case glslang::EOpSubgroupExclusiveMin:
6857 case glslang::EOpSubgroupExclusiveMax:
6858 case glslang::EOpSubgroupExclusiveAnd:
6859 case glslang::EOpSubgroupExclusiveOr:
6860 case glslang::EOpSubgroupExclusiveXor:
6861 builder.addCapability(spv::CapabilityGroupNonUniform);
6862 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6863 break;
6864 case glslang::EOpSubgroupClusteredAdd:
6865 case glslang::EOpSubgroupClusteredMul:
6866 case glslang::EOpSubgroupClusteredMin:
6867 case glslang::EOpSubgroupClusteredMax:
6868 case glslang::EOpSubgroupClusteredAnd:
6869 case glslang::EOpSubgroupClusteredOr:
6870 case glslang::EOpSubgroupClusteredXor:
6871 builder.addCapability(spv::CapabilityGroupNonUniform);
6872 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6873 break;
6874 case glslang::EOpSubgroupQuadBroadcast:
6875 case glslang::EOpSubgroupQuadSwapHorizontal:
6876 case glslang::EOpSubgroupQuadSwapVertical:
6877 case glslang::EOpSubgroupQuadSwapDiagonal:
6878 builder.addCapability(spv::CapabilityGroupNonUniform);
6879 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6880 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006881 case glslang::EOpSubgroupPartitionedAdd:
6882 case glslang::EOpSubgroupPartitionedMul:
6883 case glslang::EOpSubgroupPartitionedMin:
6884 case glslang::EOpSubgroupPartitionedMax:
6885 case glslang::EOpSubgroupPartitionedAnd:
6886 case glslang::EOpSubgroupPartitionedOr:
6887 case glslang::EOpSubgroupPartitionedXor:
6888 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6889 case glslang::EOpSubgroupPartitionedInclusiveMul:
6890 case glslang::EOpSubgroupPartitionedInclusiveMin:
6891 case glslang::EOpSubgroupPartitionedInclusiveMax:
6892 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6893 case glslang::EOpSubgroupPartitionedInclusiveOr:
6894 case glslang::EOpSubgroupPartitionedInclusiveXor:
6895 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6896 case glslang::EOpSubgroupPartitionedExclusiveMul:
6897 case glslang::EOpSubgroupPartitionedExclusiveMin:
6898 case glslang::EOpSubgroupPartitionedExclusiveMax:
6899 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6900 case glslang::EOpSubgroupPartitionedExclusiveOr:
6901 case glslang::EOpSubgroupPartitionedExclusiveXor:
6902 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6903 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6904 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006905 default: assert(0 && "Unhandled subgroup operation!");
6906 }
6907
Jeff Bolzc5b669e2019-09-08 08:49:18 -05006908
6909 const bool isUnsigned = isTypeUnsignedInt(typeProxy);
6910 const bool isFloat = isTypeFloat(typeProxy);
John Kessenich66011cb2018-03-06 16:12:04 -07006911 const bool isBool = typeProxy == glslang::EbtBool;
6912
6913 spv::Op opCode = spv::OpNop;
6914
6915 // Figure out which opcode to use.
6916 switch (op) {
6917 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6918 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6919 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6920 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6921 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6922 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6923 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6924 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6925 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6926 case glslang::EOpSubgroupBallotBitCount:
6927 case glslang::EOpSubgroupBallotInclusiveBitCount:
6928 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6929 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6930 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6931 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6932 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6933 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6934 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6935 case glslang::EOpSubgroupAdd:
6936 case glslang::EOpSubgroupInclusiveAdd:
6937 case glslang::EOpSubgroupExclusiveAdd:
6938 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006939 case glslang::EOpSubgroupPartitionedAdd:
6940 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6941 case glslang::EOpSubgroupPartitionedExclusiveAdd:
John Kessenich66011cb2018-03-06 16:12:04 -07006942 if (isFloat) {
6943 opCode = spv::OpGroupNonUniformFAdd;
6944 } else {
6945 opCode = spv::OpGroupNonUniformIAdd;
6946 }
6947 break;
6948 case glslang::EOpSubgroupMul:
6949 case glslang::EOpSubgroupInclusiveMul:
6950 case glslang::EOpSubgroupExclusiveMul:
6951 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006952 case glslang::EOpSubgroupPartitionedMul:
6953 case glslang::EOpSubgroupPartitionedInclusiveMul:
6954 case glslang::EOpSubgroupPartitionedExclusiveMul:
John Kessenich66011cb2018-03-06 16:12:04 -07006955 if (isFloat) {
6956 opCode = spv::OpGroupNonUniformFMul;
6957 } else {
6958 opCode = spv::OpGroupNonUniformIMul;
6959 }
6960 break;
6961 case glslang::EOpSubgroupMin:
6962 case glslang::EOpSubgroupInclusiveMin:
6963 case glslang::EOpSubgroupExclusiveMin:
6964 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006965 case glslang::EOpSubgroupPartitionedMin:
6966 case glslang::EOpSubgroupPartitionedInclusiveMin:
6967 case glslang::EOpSubgroupPartitionedExclusiveMin:
John Kessenich66011cb2018-03-06 16:12:04 -07006968 if (isFloat) {
6969 opCode = spv::OpGroupNonUniformFMin;
6970 } else if (isUnsigned) {
6971 opCode = spv::OpGroupNonUniformUMin;
6972 } else {
6973 opCode = spv::OpGroupNonUniformSMin;
6974 }
6975 break;
6976 case glslang::EOpSubgroupMax:
6977 case glslang::EOpSubgroupInclusiveMax:
6978 case glslang::EOpSubgroupExclusiveMax:
6979 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006980 case glslang::EOpSubgroupPartitionedMax:
6981 case glslang::EOpSubgroupPartitionedInclusiveMax:
6982 case glslang::EOpSubgroupPartitionedExclusiveMax:
John Kessenich66011cb2018-03-06 16:12:04 -07006983 if (isFloat) {
6984 opCode = spv::OpGroupNonUniformFMax;
6985 } else if (isUnsigned) {
6986 opCode = spv::OpGroupNonUniformUMax;
6987 } else {
6988 opCode = spv::OpGroupNonUniformSMax;
6989 }
6990 break;
6991 case glslang::EOpSubgroupAnd:
6992 case glslang::EOpSubgroupInclusiveAnd:
6993 case glslang::EOpSubgroupExclusiveAnd:
6994 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006995 case glslang::EOpSubgroupPartitionedAnd:
6996 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6997 case glslang::EOpSubgroupPartitionedExclusiveAnd:
John Kessenich66011cb2018-03-06 16:12:04 -07006998 if (isBool) {
6999 opCode = spv::OpGroupNonUniformLogicalAnd;
7000 } else {
7001 opCode = spv::OpGroupNonUniformBitwiseAnd;
7002 }
7003 break;
7004 case glslang::EOpSubgroupOr:
7005 case glslang::EOpSubgroupInclusiveOr:
7006 case glslang::EOpSubgroupExclusiveOr:
7007 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007008 case glslang::EOpSubgroupPartitionedOr:
7009 case glslang::EOpSubgroupPartitionedInclusiveOr:
7010 case glslang::EOpSubgroupPartitionedExclusiveOr:
John Kessenich66011cb2018-03-06 16:12:04 -07007011 if (isBool) {
7012 opCode = spv::OpGroupNonUniformLogicalOr;
7013 } else {
7014 opCode = spv::OpGroupNonUniformBitwiseOr;
7015 }
7016 break;
7017 case glslang::EOpSubgroupXor:
7018 case glslang::EOpSubgroupInclusiveXor:
7019 case glslang::EOpSubgroupExclusiveXor:
7020 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007021 case glslang::EOpSubgroupPartitionedXor:
7022 case glslang::EOpSubgroupPartitionedInclusiveXor:
7023 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007024 if (isBool) {
7025 opCode = spv::OpGroupNonUniformLogicalXor;
7026 } else {
7027 opCode = spv::OpGroupNonUniformBitwiseXor;
7028 }
7029 break;
7030 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
7031 case glslang::EOpSubgroupQuadSwapHorizontal:
7032 case glslang::EOpSubgroupQuadSwapVertical:
7033 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
7034 default: assert(0 && "Unhandled subgroup operation!");
7035 }
7036
John Kessenich149afc32018-08-14 13:31:43 -06007037 // get the right Group Operation
7038 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07007039 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06007040 default:
7041 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007042 case glslang::EOpSubgroupBallotBitCount:
7043 case glslang::EOpSubgroupAdd:
7044 case glslang::EOpSubgroupMul:
7045 case glslang::EOpSubgroupMin:
7046 case glslang::EOpSubgroupMax:
7047 case glslang::EOpSubgroupAnd:
7048 case glslang::EOpSubgroupOr:
7049 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06007050 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007051 break;
7052 case glslang::EOpSubgroupBallotInclusiveBitCount:
7053 case glslang::EOpSubgroupInclusiveAdd:
7054 case glslang::EOpSubgroupInclusiveMul:
7055 case glslang::EOpSubgroupInclusiveMin:
7056 case glslang::EOpSubgroupInclusiveMax:
7057 case glslang::EOpSubgroupInclusiveAnd:
7058 case glslang::EOpSubgroupInclusiveOr:
7059 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007060 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007061 break;
7062 case glslang::EOpSubgroupBallotExclusiveBitCount:
7063 case glslang::EOpSubgroupExclusiveAdd:
7064 case glslang::EOpSubgroupExclusiveMul:
7065 case glslang::EOpSubgroupExclusiveMin:
7066 case glslang::EOpSubgroupExclusiveMax:
7067 case glslang::EOpSubgroupExclusiveAnd:
7068 case glslang::EOpSubgroupExclusiveOr:
7069 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007070 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007071 break;
7072 case glslang::EOpSubgroupClusteredAdd:
7073 case glslang::EOpSubgroupClusteredMul:
7074 case glslang::EOpSubgroupClusteredMin:
7075 case glslang::EOpSubgroupClusteredMax:
7076 case glslang::EOpSubgroupClusteredAnd:
7077 case glslang::EOpSubgroupClusteredOr:
7078 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06007079 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007080 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007081 case glslang::EOpSubgroupPartitionedAdd:
7082 case glslang::EOpSubgroupPartitionedMul:
7083 case glslang::EOpSubgroupPartitionedMin:
7084 case glslang::EOpSubgroupPartitionedMax:
7085 case glslang::EOpSubgroupPartitionedAnd:
7086 case glslang::EOpSubgroupPartitionedOr:
7087 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06007088 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007089 break;
7090 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7091 case glslang::EOpSubgroupPartitionedInclusiveMul:
7092 case glslang::EOpSubgroupPartitionedInclusiveMin:
7093 case glslang::EOpSubgroupPartitionedInclusiveMax:
7094 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7095 case glslang::EOpSubgroupPartitionedInclusiveOr:
7096 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007097 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007098 break;
7099 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7100 case glslang::EOpSubgroupPartitionedExclusiveMul:
7101 case glslang::EOpSubgroupPartitionedExclusiveMin:
7102 case glslang::EOpSubgroupPartitionedExclusiveMax:
7103 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7104 case glslang::EOpSubgroupPartitionedExclusiveOr:
7105 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007106 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007107 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007108 }
7109
John Kessenich149afc32018-08-14 13:31:43 -06007110 // build the instruction
7111 std::vector<spv::IdImmediate> spvGroupOperands;
7112
7113 // Every operation begins with the Execution Scope operand.
7114 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7115 spvGroupOperands.push_back(executionScope);
7116
7117 // Next, for all operations that use a Group Operation, push that as an operand.
7118 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007119 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007120 spvGroupOperands.push_back(groupOperand);
7121 }
7122
John Kessenich66011cb2018-03-06 16:12:04 -07007123 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06007124 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
7125 spv::IdImmediate operand = { true, *opIt };
7126 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07007127 }
7128
7129 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06007130 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07007131 switch (op) {
7132 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06007133 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
7134 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
7135 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
7136 }
7137 if (directionId != spv::NoResult) {
7138 spv::IdImmediate direction = { true, directionId };
7139 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007140 }
7141
7142 return builder.createOp(opCode, typeId, spvGroupOperands);
7143}
7144
John Kessenich5e4b1242015-08-06 22:53:06 -06007145spv::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 -06007146{
John Kessenich66011cb2018-03-06 16:12:04 -07007147 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7148 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007149
John Kessenich140f3df2015-06-26 16:58:36 -06007150 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007151 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007152 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007153 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007154 spv::Id typeId0 = 0;
7155 if (consumedOperands > 0)
7156 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007157 spv::Id typeId1 = 0;
7158 if (consumedOperands > 1)
7159 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007160 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007161
7162 switch (op) {
7163 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007164 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007165 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007166 else if (isUnsigned)
7167 libCall = spv::GLSLstd450UMin;
7168 else
7169 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007170 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007171 break;
7172 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007173 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007174 break;
7175 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007176 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007177 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007178 else if (isUnsigned)
7179 libCall = spv::GLSLstd450UMax;
7180 else
7181 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007182 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007183 break;
7184 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007185 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007186 break;
7187 case glslang::EOpDot:
7188 opCode = spv::OpDot;
7189 break;
7190 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007191 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007192 break;
7193
7194 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007195 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007196 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007197 else if (isUnsigned)
7198 libCall = spv::GLSLstd450UClamp;
7199 else
7200 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007201 builder.promoteScalar(precision, operands.front(), operands[1]);
7202 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007203 break;
7204 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007205 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7206 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007207 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007208 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007209 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007210 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007211 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007212 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007213 break;
7214 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007215 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007216 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007217 break;
7218 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007219 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007220 builder.promoteScalar(precision, operands[0], operands[2]);
7221 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007222 break;
7223
7224 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007225 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007226 break;
7227 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007228 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007229 break;
7230 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007231 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007232 break;
7233 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007234 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007235 break;
7236 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007237 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007238 break;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007239 case glslang::EOpBarrier:
7240 {
7241 // This is for the extended controlBarrier function, with four operands.
7242 // The unextended barrier() goes through createNoArgOperation.
7243 assert(operands.size() == 4);
7244 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7245 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7246 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
7247 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7248 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7249 spv::MemorySemanticsMakeVisibleKHRMask |
7250 spv::MemorySemanticsOutputMemoryKHRMask |
7251 spv::MemorySemanticsVolatileMask)) {
7252 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7253 }
7254 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
7255 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7256 }
7257 return 0;
7258 }
7259 break;
7260 case glslang::EOpMemoryBarrier:
7261 {
7262 // This is for the extended memoryBarrier function, with three operands.
7263 // The unextended memoryBarrier() goes through createNoArgOperation.
7264 assert(operands.size() == 3);
7265 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7266 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7267 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7268 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7269 spv::MemorySemanticsMakeVisibleKHRMask |
7270 spv::MemorySemanticsOutputMemoryKHRMask |
7271 spv::MemorySemanticsVolatileMask)) {
7272 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7273 }
7274 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7275 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7276 }
7277 return 0;
7278 }
7279 break;
7280
John Kessenicha28f7a72019-08-06 07:00:58 -06007281#ifndef GLSLANG_WEB
Rex Xu7a26c172015-12-08 17:12:09 +08007282 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007283 if (typeProxy == glslang::EbtFloat16)
7284 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007285 libCall = spv::GLSLstd450InterpolateAtSample;
7286 break;
7287 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007288 if (typeProxy == glslang::EbtFloat16)
7289 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007290 libCall = spv::GLSLstd450InterpolateAtOffset;
7291 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007292 case glslang::EOpAddCarry:
7293 opCode = spv::OpIAddCarry;
7294 typeId = builder.makeStructResultType(typeId0, typeId0);
7295 consumedOperands = 2;
7296 break;
7297 case glslang::EOpSubBorrow:
7298 opCode = spv::OpISubBorrow;
7299 typeId = builder.makeStructResultType(typeId0, typeId0);
7300 consumedOperands = 2;
7301 break;
7302 case glslang::EOpUMulExtended:
7303 opCode = spv::OpUMulExtended;
7304 typeId = builder.makeStructResultType(typeId0, typeId0);
7305 consumedOperands = 2;
7306 break;
7307 case glslang::EOpIMulExtended:
7308 opCode = spv::OpSMulExtended;
7309 typeId = builder.makeStructResultType(typeId0, typeId0);
7310 consumedOperands = 2;
7311 break;
7312 case glslang::EOpBitfieldExtract:
7313 if (isUnsigned)
7314 opCode = spv::OpBitFieldUExtract;
7315 else
7316 opCode = spv::OpBitFieldSExtract;
7317 break;
7318 case glslang::EOpBitfieldInsert:
7319 opCode = spv::OpBitFieldInsert;
7320 break;
7321
7322 case glslang::EOpFma:
7323 libCall = spv::GLSLstd450Fma;
7324 break;
7325 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007326 {
7327 libCall = spv::GLSLstd450FrexpStruct;
7328 assert(builder.isPointerType(typeId1));
7329 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007330 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007331 if (width == 16)
7332 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7333 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
Rex Xu470026f2017-03-29 17:12:40 +08007334 if (builder.getNumComponents(operands[0]) == 1)
7335 frexpIntType = builder.makeIntegerType(width, true);
7336 else
7337 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
7338 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7339 consumedOperands = 1;
7340 }
John Kessenich55e7d112015-11-15 21:33:39 -07007341 break;
7342 case glslang::EOpLdexp:
7343 libCall = spv::GLSLstd450Ldexp;
7344 break;
7345
Rex Xu574ab042016-04-14 16:53:07 +08007346 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007347 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007348
John Kessenich66011cb2018-03-06 16:12:04 -07007349 case glslang::EOpSubgroupBroadcast:
7350 case glslang::EOpSubgroupBallotBitExtract:
7351 case glslang::EOpSubgroupShuffle:
7352 case glslang::EOpSubgroupShuffleXor:
7353 case glslang::EOpSubgroupShuffleUp:
7354 case glslang::EOpSubgroupShuffleDown:
7355 case glslang::EOpSubgroupClusteredAdd:
7356 case glslang::EOpSubgroupClusteredMul:
7357 case glslang::EOpSubgroupClusteredMin:
7358 case glslang::EOpSubgroupClusteredMax:
7359 case glslang::EOpSubgroupClusteredAnd:
7360 case glslang::EOpSubgroupClusteredOr:
7361 case glslang::EOpSubgroupClusteredXor:
7362 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007363 case glslang::EOpSubgroupPartitionedAdd:
7364 case glslang::EOpSubgroupPartitionedMul:
7365 case glslang::EOpSubgroupPartitionedMin:
7366 case glslang::EOpSubgroupPartitionedMax:
7367 case glslang::EOpSubgroupPartitionedAnd:
7368 case glslang::EOpSubgroupPartitionedOr:
7369 case glslang::EOpSubgroupPartitionedXor:
7370 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7371 case glslang::EOpSubgroupPartitionedInclusiveMul:
7372 case glslang::EOpSubgroupPartitionedInclusiveMin:
7373 case glslang::EOpSubgroupPartitionedInclusiveMax:
7374 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7375 case glslang::EOpSubgroupPartitionedInclusiveOr:
7376 case glslang::EOpSubgroupPartitionedInclusiveXor:
7377 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7378 case glslang::EOpSubgroupPartitionedExclusiveMul:
7379 case glslang::EOpSubgroupPartitionedExclusiveMin:
7380 case glslang::EOpSubgroupPartitionedExclusiveMax:
7381 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7382 case glslang::EOpSubgroupPartitionedExclusiveOr:
7383 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007384 return createSubgroupOperation(op, typeId, operands, typeProxy);
7385
Rex Xu9d93a232016-05-05 12:30:44 +08007386 case glslang::EOpSwizzleInvocations:
7387 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7388 libCall = spv::SwizzleInvocationsAMD;
7389 break;
7390 case glslang::EOpSwizzleInvocationsMasked:
7391 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7392 libCall = spv::SwizzleInvocationsMaskedAMD;
7393 break;
7394 case glslang::EOpWriteInvocation:
7395 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7396 libCall = spv::WriteInvocationAMD;
7397 break;
7398
7399 case glslang::EOpMin3:
7400 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7401 if (isFloat)
7402 libCall = spv::FMin3AMD;
7403 else {
7404 if (isUnsigned)
7405 libCall = spv::UMin3AMD;
7406 else
7407 libCall = spv::SMin3AMD;
7408 }
7409 break;
7410 case glslang::EOpMax3:
7411 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7412 if (isFloat)
7413 libCall = spv::FMax3AMD;
7414 else {
7415 if (isUnsigned)
7416 libCall = spv::UMax3AMD;
7417 else
7418 libCall = spv::SMax3AMD;
7419 }
7420 break;
7421 case glslang::EOpMid3:
7422 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7423 if (isFloat)
7424 libCall = spv::FMid3AMD;
7425 else {
7426 if (isUnsigned)
7427 libCall = spv::UMid3AMD;
7428 else
7429 libCall = spv::SMid3AMD;
7430 }
7431 break;
7432
7433 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007434 if (typeProxy == glslang::EbtFloat16)
7435 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007436 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7437 libCall = spv::InterpolateAtVertexAMD;
7438 break;
Chao Chen3c366992018-09-19 11:41:59 -07007439
Chao Chenb50c02e2018-09-19 11:42:24 -07007440 case glslang::EOpReportIntersectionNV:
7441 {
7442 typeId = builder.makeBoolType();
Ashwin Leleff1783d2018-10-22 16:41:44 -07007443 opCode = spv::OpReportIntersectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07007444 }
7445 break;
7446 case glslang::EOpTraceNV:
7447 {
Ashwin Leleff1783d2018-10-22 16:41:44 -07007448 builder.createNoResultOp(spv::OpTraceNV, operands);
7449 return 0;
7450 }
7451 break;
7452 case glslang::EOpExecuteCallableNV:
7453 {
7454 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007455 return 0;
7456 }
7457 break;
Chao Chen3c366992018-09-19 11:41:59 -07007458 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7459 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7460 return 0;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007461 case glslang::EOpCooperativeMatrixMulAdd:
7462 opCode = spv::OpCooperativeMatrixMulAddNV;
7463 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007464#endif // GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007465 default:
7466 return 0;
7467 }
7468
7469 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007470 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007471 // Use an extended instruction from the standard library.
7472 // Construct the call arguments, without modifying the original operands vector.
7473 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7474 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007475 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007476 } else if (opCode == spv::OpDot && !isFloat) {
7477 // int dot(int, int)
7478 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7479 const int componentCount = builder.getNumComponents(operands[0]);
7480 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7481 builder.setPrecision(mulOp, precision);
7482 id = builder.createCompositeExtract(mulOp, typeId, 0);
7483 for (int i = 1; i < componentCount; ++i) {
7484 builder.setPrecision(id, precision);
7485 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(operands[0], typeId, i));
7486 }
John Kessenich2359bd02015-12-06 19:29:11 -07007487 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007488 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007489 case 0:
7490 // should all be handled by visitAggregate and createNoArgOperation
7491 assert(0);
7492 return 0;
7493 case 1:
7494 // should all be handled by createUnaryOperation
7495 assert(0);
7496 return 0;
7497 case 2:
7498 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7499 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007500 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007501 // anything 3 or over doesn't have l-value operands, so all should be consumed
7502 assert(consumedOperands == operands.size());
7503 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007504 break;
7505 }
7506 }
7507
John Kessenichb9197c82019-08-11 07:41:45 -06007508#ifndef GLSLANG_WEB
John Kessenich55e7d112015-11-15 21:33:39 -07007509 // Decode the return types that were structures
7510 switch (op) {
7511 case glslang::EOpAddCarry:
7512 case glslang::EOpSubBorrow:
7513 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7514 id = builder.createCompositeExtract(id, typeId0, 0);
7515 break;
7516 case glslang::EOpUMulExtended:
7517 case glslang::EOpIMulExtended:
7518 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7519 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7520 break;
7521 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007522 {
7523 assert(operands.size() == 2);
7524 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7525 // "exp" is floating-point type (from HLSL intrinsic)
7526 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7527 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7528 builder.createStore(member1, operands[1]);
7529 } else
7530 // "exp" is integer type (from GLSL built-in function)
7531 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7532 id = builder.createCompositeExtract(id, typeId0, 0);
7533 }
John Kessenich55e7d112015-11-15 21:33:39 -07007534 break;
7535 default:
7536 break;
7537 }
John Kessenichb9197c82019-08-11 07:41:45 -06007538#endif
John Kessenich55e7d112015-11-15 21:33:39 -07007539
John Kessenich32cfd492016-02-02 12:37:46 -07007540 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007541}
7542
Rex Xu9d93a232016-05-05 12:30:44 +08007543// Intrinsics with no arguments (or no return value, and no precision).
7544spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007545{
Jeff Bolz36831c92018-09-05 10:11:41 -05007546 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
7547 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007548
7549 switch (op) {
John Kessenich140f3df2015-06-26 16:58:36 -06007550 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007551 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007552 if (glslangIntermediate->usingVulkanMemoryModel()) {
7553 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7554 spv::MemorySemanticsOutputMemoryKHRMask |
7555 spv::MemorySemanticsAcquireReleaseMask);
7556 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7557 } else {
7558 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7559 }
John Kessenich82979362017-12-11 04:02:24 -07007560 } else {
7561 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7562 spv::MemorySemanticsWorkgroupMemoryMask |
7563 spv::MemorySemanticsAcquireReleaseMask);
7564 }
John Kessenich140f3df2015-06-26 16:58:36 -06007565 return 0;
7566 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007567 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7568 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007569 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007570 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007571 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7572 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007573 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007574 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007575 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7576 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007577 return 0;
7578 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007579 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7580 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007581 return 0;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007582#ifndef GLSLANG_WEB
7583 case glslang::EOpMemoryBarrierAtomicCounter:
7584 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7585 spv::MemorySemanticsAcquireReleaseMask);
7586 return 0;
7587 case glslang::EOpMemoryBarrierImage:
7588 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7589 spv::MemorySemanticsAcquireReleaseMask);
7590 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007591 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007592 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007593 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007594 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007595 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007596 case glslang::EOpDeviceMemoryBarrier:
7597 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7598 spv::MemorySemanticsImageMemoryMask |
7599 spv::MemorySemanticsAcquireReleaseMask);
7600 return 0;
7601 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7602 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7603 spv::MemorySemanticsImageMemoryMask |
7604 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007605 return 0;
7606 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007607 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7608 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007609 return 0;
7610 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007611 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7612 spv::MemorySemanticsWorkgroupMemoryMask |
7613 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007614 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007615 case glslang::EOpSubgroupBarrier:
7616 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7617 spv::MemorySemanticsAcquireReleaseMask);
7618 return spv::NoResult;
7619 case glslang::EOpSubgroupMemoryBarrier:
7620 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7621 spv::MemorySemanticsAcquireReleaseMask);
7622 return spv::NoResult;
7623 case glslang::EOpSubgroupMemoryBarrierBuffer:
7624 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7625 spv::MemorySemanticsAcquireReleaseMask);
7626 return spv::NoResult;
7627 case glslang::EOpSubgroupMemoryBarrierImage:
7628 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7629 spv::MemorySemanticsAcquireReleaseMask);
7630 return spv::NoResult;
7631 case glslang::EOpSubgroupMemoryBarrierShared:
7632 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7633 spv::MemorySemanticsAcquireReleaseMask);
7634 return spv::NoResult;
John Kessenichf8d1d742019-10-21 06:55:11 -06007635
7636 case glslang::EOpEmitVertex:
7637 builder.createNoResultOp(spv::OpEmitVertex);
7638 return 0;
7639 case glslang::EOpEndPrimitive:
7640 builder.createNoResultOp(spv::OpEndPrimitive);
7641 return 0;
7642
John Kessenich66011cb2018-03-06 16:12:04 -07007643 case glslang::EOpSubgroupElect: {
7644 std::vector<spv::Id> operands;
7645 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7646 }
Rex Xu9d93a232016-05-05 12:30:44 +08007647 case glslang::EOpTime:
7648 {
7649 std::vector<spv::Id> args; // Dummy arguments
7650 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7651 return builder.setPrecision(id, precision);
7652 }
Chao Chenb50c02e2018-09-19 11:42:24 -07007653 case glslang::EOpIgnoreIntersectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007654 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007655 return 0;
7656 case glslang::EOpTerminateRayNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007657 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007658 return 0;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05007659
7660 case glslang::EOpBeginInvocationInterlock:
7661 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
7662 return 0;
7663 case glslang::EOpEndInvocationInterlock:
7664 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
7665 return 0;
7666
Jeff Bolzba6170b2019-07-01 09:23:23 -05007667 case glslang::EOpIsHelperInvocation:
7668 {
7669 std::vector<spv::Id> args; // Dummy arguments
Rex Xubb7307b2019-07-15 14:57:20 +08007670 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
7671 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
7672 return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
Jeff Bolzba6170b2019-07-01 09:23:23 -05007673 }
7674
amhagan91fb0092019-07-10 21:14:38 -04007675 case glslang::EOpReadClockSubgroupKHR: {
7676 std::vector<spv::Id> args;
7677 args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
7678 builder.addExtension(spv::E_SPV_KHR_shader_clock);
7679 builder.addCapability(spv::CapabilityShaderClockKHR);
7680 return builder.createOp(spv::OpReadClockKHR, typeId, args);
7681 }
7682
7683 case glslang::EOpReadClockDeviceKHR: {
7684 std::vector<spv::Id> args;
7685 args.push_back(builder.makeUintConstant(spv::ScopeDevice));
7686 builder.addExtension(spv::E_SPV_KHR_shader_clock);
7687 builder.addCapability(spv::CapabilityShaderClockKHR);
7688 return builder.createOp(spv::OpReadClockKHR, typeId, args);
7689 }
John Kessenich3dd1ce52019-10-17 07:08:40 -06007690#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007691 default:
John Kessenich155d3512019-08-08 23:29:20 -06007692 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007693 }
John Kessenich155d3512019-08-08 23:29:20 -06007694
7695 logger->missingFunctionality("unknown operation with no arguments");
7696
7697 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007698}
7699
7700spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7701{
John Kessenich2f273362015-07-18 22:34:27 -06007702 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007703 spv::Id id;
7704 if (symbolValues.end() != iter) {
7705 id = iter->second;
7706 return id;
7707 }
7708
7709 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06007710 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
7711 auto forcedType = getForcedType(builtIn, symbol->getType());
7712 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06007713 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06007714 if (forcedType.second != spv::NoType)
7715 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06007716
Rex Xuc884b4a2016-06-29 15:03:44 +08007717 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007718 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7719 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7720 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenicha28f7a72019-08-06 07:00:58 -06007721#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07007722 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
John Kessenichb9197c82019-08-11 07:41:45 -06007723 if (symbol->getQualifier().hasComponent())
7724 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
7725 if (symbol->getQualifier().hasIndex())
7726 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
Chao Chen3c366992018-09-19 11:41:59 -07007727#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007728 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007729 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich91e4aa52016-07-07 17:46:42 -06007730 // atomic counters use this:
7731 if (symbol->getQualifier().hasOffset())
7732 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007733 }
7734
scygan2c864272016-05-18 18:09:17 +02007735 if (symbol->getQualifier().hasLocation())
7736 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007737 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007738 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007739 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007740 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007741 }
John Kessenich140f3df2015-06-26 16:58:36 -06007742 if (symbol->getQualifier().hasSet())
7743 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007744 else if (IsDescriptorResource(symbol->getType())) {
7745 // default to 0
7746 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7747 }
John Kessenich140f3df2015-06-26 16:58:36 -06007748 if (symbol->getQualifier().hasBinding())
7749 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06007750 else if (IsDescriptorResource(symbol->getType())) {
7751 // default to 0
7752 builder.addDecoration(id, spv::DecorationBinding, 0);
7753 }
John Kessenich6c292d32016-02-15 20:58:50 -07007754 if (symbol->getQualifier().hasAttachment())
7755 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06007756 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007757 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07007758 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007759 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007760 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7761 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7762 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7763 }
7764 if (symbol->getQualifier().hasXfbOffset())
7765 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007766 }
7767
John Kessenichb9197c82019-08-11 07:41:45 -06007768 // add built-in variable decoration
7769 if (builtIn != spv::BuiltInMax) {
7770 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
7771 }
7772
7773#ifndef GLSLANG_WEB
Rex Xu1da878f2016-02-21 20:59:01 +08007774 if (symbol->getType().isImage()) {
7775 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05007776 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007777 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007778 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007779 }
7780
John Kessenich5611c6d2018-04-05 11:25:02 -06007781 // nonuniform
7782 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7783
chaoc0ad6a4e2016-12-19 16:29:34 -08007784 if (builtIn == spv::BuiltInSampleMask) {
7785 spv::Decoration decoration;
7786 // GL_NV_sample_mask_override_coverage extension
7787 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007788 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007789 else
7790 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007791 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007792 if (decoration != spv::DecorationMax) {
Jason Macnakdbd4c3c2019-07-12 14:33:02 -07007793 builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
chaoc0ad6a4e2016-12-19 16:29:34 -08007794 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7795 }
7796 }
chaoc771d89f2017-01-13 01:10:53 -08007797 else if (builtIn == spv::BuiltInLayer) {
7798 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007799 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007800 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007801 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7802 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7803 }
John Kessenichb41bff62017-08-11 13:07:17 -06007804 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007805 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7806 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007807 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7808 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7809 }
7810 }
7811
chaoc6e5acae2016-12-20 13:28:52 -08007812 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007813 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007814 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007815 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7816 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007817 if (symbol->getQualifier().pervertexNV) {
7818 builder.addDecoration(id, spv::DecorationPerVertexNV);
7819 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7820 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7821 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007822
John Kessenich5d610ee2018-03-07 18:05:55 -07007823 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7824 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7825 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7826 symbol->getType().getQualifier().semanticName);
7827 }
7828
John Kessenich7015bd62019-08-01 03:28:08 -06007829 if (symbol->isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007830 builder.addDecoration(id, symbol->getType().getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
7831 }
John Kessenichb9197c82019-08-11 07:41:45 -06007832#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007833
John Kessenich140f3df2015-06-26 16:58:36 -06007834 return id;
7835}
7836
John Kessenicha28f7a72019-08-06 07:00:58 -06007837#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07007838// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7839void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7840{
7841 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07007842 if (qualifier.perPrimitiveNV) {
7843 // Need to add capability/extension for fragment shader.
7844 // Mesh shader already adds this by default.
7845 if (glslangIntermediate->getStage() == EShLangFragment) {
7846 builder.addCapability(spv::CapabilityMeshShadingNV);
7847 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7848 }
Chao Chen3c366992018-09-19 11:41:59 -07007849 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007850 }
Chao Chen3c366992018-09-19 11:41:59 -07007851 if (qualifier.perViewNV)
7852 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7853 if (qualifier.perTaskNV)
7854 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7855 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07007856 if (qualifier.perPrimitiveNV) {
7857 // Need to add capability/extension for fragment shader.
7858 // Mesh shader already adds this by default.
7859 if (glslangIntermediate->getStage() == EShLangFragment) {
7860 builder.addCapability(spv::CapabilityMeshShadingNV);
7861 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7862 }
Chao Chen3c366992018-09-19 11:41:59 -07007863 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007864 }
Chao Chen3c366992018-09-19 11:41:59 -07007865 if (qualifier.perViewNV)
7866 builder.addDecoration(id, spv::DecorationPerViewNV);
7867 if (qualifier.perTaskNV)
7868 builder.addDecoration(id, spv::DecorationPerTaskNV);
7869 }
7870}
7871#endif
7872
John Kessenich55e7d112015-11-15 21:33:39 -07007873// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07007874// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07007875//
7876// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7877//
7878// Recursively walk the nodes. The nodes form a tree whose leaves are
7879// regular constants, which themselves are trees that createSpvConstant()
7880// recursively walks. So, this function walks the "top" of the tree:
7881// - emit specialization constant-building instructions for specConstant
7882// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04007883spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07007884{
John Kessenich7cc0e282016-03-20 00:46:02 -06007885 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07007886
qining4f4bb812016-04-03 23:55:17 -04007887 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07007888 if (! node.getQualifier().specConstant) {
7889 // hand off to the non-spec-constant path
7890 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
7891 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04007892 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07007893 nextConst, false);
7894 }
7895
7896 // We now know we have a specialization constant to build
7897
John Kessenichd94c0032016-05-30 19:29:40 -06007898 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04007899 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
7900 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
7901 std::vector<spv::Id> dimConstId;
7902 for (int dim = 0; dim < 3; ++dim) {
7903 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
7904 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07007905 if (specConst) {
7906 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
7907 glslangIntermediate->getLocalSizeSpecId(dim));
7908 }
qining4f4bb812016-04-03 23:55:17 -04007909 }
7910 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
7911 }
7912
7913 // An AST node labelled as specialization constant should be a symbol node.
7914 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
7915 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007916 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04007917 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04007918 // Traverse the constant constructor sub tree like generating normal run-time instructions.
7919 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
7920 // will set the builder into spec constant op instruction generating mode.
7921 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007922 result = accessChainLoad(sub_tree->getType());
7923 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04007924 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007925 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05007926 } else {
7927 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05007928 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07007929 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007930 builder.addName(result, sn->getName().c_str());
7931 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07007932 }
qining4f4bb812016-04-03 23:55:17 -04007933
7934 // Neither a front-end constant node, nor a specialization constant node with constant union array or
7935 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04007936 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04007937 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07007938}
7939
John Kessenich140f3df2015-06-26 16:58:36 -06007940// Use 'consts' as the flattened glslang source of scalar constants to recursively
7941// build the aggregate SPIR-V constant.
7942//
7943// If there are not enough elements present in 'consts', 0 will be substituted;
7944// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
7945//
qining08408382016-03-21 09:51:37 -04007946spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06007947{
7948 // vector of constants for SPIR-V
7949 std::vector<spv::Id> spvConsts;
7950
7951 // Type is used for struct and array constants
7952 spv::Id typeId = convertGlslangToSpvType(glslangType);
7953
7954 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007955 glslang::TType elementType(glslangType, 0);
7956 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04007957 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007958 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007959 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06007960 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04007961 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007962 } else if (glslangType.isCoopMat()) {
7963 glslang::TType componentType(glslangType.getBasicType());
7964 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007965 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007966 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
7967 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04007968 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06007969 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06007970 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
7971 bool zero = nextConst >= consts.size();
7972 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06007973 case glslang::EbtInt:
7974 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
7975 break;
7976 case glslang::EbtUint:
7977 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
7978 break;
7979 case glslang::EbtFloat:
7980 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7981 break;
7982 case glslang::EbtBool:
7983 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7984 break;
7985#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07007986 case glslang::EbtInt8:
7987 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
7988 break;
7989 case glslang::EbtUint8:
7990 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
7991 break;
7992 case glslang::EbtInt16:
7993 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
7994 break;
7995 case glslang::EbtUint16:
7996 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
7997 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007998 case glslang::EbtInt64:
7999 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
8000 break;
8001 case glslang::EbtUint64:
8002 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
8003 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008004 case glslang::EbtDouble:
8005 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
8006 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008007 case glslang::EbtFloat16:
8008 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8009 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008010#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008011 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008012 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008013 break;
8014 }
8015 ++nextConst;
8016 }
8017 } else {
8018 // we have a non-aggregate (scalar) constant
8019 bool zero = nextConst >= consts.size();
8020 spv::Id scalar = 0;
8021 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008022 case glslang::EbtInt:
8023 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
8024 break;
8025 case glslang::EbtUint:
8026 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
8027 break;
8028 case glslang::EbtFloat:
8029 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8030 break;
8031 case glslang::EbtBool:
8032 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
8033 break;
8034#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008035 case glslang::EbtInt8:
8036 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
8037 break;
8038 case glslang::EbtUint8:
8039 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
8040 break;
8041 case glslang::EbtInt16:
8042 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
8043 break;
8044 case glslang::EbtUint16:
8045 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
8046 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008047 case glslang::EbtInt64:
8048 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
8049 break;
8050 case glslang::EbtUint64:
8051 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8052 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008053 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07008054 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06008055 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008056 case glslang::EbtFloat16:
8057 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8058 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06008059 case glslang::EbtReference:
8060 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8061 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
8062 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008063#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008064 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008065 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008066 break;
8067 }
8068 ++nextConst;
8069 return scalar;
8070 }
8071
8072 return builder.makeCompositeConstant(typeId, spvConsts);
8073}
8074
John Kessenich7c1aa102015-10-15 13:29:11 -06008075// Return true if the node is a constant or symbol whose reading has no
8076// non-trivial observable cost or effect.
8077bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
8078{
8079 // don't know what this is
8080 if (node == nullptr)
8081 return false;
8082
8083 // a constant is safe
8084 if (node->getAsConstantUnion() != nullptr)
8085 return true;
8086
8087 // not a symbol means non-trivial
8088 if (node->getAsSymbolNode() == nullptr)
8089 return false;
8090
8091 // a symbol, depends on what's being read
8092 switch (node->getType().getQualifier().storage) {
8093 case glslang::EvqTemporary:
8094 case glslang::EvqGlobal:
8095 case glslang::EvqIn:
8096 case glslang::EvqInOut:
8097 case glslang::EvqConst:
8098 case glslang::EvqConstReadOnly:
8099 case glslang::EvqUniform:
8100 return true;
8101 default:
8102 return false;
8103 }
qining25262b32016-05-06 17:25:16 -04008104}
John Kessenich7c1aa102015-10-15 13:29:11 -06008105
8106// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06008107// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06008108// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06008109// Return true if trivial.
8110bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
8111{
8112 if (node == nullptr)
8113 return false;
8114
John Kessenich84cc15f2017-05-24 16:44:47 -06008115 // count non scalars as trivial, as well as anything coming from HLSL
8116 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06008117 return true;
8118
John Kessenich7c1aa102015-10-15 13:29:11 -06008119 // symbols and constants are trivial
8120 if (isTrivialLeaf(node))
8121 return true;
8122
8123 // otherwise, it needs to be a simple operation or one or two leaf nodes
8124
8125 // not a simple operation
8126 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
8127 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
8128 if (binaryNode == nullptr && unaryNode == nullptr)
8129 return false;
8130
8131 // not on leaf nodes
8132 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
8133 return false;
8134
8135 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
8136 return false;
8137 }
8138
8139 switch (node->getAsOperator()->getOp()) {
8140 case glslang::EOpLogicalNot:
8141 case glslang::EOpConvIntToBool:
8142 case glslang::EOpConvUintToBool:
8143 case glslang::EOpConvFloatToBool:
8144 case glslang::EOpConvDoubleToBool:
8145 case glslang::EOpEqual:
8146 case glslang::EOpNotEqual:
8147 case glslang::EOpLessThan:
8148 case glslang::EOpGreaterThan:
8149 case glslang::EOpLessThanEqual:
8150 case glslang::EOpGreaterThanEqual:
8151 case glslang::EOpIndexDirect:
8152 case glslang::EOpIndexDirectStruct:
8153 case glslang::EOpLogicalXor:
8154 case glslang::EOpAny:
8155 case glslang::EOpAll:
8156 return true;
8157 default:
8158 return false;
8159 }
8160}
8161
8162// Emit short-circuiting code, where 'right' is never evaluated unless
8163// the left side is true (for &&) or false (for ||).
8164spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
8165{
8166 spv::Id boolTypeId = builder.makeBoolType();
8167
8168 // emit left operand
8169 builder.clearAccessChain();
8170 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008171 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008172
8173 // Operands to accumulate OpPhi operands
8174 std::vector<spv::Id> phiOperands;
8175 // accumulate left operand's phi information
8176 phiOperands.push_back(leftId);
8177 phiOperands.push_back(builder.getBuildPoint()->getId());
8178
8179 // Make the two kinds of operation symmetric with a "!"
8180 // || => emit "if (! left) result = right"
8181 // && => emit "if ( left) result = right"
8182 //
8183 // TODO: this runtime "not" for || could be avoided by adding functionality
8184 // to 'builder' to have an "else" without an "then"
8185 if (op == glslang::EOpLogicalOr)
8186 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8187
8188 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008189 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008190
8191 // emit right operand as the "then" part of the "if"
8192 builder.clearAccessChain();
8193 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008194 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008195
8196 // accumulate left operand's phi information
8197 phiOperands.push_back(rightId);
8198 phiOperands.push_back(builder.getBuildPoint()->getId());
8199
8200 // finish the "if"
8201 ifBuilder.makeEndIf();
8202
8203 // phi together the two results
8204 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8205}
8206
John Kessenicha28f7a72019-08-06 07:00:58 -06008207#ifndef GLSLANG_WEB
Rex Xu9d93a232016-05-05 12:30:44 +08008208// Return type Id of the imported set of extended instructions corresponds to the name.
8209// Import this set if it has not been imported yet.
8210spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8211{
8212 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8213 return extBuiltinMap[name];
8214 else {
Rex Xu51596642016-09-21 18:56:12 +08008215 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008216 spv::Id extBuiltins = builder.import(name);
8217 extBuiltinMap[name] = extBuiltins;
8218 return extBuiltins;
8219 }
8220}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008221#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008222
John Kessenich140f3df2015-06-26 16:58:36 -06008223}; // end anonymous namespace
8224
8225namespace glslang {
8226
John Kessenich68d78fd2015-07-12 19:28:10 -06008227void GetSpirvVersion(std::string& version)
8228{
John Kessenich9e55f632015-07-15 10:03:39 -06008229 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008230 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008231 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008232 version = buf;
8233}
8234
John Kessenicha372a3e2017-11-02 22:32:14 -06008235// For low-order part of the generator's magic number. Bump up
8236// when there is a change in the style (e.g., if SSA form changes,
8237// or a different instruction sequence to do something gets used).
8238int GetSpirvGeneratorVersion()
8239{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008240 // return 1; // start
8241 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008242 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008243 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008244 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008245 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8246 // versions 4 and 6 each generate OpArrayLength as it has long been done
John Kessenich31c33702019-11-02 21:26:40 -06008247 // return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
8248 return 8; // switch to new dead block eliminator; use OpUnreachable
John Kessenicha372a3e2017-11-02 22:32:14 -06008249}
8250
John Kessenich140f3df2015-06-26 16:58:36 -06008251// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008252void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008253{
8254 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008255 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008256 if (out.fail())
8257 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008258 for (int i = 0; i < (int)spirv.size(); ++i) {
8259 unsigned int word = spirv[i];
8260 out.write((const char*)&word, 4);
8261 }
8262 out.close();
8263}
8264
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008265// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008266void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008267{
John Kessenich155d3512019-08-08 23:29:20 -06008268#ifndef GLSLANG_WEB
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008269 std::ofstream out;
8270 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008271 if (out.fail())
8272 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07008273 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06008274 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07008275 std::endl;
Flavio15017db2017-02-15 14:29:33 -08008276 if (varName != nullptr) {
8277 out << "\t #pragma once" << std::endl;
8278 out << "const uint32_t " << varName << "[] = {" << std::endl;
8279 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008280 const int WORDS_PER_LINE = 8;
8281 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8282 out << "\t";
8283 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8284 const unsigned int word = spirv[i + j];
8285 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8286 if (i + j + 1 < (int)spirv.size()) {
8287 out << ",";
8288 }
8289 }
8290 out << std::endl;
8291 }
Flavio15017db2017-02-15 14:29:33 -08008292 if (varName != nullptr) {
8293 out << "};";
8294 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008295 out.close();
John Kessenich155d3512019-08-08 23:29:20 -06008296#endif
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008297}
8298
John Kessenich140f3df2015-06-26 16:58:36 -06008299//
8300// Set up the glslang traversal
8301//
John Kessenich4e11b612018-08-30 16:56:59 -06008302void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008303{
Lei Zhang17535f72016-05-04 15:55:59 -04008304 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008305 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008306}
8307
John Kessenich4e11b612018-08-30 16:56:59 -06008308void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008309 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008310{
John Kessenich140f3df2015-06-26 16:58:36 -06008311 TIntermNode* root = intermediate.getTreeRoot();
8312
8313 if (root == 0)
8314 return;
8315
John Kessenich4e11b612018-08-30 16:56:59 -06008316 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008317 if (options == nullptr)
8318 options = &defaultOptions;
8319
John Kessenich4e11b612018-08-30 16:56:59 -06008320 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008321
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008322 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008323 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008324 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008325 it.dumpSpv(spirv);
8326
GregFfb03a552018-03-29 11:49:14 -06008327#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008328 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8329 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008330 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
8331 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer) {
John Kesseniche7df8e02018-08-22 17:12:46 -06008332 SpirvToolsLegalize(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008333 prelegalization = false;
8334 }
John Kessenich717c80a2018-08-23 15:17:10 -06008335
John Kessenich4e11b612018-08-30 16:56:59 -06008336 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008337 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008338
John Kessenich717c80a2018-08-23 15:17:10 -06008339 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008340 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008341
GregFcd1f1692017-09-21 18:40:22 -06008342#endif
8343
John Kessenich4e11b612018-08-30 16:56:59 -06008344 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008345}
8346
8347}; // end namespace glslang