blob: df42458376734d18e45ebbe19d690fa350ba23cc [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
Chao Chenb50c02e2018-09-19 11:42:24 -07002611 case glslang::EOpIgnoreIntersectionNV:
2612 case glslang::EOpTerminateRayNV:
2613 case glslang::EOpTraceNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07002614 case glslang::EOpExecuteCallableNV:
Chao Chen3c366992018-09-19 11:41:59 -07002615 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2616 noReturnValue = true;
2617 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002618 case glslang::EOpCooperativeMatrixLoad:
2619 case glslang::EOpCooperativeMatrixStore:
2620 noReturnValue = true;
2621 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002622 case glslang::EOpBeginInvocationInterlock:
2623 case glslang::EOpEndInvocationInterlock:
2624 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2625 noReturnValue = true;
2626 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002627#endif
Chao Chen3c366992018-09-19 11:41:59 -07002628
John Kessenich140f3df2015-06-26 16:58:36 -06002629 default:
2630 break;
2631 }
2632
2633 //
2634 // See if it maps to a regular operation.
2635 //
John Kessenich140f3df2015-06-26 16:58:36 -06002636 if (binOp != glslang::EOpNull) {
2637 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2638 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2639 assert(left && right);
2640
2641 builder.clearAccessChain();
2642 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002643 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002644
2645 builder.clearAccessChain();
2646 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002647 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002648
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002649 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002650 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002651 TranslateNoContractionDecoration(node->getType().getQualifier()),
2652 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002653 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002654 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002655 left->getType().getBasicType(), reduceComparison);
2656
2657 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002658 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002659 builder.clearAccessChain();
2660 builder.setAccessChainRValue(result);
2661
2662 return false;
2663 }
2664
John Kessenich426394d2015-07-23 10:22:48 -06002665 //
2666 // Create the list of operands.
2667 //
John Kessenich140f3df2015-06-26 16:58:36 -06002668 glslang::TIntermSequence& glslangOperands = node->getSequence();
2669 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002670 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002671 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002672 // special case l-value operands; there are just a few
2673 bool lvalue = false;
2674 switch (node->getOp()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002675 case glslang::EOpModf:
2676 if (arg == 1)
2677 lvalue = true;
2678 break;
John Kesseniche5eee8f2019-10-18 01:03:11 -06002679
2680 case glslang::EOpAtomicAdd:
2681 case glslang::EOpAtomicMin:
2682 case glslang::EOpAtomicMax:
2683 case glslang::EOpAtomicAnd:
2684 case glslang::EOpAtomicOr:
2685 case glslang::EOpAtomicXor:
2686 case glslang::EOpAtomicExchange:
2687 case glslang::EOpAtomicCompSwap:
2688 if (arg == 0)
2689 lvalue = true;
2690 break;
2691
John Kessenicha28f7a72019-08-06 07:00:58 -06002692#ifndef GLSLANG_WEB
2693 case glslang::EOpFrexp:
2694 if (arg == 1)
2695 lvalue = true;
2696 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002697 case glslang::EOpInterpolateAtSample:
2698 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002699 case glslang::EOpInterpolateAtVertex:
John Kessenich8c8505c2016-07-26 12:50:38 -06002700 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002701 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002702
2703 // Does it need a swizzle inversion? If so, evaluation is inverted;
2704 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002705 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002706 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2707 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2708 }
Rex Xu7a26c172015-12-08 17:12:09 +08002709 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05002710 case glslang::EOpAtomicLoad:
2711 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002712 case glslang::EOpAtomicCounterAdd:
2713 case glslang::EOpAtomicCounterSubtract:
2714 case glslang::EOpAtomicCounterMin:
2715 case glslang::EOpAtomicCounterMax:
2716 case glslang::EOpAtomicCounterAnd:
2717 case glslang::EOpAtomicCounterOr:
2718 case glslang::EOpAtomicCounterXor:
2719 case glslang::EOpAtomicCounterExchange:
2720 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002721 if (arg == 0)
2722 lvalue = true;
2723 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002724 case glslang::EOpAddCarry:
2725 case glslang::EOpSubBorrow:
2726 if (arg == 2)
2727 lvalue = true;
2728 break;
2729 case glslang::EOpUMulExtended:
2730 case glslang::EOpIMulExtended:
2731 if (arg >= 2)
2732 lvalue = true;
2733 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002734 case glslang::EOpCooperativeMatrixLoad:
2735 if (arg == 0 || arg == 1)
2736 lvalue = true;
2737 break;
2738 case glslang::EOpCooperativeMatrixStore:
2739 if (arg == 1)
2740 lvalue = true;
2741 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002742#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002743 default:
2744 break;
2745 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002746 builder.clearAccessChain();
2747 if (invertedType != spv::NoType && arg == 0)
2748 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2749 else
2750 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002751
John Kessenichb9197c82019-08-11 07:41:45 -06002752#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002753 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2754 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2755
2756 if (arg == 1) {
2757 // fold "element" parameter into the access chain
2758 spv::Builder::AccessChain save = builder.getAccessChain();
2759 builder.clearAccessChain();
2760 glslangOperands[2]->traverse(this);
2761
2762 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2763
2764 builder.setAccessChain(save);
2765
2766 // Point to the first element of the array.
2767 builder.accessChainPush(elementId, TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
Jeff Bolz7895e472019-03-06 13:34:10 -06002768 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002769
2770 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2771 unsigned int alignment = builder.getAccessChain().alignment;
2772
2773 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2774 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2775 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2776 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2777 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
2778 if (builder.getStorageClass(builder.getAccessChain().base) == spv::StorageClassPhysicalStorageBufferEXT) {
2779 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2780 }
2781
2782 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2783
2784 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2785 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2786 }
2787
2788 if (memoryAccess & (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2789 memoryAccessOperands.push_back(spv::IdImmediate(true, builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
2790 }
2791 } else if (arg == 2) {
2792 continue;
2793 }
2794 }
John Kessenichb9197c82019-08-11 07:41:45 -06002795#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002796
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002797 if (lvalue) {
John Kessenich140f3df2015-06-26 16:58:36 -06002798 operands.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002799 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2800 lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
2801 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002802 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich32cfd492016-02-02 12:37:46 -07002803 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002804 }
John Kessenich140f3df2015-06-26 16:58:36 -06002805 }
John Kessenich426394d2015-07-23 10:22:48 -06002806
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002807 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichb9197c82019-08-11 07:41:45 -06002808#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002809 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
2810 std::vector<spv::IdImmediate> idImmOps;
2811
2812 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2813 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2814 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2815 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2816 // get the pointee type
2817 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
2818 assert(builder.isCooperativeMatrixType(typeId));
2819 // do the op
2820 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
2821 // store the result to the pointer (out param 'm')
2822 builder.createStore(result, operands[0]);
2823 result = 0;
2824 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
2825 std::vector<spv::IdImmediate> idImmOps;
2826
2827 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2828 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
2829 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2830 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2831 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2832
2833 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
2834 result = 0;
John Kessenichb9197c82019-08-11 07:41:45 -06002835 } else
2836#endif
John Kesseniche5eee8f2019-10-18 01:03:11 -06002837 if (atomic) {
2838 // Handle all atomics
2839 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(), lvalueCoherentFlags);
2840 } else {
John Kessenich426394d2015-07-23 10:22:48 -06002841 // Pass through to generic operations.
2842 switch (glslangOperands.size()) {
2843 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002844 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002845 break;
2846 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002847 {
2848 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002849 TranslateNoContractionDecoration(node->getType().getQualifier()),
2850 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002851 result = createUnaryOperation(
2852 node->getOp(), decorations,
2853 resultType(), operands.front(),
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002854 glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -06002855 }
John Kessenich426394d2015-07-23 10:22:48 -06002856 break;
2857 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002858 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002859 break;
2860 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002861 if (invertedType)
2862 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002863 }
2864
2865 if (noReturnValue)
2866 return false;
2867
2868 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002869 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002870 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002871 } else {
2872 builder.clearAccessChain();
2873 builder.setAccessChainRValue(result);
2874 return false;
2875 }
2876}
2877
John Kessenich433e9ff2017-01-26 20:31:11 -07002878// This path handles both if-then-else and ?:
2879// The if-then-else has a node type of void, while
2880// ?: has either a void or a non-void node type
2881//
2882// Leaving the result, when not void:
2883// GLSL only has r-values as the result of a :?, but
2884// if we have an l-value, that can be more efficient if it will
2885// become the base of a complex r-value expression, because the
2886// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002887bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2888{
John Kessenich0c1e71a2019-01-10 18:23:06 +07002889 // see if OpSelect can handle it
2890 const auto isOpSelectable = [&]() {
2891 if (node->getBasicType() == glslang::EbtVoid)
2892 return false;
2893 // OpSelect can do all other types starting with SPV 1.4
2894 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
2895 // pre-1.4, only scalars and vectors can be handled
2896 if ((!node->getType().isScalar() && !node->getType().isVector()))
2897 return false;
2898 }
2899 return true;
2900 };
2901
John Kessenich4bee5312018-02-20 21:29:05 -07002902 // See if it simple and safe, or required, to execute both sides.
2903 // Crucially, side effects must be either semantically required or avoided,
2904 // and there are performance trade-offs.
2905 // Return true if required or a good idea (and safe) to execute both sides,
2906 // false otherwise.
2907 const auto bothSidesPolicy = [&]() -> bool {
2908 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002909 if (node->getTrueBlock() == nullptr ||
2910 node->getFalseBlock() == nullptr)
2911 return false;
2912
John Kessenich4bee5312018-02-20 21:29:05 -07002913 // required? (unless we write additional code to look for side effects
2914 // and make performance trade-offs if none are present)
2915 if (!node->getShortCircuit())
2916 return true;
2917
2918 // if not required to execute both, decide based on performance/practicality...
2919
John Kessenich0c1e71a2019-01-10 18:23:06 +07002920 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07002921 return false;
2922
John Kessenich433e9ff2017-01-26 20:31:11 -07002923 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2924 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2925
2926 // return true if a single operand to ? : is okay for OpSelect
2927 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002928 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002929 };
2930
2931 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2932 operandOkay(node->getFalseBlock()->getAsTyped());
2933 };
2934
John Kessenich4bee5312018-02-20 21:29:05 -07002935 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2936 // emit the condition before doing anything with selection
2937 node->getCondition()->traverse(this);
2938 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2939
2940 // Find a way of executing both sides and selecting the right result.
2941 const auto executeBothSides = [&]() -> void {
2942 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002943 node->getTrueBlock()->traverse(this);
2944 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2945 node->getFalseBlock()->traverse(this);
2946 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2947
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002948 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002949
John Kessenich4bee5312018-02-20 21:29:05 -07002950 // done if void
2951 if (node->getBasicType() == glslang::EbtVoid)
2952 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002953
John Kessenich4bee5312018-02-20 21:29:05 -07002954 // emit code to select between trueValue and falseValue
2955
2956 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07002957 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07002958 // Emit OpSelect for this selection.
2959
2960 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07002961 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
2962 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07002963 condition = builder.smearScalar(spv::NoPrecision, condition,
2964 builder.makeVectorType(builder.makeBoolType(),
2965 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07002966 }
John Kessenich4bee5312018-02-20 21:29:05 -07002967
2968 // OpSelect
2969 result = builder.createTriOp(spv::OpSelect,
2970 convertGlslangToSpvType(node->getType()), condition,
2971 trueValue, falseValue);
2972
2973 builder.clearAccessChain();
2974 builder.setAccessChainRValue(result);
2975 } else {
2976 // We need control flow to select the result.
2977 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2978 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2979
2980 // Selection control:
2981 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2982
2983 // make an "if" based on the value created by the condition
2984 spv::Builder::If ifBuilder(condition, control, builder);
2985
2986 // emit the "then" statement
2987 builder.createStore(trueValue, result);
2988 ifBuilder.makeBeginElse();
2989 // emit the "else" statement
2990 builder.createStore(falseValue, result);
2991
2992 // finish off the control flow
2993 ifBuilder.makeEndIf();
2994
2995 builder.clearAccessChain();
2996 builder.setAccessChainLValue(result);
2997 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002998 };
2999
John Kessenich4bee5312018-02-20 21:29:05 -07003000 // Execute the one side needed, as per the condition
3001 const auto executeOneSide = [&]() {
3002 // Always emit control flow.
3003 if (node->getBasicType() != glslang::EbtVoid)
3004 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07003005
John Kessenich4bee5312018-02-20 21:29:05 -07003006 // Selection control:
3007 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3008
3009 // make an "if" based on the value created by the condition
3010 spv::Builder::If ifBuilder(condition, control, builder);
3011
3012 // emit the "then" statement
3013 if (node->getTrueBlock() != nullptr) {
3014 node->getTrueBlock()->traverse(this);
3015 if (result != spv::NoResult)
3016 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
3017 }
3018
3019 if (node->getFalseBlock() != nullptr) {
3020 ifBuilder.makeBeginElse();
3021 // emit the "else" statement
3022 node->getFalseBlock()->traverse(this);
3023 if (result != spv::NoResult)
3024 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
3025 }
3026
3027 // finish off the control flow
3028 ifBuilder.makeEndIf();
3029
3030 if (result != spv::NoResult) {
3031 builder.clearAccessChain();
3032 builder.setAccessChainLValue(result);
3033 }
3034 };
3035
3036 // Try for OpSelect (or a requirement to execute both sides)
3037 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003038 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
3039 if (node->getType().getQualifier().isSpecConstant())
3040 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07003041 executeBothSides();
3042 } else
3043 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06003044
3045 return false;
3046}
3047
3048bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
3049{
3050 // emit and get the condition before doing anything with switch
3051 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003052 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06003053
Rex Xu57e65922017-07-04 23:23:40 +08003054 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07003055 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08003056
John Kessenich140f3df2015-06-26 16:58:36 -06003057 // browse the children to sort out code segments
3058 int defaultSegment = -1;
3059 std::vector<TIntermNode*> codeSegments;
3060 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
3061 std::vector<int> caseValues;
3062 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
3063 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
3064 TIntermNode* child = *c;
3065 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02003066 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003067 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02003068 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003069 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
3070 } else
3071 codeSegments.push_back(child);
3072 }
3073
qining25262b32016-05-06 17:25:16 -04003074 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06003075 // statements between the last case and the end of the switch statement
3076 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
3077 (int)codeSegments.size() == defaultSegment)
3078 codeSegments.push_back(nullptr);
3079
3080 // make the switch statement
3081 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08003082 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06003083
3084 // emit all the code in the segments
3085 breakForLoop.push(false);
3086 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
3087 builder.nextSwitchSegment(segmentBlocks, s);
3088 if (codeSegments[s])
3089 codeSegments[s]->traverse(this);
3090 else
3091 builder.addSwitchBreak();
3092 }
3093 breakForLoop.pop();
3094
3095 builder.endSwitch(segmentBlocks);
3096
3097 return false;
3098}
3099
3100void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
3101{
3102 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003103 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06003104
3105 builder.clearAccessChain();
3106 builder.setAccessChainRValue(constant);
3107}
3108
3109bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
3110{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003111 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003112 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06003113
3114 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07003115 std::vector<unsigned int> operands;
3116 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06003117
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003118 // Spec requires back edges to target header blocks, and every header block
3119 // must dominate its merge block. Make a header block first to ensure these
3120 // conditions are met. By definition, it will contain OpLoopMerge, followed
3121 // by a block-ending branch. But we don't want to put any other body/test
3122 // instructions in it, since the body/test may have arbitrary instructions,
3123 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003124 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003125 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07003126 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003127 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003128 spv::Block& test = builder.makeNewBlock();
3129 builder.createBranch(&test);
3130
3131 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06003132 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06003133 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003134 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
3135
3136 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003137 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003138 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003139 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003140 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003141 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003142
3143 builder.setBuildPoint(&blocks.continue_target);
3144 if (node->getTerminal())
3145 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003146 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04003147 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003148 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003149 builder.createBranch(&blocks.body);
3150
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003151 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003152 builder.setBuildPoint(&blocks.body);
3153 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003154 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003155 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003156 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003157
3158 builder.setBuildPoint(&blocks.continue_target);
3159 if (node->getTerminal())
3160 node->getTerminal()->traverse(this);
3161 if (node->getTest()) {
3162 node->getTest()->traverse(this);
3163 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07003164 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003165 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003166 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05003167 // TODO: unless there was a break/return/discard instruction
3168 // somewhere in the body, this is an infinite loop, so we should
3169 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003170 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003171 }
John Kessenich140f3df2015-06-26 16:58:36 -06003172 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003173 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003174 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06003175 return false;
3176}
3177
3178bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
3179{
3180 if (node->getExpression())
3181 node->getExpression()->traverse(this);
3182
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003183 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003184
John Kessenich140f3df2015-06-26 16:58:36 -06003185 switch (node->getFlowOp()) {
3186 case glslang::EOpKill:
3187 builder.makeDiscard();
3188 break;
3189 case glslang::EOpBreak:
3190 if (breakForLoop.top())
3191 builder.createLoopExit();
3192 else
3193 builder.addSwitchBreak();
3194 break;
3195 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06003196 builder.createLoopContinue();
3197 break;
3198 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06003199 if (node->getExpression()) {
3200 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3201 spv::Id returnId = accessChainLoad(glslangReturnType);
3202 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
3203 builder.clearAccessChain();
3204 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
3205 builder.setAccessChainLValue(copyId);
3206 multiTypeStore(glslangReturnType, returnId);
3207 returnId = builder.createLoad(copyId);
3208 }
3209 builder.makeReturn(false, returnId);
3210 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003211 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003212
3213 builder.clearAccessChain();
3214 break;
3215
John Kessenichb9197c82019-08-11 07:41:45 -06003216#ifndef GLSLANG_WEB
Jeff Bolzba6170b2019-07-01 09:23:23 -05003217 case glslang::EOpDemote:
3218 builder.createNoResultOp(spv::OpDemoteToHelperInvocationEXT);
3219 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
3220 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
3221 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003222#endif
Jeff Bolzba6170b2019-07-01 09:23:23 -05003223
John Kessenich140f3df2015-06-26 16:58:36 -06003224 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003225 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003226 break;
3227 }
3228
3229 return false;
3230}
3231
John Kessenich9c14f772019-06-17 08:38:35 -06003232spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node, spv::Id forcedType)
John Kessenich140f3df2015-06-26 16:58:36 -06003233{
qining25262b32016-05-06 17:25:16 -04003234 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003235 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003236 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003237 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003238 spv::Id result = createSpvConstant(*node);
3239 if (result != spv::NoResult)
3240 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003241 }
3242
3243 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003244 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06003245 spv::Id spvType = forcedType == spv::NoType ? convertGlslangToSpvType(node->getType())
3246 : forcedType;
John Kessenich140f3df2015-06-26 16:58:36 -06003247
John Kessenichb9197c82019-08-11 07:41:45 -06003248 const bool contains16BitType = node->getType().contains16BitFloat() ||
3249 node->getType().contains16BitInt();
Rex Xuf89ad982017-04-07 23:22:33 +08003250 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003251 switch (storageClass) {
3252 case spv::StorageClassInput:
3253 case spv::StorageClassOutput:
John Kessenich8317e6c2019-08-18 23:58:08 -06003254 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003255 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003256 break;
John Kessenich18310872018-05-14 22:08:53 -06003257 case spv::StorageClassUniform:
John Kessenich8317e6c2019-08-18 23:58:08 -06003258 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003259 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3260 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003261 else
3262 builder.addCapability(spv::CapabilityStorageUniform16);
3263 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003264#ifndef GLSLANG_WEB
3265 case spv::StorageClassPushConstant:
John Kessenich8317e6c2019-08-18 23:58:08 -06003266 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenichb9197c82019-08-11 07:41:45 -06003267 builder.addCapability(spv::CapabilityStoragePushConstant16);
3268 break;
John Kessenich18310872018-05-14 22:08:53 -06003269 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003270 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich8317e6c2019-08-18 23:58:08 -06003271 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenich18310872018-05-14 22:08:53 -06003272 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3273 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003274#endif
John Kessenich18310872018-05-14 22:08:53 -06003275 default:
John Kessenichb9197c82019-08-11 07:41:45 -06003276 if (node->getType().contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003277 builder.addCapability(spv::CapabilityFloat16);
John Kessenichb9197c82019-08-11 07:41:45 -06003278 if (node->getType().contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003279 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06003280 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003281 }
3282 }
Rex Xuf89ad982017-04-07 23:22:33 +08003283
John Kessenichb9197c82019-08-11 07:41:45 -06003284 if (node->getType().contains8BitInt()) {
John Kessenich312dcfb2018-07-03 13:19:51 -06003285 if (storageClass == spv::StorageClassPushConstant) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003286 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003287 builder.addCapability(spv::CapabilityStoragePushConstant8);
3288 } else if (storageClass == spv::StorageClassUniform) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003289 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003290 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003291 } else if (storageClass == spv::StorageClassStorageBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003292 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
Neil Henningb6b01f02018-10-23 15:02:29 +01003293 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003294 } else {
3295 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06003296 }
3297 }
3298
John Kessenich140f3df2015-06-26 16:58:36 -06003299 const char* name = node->getName().c_str();
3300 if (glslang::IsAnonymous(name))
3301 name = "";
3302
3303 return builder.createVariable(storageClass, spvType, name);
3304}
3305
3306// Return type Id of the sampled type.
3307spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3308{
3309 switch (sampler.type) {
John Kessenicha28f7a72019-08-06 07:00:58 -06003310 case glslang::EbtInt: return builder.makeIntType(32);
3311 case glslang::EbtUint: return builder.makeUintType(32);
John Kessenich140f3df2015-06-26 16:58:36 -06003312 case glslang::EbtFloat: return builder.makeFloatType(32);
John Kessenicha28f7a72019-08-06 07:00:58 -06003313#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08003314 case glslang::EbtFloat16:
3315 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3316 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3317 return builder.makeFloatType(16);
3318#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003319 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003320 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003321 return builder.makeFloatType(32);
3322 }
3323}
3324
John Kessenich8c8505c2016-07-26 12:50:38 -06003325// If node is a swizzle operation, return the type that should be used if
3326// the swizzle base is first consumed by another operation, before the swizzle
3327// is applied.
3328spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3329{
John Kessenichecba76f2017-01-06 00:34:48 -07003330 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003331 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3332 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3333 else
3334 return spv::NoType;
3335}
3336
3337// When inverting a swizzle with a parent op, this function
3338// will apply the swizzle operation to a completed parent operation.
3339spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
3340{
3341 std::vector<unsigned> swizzle;
3342 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3343 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3344}
3345
John Kessenich8c8505c2016-07-26 12:50:38 -06003346// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3347void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3348{
3349 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3350 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3351 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3352}
3353
John Kessenich3ac051e2015-12-20 11:29:16 -07003354// Convert from a glslang type to an SPV type, by calling into a
3355// recursive version of this function. This establishes the inherited
3356// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003357spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003358{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003359 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003360}
3361
3362// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003363// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003364// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003365spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003366 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3367 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003368{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003369 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003370
3371 switch (type.getBasicType()) {
3372 case glslang::EbtVoid:
3373 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003374 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003375 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003376 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003377 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3378 // a 32-bit int where non-0 means true.
3379 if (explicitLayout != glslang::ElpNone)
3380 spvType = builder.makeUintType(32);
3381 else
3382 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003383 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003384 case glslang::EbtInt:
3385 spvType = builder.makeIntType(32);
3386 break;
3387 case glslang::EbtUint:
3388 spvType = builder.makeUintType(32);
3389 break;
3390 case glslang::EbtFloat:
3391 spvType = builder.makeFloatType(32);
3392 break;
3393#ifndef GLSLANG_WEB
3394 case glslang::EbtDouble:
3395 spvType = builder.makeFloatType(64);
3396 break;
3397 case glslang::EbtFloat16:
3398 spvType = builder.makeFloatType(16);
3399 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003400 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003401 spvType = builder.makeIntType(8);
3402 break;
3403 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003404 spvType = builder.makeUintType(8);
3405 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003406 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003407 spvType = builder.makeIntType(16);
3408 break;
3409 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003410 spvType = builder.makeUintType(16);
3411 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003412 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003413 spvType = builder.makeIntType(64);
3414 break;
3415 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003416 spvType = builder.makeUintType(64);
3417 break;
John Kessenich426394d2015-07-23 10:22:48 -06003418 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003419 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003420 spvType = builder.makeUintType(32);
3421 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003422 case glslang::EbtAccStructNV:
3423 spvType = builder.makeAccelerationStructureNVType();
3424 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003425 case glslang::EbtReference:
3426 {
3427 // Make the forward pointer, then recurse to convert the structure type, then
3428 // patch up the forward pointer with a real pointer type.
3429 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3430 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3431 forwardPointers[type.getReferentType()] = forwardId;
3432 }
3433 spvType = forwardPointers[type.getReferentType()];
3434 if (!forwardReferenceOnly) {
3435 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3436 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3437 forwardPointers[type.getReferentType()],
3438 referentType);
3439 }
3440 }
3441 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003442#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003443 case glslang::EbtSampler:
3444 {
3445 const glslang::TSampler& sampler = type.getSampler();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003446 if (sampler.isPureSampler()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003447 spvType = builder.makeSamplerType();
3448 } else {
3449 // an image is present, make its type
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003450 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler),
3451 sampler.isShadow(), sampler.isArrayed(), sampler.isMultiSample(),
3452 sampler.isImageClass() ? 2 : 1, TranslateImageFormat(type));
3453 if (sampler.isCombined()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003454 // already has both image and sampler, make the combined type
3455 spvType = builder.makeSampledImageType(spvType);
3456 }
John Kessenich55e7d112015-11-15 21:33:39 -07003457 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003458 }
John Kessenich140f3df2015-06-26 16:58:36 -06003459 break;
3460 case glslang::EbtStruct:
3461 case glslang::EbtBlock:
3462 {
3463 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003464 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003465
3466 // Try to share structs for different layouts, but not yet for other
3467 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003468 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003469 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003470 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003471 break;
3472
3473 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003474 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06003475 memberRemapper[glslangMembers].resize(glslangMembers->size());
3476 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003477 }
3478 break;
3479 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003480 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003481 break;
3482 }
3483
3484 if (type.isMatrix())
3485 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3486 else {
3487 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3488 if (type.getVectorSize() > 1)
3489 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3490 }
3491
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003492 if (type.isCoopMat()) {
3493 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3494 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3495 if (type.getBasicType() == glslang::EbtFloat16)
3496 builder.addCapability(spv::CapabilityFloat16);
Jeff Bolz387657e2019-08-22 20:28:00 -05003497 if (type.getBasicType() == glslang::EbtUint8 ||
3498 type.getBasicType() == glslang::EbtInt8) {
3499 builder.addCapability(spv::CapabilityInt8);
3500 }
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003501
3502 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3503 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3504 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3505
3506 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3507 }
3508
John Kessenich140f3df2015-06-26 16:58:36 -06003509 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003510 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3511
John Kessenichc9a80832015-09-12 12:17:44 -06003512 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003513 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003514 // We need to decorate array strides for types needing explicit layout, except blocks.
3515 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003516 // Use a dummy glslang type for querying internal strides of
3517 // arrays of arrays, but using just a one-dimensional array.
3518 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003519 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3520 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003521
3522 // Will compute the higher-order strides here, rather than making a whole
3523 // pile of types and doing repetitive recursion on their contents.
3524 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3525 }
John Kessenichf8842e52016-01-04 19:22:56 -07003526
3527 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003528 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003529 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003530 if (stride > 0)
3531 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003532 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003533 }
3534 } else {
3535 // single-dimensional array, and don't yet have stride
3536
John Kessenichf8842e52016-01-04 19:22:56 -07003537 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003538 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3539 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003540 }
John Kessenich31ed4832015-09-09 17:51:38 -06003541
John Kessenichead86222018-03-28 18:01:20 -06003542 // Do the outer dimension, which might not be known for a runtime-sized array.
3543 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3544 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003545 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003546 else {
John Kessenichb9197c82019-08-11 07:41:45 -06003547#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003548 if (!lastBufferBlockMember) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003549 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06003550 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3551 }
John Kessenichb9197c82019-08-11 07:41:45 -06003552#endif
John Kessenich3dd1ce52019-10-17 07:08:40 -06003553 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003554 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003555 if (stride > 0)
3556 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003557 }
3558
3559 return spvType;
3560}
3561
John Kessenich0e737842017-03-24 18:38:16 -06003562// TODO: this functionality should exist at a higher level, in creating the AST
3563//
3564// Identify interface members that don't have their required extension turned on.
3565//
3566bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3567{
John Kessenicha28f7a72019-08-06 07:00:58 -06003568#ifndef GLSLANG_WEB
John Kessenich0e737842017-03-24 18:38:16 -06003569 auto& extensions = glslangIntermediate->getRequestedExtensions();
3570
Rex Xubcf291a2017-03-29 23:01:36 +08003571 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3572 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3573 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003574 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3575 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3576 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003577
3578 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3579 if (member.getFieldName() == "gl_ViewportMask" &&
3580 extensions.find("GL_NV_viewport_array2") == extensions.end())
3581 return true;
3582 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3583 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3584 return true;
3585 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3586 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3587 return true;
3588 }
3589#endif
John Kessenich0e737842017-03-24 18:38:16 -06003590
3591 return false;
3592};
3593
John Kessenich6090df02016-06-30 21:18:02 -06003594// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3595// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3596// Mutually recursive with convertGlslangToSpvType().
3597spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3598 const glslang::TTypeList* glslangMembers,
3599 glslang::TLayoutPacking explicitLayout,
3600 const glslang::TQualifier& qualifier)
3601{
3602 // Create a vector of struct types for SPIR-V to consume
3603 std::vector<spv::Id> spvMembers;
3604 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 -06003605 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003606 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3607 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3608 if (glslangMember.hiddenMember()) {
3609 ++memberDelta;
3610 if (type.getBasicType() == glslang::EbtBlock)
3611 memberRemapper[glslangMembers][i] = -1;
3612 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003613 if (type.getBasicType() == glslang::EbtBlock) {
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003614 if (filterMember(glslangMember)) {
3615 memberDelta++;
3616 memberRemapper[glslangMembers][i] = -1;
John Kessenich0e737842017-03-24 18:38:16 -06003617 continue;
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003618 }
3619 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003620 }
John Kessenich6090df02016-06-30 21:18:02 -06003621 // modify just this child's view of the qualifier
3622 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3623 InheritQualifiers(memberQualifier, qualifier);
3624
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003625 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003626 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003627 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003628
3629 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003630 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3631 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003632
3633 // Make forward pointers for any pointer members, and create a list of members to
3634 // convert to spirv types after creating the struct.
John Kessenich7015bd62019-08-01 03:28:08 -06003635 if (glslangMember.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003636 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3637 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3638 }
3639 spvMembers.push_back(
3640 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, true));
3641 } else {
3642 spvMembers.push_back(
3643 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, false));
3644 }
John Kessenich6090df02016-06-30 21:18:02 -06003645 }
3646 }
3647
3648 // Make the SPIR-V type
3649 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003650 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003651 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3652
3653 // Decorate it
3654 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3655
John Kessenichd72f4882019-01-16 14:55:37 +07003656 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003657 auto it = deferredForwardPointers[i];
3658 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3659 }
3660
John Kessenich6090df02016-06-30 21:18:02 -06003661 return spvType;
3662}
3663
3664void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3665 const glslang::TTypeList* glslangMembers,
3666 glslang::TLayoutPacking explicitLayout,
3667 const glslang::TQualifier& qualifier,
3668 spv::Id spvType)
3669{
3670 // Name and decorate the non-hidden members
3671 int offset = -1;
3672 int locationOffset = 0; // for use within the members of this struct
3673 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3674 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3675 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003676 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003677 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06003678 if (filterMember(glslangMember))
3679 continue;
3680 }
John Kessenich6090df02016-06-30 21:18:02 -06003681
3682 // modify just this child's view of the qualifier
3683 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3684 InheritQualifiers(memberQualifier, qualifier);
3685
3686 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003687 if (member < 0)
3688 continue;
3689
3690 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3691 builder.addMemberDecoration(spvType, member,
3692 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3693 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3694 // Add interpolation and auxiliary storage decorations only to
3695 // top-level members of Input and Output storage classes
3696 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3697 type.getQualifier().storage == glslang::EvqVaryingOut) {
3698 if (type.getBasicType() == glslang::EbtBlock ||
3699 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3700 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3701 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenicha28f7a72019-08-06 07:00:58 -06003702#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07003703 addMeshNVDecoration(spvType, member, memberQualifier);
3704#endif
John Kessenich6090df02016-06-30 21:18:02 -06003705 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003706 }
3707 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003708
John Kessenichb9197c82019-08-11 07:41:45 -06003709#ifndef GLSLANG_WEB
John Kessenich5d610ee2018-03-07 18:05:55 -07003710 if (type.getBasicType() == glslang::EbtBlock &&
3711 qualifier.storage == glslang::EvqBuffer) {
3712 // Add memory decorations only to top-level members of shader storage block
3713 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003714 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003715 for (unsigned int i = 0; i < memory.size(); ++i)
3716 builder.addMemberDecoration(spvType, member, memory[i]);
3717 }
John Kessenichf8d1d742019-10-21 06:55:11 -06003718
John Kessenichb9197c82019-08-11 07:41:45 -06003719#endif
John Kessenich6090df02016-06-30 21:18:02 -06003720
John Kessenich5d610ee2018-03-07 18:05:55 -07003721 // Location assignment was already completed correctly by the front end,
3722 // just track whether a member needs to be decorated.
3723 // Ignore member locations if the container is an array, as that's
3724 // ill-specified and decisions have been made to not allow this.
3725 if (! type.isArray() && memberQualifier.hasLocation())
3726 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003727
John Kessenich5d610ee2018-03-07 18:05:55 -07003728 if (qualifier.hasLocation()) // track for upcoming inheritance
3729 locationOffset += glslangIntermediate->computeTypeLocationSize(
3730 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003731
John Kessenich5d610ee2018-03-07 18:05:55 -07003732 // component, XFB, others
3733 if (glslangMember.getQualifier().hasComponent())
3734 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3735 glslangMember.getQualifier().layoutComponent);
3736 if (glslangMember.getQualifier().hasXfbOffset())
3737 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3738 glslangMember.getQualifier().layoutXfbOffset);
3739 else if (explicitLayout != glslang::ElpNone) {
3740 // figure out what to do with offset, which is accumulating
3741 int nextOffset;
3742 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3743 if (offset >= 0)
3744 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3745 offset = nextOffset;
3746 }
John Kessenich6090df02016-06-30 21:18:02 -06003747
John Kessenich5d610ee2018-03-07 18:05:55 -07003748 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3749 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3750 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003751
John Kessenich5d610ee2018-03-07 18:05:55 -07003752 // built-in variable decorations
3753 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3754 if (builtIn != spv::BuiltInMax)
3755 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003756
John Kessenichb9197c82019-08-11 07:41:45 -06003757#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003758 // nonuniform
3759 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3760
John Kessenichead86222018-03-28 18:01:20 -06003761 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3762 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3763 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3764 memberQualifier.semanticName);
3765 }
3766
John Kessenich5d610ee2018-03-07 18:05:55 -07003767 if (builtIn == spv::BuiltInLayer) {
3768 // SPV_NV_viewport_array2 extension
3769 if (glslangMember.getQualifier().layoutViewportRelative){
3770 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3771 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3772 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003773 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003774 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3775 builder.addMemberDecoration(spvType, member,
3776 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3777 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3778 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3779 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003780 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003781 }
3782 if (glslangMember.getQualifier().layoutPassthrough) {
3783 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3784 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3785 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3786 }
chaoc771d89f2017-01-13 01:10:53 -08003787#endif
John Kessenich6090df02016-06-30 21:18:02 -06003788 }
3789
3790 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003791 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3792 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003793}
3794
John Kessenich6c292d32016-02-15 20:58:50 -07003795// Turn the expression forming the array size into an id.
3796// This is not quite trivial, because of specialization constants.
3797// Sometimes, a raw constant is turned into an Id, and sometimes
3798// a specialization constant expression is.
3799spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3800{
3801 // First, see if this is sized with a node, meaning a specialization constant:
3802 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3803 if (specNode != nullptr) {
3804 builder.clearAccessChain();
3805 specNode->traverse(this);
3806 return accessChainLoad(specNode->getAsTyped()->getType());
3807 }
qining25262b32016-05-06 17:25:16 -04003808
John Kessenich6c292d32016-02-15 20:58:50 -07003809 // Otherwise, need a compile-time (front end) size, get it:
3810 int size = arraySizes.getDimSize(dim);
3811 assert(size > 0);
3812 return builder.makeUintConstant(size);
3813}
3814
John Kessenich103bef92016-02-08 21:38:15 -07003815// Wrap the builder's accessChainLoad to:
3816// - localize handling of RelaxedPrecision
3817// - use the SPIR-V inferred type instead of another conversion of the glslang type
3818// (avoids unnecessary work and possible type punning for structures)
3819// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003820spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3821{
John Kessenich103bef92016-02-08 21:38:15 -07003822 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003823
3824 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3825 coherentFlags |= TranslateCoherent(type);
3826
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003827 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003828 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003829
John Kessenich5611c6d2018-04-05 11:25:02 -06003830 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003831 TranslateNonUniformDecoration(type.getQualifier()),
3832 nominalTypeId,
3833 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003834 TranslateMemoryScope(coherentFlags),
3835 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07003836
3837 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003838 if (type.getBasicType() == glslang::EbtBool) {
3839 if (builder.isScalarType(nominalTypeId)) {
3840 // Conversion for bool
3841 spv::Id boolType = builder.makeBoolType();
3842 if (nominalTypeId != boolType)
3843 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3844 } else if (builder.isVectorType(nominalTypeId)) {
3845 // Conversion for bvec
3846 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3847 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3848 if (nominalTypeId != bvecType)
3849 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3850 }
3851 }
John Kessenich103bef92016-02-08 21:38:15 -07003852
3853 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003854}
3855
Rex Xu27253232016-02-23 17:51:09 +08003856// Wrap the builder's accessChainStore to:
3857// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003858//
3859// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003860void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3861{
3862 // Need to convert to abstract types when necessary
3863 if (type.getBasicType() == glslang::EbtBool) {
3864 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3865
3866 if (builder.isScalarType(nominalTypeId)) {
3867 // Conversion for bool
3868 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003869 if (nominalTypeId != boolType) {
3870 // keep these outside arguments, for determinant order-of-evaluation
3871 spv::Id one = builder.makeUintConstant(1);
3872 spv::Id zero = builder.makeUintConstant(0);
3873 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3874 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003875 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003876 } else if (builder.isVectorType(nominalTypeId)) {
3877 // Conversion for bvec
3878 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3879 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003880 if (nominalTypeId != bvecType) {
3881 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003882 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3883 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3884 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003885 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003886 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3887 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003888 }
3889 }
3890
Jeff Bolz36831c92018-09-05 10:11:41 -05003891 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3892 coherentFlags |= TranslateCoherent(type);
3893
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003894 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003895 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003896
Jeff Bolz36831c92018-09-05 10:11:41 -05003897 builder.accessChainStore(rvalue,
3898 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003899 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08003900}
3901
John Kessenich4bf71552016-09-02 11:20:21 -06003902// For storing when types match at the glslang level, but not might match at the
3903// SPIR-V level.
3904//
3905// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003906// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003907// as in a member-decorated way.
3908//
3909// NOTE: This function can handle any store request; if it's not special it
3910// simplifies to a simple OpStore.
3911//
3912// Implicitly uses the existing builder.accessChain as the storage target.
3913void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3914{
John Kessenichb3e24e42016-09-11 12:33:43 -06003915 // we only do the complex path here if it's an aggregate
3916 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003917 accessChainStore(type, rValue);
3918 return;
3919 }
3920
John Kessenichb3e24e42016-09-11 12:33:43 -06003921 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003922 spv::Id rType = builder.getTypeId(rValue);
3923 spv::Id lValue = builder.accessChainGetLValue();
3924 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3925 if (lType == rType) {
3926 accessChainStore(type, rValue);
3927 return;
3928 }
3929
John Kessenichb3e24e42016-09-11 12:33:43 -06003930 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003931 // where the two types were the same type in GLSL. This requires member
3932 // by member copy, recursively.
3933
John Kessenichfbb6bdf2019-01-15 21:48:27 +07003934 // SPIR-V 1.4 added an instruction to do help do this.
3935 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
3936 // However, bool in uniform space is changed to int, so
3937 // OpCopyLogical does not work for that.
3938 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
3939 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
3940 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
3941 if (lBool == rBool) {
3942 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
3943 accessChainStore(type, logicalCopy);
3944 return;
3945 }
3946 }
3947
John Kessenichb3e24e42016-09-11 12:33:43 -06003948 // If an array, copy element by element.
3949 if (type.isArray()) {
3950 glslang::TType glslangElementType(type, 0);
3951 spv::Id elementRType = builder.getContainedTypeId(rType);
3952 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3953 // get the source member
3954 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003955
John Kessenichb3e24e42016-09-11 12:33:43 -06003956 // set up the target storage
3957 builder.clearAccessChain();
3958 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003959 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06003960
John Kessenichb3e24e42016-09-11 12:33:43 -06003961 // store the member
3962 multiTypeStore(glslangElementType, elementRValue);
3963 }
3964 } else {
3965 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003966
John Kessenichb3e24e42016-09-11 12:33:43 -06003967 // loop over structure members
3968 const glslang::TTypeList& members = *type.getStruct();
3969 for (int m = 0; m < (int)members.size(); ++m) {
3970 const glslang::TType& glslangMemberType = *members[m].type;
3971
3972 // get the source member
3973 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3974 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3975
3976 // set up the target storage
3977 builder.clearAccessChain();
3978 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003979 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06003980
3981 // store the member
3982 multiTypeStore(glslangMemberType, memberRValue);
3983 }
John Kessenich4bf71552016-09-02 11:20:21 -06003984 }
3985}
3986
John Kessenichf85e8062015-12-19 13:57:10 -07003987// Decide whether or not this type should be
3988// decorated with offsets and strides, and if so
3989// whether std140 or std430 rules should be applied.
3990glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003991{
John Kessenichf85e8062015-12-19 13:57:10 -07003992 // has to be a block
3993 if (type.getBasicType() != glslang::EbtBlock)
3994 return glslang::ElpNone;
3995
Chao Chen3c366992018-09-19 11:41:59 -07003996 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07003997 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07003998 type.getQualifier().storage != glslang::EvqBuffer &&
3999 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07004000 return glslang::ElpNone;
4001
4002 // return the layout to use
4003 switch (type.getQualifier().layoutPacking) {
4004 case glslang::ElpStd140:
4005 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004006 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07004007 return type.getQualifier().layoutPacking;
4008 default:
4009 return glslang::ElpNone;
4010 }
John Kessenich31ed4832015-09-09 17:51:38 -06004011}
4012
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004013// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07004014int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004015{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004016 int size;
John Kessenich49987892015-12-29 17:11:44 -07004017 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004018 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07004019
4020 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004021}
4022
John Kessenich49987892015-12-29 17:11:44 -07004023// 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 -07004024// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07004025int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004026{
John Kessenich49987892015-12-29 17:11:44 -07004027 glslang::TType elementType;
4028 elementType.shallowCopy(matrixType);
4029 elementType.clearArraySizes();
4030
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004031 int size;
John Kessenich49987892015-12-29 17:11:44 -07004032 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004033 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07004034
4035 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004036}
4037
John Kessenich5e4b1242015-08-06 22:53:06 -06004038// Given a member type of a struct, realign the current offset for it, and compute
4039// the next (not yet aligned) offset for the next member, which will get aligned
4040// on the next call.
4041// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
4042// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
4043// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06004044void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07004045 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06004046{
4047 // this will get a positive value when deemed necessary
4048 nextOffset = -1;
4049
John Kessenich5e4b1242015-08-06 22:53:06 -06004050 // override anything in currentOffset with user-set offset
4051 if (memberType.getQualifier().hasOffset())
4052 currentOffset = memberType.getQualifier().layoutOffset;
4053
4054 // It could be that current linker usage in glslang updated all the layoutOffset,
4055 // in which case the following code does not matter. But, that's not quite right
4056 // once cross-compilation unit GLSL validation is done, as the original user
4057 // settings are needed in layoutOffset, and then the following will come into play.
4058
John Kessenichf85e8062015-12-19 13:57:10 -07004059 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06004060 if (! memberType.getQualifier().hasOffset())
4061 currentOffset = -1;
4062
4063 return;
4064 }
4065
John Kessenichf85e8062015-12-19 13:57:10 -07004066 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06004067 if (currentOffset < 0)
4068 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04004069
John Kessenich5e4b1242015-08-06 22:53:06 -06004070 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
4071 // but possibly not yet correctly aligned.
4072
4073 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07004074 int dummyStride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004075 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06004076
4077 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06004078 // TODO: make this consistent in early phases of code:
4079 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
4080 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
4081 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06004082 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06004083 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06004084 int dummySize;
4085 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
4086 if (componentAlignment <= 4)
4087 memberAlignment = componentAlignment;
4088 }
4089
4090 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06004091 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06004092
4093 // Bump up to vec4 if there is a bad straddle
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004094 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06004095 glslang::RoundToPow2(currentOffset, 16);
4096
John Kessenich5e4b1242015-08-06 22:53:06 -06004097 nextOffset = currentOffset + memberSize;
4098}
4099
David Netoa901ffe2016-06-08 14:11:40 +01004100void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06004101{
David Netoa901ffe2016-06-08 14:11:40 +01004102 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
4103 switch (glslangBuiltIn)
4104 {
John Kessenicha28f7a72019-08-06 07:00:58 -06004105 case glslang::EbvPointSize:
4106#ifndef GLSLANG_WEB
David Netoa901ffe2016-06-08 14:11:40 +01004107 case glslang::EbvClipDistance:
4108 case glslang::EbvCullDistance:
chaoc771d89f2017-01-13 01:10:53 -08004109 case glslang::EbvViewportMaskNV:
4110 case glslang::EbvSecondaryPositionNV:
4111 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08004112 case glslang::EbvPositionPerViewNV:
4113 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07004114 case glslang::EbvTaskCountNV:
4115 case glslang::EbvPrimitiveCountNV:
4116 case glslang::EbvPrimitiveIndicesNV:
4117 case glslang::EbvClipDistancePerViewNV:
4118 case glslang::EbvCullDistancePerViewNV:
4119 case glslang::EbvLayerPerViewNV:
4120 case glslang::EbvMeshViewCountNV:
4121 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004122#endif
David Netoa901ffe2016-06-08 14:11:40 +01004123 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4124 // Alternately, we could just call this for any glslang built-in, since the
4125 // capability already guards against duplicates.
4126 TranslateBuiltInDecoration(glslangBuiltIn, false);
4127 break;
4128 default:
4129 // Capabilities were already generated when the struct was declared.
4130 break;
4131 }
John Kessenichebb50532016-05-16 19:22:05 -06004132}
4133
John Kessenich6fccb3c2016-09-19 16:01:41 -06004134bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004135{
John Kessenicheee9d532016-09-19 18:09:30 -06004136 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004137}
4138
John Kessenichd41993d2017-09-10 15:21:05 -06004139// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004140// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4141// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004142bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004143{
John Kessenich6a14f782017-12-04 02:48:10 -07004144 assert(qualifier == glslang::EvqIn ||
4145 qualifier == glslang::EvqOut ||
4146 qualifier == glslang::EvqInOut ||
4147 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06004148 return qualifier != glslang::EvqConstReadOnly;
4149}
4150
4151// Is parameter pass-by-original?
4152bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4153 bool implicitThisParam)
4154{
4155 if (implicitThisParam) // implicit this
4156 return true;
4157 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004158 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004159 return paramType.containsOpaque() || // sampler, etc.
4160 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4161}
4162
John Kessenich140f3df2015-06-26 16:58:36 -06004163// Make all the functions, skeletally, without actually visiting their bodies.
4164void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4165{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004166 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004167 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4168 if (paramPrecision != spv::NoPrecision)
4169 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004170 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenich7015bd62019-08-01 03:28:08 -06004171 if (type.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004172 // Original and non-writable params pass the pointer directly and
4173 // use restrict/aliased, others are stored to a pointer in Function
4174 // memory and use RestrictPointer/AliasedPointer.
4175 if (originalParam(type.getQualifier().storage, type, false) ||
4176 !writableParam(type.getQualifier().storage)) {
John Kessenichf8d1d742019-10-21 06:55:11 -06004177 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrict :
4178 spv::DecorationAliased);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004179 } else {
John Kessenichf8d1d742019-10-21 06:55:11 -06004180 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrictPointerEXT :
4181 spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004182 }
4183 }
John Kessenichfad62972017-07-18 02:35:46 -06004184 };
4185
John Kessenich140f3df2015-06-26 16:58:36 -06004186 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4187 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004188 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004189 continue;
4190
4191 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004192 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004193 //
qining25262b32016-05-06 17:25:16 -04004194 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004195 // function. What it is an address of varies:
4196 //
John Kessenich4bf71552016-09-02 11:20:21 -06004197 // - "in" parameters not marked as "const" can be written to without modifying the calling
4198 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004199 //
4200 // - "const in" parameters can just be the r-value, as no writes need occur.
4201 //
John Kessenich4bf71552016-09-02 11:20:21 -06004202 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4203 // 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 -06004204
4205 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004206 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004207 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4208
John Kessenich155d3512019-08-08 23:29:20 -06004209#ifdef ENABLE_HLSL
John Kessenichfad62972017-07-18 02:35:46 -06004210 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4211 glslangIntermediate->implicitThisName;
John Kessenich155d3512019-08-08 23:29:20 -06004212#else
4213 bool implicitThis = false;
4214#endif
John Kessenich37789792017-03-21 23:56:40 -06004215
John Kessenichfad62972017-07-18 02:35:46 -06004216 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004217 for (int p = 0; p < (int)parameters.size(); ++p) {
4218 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4219 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004220 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004221 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004222 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004223 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4224 else
John Kessenich4bf71552016-09-02 11:20:21 -06004225 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004226 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004227 paramTypes.push_back(typeId);
4228 }
4229
4230 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004231 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4232 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004233 glslFunction->getName().c_str(), paramTypes,
4234 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004235 if (implicitThis)
4236 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004237
4238 // Track function to emit/call later
4239 functionMap[glslFunction->getName().c_str()] = function;
4240
4241 // Set the parameter id's
4242 for (int p = 0; p < (int)parameters.size(); ++p) {
4243 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4244 // give a name too
4245 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004246
4247 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
John Kessenichb9197c82019-08-11 07:41:45 -06004248 if (paramType.contains8BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004249 builder.addCapability(spv::CapabilityInt8);
John Kessenichb9197c82019-08-11 07:41:45 -06004250 if (paramType.contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004251 builder.addCapability(spv::CapabilityInt16);
John Kessenichb9197c82019-08-11 07:41:45 -06004252 if (paramType.contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004253 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004254 }
4255 }
4256}
4257
4258// Process all the initializers, while skipping the functions and link objects
4259void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4260{
4261 builder.setBuildPoint(shaderEntry->getLastBlock());
4262 for (int i = 0; i < (int)initializers.size(); ++i) {
4263 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
4264 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
4265
4266 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004267 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004268 initializer->traverse(this);
4269 }
4270 }
4271}
4272
4273// Process all the functions, while skipping initializers.
4274void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4275{
4276 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4277 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004278 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004279 node->traverse(this);
4280 }
4281}
4282
4283void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4284{
qining25262b32016-05-06 17:25:16 -04004285 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004286 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004287 currentFunction = functionMap[node->getName().c_str()];
4288 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004289 builder.setBuildPoint(functionBlock);
4290}
4291
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004292void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments, spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004293{
Rex Xufc618912015-09-09 16:42:49 +08004294 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004295
4296 glslang::TSampler sampler = {};
4297 bool cubeCompare = false;
John Kessenicha28f7a72019-08-06 07:00:58 -06004298#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004299 bool f16ShadowCompare = false;
4300#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004301 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004302 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4303 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
John Kessenicha28f7a72019-08-06 07:00:58 -06004304#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004305 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
4306#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004307 }
4308
John Kessenich140f3df2015-06-26 16:58:36 -06004309 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4310 builder.clearAccessChain();
4311 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004312
John Kessenicha28f7a72019-08-06 07:00:58 -06004313#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08004314 // Special case l-value operands
4315 bool lvalue = false;
4316 switch (node.getOp()) {
4317 case glslang::EOpImageAtomicAdd:
4318 case glslang::EOpImageAtomicMin:
4319 case glslang::EOpImageAtomicMax:
4320 case glslang::EOpImageAtomicAnd:
4321 case glslang::EOpImageAtomicOr:
4322 case glslang::EOpImageAtomicXor:
4323 case glslang::EOpImageAtomicExchange:
4324 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004325 case glslang::EOpImageAtomicLoad:
4326 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004327 if (i == 0)
4328 lvalue = true;
4329 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004330 case glslang::EOpSparseImageLoad:
4331 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4332 lvalue = true;
4333 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004334 case glslang::EOpSparseTexture:
4335 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4336 lvalue = true;
4337 break;
4338 case glslang::EOpSparseTextureClamp:
4339 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4340 lvalue = true;
4341 break;
4342 case glslang::EOpSparseTextureLod:
4343 case glslang::EOpSparseTextureOffset:
4344 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4345 lvalue = true;
4346 break;
Rex Xu48edadf2015-12-31 16:11:41 +08004347 case glslang::EOpSparseTextureFetch:
4348 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4349 lvalue = true;
4350 break;
4351 case glslang::EOpSparseTextureFetchOffset:
4352 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4353 lvalue = true;
4354 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004355 case glslang::EOpSparseTextureLodOffset:
4356 case glslang::EOpSparseTextureGrad:
4357 case glslang::EOpSparseTextureOffsetClamp:
4358 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4359 lvalue = true;
4360 break;
4361 case glslang::EOpSparseTextureGradOffset:
4362 case glslang::EOpSparseTextureGradClamp:
4363 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4364 lvalue = true;
4365 break;
4366 case glslang::EOpSparseTextureGradOffsetClamp:
4367 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4368 lvalue = true;
4369 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004370 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004371 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4372 lvalue = true;
4373 break;
4374 case glslang::EOpSparseTextureGatherOffset:
4375 case glslang::EOpSparseTextureGatherOffsets:
4376 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4377 lvalue = true;
4378 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004379 case glslang::EOpSparseTextureGatherLod:
4380 if (i == 3)
4381 lvalue = true;
4382 break;
4383 case glslang::EOpSparseTextureGatherLodOffset:
4384 case glslang::EOpSparseTextureGatherLodOffsets:
4385 if (i == 4)
4386 lvalue = true;
4387 break;
Rex Xu129799a2017-07-05 17:23:28 +08004388 case glslang::EOpSparseImageLoadLod:
4389 if (i == 3)
4390 lvalue = true;
4391 break;
Chao Chen3a137962018-09-19 11:41:27 -07004392 case glslang::EOpImageSampleFootprintNV:
4393 if (i == 4)
4394 lvalue = true;
4395 break;
4396 case glslang::EOpImageSampleFootprintClampNV:
4397 case glslang::EOpImageSampleFootprintLodNV:
4398 if (i == 5)
4399 lvalue = true;
4400 break;
4401 case glslang::EOpImageSampleFootprintGradNV:
4402 if (i == 6)
4403 lvalue = true;
4404 break;
4405 case glslang::EOpImageSampleFootprintGradClampNV:
4406 if (i == 7)
4407 lvalue = true;
4408 break;
Rex Xufc618912015-09-09 16:42:49 +08004409 default:
4410 break;
4411 }
4412
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004413 if (lvalue) {
Rex Xufc618912015-09-09 16:42:49 +08004414 arguments.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004415 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
4416 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4417 } else
John Kessenicha28f7a72019-08-06 07:00:58 -06004418#endif
John Kessenich32cfd492016-02-02 12:37:46 -07004419 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004420 }
4421}
4422
John Kessenichfc51d282015-08-19 13:34:18 -06004423void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004424{
John Kessenichfc51d282015-08-19 13:34:18 -06004425 builder.clearAccessChain();
4426 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004427 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004428}
John Kessenich140f3df2015-06-26 16:58:36 -06004429
John Kessenichfc51d282015-08-19 13:34:18 -06004430spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4431{
John Kesseniche485c7a2017-05-31 18:50:53 -06004432 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004433 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004434
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004435 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004436
John Kessenichfc51d282015-08-19 13:34:18 -06004437 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004438
John Kessenichf43c7392019-03-31 10:51:57 -06004439 const glslang::TType &imageType = node->getAsAggregate()
4440 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4441 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004442 const glslang::TSampler sampler = imageType.getSampler();
John Kessenicha28f7a72019-08-06 07:00:58 -06004443#ifdef GLSLANG_WEB
4444 const bool f16ShadowCompare = false;
4445#else
Rex Xu1e5d7b02016-11-29 17:36:31 +08004446 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004447 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4448 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004449#endif
4450
John Kessenichf43c7392019-03-31 10:51:57 -06004451 const auto signExtensionMask = [&]() {
4452 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4453 if (sampler.type == glslang::EbtUint)
4454 return spv::ImageOperandsZeroExtendMask;
4455 else if (sampler.type == glslang::EbtInt)
4456 return spv::ImageOperandsSignExtendMask;
4457 }
4458 return spv::ImageOperandsMaskNone;
4459 };
4460
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004461 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4462
John Kessenichfc51d282015-08-19 13:34:18 -06004463 std::vector<spv::Id> arguments;
4464 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004465 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004466 else
4467 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004468 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004469
4470 spv::Builder::TextureParameters params = { };
4471 params.sampler = arguments[0];
4472
Rex Xu04db3f52015-09-16 11:44:02 +08004473 glslang::TCrackedTextureOp cracked;
4474 node->crackTexture(sampler, cracked);
4475
amhagan05506bb2017-06-13 16:53:02 -04004476 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004477
John Kessenichfc51d282015-08-19 13:34:18 -06004478 // Check for queries
4479 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004480 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4481 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004482 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004483
John Kessenichfc51d282015-08-19 13:34:18 -06004484 switch (node->getOp()) {
4485 case glslang::EOpImageQuerySize:
4486 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004487 if (arguments.size() > 1) {
4488 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004489 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004490 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004491 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenicha28f7a72019-08-06 07:00:58 -06004492#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06004493 case glslang::EOpImageQuerySamples:
4494 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004495 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004496 case glslang::EOpTextureQueryLod:
4497 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004498 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004499 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004500 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004501 case glslang::EOpSparseTexelsResident:
4502 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenicha28f7a72019-08-06 07:00:58 -06004503#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004504 default:
4505 assert(0);
4506 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004507 }
John Kessenich140f3df2015-06-26 16:58:36 -06004508 }
4509
LoopDawg4425f242018-02-18 11:40:01 -07004510 int components = node->getType().getVectorSize();
4511
4512 if (node->getOp() == glslang::EOpTextureFetch) {
4513 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4514 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4515 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4516 // here around e.g. which ones return scalars or other types.
4517 components = 4;
4518 }
4519
4520 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4521
4522 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4523
Rex Xufc618912015-09-09 16:42:49 +08004524 // Check for image functions other than queries
4525 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004526 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004527 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004528 spv::IdImmediate image = { true, *(opIt++) };
4529 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004530
4531 // Handle subpass operations
4532 // TODO: GLSL should change to have the "MS" only on the type rather than the
4533 // built-in function.
4534 if (cracked.subpass) {
4535 // add on the (0,0) coordinate
4536 spv::Id zero = builder.makeIntConstant(0);
4537 std::vector<spv::Id> comps;
4538 comps.push_back(zero);
4539 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004540 spv::IdImmediate coord = { true,
4541 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4542 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004543 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4544 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004545 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004546 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4547 }
4548 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004549 operands.push_back(imageOperands);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004550 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004551 spv::IdImmediate imageOperand = { true, *(opIt++) };
4552 operands.push_back(imageOperand);
4553 }
John Kessenich6c292d32016-02-15 20:58:50 -07004554 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004555 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4556 builder.setPrecision(result, precision);
4557 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004558 }
4559
John Kessenich149afc32018-08-14 13:31:43 -06004560 spv::IdImmediate coord = { true, *(opIt++) };
4561 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004562 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004563 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004564 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004565 mask = mask | spv::ImageOperandsSampleMask;
4566 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004567 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004568 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4569 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004570 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004571 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004572 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4573 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004574 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004575 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004576 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4577 operands.push_back(imageOperands);
4578 }
4579 if (mask & spv::ImageOperandsSampleMask) {
4580 spv::IdImmediate imageOperand = { true, *opIt++ };
4581 operands.push_back(imageOperand);
4582 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004583 if (mask & spv::ImageOperandsLodMask) {
4584 spv::IdImmediate imageOperand = { true, *opIt++ };
4585 operands.push_back(imageOperand);
4586 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004587 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004588 spv::IdImmediate imageOperand = { true,
4589 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004590 operands.push_back(imageOperand);
4591 }
4592
John Kessenich149afc32018-08-14 13:31:43 -06004593 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004594 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004595
John Kessenich149afc32018-08-14 13:31:43 -06004596 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004597 builder.setPrecision(result[0], precision);
4598
4599 // If needed, add a conversion constructor to the proper size.
4600 if (components != node->getType().getVectorSize())
4601 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4602
4603 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004604 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004605
Jeff Bolz36831c92018-09-05 10:11:41 -05004606 // Push the texel value before the operands
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004607 if (sampler.isMultiSample() || cracked.lod) {
John Kessenich149afc32018-08-14 13:31:43 -06004608 spv::IdImmediate texel = { true, *(opIt + 1) };
4609 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004610 } else {
4611 spv::IdImmediate texel = { true, *opIt };
4612 operands.push_back(texel);
4613 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004614
4615 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004616 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004617 mask = mask | spv::ImageOperandsSampleMask;
4618 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004619 if (cracked.lod) {
4620 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4621 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4622 mask = mask | spv::ImageOperandsLodMask;
4623 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004624 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4625 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004626 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004627 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004628 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4629 operands.push_back(imageOperands);
4630 }
4631 if (mask & spv::ImageOperandsSampleMask) {
4632 spv::IdImmediate imageOperand = { true, *opIt++ };
4633 operands.push_back(imageOperand);
4634 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004635 if (mask & spv::ImageOperandsLodMask) {
4636 spv::IdImmediate imageOperand = { true, *opIt++ };
4637 operands.push_back(imageOperand);
4638 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004639 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004640 spv::IdImmediate imageOperand = { true,
4641 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004642 operands.push_back(imageOperand);
4643 }
4644
John Kessenich56bab042015-09-16 10:54:31 -06004645 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004646 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004647 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004648 return spv::NoResult;
John Kessenichf43c7392019-03-31 10:51:57 -06004649 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4650 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu5eafa472016-02-19 22:24:03 +08004651 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004652 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004653 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4654
Jeff Bolz36831c92018-09-05 10:11:41 -05004655 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004656 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004657 mask = mask | spv::ImageOperandsSampleMask;
4658 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004659 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004660 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4661 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4662
Jeff Bolz36831c92018-09-05 10:11:41 -05004663 mask = mask | spv::ImageOperandsLodMask;
4664 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004665 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4666 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004667 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004668 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004669 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004670 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004671 }
4672 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004673 spv::IdImmediate imageOperand = { true, *opIt++ };
4674 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004675 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004676 if (mask & spv::ImageOperandsLodMask) {
4677 spv::IdImmediate imageOperand = { true, *opIt++ };
4678 operands.push_back(imageOperand);
4679 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004680 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4681 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4682 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004683 }
4684
4685 // Create the return type that was a special structure
4686 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004687 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004688 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4689 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4690
4691 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4692
4693 // Decode the return type
4694 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4695 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004696 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004697 // Process image atomic operations
4698
4699 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4700 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004701 // For non-MS, the sample value should be 0
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004702 spv::IdImmediate sample = { true, sampler.isMultiSample() ? *(opIt++) : builder.makeUintConstant(0) };
John Kessenich149afc32018-08-14 13:31:43 -06004703 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004704
Jeff Bolz36831c92018-09-05 10:11:41 -05004705 spv::Id resultTypeId;
4706 // imageAtomicStore has a void return type so base the pointer type on
4707 // the type of the value operand.
4708 if (node->getOp() == glslang::EOpImageAtomicStore) {
4709 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
4710 } else {
4711 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4712 }
John Kessenich56bab042015-09-16 10:54:31 -06004713 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08004714
4715 std::vector<spv::Id> operands;
4716 operands.push_back(pointer);
4717 for (; opIt != arguments.end(); ++opIt)
4718 operands.push_back(*opIt);
4719
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004720 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(), lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08004721 }
4722 }
4723
John Kessenicha28f7a72019-08-06 07:00:58 -06004724#ifndef GLSLANG_WEB
amhagan05506bb2017-06-13 16:53:02 -04004725 // Check for fragment mask functions other than queries
4726 if (cracked.fragMask) {
4727 assert(sampler.ms);
4728
4729 auto opIt = arguments.begin();
4730 std::vector<spv::Id> operands;
4731
4732 // Extract the image if necessary
4733 if (builder.isSampledImage(params.sampler))
4734 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4735
4736 operands.push_back(params.sampler);
4737 ++opIt;
4738
4739 if (sampler.isSubpass()) {
4740 // add on the (0,0) coordinate
4741 spv::Id zero = builder.makeIntConstant(0);
4742 std::vector<spv::Id> comps;
4743 comps.push_back(zero);
4744 comps.push_back(zero);
4745 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
4746 }
4747
4748 for (; opIt != arguments.end(); ++opIt)
4749 operands.push_back(*opIt);
4750
4751 spv::Op fragMaskOp = spv::OpNop;
4752 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4753 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4754 else if (node->getOp() == glslang::EOpFragmentFetch)
4755 fragMaskOp = spv::OpFragmentFetchAMD;
4756
4757 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4758 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4759 return builder.createOp(fragMaskOp, resultType(), operands);
4760 }
4761#endif
4762
Rex Xufc618912015-09-09 16:42:49 +08004763 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004764 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004765 bool imageFootprint = node->isImageFootprint();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004766 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.isArrayed() && sampler.isShadow();
Rex Xu71519fe2015-11-11 15:35:47 +08004767
John Kessenichfc51d282015-08-19 13:34:18 -06004768 // check for bias argument
4769 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004770 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06004771 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004772 if (cracked.gather)
4773 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004774
4775 if (f16ShadowCompare)
4776 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06004777 if (cracked.offset)
4778 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004779 else if (cracked.offsets)
4780 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06004781 if (cracked.grad)
4782 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004783 if (cracked.lodClamp)
4784 ++nonBiasArgCount;
4785 if (sparse)
4786 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004787 if (imageFootprint)
4788 //Following three extra arguments
4789 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4790 nonBiasArgCount += 3;
John Kessenichfc51d282015-08-19 13:34:18 -06004791 if ((int)arguments.size() > nonBiasArgCount)
4792 bias = true;
4793 }
4794
John Kessenicha5c33d62016-06-02 23:45:21 -06004795 // See if the sampler param should really be just the SPV image part
4796 if (cracked.fetch) {
4797 // a fetch needs to have the image extracted first
4798 if (builder.isSampledImage(params.sampler))
4799 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4800 }
4801
John Kessenicha28f7a72019-08-06 07:00:58 -06004802#ifndef GLSLANG_WEB
Rex Xu225e0fc2016-11-17 17:47:59 +08004803 if (cracked.gather) {
4804 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4805 if (bias || cracked.lod ||
4806 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4807 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004808 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004809 }
4810 }
4811#endif
4812
John Kessenichfc51d282015-08-19 13:34:18 -06004813 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004814
John Kessenichfc51d282015-08-19 13:34:18 -06004815 params.coords = arguments[1];
4816 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004817 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004818
4819 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004820 if (cubeCompare || f16ShadowCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06004821 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004822 ++extraArgs;
4823 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004824 params.Dref = arguments[2];
4825 ++extraArgs;
4826 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004827 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004828 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004829 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004830 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004831 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004832 dRefComp = builder.getNumComponents(params.coords) - 1;
4833 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004834 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4835 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004836
4837 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004838 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004839 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004840 ++extraArgs;
John Kessenichb9197c82019-08-11 07:41:45 -06004841 } else if (glslangIntermediate->getStage() != EShLangFragment &&
4842 !(glslangIntermediate->getStage() == EShLangCompute &&
4843 glslangIntermediate->hasLayoutDerivativeModeNone())) {
John Kessenich019f08f2016-02-15 15:40:42 -07004844 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4845 noImplicitLod = true;
4846 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004847
4848 // multisample
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004849 if (sampler.isMultiSample()) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004850 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004851 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004852 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004853
4854 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004855 if (cracked.grad) {
4856 params.gradX = arguments[2 + extraArgs];
4857 params.gradY = arguments[3 + extraArgs];
4858 extraArgs += 2;
4859 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004860
4861 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004862 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004863 params.offset = arguments[2 + extraArgs];
4864 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004865 } else if (cracked.offsets) {
4866 params.offsets = arguments[2 + extraArgs];
4867 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004868 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004869
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004870#ifndef GLSLANG_WEB
John Kessenich76d4dfc2016-06-16 12:43:23 -06004871 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004872 if (cracked.lodClamp) {
4873 params.lodClamp = arguments[2 + extraArgs];
4874 ++extraArgs;
4875 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004876 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004877 if (sparse) {
4878 params.texelOut = arguments[2 + extraArgs];
4879 ++extraArgs;
4880 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004881 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004882 if (cracked.gather && ! sampler.shadow) {
4883 // default component is 0, if missing, otherwise an argument
4884 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004885 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004886 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004887 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004888 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004889 }
Chao Chen3a137962018-09-19 11:41:27 -07004890 spv::Id resultStruct = spv::NoResult;
4891 if (imageFootprint) {
4892 //Following three extra arguments
4893 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4894 params.granularity = arguments[2 + extraArgs];
4895 params.coarse = arguments[3 + extraArgs];
4896 resultStruct = arguments[4 + extraArgs];
4897 extraArgs += 3;
4898 }
4899#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004900 // bias
4901 if (bias) {
4902 params.bias = arguments[2 + extraArgs];
4903 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004904 }
John Kessenichfc51d282015-08-19 13:34:18 -06004905
John Kessenicha28f7a72019-08-06 07:00:58 -06004906#ifndef GLSLANG_WEB
Chao Chen3a137962018-09-19 11:41:27 -07004907 if (imageFootprint) {
4908 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
4909 builder.addCapability(spv::CapabilityImageFootprintNV);
4910
4911
4912 //resultStructType(OpenGL type) contains 5 elements:
4913 //struct gl_TextureFootprint2DNV {
4914 // uvec2 anchor;
4915 // uvec2 offset;
4916 // uvec2 mask;
4917 // uint lod;
4918 // uint granularity;
4919 //};
4920 //or
4921 //struct gl_TextureFootprint3DNV {
4922 // uvec3 anchor;
4923 // uvec3 offset;
4924 // uvec2 mask;
4925 // uint lod;
4926 // uint granularity;
4927 //};
4928 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
4929 assert(builder.isStructType(resultStructType));
4930
4931 //resType (SPIR-V type) contains 6 elements:
4932 //Member 0 must be a Boolean type scalar(LOD),
4933 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
4934 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
4935 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
4936 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
4937 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
4938 std::vector<spv::Id> members;
4939 members.push_back(resultType());
4940 for (int i = 0; i < 5; i++) {
4941 members.push_back(builder.getContainedTypeId(resultStructType, i));
4942 }
4943 spv::Id resType = builder.makeStructType(members, "ResType");
4944
4945 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06004946 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
4947 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07004948
4949 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
4950 for (int i = 0; i < 5; i++) {
4951 builder.clearAccessChain();
4952 builder.setAccessChainLValue(resultStruct);
4953
4954 //Accessing to a struct we created, no coherent flag is set
4955 spv::Builder::AccessChain::CoherentFlags flags;
4956 flags.clear();
4957
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004958 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
Chao Chen3a137962018-09-19 11:41:27 -07004959 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1), i+1));
4960 }
4961 return builder.createCompositeExtract(res, resultType(), 0);
4962 }
4963#endif
4964
John Kessenich65336482016-06-16 14:06:26 -06004965 // projective component (might not to move)
4966 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4967 // are divided by the last component of P."
4968 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4969 // unused components will appear after all used components."
4970 if (cracked.proj) {
4971 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4972 int projTargetComp;
4973 switch (sampler.dim) {
4974 case glslang::Esd1D: projTargetComp = 1; break;
4975 case glslang::Esd2D: projTargetComp = 2; break;
4976 case glslang::EsdRect: projTargetComp = 2; break;
4977 default: projTargetComp = projSourceComp; break;
4978 }
4979 // copy the projective coordinate if we have to
4980 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004981 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004982 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4983 projSourceComp);
4984 params.coords = builder.createCompositeInsert(projComp, params.coords,
4985 builder.getTypeId(params.coords), projTargetComp);
4986 }
4987 }
4988
John Kessenichf8d1d742019-10-21 06:55:11 -06004989#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -05004990 // nonprivate
4991 if (imageType.getQualifier().nonprivate) {
4992 params.nonprivate = true;
4993 }
4994
4995 // volatile
4996 if (imageType.getQualifier().volatil) {
4997 params.volatil = true;
4998 }
John Kessenichf8d1d742019-10-21 06:55:11 -06004999#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05005000
St0fFa1184dd2018-04-09 21:08:14 +02005001 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06005002 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
5003 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02005004 );
LoopDawg4425f242018-02-18 11:40:01 -07005005
5006 if (components != node->getType().getVectorSize())
5007 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
5008
5009 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06005010}
5011
5012spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
5013{
5014 // Grab the function's pointer from the previously created function
5015 spv::Function* function = functionMap[node->getName().c_str()];
5016 if (! function)
5017 return 0;
5018
5019 const glslang::TIntermSequence& glslangArgs = node->getSequence();
5020 const glslang::TQualifierList& qualifiers = node->getQualifierList();
5021
5022 // See comments in makeFunctions() for details about the semantics for parameter passing.
5023 //
5024 // These imply we need a four step process:
5025 // 1. Evaluate the arguments
5026 // 2. Allocate and make copies of in, out, and inout arguments
5027 // 3. Make the call
5028 // 4. Copy back the results
5029
John Kessenichd3ed90b2018-05-04 11:43:03 -06005030 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06005031 std::vector<spv::Builder::AccessChain> lValues;
5032 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07005033 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06005034 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005035 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06005036 // build l-value
5037 builder.clearAccessChain();
5038 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06005039 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06005040 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07005041 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005042 // save l-value
5043 lValues.push_back(builder.getAccessChain());
5044 } else {
5045 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07005046 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06005047 }
5048 }
5049
5050 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
5051 // copy the original into that space.
5052 //
5053 // Also, build up the list of actual arguments to pass in for the call
5054 int lValueCount = 0;
5055 int rValueCount = 0;
5056 std::vector<spv::Id> spvArgs;
5057 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
5058 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06005059 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07005060 builder.setAccessChain(lValues[lValueCount]);
5061 arg = builder.accessChainGetLValue();
5062 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06005063 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005064 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06005065 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06005066 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
5067 // need to copy the input into output space
5068 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07005069 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06005070 builder.clearAccessChain();
5071 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005072 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005073 }
5074 ++lValueCount;
5075 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005076 // process r-value, which involves a copy for a type mismatch
5077 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
5078 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
5079 builder.clearAccessChain();
5080 builder.setAccessChainLValue(argCopy);
5081 multiTypeStore(*argTypes[a], rValues[rValueCount]);
5082 arg = builder.createLoad(argCopy);
5083 } else
5084 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005085 ++rValueCount;
5086 }
5087 spvArgs.push_back(arg);
5088 }
5089
5090 // 3. Make the call.
5091 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005092 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06005093
5094 // 4. Copy back out an "out" arguments.
5095 lValueCount = 0;
5096 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005097 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005098 ++lValueCount;
5099 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005100 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
5101 spv::Id copy = builder.createLoad(spvArgs[a]);
5102 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005103 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005104 }
5105 ++lValueCount;
5106 }
5107 }
5108
5109 return result;
5110}
5111
5112// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005113spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005114 spv::Id typeId, spv::Id left, spv::Id right,
5115 glslang::TBasicType typeProxy, bool reduceComparison)
5116{
John Kessenich66011cb2018-03-06 16:12:04 -07005117 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5118 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005119 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005120
5121 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005122 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005123 bool comparison = false;
5124
5125 switch (op) {
5126 case glslang::EOpAdd:
5127 case glslang::EOpAddAssign:
5128 if (isFloat)
5129 binOp = spv::OpFAdd;
5130 else
5131 binOp = spv::OpIAdd;
5132 break;
5133 case glslang::EOpSub:
5134 case glslang::EOpSubAssign:
5135 if (isFloat)
5136 binOp = spv::OpFSub;
5137 else
5138 binOp = spv::OpISub;
5139 break;
5140 case glslang::EOpMul:
5141 case glslang::EOpMulAssign:
5142 if (isFloat)
5143 binOp = spv::OpFMul;
5144 else
5145 binOp = spv::OpIMul;
5146 break;
5147 case glslang::EOpVectorTimesScalar:
5148 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005149 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005150 if (builder.isVector(right))
5151 std::swap(left, right);
5152 assert(builder.isScalar(right));
5153 needMatchingVectors = false;
5154 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005155 } else if (isFloat)
5156 binOp = spv::OpFMul;
5157 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005158 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005159 break;
5160 case glslang::EOpVectorTimesMatrix:
5161 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005162 binOp = spv::OpVectorTimesMatrix;
5163 break;
5164 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005165 binOp = spv::OpMatrixTimesVector;
5166 break;
5167 case glslang::EOpMatrixTimesScalar:
5168 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005169 binOp = spv::OpMatrixTimesScalar;
5170 break;
5171 case glslang::EOpMatrixTimesMatrix:
5172 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005173 binOp = spv::OpMatrixTimesMatrix;
5174 break;
5175 case glslang::EOpOuterProduct:
5176 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005177 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005178 break;
5179
5180 case glslang::EOpDiv:
5181 case glslang::EOpDivAssign:
5182 if (isFloat)
5183 binOp = spv::OpFDiv;
5184 else if (isUnsigned)
5185 binOp = spv::OpUDiv;
5186 else
5187 binOp = spv::OpSDiv;
5188 break;
5189 case glslang::EOpMod:
5190 case glslang::EOpModAssign:
5191 if (isFloat)
5192 binOp = spv::OpFMod;
5193 else if (isUnsigned)
5194 binOp = spv::OpUMod;
5195 else
5196 binOp = spv::OpSMod;
5197 break;
5198 case glslang::EOpRightShift:
5199 case glslang::EOpRightShiftAssign:
5200 if (isUnsigned)
5201 binOp = spv::OpShiftRightLogical;
5202 else
5203 binOp = spv::OpShiftRightArithmetic;
5204 break;
5205 case glslang::EOpLeftShift:
5206 case glslang::EOpLeftShiftAssign:
5207 binOp = spv::OpShiftLeftLogical;
5208 break;
5209 case glslang::EOpAnd:
5210 case glslang::EOpAndAssign:
5211 binOp = spv::OpBitwiseAnd;
5212 break;
5213 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005214 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005215 binOp = spv::OpLogicalAnd;
5216 break;
5217 case glslang::EOpInclusiveOr:
5218 case glslang::EOpInclusiveOrAssign:
5219 binOp = spv::OpBitwiseOr;
5220 break;
5221 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005222 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005223 binOp = spv::OpLogicalOr;
5224 break;
5225 case glslang::EOpExclusiveOr:
5226 case glslang::EOpExclusiveOrAssign:
5227 binOp = spv::OpBitwiseXor;
5228 break;
5229 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005230 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005231 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005232 break;
5233
5234 case glslang::EOpLessThan:
5235 case glslang::EOpGreaterThan:
5236 case glslang::EOpLessThanEqual:
5237 case glslang::EOpGreaterThanEqual:
5238 case glslang::EOpEqual:
5239 case glslang::EOpNotEqual:
5240 case glslang::EOpVectorEqual:
5241 case glslang::EOpVectorNotEqual:
5242 comparison = true;
5243 break;
5244 default:
5245 break;
5246 }
5247
John Kessenich7c1aa102015-10-15 13:29:11 -06005248 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005249 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005250 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005251 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5252 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005253 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005254
5255 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005256 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005257 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005258
qining25262b32016-05-06 17:25:16 -04005259 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005260 decorations.addNoContraction(builder, result);
5261 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005262 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005263 }
5264
5265 if (! comparison)
5266 return 0;
5267
John Kessenich7c1aa102015-10-15 13:29:11 -06005268 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005269
John Kessenich4583b612016-08-07 19:14:22 -06005270 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005271 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5272 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenichb9197c82019-08-11 07:41:45 -06005273 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005274 return result;
5275 }
John Kessenich140f3df2015-06-26 16:58:36 -06005276
5277 switch (op) {
5278 case glslang::EOpLessThan:
5279 if (isFloat)
5280 binOp = spv::OpFOrdLessThan;
5281 else if (isUnsigned)
5282 binOp = spv::OpULessThan;
5283 else
5284 binOp = spv::OpSLessThan;
5285 break;
5286 case glslang::EOpGreaterThan:
5287 if (isFloat)
5288 binOp = spv::OpFOrdGreaterThan;
5289 else if (isUnsigned)
5290 binOp = spv::OpUGreaterThan;
5291 else
5292 binOp = spv::OpSGreaterThan;
5293 break;
5294 case glslang::EOpLessThanEqual:
5295 if (isFloat)
5296 binOp = spv::OpFOrdLessThanEqual;
5297 else if (isUnsigned)
5298 binOp = spv::OpULessThanEqual;
5299 else
5300 binOp = spv::OpSLessThanEqual;
5301 break;
5302 case glslang::EOpGreaterThanEqual:
5303 if (isFloat)
5304 binOp = spv::OpFOrdGreaterThanEqual;
5305 else if (isUnsigned)
5306 binOp = spv::OpUGreaterThanEqual;
5307 else
5308 binOp = spv::OpSGreaterThanEqual;
5309 break;
5310 case glslang::EOpEqual:
5311 case glslang::EOpVectorEqual:
5312 if (isFloat)
5313 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005314 else if (isBool)
5315 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005316 else
5317 binOp = spv::OpIEqual;
5318 break;
5319 case glslang::EOpNotEqual:
5320 case glslang::EOpVectorNotEqual:
5321 if (isFloat)
5322 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005323 else if (isBool)
5324 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005325 else
5326 binOp = spv::OpINotEqual;
5327 break;
5328 default:
5329 break;
5330 }
5331
qining25262b32016-05-06 17:25:16 -04005332 if (binOp != spv::OpNop) {
5333 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005334 decorations.addNoContraction(builder, result);
5335 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005336 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005337 }
John Kessenich140f3df2015-06-26 16:58:36 -06005338
5339 return 0;
5340}
5341
John Kessenich04bb8a02015-12-12 12:28:14 -07005342//
5343// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5344// These can be any of:
5345//
5346// matrix * scalar
5347// scalar * matrix
5348// matrix * matrix linear algebraic
5349// matrix * vector
5350// vector * matrix
5351// matrix * matrix componentwise
5352// matrix op matrix op in {+, -, /}
5353// matrix op scalar op in {+, -, /}
5354// scalar op matrix op in {+, -, /}
5355//
John Kessenichead86222018-03-28 18:01:20 -06005356spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5357 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005358{
5359 bool firstClass = true;
5360
5361 // First, handle first-class matrix operations (* and matrix/scalar)
5362 switch (op) {
5363 case spv::OpFDiv:
5364 if (builder.isMatrix(left) && builder.isScalar(right)) {
5365 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005366 spv::Id resultType = builder.getTypeId(right);
5367 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005368 op = spv::OpMatrixTimesScalar;
5369 } else
5370 firstClass = false;
5371 break;
5372 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005373 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005374 std::swap(left, right);
5375 assert(builder.isScalar(right));
5376 break;
5377 case spv::OpVectorTimesMatrix:
5378 assert(builder.isVector(left));
5379 assert(builder.isMatrix(right));
5380 break;
5381 case spv::OpMatrixTimesVector:
5382 assert(builder.isMatrix(left));
5383 assert(builder.isVector(right));
5384 break;
5385 case spv::OpMatrixTimesMatrix:
5386 assert(builder.isMatrix(left));
5387 assert(builder.isMatrix(right));
5388 break;
5389 default:
5390 firstClass = false;
5391 break;
5392 }
5393
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005394 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5395 firstClass = true;
5396
qining25262b32016-05-06 17:25:16 -04005397 if (firstClass) {
5398 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005399 decorations.addNoContraction(builder, result);
5400 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005401 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005402 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005403
LoopDawg592860c2016-06-09 08:57:35 -06005404 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005405 // The result type of all of them is the same type as the (a) matrix operand.
5406 // The algorithm is to:
5407 // - break the matrix(es) into vectors
5408 // - smear any scalar to a vector
5409 // - do vector operations
5410 // - make a matrix out the vector results
5411 switch (op) {
5412 case spv::OpFAdd:
5413 case spv::OpFSub:
5414 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005415 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005416 case spv::OpFMul:
5417 {
5418 // one time set up...
5419 bool leftMat = builder.isMatrix(left);
5420 bool rightMat = builder.isMatrix(right);
5421 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5422 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5423 spv::Id scalarType = builder.getScalarTypeId(typeId);
5424 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5425 std::vector<spv::Id> results;
5426 spv::Id smearVec = spv::NoResult;
5427 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005428 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005429 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005430 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005431
5432 // do each vector op
5433 for (unsigned int c = 0; c < numCols; ++c) {
5434 std::vector<unsigned int> indexes;
5435 indexes.push_back(c);
5436 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5437 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005438 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005439 decorations.addNoContraction(builder, result);
5440 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005441 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005442 }
5443
5444 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005445 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005446 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005447 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005448 }
5449 default:
5450 assert(0);
5451 return spv::NoResult;
5452 }
5453}
5454
John Kessenichead86222018-03-28 18:01:20 -06005455spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005456 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005457{
5458 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005459 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005460 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005461 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5462 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005463
5464 switch (op) {
5465 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005466 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005467 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005468 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005469 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005470 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005471 unaryOp = spv::OpSNegate;
5472 break;
5473
5474 case glslang::EOpLogicalNot:
5475 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005476 unaryOp = spv::OpLogicalNot;
5477 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005478 case glslang::EOpBitwiseNot:
5479 unaryOp = spv::OpNot;
5480 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005481
John Kessenich140f3df2015-06-26 16:58:36 -06005482 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005483 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005484 break;
5485 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005486 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005487 break;
5488 case glslang::EOpTranspose:
5489 unaryOp = spv::OpTranspose;
5490 break;
5491
5492 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005493 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005494 break;
5495 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005496 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005497 break;
5498 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005499 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005500 break;
5501 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005502 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005503 break;
5504 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005505 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005506 break;
5507 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005508 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005509 break;
5510 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005511 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005512 break;
5513 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005514 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005515 break;
5516
5517 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005518 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005519 break;
5520 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005521 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005522 break;
5523 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005524 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005525 break;
5526 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005527 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005528 break;
5529 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005530 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005531 break;
5532 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005533 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005534 break;
5535
5536 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005537 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005538 break;
5539 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005540 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005541 break;
5542
5543 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005544 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005545 break;
5546 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005547 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005548 break;
5549 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005550 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005551 break;
5552 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005553 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005554 break;
5555 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005556 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005557 break;
5558 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005559 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005560 break;
5561
5562 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005563 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005564 break;
5565 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005566 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005567 break;
5568 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005569 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005570 break;
5571 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005572 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005573 break;
5574 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005575 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005576 break;
5577 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005578 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005579 break;
5580
5581 case glslang::EOpIsNan:
5582 unaryOp = spv::OpIsNan;
5583 break;
5584 case glslang::EOpIsInf:
5585 unaryOp = spv::OpIsInf;
5586 break;
LoopDawg592860c2016-06-09 08:57:35 -06005587 case glslang::EOpIsFinite:
5588 unaryOp = spv::OpIsFinite;
5589 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005590
Rex Xucbc426e2015-12-15 16:03:10 +08005591 case glslang::EOpFloatBitsToInt:
5592 case glslang::EOpFloatBitsToUint:
5593 case glslang::EOpIntBitsToFloat:
5594 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005595 case glslang::EOpDoubleBitsToInt64:
5596 case glslang::EOpDoubleBitsToUint64:
5597 case glslang::EOpInt64BitsToDouble:
5598 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005599 case glslang::EOpFloat16BitsToInt16:
5600 case glslang::EOpFloat16BitsToUint16:
5601 case glslang::EOpInt16BitsToFloat16:
5602 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005603 unaryOp = spv::OpBitcast;
5604 break;
5605
John Kessenich140f3df2015-06-26 16:58:36 -06005606 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005607 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005608 break;
5609 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005610 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005611 break;
5612 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005613 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005614 break;
5615 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005616 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005617 break;
5618 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005619 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005620 break;
5621 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005622 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005623 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005624#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06005625 case glslang::EOpPackSnorm4x8:
5626 libCall = spv::GLSLstd450PackSnorm4x8;
5627 break;
5628 case glslang::EOpUnpackSnorm4x8:
5629 libCall = spv::GLSLstd450UnpackSnorm4x8;
5630 break;
5631 case glslang::EOpPackUnorm4x8:
5632 libCall = spv::GLSLstd450PackUnorm4x8;
5633 break;
5634 case glslang::EOpUnpackUnorm4x8:
5635 libCall = spv::GLSLstd450UnpackUnorm4x8;
5636 break;
5637 case glslang::EOpPackDouble2x32:
5638 libCall = spv::GLSLstd450PackDouble2x32;
5639 break;
5640 case glslang::EOpUnpackDouble2x32:
5641 libCall = spv::GLSLstd450UnpackDouble2x32;
5642 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005643#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005644
Rex Xu8ff43de2016-04-22 16:51:45 +08005645 case glslang::EOpPackInt2x32:
5646 case glslang::EOpUnpackInt2x32:
5647 case glslang::EOpPackUint2x32:
5648 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005649 case glslang::EOpPack16:
5650 case glslang::EOpPack32:
5651 case glslang::EOpPack64:
5652 case glslang::EOpUnpack32:
5653 case glslang::EOpUnpack16:
5654 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005655 case glslang::EOpPackInt2x16:
5656 case glslang::EOpUnpackInt2x16:
5657 case glslang::EOpPackUint2x16:
5658 case glslang::EOpUnpackUint2x16:
5659 case glslang::EOpPackInt4x16:
5660 case glslang::EOpUnpackInt4x16:
5661 case glslang::EOpPackUint4x16:
5662 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005663 case glslang::EOpPackFloat2x16:
5664 case glslang::EOpUnpackFloat2x16:
5665 unaryOp = spv::OpBitcast;
5666 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005667
John Kessenich140f3df2015-06-26 16:58:36 -06005668 case glslang::EOpDPdx:
5669 unaryOp = spv::OpDPdx;
5670 break;
5671 case glslang::EOpDPdy:
5672 unaryOp = spv::OpDPdy;
5673 break;
5674 case glslang::EOpFwidth:
5675 unaryOp = spv::OpFwidth;
5676 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005677
John Kessenich140f3df2015-06-26 16:58:36 -06005678 case glslang::EOpAny:
5679 unaryOp = spv::OpAny;
5680 break;
5681 case glslang::EOpAll:
5682 unaryOp = spv::OpAll;
5683 break;
5684
5685 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005686 if (isFloat)
5687 libCall = spv::GLSLstd450FAbs;
5688 else
5689 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005690 break;
5691 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005692 if (isFloat)
5693 libCall = spv::GLSLstd450FSign;
5694 else
5695 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005696 break;
5697
John Kessenicha28f7a72019-08-06 07:00:58 -06005698#ifndef GLSLANG_WEB
5699 case glslang::EOpDPdxFine:
5700 unaryOp = spv::OpDPdxFine;
5701 break;
5702 case glslang::EOpDPdyFine:
5703 unaryOp = spv::OpDPdyFine;
5704 break;
5705 case glslang::EOpFwidthFine:
5706 unaryOp = spv::OpFwidthFine;
5707 break;
5708 case glslang::EOpDPdxCoarse:
5709 unaryOp = spv::OpDPdxCoarse;
5710 break;
5711 case glslang::EOpDPdyCoarse:
5712 unaryOp = spv::OpDPdyCoarse;
5713 break;
5714 case glslang::EOpFwidthCoarse:
5715 unaryOp = spv::OpFwidthCoarse;
5716 break;
5717 case glslang::EOpInterpolateAtCentroid:
5718 if (typeProxy == glslang::EbtFloat16)
5719 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5720 libCall = spv::GLSLstd450InterpolateAtCentroid;
5721 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005722 case glslang::EOpAtomicCounterIncrement:
5723 case glslang::EOpAtomicCounterDecrement:
5724 case glslang::EOpAtomicCounter:
5725 {
5726 // Handle all of the atomics in one place, in createAtomicOperation()
5727 std::vector<spv::Id> operands;
5728 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005729 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06005730 }
5731
John Kessenichfc51d282015-08-19 13:34:18 -06005732 case glslang::EOpBitFieldReverse:
5733 unaryOp = spv::OpBitReverse;
5734 break;
5735 case glslang::EOpBitCount:
5736 unaryOp = spv::OpBitCount;
5737 break;
5738 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005739 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005740 break;
5741 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005742 if (isUnsigned)
5743 libCall = spv::GLSLstd450FindUMsb;
5744 else
5745 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005746 break;
5747
Rex Xu574ab042016-04-14 16:53:07 +08005748 case glslang::EOpBallot:
5749 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005750 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005751 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005752 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005753 case glslang::EOpMinInvocations:
5754 case glslang::EOpMaxInvocations:
5755 case glslang::EOpAddInvocations:
5756 case glslang::EOpMinInvocationsNonUniform:
5757 case glslang::EOpMaxInvocationsNonUniform:
5758 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005759 case glslang::EOpMinInvocationsInclusiveScan:
5760 case glslang::EOpMaxInvocationsInclusiveScan:
5761 case glslang::EOpAddInvocationsInclusiveScan:
5762 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5763 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5764 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5765 case glslang::EOpMinInvocationsExclusiveScan:
5766 case glslang::EOpMaxInvocationsExclusiveScan:
5767 case glslang::EOpAddInvocationsExclusiveScan:
5768 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5769 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5770 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu51596642016-09-21 18:56:12 +08005771 {
5772 std::vector<spv::Id> operands;
5773 operands.push_back(operand);
5774 return createInvocationsOperation(op, typeId, operands, typeProxy);
5775 }
John Kessenich66011cb2018-03-06 16:12:04 -07005776 case glslang::EOpSubgroupAll:
5777 case glslang::EOpSubgroupAny:
5778 case glslang::EOpSubgroupAllEqual:
5779 case glslang::EOpSubgroupBroadcastFirst:
5780 case glslang::EOpSubgroupBallot:
5781 case glslang::EOpSubgroupInverseBallot:
5782 case glslang::EOpSubgroupBallotBitCount:
5783 case glslang::EOpSubgroupBallotInclusiveBitCount:
5784 case glslang::EOpSubgroupBallotExclusiveBitCount:
5785 case glslang::EOpSubgroupBallotFindLSB:
5786 case glslang::EOpSubgroupBallotFindMSB:
5787 case glslang::EOpSubgroupAdd:
5788 case glslang::EOpSubgroupMul:
5789 case glslang::EOpSubgroupMin:
5790 case glslang::EOpSubgroupMax:
5791 case glslang::EOpSubgroupAnd:
5792 case glslang::EOpSubgroupOr:
5793 case glslang::EOpSubgroupXor:
5794 case glslang::EOpSubgroupInclusiveAdd:
5795 case glslang::EOpSubgroupInclusiveMul:
5796 case glslang::EOpSubgroupInclusiveMin:
5797 case glslang::EOpSubgroupInclusiveMax:
5798 case glslang::EOpSubgroupInclusiveAnd:
5799 case glslang::EOpSubgroupInclusiveOr:
5800 case glslang::EOpSubgroupInclusiveXor:
5801 case glslang::EOpSubgroupExclusiveAdd:
5802 case glslang::EOpSubgroupExclusiveMul:
5803 case glslang::EOpSubgroupExclusiveMin:
5804 case glslang::EOpSubgroupExclusiveMax:
5805 case glslang::EOpSubgroupExclusiveAnd:
5806 case glslang::EOpSubgroupExclusiveOr:
5807 case glslang::EOpSubgroupExclusiveXor:
5808 case glslang::EOpSubgroupQuadSwapHorizontal:
5809 case glslang::EOpSubgroupQuadSwapVertical:
5810 case glslang::EOpSubgroupQuadSwapDiagonal: {
5811 std::vector<spv::Id> operands;
5812 operands.push_back(operand);
5813 return createSubgroupOperation(op, typeId, operands, typeProxy);
5814 }
Rex Xu9d93a232016-05-05 12:30:44 +08005815 case glslang::EOpMbcnt:
5816 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5817 libCall = spv::MbcntAMD;
5818 break;
5819
5820 case glslang::EOpCubeFaceIndex:
5821 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5822 libCall = spv::CubeFaceIndexAMD;
5823 break;
5824
5825 case glslang::EOpCubeFaceCoord:
5826 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5827 libCall = spv::CubeFaceCoordAMD;
5828 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005829 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005830 unaryOp = spv::OpGroupNonUniformPartitionNV;
5831 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005832 case glslang::EOpConstructReference:
5833 unaryOp = spv::OpBitcast;
5834 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005835#endif
Jeff Bolz88220d52019-05-08 10:24:46 -05005836
5837 case glslang::EOpCopyObject:
5838 unaryOp = spv::OpCopyObject;
5839 break;
5840
John Kessenich140f3df2015-06-26 16:58:36 -06005841 default:
5842 return 0;
5843 }
5844
5845 spv::Id id;
5846 if (libCall >= 0) {
5847 std::vector<spv::Id> args;
5848 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005849 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005850 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005851 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005852 }
John Kessenich140f3df2015-06-26 16:58:36 -06005853
John Kessenichb9197c82019-08-11 07:41:45 -06005854 decorations.addNoContraction(builder, id);
5855 decorations.addNonUniform(builder, id);
John Kessenichead86222018-03-28 18:01:20 -06005856 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005857}
5858
John Kessenich7a53f762016-01-20 11:19:27 -07005859// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005860spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5861 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005862{
5863 // Handle unary operations vector by vector.
5864 // The result type is the same type as the original type.
5865 // The algorithm is to:
5866 // - break the matrix into vectors
5867 // - apply the operation to each vector
5868 // - make a matrix out the vector results
5869
5870 // get the types sorted out
5871 int numCols = builder.getNumColumns(operand);
5872 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005873 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5874 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005875 std::vector<spv::Id> results;
5876
5877 // do each vector op
5878 for (int c = 0; c < numCols; ++c) {
5879 std::vector<unsigned int> indexes;
5880 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005881 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5882 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005883 decorations.addNoContraction(builder, destVec);
5884 decorations.addNonUniform(builder, destVec);
John Kessenichead86222018-03-28 18:01:20 -06005885 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005886 }
5887
5888 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005889 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005890 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005891 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005892}
5893
John Kessenichad7645f2018-06-04 19:11:25 -06005894// For converting integers where both the bitwidth and the signedness could
5895// change, but only do the width change here. The caller is still responsible
5896// for the signedness conversion.
5897spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005898{
John Kessenichad7645f2018-06-04 19:11:25 -06005899 // Get the result type width, based on the type to convert to.
5900 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005901 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005902 case glslang::EOpConvInt16ToUint8:
5903 case glslang::EOpConvIntToUint8:
5904 case glslang::EOpConvInt64ToUint8:
5905 case glslang::EOpConvUint16ToInt8:
5906 case glslang::EOpConvUintToInt8:
5907 case glslang::EOpConvUint64ToInt8:
5908 width = 8;
5909 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005910 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005911 case glslang::EOpConvIntToUint16:
5912 case glslang::EOpConvInt64ToUint16:
5913 case glslang::EOpConvUint8ToInt16:
5914 case glslang::EOpConvUintToInt16:
5915 case glslang::EOpConvUint64ToInt16:
5916 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005917 break;
5918 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005919 case glslang::EOpConvInt16ToUint:
5920 case glslang::EOpConvInt64ToUint:
5921 case glslang::EOpConvUint8ToInt:
5922 case glslang::EOpConvUint16ToInt:
5923 case glslang::EOpConvUint64ToInt:
5924 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005925 break;
5926 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005927 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005928 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005929 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005930 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005931 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005932 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005933 break;
5934
5935 default:
5936 assert(false && "Default missing");
5937 break;
5938 }
5939
John Kessenichad7645f2018-06-04 19:11:25 -06005940 // Get the conversion operation and result type,
5941 // based on the target width, but the source type.
5942 spv::Id type = spv::NoType;
5943 spv::Op convOp = spv::OpNop;
5944 switch(op) {
5945 case glslang::EOpConvInt8ToUint16:
5946 case glslang::EOpConvInt8ToUint:
5947 case glslang::EOpConvInt8ToUint64:
5948 case glslang::EOpConvInt16ToUint8:
5949 case glslang::EOpConvInt16ToUint:
5950 case glslang::EOpConvInt16ToUint64:
5951 case glslang::EOpConvIntToUint8:
5952 case glslang::EOpConvIntToUint16:
5953 case glslang::EOpConvIntToUint64:
5954 case glslang::EOpConvInt64ToUint8:
5955 case glslang::EOpConvInt64ToUint16:
5956 case glslang::EOpConvInt64ToUint:
5957 convOp = spv::OpSConvert;
5958 type = builder.makeIntType(width);
5959 break;
5960 default:
5961 convOp = spv::OpUConvert;
5962 type = builder.makeUintType(width);
5963 break;
5964 }
5965
John Kessenich66011cb2018-03-06 16:12:04 -07005966 if (vectorSize > 0)
5967 type = builder.makeVectorType(type, vectorSize);
5968
John Kessenichad7645f2018-06-04 19:11:25 -06005969 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005970}
5971
John Kessenichead86222018-03-28 18:01:20 -06005972spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5973 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005974{
5975 spv::Op convOp = spv::OpNop;
5976 spv::Id zero = 0;
5977 spv::Id one = 0;
5978
5979 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5980
5981 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005982 case glslang::EOpConvIntToBool:
5983 case glslang::EOpConvUintToBool:
5984 zero = builder.makeUintConstant(0);
5985 zero = makeSmearedConstant(zero, vectorSize);
5986 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06005987 case glslang::EOpConvFloatToBool:
5988 zero = builder.makeFloatConstant(0.0F);
5989 zero = makeSmearedConstant(zero, vectorSize);
5990 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06005991 case glslang::EOpConvBoolToFloat:
5992 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005993 zero = builder.makeFloatConstant(0.0F);
5994 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06005995 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005996
John Kessenich140f3df2015-06-26 16:58:36 -06005997 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005998 case glslang::EOpConvBoolToInt64:
John Kessenichb9197c82019-08-11 07:41:45 -06005999#ifndef GLSLANG_WEB
6000 if (op == glslang::EOpConvBoolToInt64) {
Rex Xucabbb782017-03-24 13:41:14 +08006001 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006002 one = builder.makeInt64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006003 } else
6004#endif
6005 {
6006 zero = builder.makeIntConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006007 one = builder.makeIntConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006008 }
Rex Xucabbb782017-03-24 13:41:14 +08006009
John Kessenich140f3df2015-06-26 16:58:36 -06006010 convOp = spv::OpSelect;
6011 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006012
John Kessenich140f3df2015-06-26 16:58:36 -06006013 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006014 case glslang::EOpConvBoolToUint64:
John Kessenichb9197c82019-08-11 07:41:45 -06006015#ifndef GLSLANG_WEB
6016 if (op == glslang::EOpConvBoolToUint64) {
Rex Xucabbb782017-03-24 13:41:14 +08006017 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006018 one = builder.makeUint64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006019 } else
6020#endif
6021 {
6022 zero = builder.makeUintConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006023 one = builder.makeUintConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006024 }
Rex Xucabbb782017-03-24 13:41:14 +08006025
John Kessenich140f3df2015-06-26 16:58:36 -06006026 convOp = spv::OpSelect;
6027 break;
6028
John Kessenich66011cb2018-03-06 16:12:04 -07006029 case glslang::EOpConvInt8ToFloat16:
6030 case glslang::EOpConvInt8ToFloat:
6031 case glslang::EOpConvInt8ToDouble:
6032 case glslang::EOpConvInt16ToFloat16:
6033 case glslang::EOpConvInt16ToFloat:
6034 case glslang::EOpConvInt16ToDouble:
6035 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006036 case glslang::EOpConvIntToFloat:
6037 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006038 case glslang::EOpConvInt64ToFloat:
6039 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006040 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006041 convOp = spv::OpConvertSToF;
6042 break;
6043
John Kessenich66011cb2018-03-06 16:12:04 -07006044 case glslang::EOpConvUint8ToFloat16:
6045 case glslang::EOpConvUint8ToFloat:
6046 case glslang::EOpConvUint8ToDouble:
6047 case glslang::EOpConvUint16ToFloat16:
6048 case glslang::EOpConvUint16ToFloat:
6049 case glslang::EOpConvUint16ToDouble:
6050 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006051 case glslang::EOpConvUintToFloat:
6052 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006053 case glslang::EOpConvUint64ToFloat:
6054 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006055 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006056 convOp = spv::OpConvertUToF;
6057 break;
6058
John Kessenich66011cb2018-03-06 16:12:04 -07006059 case glslang::EOpConvFloat16ToInt8:
6060 case glslang::EOpConvFloatToInt8:
6061 case glslang::EOpConvDoubleToInt8:
6062 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006063 case glslang::EOpConvFloatToInt16:
6064 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006065 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006066 case glslang::EOpConvFloatToInt:
6067 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006068 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006069 case glslang::EOpConvFloatToInt64:
6070 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006071 convOp = spv::OpConvertFToS;
6072 break;
6073
John Kessenich66011cb2018-03-06 16:12:04 -07006074 case glslang::EOpConvUint8ToInt8:
6075 case glslang::EOpConvInt8ToUint8:
6076 case glslang::EOpConvUint16ToInt16:
6077 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006078 case glslang::EOpConvUintToInt:
6079 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006080 case glslang::EOpConvUint64ToInt64:
6081 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006082 if (builder.isInSpecConstCodeGenMode()) {
6083 // Build zero scalar or vector for OpIAdd.
John Kessenich39697cd2019-08-08 10:35:51 -06006084#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07006085 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6086 zero = builder.makeUint8Constant(0);
6087 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006088 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006089 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6090 zero = builder.makeUint64Constant(0);
John Kessenich39697cd2019-08-08 10:35:51 -06006091 } else
6092#endif
6093 {
Rex Xucabbb782017-03-24 13:41:14 +08006094 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006095 }
qining189b2032016-04-12 23:16:20 -04006096 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006097 // Use OpIAdd, instead of OpBitcast to do the conversion when
6098 // generating for OpSpecConstantOp instruction.
6099 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6100 }
6101 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006102 convOp = spv::OpBitcast;
6103 break;
6104
John Kessenich66011cb2018-03-06 16:12:04 -07006105 case glslang::EOpConvFloat16ToUint8:
6106 case glslang::EOpConvFloatToUint8:
6107 case glslang::EOpConvDoubleToUint8:
6108 case glslang::EOpConvFloat16ToUint16:
6109 case glslang::EOpConvFloatToUint16:
6110 case glslang::EOpConvDoubleToUint16:
6111 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006112 case glslang::EOpConvFloatToUint:
6113 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006114 case glslang::EOpConvFloatToUint64:
6115 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006116 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006117 convOp = spv::OpConvertFToU;
6118 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006119
John Kessenich39697cd2019-08-08 10:35:51 -06006120#ifndef GLSLANG_WEB
6121 case glslang::EOpConvInt8ToBool:
6122 case glslang::EOpConvUint8ToBool:
6123 zero = builder.makeUint8Constant(0);
6124 zero = makeSmearedConstant(zero, vectorSize);
6125 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6126 case glslang::EOpConvInt16ToBool:
6127 case glslang::EOpConvUint16ToBool:
6128 zero = builder.makeUint16Constant(0);
6129 zero = makeSmearedConstant(zero, vectorSize);
6130 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6131 case glslang::EOpConvInt64ToBool:
6132 case glslang::EOpConvUint64ToBool:
6133 zero = builder.makeUint64Constant(0);
6134 zero = makeSmearedConstant(zero, vectorSize);
6135 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6136 case glslang::EOpConvDoubleToBool:
6137 zero = builder.makeDoubleConstant(0.0);
6138 zero = makeSmearedConstant(zero, vectorSize);
6139 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6140 case glslang::EOpConvFloat16ToBool:
6141 zero = builder.makeFloat16Constant(0.0F);
6142 zero = makeSmearedConstant(zero, vectorSize);
6143 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6144 case glslang::EOpConvBoolToDouble:
6145 convOp = spv::OpSelect;
6146 zero = builder.makeDoubleConstant(0.0);
6147 one = builder.makeDoubleConstant(1.0);
6148 break;
6149 case glslang::EOpConvBoolToFloat16:
6150 convOp = spv::OpSelect;
6151 zero = builder.makeFloat16Constant(0.0F);
6152 one = builder.makeFloat16Constant(1.0F);
6153 break;
6154 case glslang::EOpConvBoolToInt8:
6155 zero = builder.makeInt8Constant(0);
6156 one = builder.makeInt8Constant(1);
6157 convOp = spv::OpSelect;
6158 break;
6159 case glslang::EOpConvBoolToUint8:
6160 zero = builder.makeUint8Constant(0);
6161 one = builder.makeUint8Constant(1);
6162 convOp = spv::OpSelect;
6163 break;
6164 case glslang::EOpConvBoolToInt16:
6165 zero = builder.makeInt16Constant(0);
6166 one = builder.makeInt16Constant(1);
6167 convOp = spv::OpSelect;
6168 break;
6169 case glslang::EOpConvBoolToUint16:
6170 zero = builder.makeUint16Constant(0);
6171 one = builder.makeUint16Constant(1);
6172 convOp = spv::OpSelect;
6173 break;
6174 case glslang::EOpConvDoubleToFloat:
6175 case glslang::EOpConvFloatToDouble:
6176 case glslang::EOpConvDoubleToFloat16:
6177 case glslang::EOpConvFloat16ToDouble:
6178 case glslang::EOpConvFloatToFloat16:
6179 case glslang::EOpConvFloat16ToFloat:
6180 convOp = spv::OpFConvert;
6181 if (builder.isMatrixType(destType))
6182 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
6183 break;
6184
John Kessenich66011cb2018-03-06 16:12:04 -07006185 case glslang::EOpConvInt8ToInt16:
6186 case glslang::EOpConvInt8ToInt:
6187 case glslang::EOpConvInt8ToInt64:
6188 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006189 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006190 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006191 case glslang::EOpConvIntToInt8:
6192 case glslang::EOpConvIntToInt16:
6193 case glslang::EOpConvIntToInt64:
6194 case glslang::EOpConvInt64ToInt8:
6195 case glslang::EOpConvInt64ToInt16:
6196 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006197 convOp = spv::OpSConvert;
6198 break;
6199
John Kessenich66011cb2018-03-06 16:12:04 -07006200 case glslang::EOpConvUint8ToUint16:
6201 case glslang::EOpConvUint8ToUint:
6202 case glslang::EOpConvUint8ToUint64:
6203 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006204 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006205 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006206 case glslang::EOpConvUintToUint8:
6207 case glslang::EOpConvUintToUint16:
6208 case glslang::EOpConvUintToUint64:
6209 case glslang::EOpConvUint64ToUint8:
6210 case glslang::EOpConvUint64ToUint16:
6211 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006212 convOp = spv::OpUConvert;
6213 break;
6214
John Kessenich66011cb2018-03-06 16:12:04 -07006215 case glslang::EOpConvInt8ToUint16:
6216 case glslang::EOpConvInt8ToUint:
6217 case glslang::EOpConvInt8ToUint64:
6218 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006219 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006220 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006221 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006222 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006223 case glslang::EOpConvIntToUint64:
6224 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006225 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006226 case glslang::EOpConvInt64ToUint:
6227 case glslang::EOpConvUint8ToInt16:
6228 case glslang::EOpConvUint8ToInt:
6229 case glslang::EOpConvUint8ToInt64:
6230 case glslang::EOpConvUint16ToInt8:
6231 case glslang::EOpConvUint16ToInt:
6232 case glslang::EOpConvUint16ToInt64:
6233 case glslang::EOpConvUintToInt8:
6234 case glslang::EOpConvUintToInt16:
6235 case glslang::EOpConvUintToInt64:
6236 case glslang::EOpConvUint64ToInt8:
6237 case glslang::EOpConvUint64ToInt16:
6238 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006239 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006240 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006241
6242 if (builder.isInSpecConstCodeGenMode()) {
6243 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006244 switch(op) {
6245 case glslang::EOpConvInt16ToUint8:
6246 case glslang::EOpConvIntToUint8:
6247 case glslang::EOpConvInt64ToUint8:
6248 case glslang::EOpConvUint16ToInt8:
6249 case glslang::EOpConvUintToInt8:
6250 case glslang::EOpConvUint64ToInt8:
6251 zero = builder.makeUint8Constant(0);
6252 break;
6253 case glslang::EOpConvInt8ToUint16:
6254 case glslang::EOpConvIntToUint16:
6255 case glslang::EOpConvInt64ToUint16:
6256 case glslang::EOpConvUint8ToInt16:
6257 case glslang::EOpConvUintToInt16:
6258 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006259 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006260 break;
6261 case glslang::EOpConvInt8ToUint:
6262 case glslang::EOpConvInt16ToUint:
6263 case glslang::EOpConvInt64ToUint:
6264 case glslang::EOpConvUint8ToInt:
6265 case glslang::EOpConvUint16ToInt:
6266 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006267 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006268 break;
6269 case glslang::EOpConvInt8ToUint64:
6270 case glslang::EOpConvInt16ToUint64:
6271 case glslang::EOpConvIntToUint64:
6272 case glslang::EOpConvUint8ToInt64:
6273 case glslang::EOpConvUint16ToInt64:
6274 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006275 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006276 break;
6277 default:
6278 assert(false && "Default missing");
6279 break;
6280 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006281 zero = makeSmearedConstant(zero, vectorSize);
6282 // Use OpIAdd, instead of OpBitcast to do the conversion when
6283 // generating for OpSpecConstantOp instruction.
6284 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6285 }
6286 // For normal run-time conversion instruction, use OpBitcast.
6287 convOp = spv::OpBitcast;
6288 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006289 case glslang::EOpConvUint64ToPtr:
6290 convOp = spv::OpConvertUToPtr;
6291 break;
6292 case glslang::EOpConvPtrToUint64:
6293 convOp = spv::OpConvertPtrToU;
6294 break;
John Kessenich90e402f2019-09-17 23:19:38 -06006295 case glslang::EOpConvPtrToUvec2:
6296 case glslang::EOpConvUvec2ToPtr:
John Kessenichee8e9c12019-10-10 20:54:21 -06006297 if (builder.isVector(operand))
6298 builder.promoteIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer,
6299 spv::E_SPV_KHR_physical_storage_buffer, spv::Spv_1_5);
John Kessenich90e402f2019-09-17 23:19:38 -06006300 convOp = spv::OpBitcast;
6301 break;
John Kessenich39697cd2019-08-08 10:35:51 -06006302#endif
6303
John Kessenich140f3df2015-06-26 16:58:36 -06006304 default:
6305 break;
6306 }
6307
6308 spv::Id result = 0;
6309 if (convOp == spv::OpNop)
6310 return result;
6311
6312 if (convOp == spv::OpSelect) {
6313 zero = makeSmearedConstant(zero, vectorSize);
6314 one = makeSmearedConstant(one, vectorSize);
6315 result = builder.createTriOp(convOp, destType, operand, one, zero);
6316 } else
6317 result = builder.createUnaryOp(convOp, destType, operand);
6318
John Kessenichead86222018-03-28 18:01:20 -06006319 result = builder.setPrecision(result, decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006320 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006321 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006322}
6323
6324spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6325{
6326 if (vectorSize == 0)
6327 return constant;
6328
6329 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6330 std::vector<spv::Id> components;
6331 for (int c = 0; c < vectorSize; ++c)
6332 components.push_back(constant);
6333 return builder.makeCompositeConstant(vectorTypeId, components);
6334}
6335
John Kessenich426394d2015-07-23 10:22:48 -06006336// For glslang ops that map to SPV atomic opCodes
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006337spv::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 -06006338{
6339 spv::Op opCode = spv::OpNop;
6340
6341 switch (op) {
6342 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006343 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006344 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006345 opCode = spv::OpAtomicIAdd;
6346 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006347 case glslang::EOpAtomicCounterSubtract:
6348 opCode = spv::OpAtomicISub;
6349 break;
John Kessenich426394d2015-07-23 10:22:48 -06006350 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006351 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006352 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08006353 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006354 break;
6355 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006356 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006357 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08006358 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006359 break;
6360 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006361 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006362 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006363 opCode = spv::OpAtomicAnd;
6364 break;
6365 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006366 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006367 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006368 opCode = spv::OpAtomicOr;
6369 break;
6370 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006371 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006372 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006373 opCode = spv::OpAtomicXor;
6374 break;
6375 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006376 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006377 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006378 opCode = spv::OpAtomicExchange;
6379 break;
6380 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006381 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006382 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006383 opCode = spv::OpAtomicCompareExchange;
6384 break;
6385 case glslang::EOpAtomicCounterIncrement:
6386 opCode = spv::OpAtomicIIncrement;
6387 break;
6388 case glslang::EOpAtomicCounterDecrement:
6389 opCode = spv::OpAtomicIDecrement;
6390 break;
6391 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006392 case glslang::EOpImageAtomicLoad:
6393 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006394 opCode = spv::OpAtomicLoad;
6395 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006396 case glslang::EOpAtomicStore:
6397 case glslang::EOpImageAtomicStore:
6398 opCode = spv::OpAtomicStore;
6399 break;
John Kessenich426394d2015-07-23 10:22:48 -06006400 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006401 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006402 break;
6403 }
6404
Rex Xue8fe8b02017-09-26 15:42:56 +08006405 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6406 builder.addCapability(spv::CapabilityInt64Atomics);
6407
John Kessenich426394d2015-07-23 10:22:48 -06006408 // Sort out the operands
6409 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006410 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006411 // - compare-exchange swaps the value and comparator
6412 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006413 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006414 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6415 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6416 spv::Id scopeId;
6417 if (glslangIntermediate->usingVulkanMemoryModel()) {
6418 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6419 } else {
6420 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6421 }
6422 // semantics default to relaxed
Jeff Bolz016ddee2019-10-17 11:22:57 -05006423 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.isVolatile() && glslangIntermediate->usingVulkanMemoryModel() ?
John Kessenichb9197c82019-08-11 07:41:45 -06006424 spv::MemorySemanticsVolatileMask :
6425 spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006426 spv::Id semanticsId2 = semanticsId;
6427
6428 pointerId = operands[0];
6429 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6430 // no additional operands
6431 } else if (opCode == spv::OpAtomicCompareExchange) {
6432 compareId = operands[1];
6433 valueId = operands[2];
6434 if (operands.size() > 3) {
6435 scopeId = operands[3];
6436 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6437 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
6438 }
6439 } else if (opCode == spv::OpAtomicLoad) {
6440 if (operands.size() > 1) {
6441 scopeId = operands[1];
6442 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
6443 }
6444 } else {
6445 // atomic store or RMW
6446 valueId = operands[1];
6447 if (operands.size() > 2) {
6448 scopeId = operands[2];
6449 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
6450 }
Rex Xu04db3f52015-09-16 11:44:02 +08006451 }
John Kessenich426394d2015-07-23 10:22:48 -06006452
Jeff Bolz36831c92018-09-05 10:11:41 -05006453 // Check for capabilities
6454 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006455 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6456 spv::MemorySemanticsMakeVisibleKHRMask |
6457 spv::MemorySemanticsOutputMemoryKHRMask |
6458 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006459 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6460 }
John Kessenich426394d2015-07-23 10:22:48 -06006461
Jeff Bolz36831c92018-09-05 10:11:41 -05006462 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6463 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6464 }
John Kessenich48d6e792017-10-06 21:21:48 -06006465
Jeff Bolz36831c92018-09-05 10:11:41 -05006466 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6467 spvAtomicOperands.push_back(pointerId);
6468 spvAtomicOperands.push_back(scopeId);
6469 spvAtomicOperands.push_back(semanticsId);
6470 if (opCode == spv::OpAtomicCompareExchange) {
6471 spvAtomicOperands.push_back(semanticsId2);
6472 spvAtomicOperands.push_back(valueId);
6473 spvAtomicOperands.push_back(compareId);
6474 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6475 spvAtomicOperands.push_back(valueId);
6476 }
John Kessenich48d6e792017-10-06 21:21:48 -06006477
Jeff Bolz36831c92018-09-05 10:11:41 -05006478 if (opCode == spv::OpAtomicStore) {
6479 builder.createNoResultOp(opCode, spvAtomicOperands);
6480 return 0;
6481 } else {
6482 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6483
6484 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6485 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6486 if (op == glslang::EOpAtomicCounterDecrement)
6487 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6488
6489 return resultId;
6490 }
John Kessenich426394d2015-07-23 10:22:48 -06006491}
6492
John Kessenich91cef522016-05-05 16:45:40 -06006493// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08006494spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006495{
John Kessenich66011cb2018-03-06 16:12:04 -07006496 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6497 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08006498
Rex Xu51596642016-09-21 18:56:12 +08006499 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006500 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006501 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6502
chaocf200da82016-12-20 12:44:35 -08006503 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6504 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006505 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6506 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006507 } else if (op == glslang::EOpAnyInvocation ||
6508 op == glslang::EOpAllInvocations ||
6509 op == glslang::EOpAllInvocationsEqual) {
6510 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6511 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006512 } else {
6513 builder.addCapability(spv::CapabilityGroups);
Rex Xu17ff3432016-10-14 17:41:45 +08006514 if (op == glslang::EOpMinInvocationsNonUniform ||
6515 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006516 op == glslang::EOpAddInvocationsNonUniform ||
6517 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6518 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6519 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6520 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6521 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6522 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006523 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +08006524
Rex Xu430ef402016-10-14 17:22:23 +08006525 switch (op) {
6526 case glslang::EOpMinInvocations:
6527 case glslang::EOpMaxInvocations:
6528 case glslang::EOpAddInvocations:
6529 case glslang::EOpMinInvocationsNonUniform:
6530 case glslang::EOpMaxInvocationsNonUniform:
6531 case glslang::EOpAddInvocationsNonUniform:
6532 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006533 break;
6534 case glslang::EOpMinInvocationsInclusiveScan:
6535 case glslang::EOpMaxInvocationsInclusiveScan:
6536 case glslang::EOpAddInvocationsInclusiveScan:
6537 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6538 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6539 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6540 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006541 break;
6542 case glslang::EOpMinInvocationsExclusiveScan:
6543 case glslang::EOpMaxInvocationsExclusiveScan:
6544 case glslang::EOpAddInvocationsExclusiveScan:
6545 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6546 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6547 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6548 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006549 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006550 default:
6551 break;
Rex Xu430ef402016-10-14 17:22:23 +08006552 }
John Kessenich149afc32018-08-14 13:31:43 -06006553 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6554 spvGroupOperands.push_back(scope);
6555 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006556 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006557 spvGroupOperands.push_back(groupOp);
6558 }
Rex Xu51596642016-09-21 18:56:12 +08006559 }
6560
John Kessenich149afc32018-08-14 13:31:43 -06006561 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6562 spv::IdImmediate op = { true, *opIt };
6563 spvGroupOperands.push_back(op);
6564 }
John Kessenich91cef522016-05-05 16:45:40 -06006565
6566 switch (op) {
6567 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006568 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006569 break;
John Kessenich91cef522016-05-05 16:45:40 -06006570 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006571 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006572 break;
John Kessenich91cef522016-05-05 16:45:40 -06006573 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006574 opCode = spv::OpSubgroupAllEqualKHR;
6575 break;
Rex Xu51596642016-09-21 18:56:12 +08006576 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006577 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006578 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006579 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006580 break;
6581 case glslang::EOpReadFirstInvocation:
6582 opCode = spv::OpSubgroupFirstInvocationKHR;
6583 break;
6584 case glslang::EOpBallot:
6585 {
6586 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6587 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6588 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6589 //
6590 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6591 //
6592 spv::Id uintType = builder.makeUintType(32);
6593 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6594 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6595
6596 std::vector<spv::Id> components;
6597 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6598 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6599
6600 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6601 return builder.createUnaryOp(spv::OpBitcast, typeId,
6602 builder.createCompositeConstruct(uvec2Type, components));
6603 }
6604
Rex Xu9d93a232016-05-05 12:30:44 +08006605 case glslang::EOpMinInvocations:
6606 case glslang::EOpMaxInvocations:
6607 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006608 case glslang::EOpMinInvocationsInclusiveScan:
6609 case glslang::EOpMaxInvocationsInclusiveScan:
6610 case glslang::EOpAddInvocationsInclusiveScan:
6611 case glslang::EOpMinInvocationsExclusiveScan:
6612 case glslang::EOpMaxInvocationsExclusiveScan:
6613 case glslang::EOpAddInvocationsExclusiveScan:
6614 if (op == glslang::EOpMinInvocations ||
6615 op == glslang::EOpMinInvocationsInclusiveScan ||
6616 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006617 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006618 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006619 else {
6620 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006621 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006622 else
Rex Xu51596642016-09-21 18:56:12 +08006623 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006624 }
Rex Xu430ef402016-10-14 17:22:23 +08006625 } else if (op == glslang::EOpMaxInvocations ||
6626 op == glslang::EOpMaxInvocationsInclusiveScan ||
6627 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006628 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006629 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006630 else {
6631 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006632 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006633 else
Rex Xu51596642016-09-21 18:56:12 +08006634 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006635 }
6636 } else {
6637 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006638 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006639 else
Rex Xu51596642016-09-21 18:56:12 +08006640 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006641 }
6642
Rex Xu2bbbe062016-08-23 15:41:05 +08006643 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006644 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006645
6646 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006647 case glslang::EOpMinInvocationsNonUniform:
6648 case glslang::EOpMaxInvocationsNonUniform:
6649 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006650 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6651 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6652 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6653 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6654 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6655 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6656 if (op == glslang::EOpMinInvocationsNonUniform ||
6657 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6658 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006659 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006660 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006661 else {
6662 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006663 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006664 else
Rex Xu51596642016-09-21 18:56:12 +08006665 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006666 }
6667 }
Rex Xu430ef402016-10-14 17:22:23 +08006668 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6669 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6670 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006671 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006672 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006673 else {
6674 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006675 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006676 else
Rex Xu51596642016-09-21 18:56:12 +08006677 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006678 }
6679 }
6680 else {
6681 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006682 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006683 else
Rex Xu51596642016-09-21 18:56:12 +08006684 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006685 }
6686
Rex Xu2bbbe062016-08-23 15:41:05 +08006687 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006688 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006689
6690 break;
John Kessenich91cef522016-05-05 16:45:40 -06006691 default:
6692 logger->missingFunctionality("invocation operation");
6693 return spv::NoResult;
6694 }
Rex Xu51596642016-09-21 18:56:12 +08006695
6696 assert(opCode != spv::OpNop);
6697 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006698}
6699
Rex Xu2bbbe062016-08-23 15:41:05 +08006700// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006701spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6702 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006703{
6704 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6705 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006706 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006707 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006708 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
6709 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
6710 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
6711
6712 // Handle group invocation operations scalar by scalar.
6713 // The result type is the same type as the original type.
6714 // The algorithm is to:
6715 // - break the vector into scalars
6716 // - apply the operation to each scalar
6717 // - make a vector out the scalar results
6718
6719 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006720 int numComponents = builder.getNumComponents(operands[0]);
6721 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006722 std::vector<spv::Id> results;
6723
6724 // do each scalar op
6725 for (int comp = 0; comp < numComponents; ++comp) {
6726 std::vector<unsigned int> indexes;
6727 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006728 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6729 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006730 if (op == spv::OpSubgroupReadInvocationKHR) {
6731 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006732 spv::IdImmediate operand = { true, operands[1] };
6733 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006734 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006735 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6736 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006737 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006738 spv::IdImmediate operand = { true, operands[1] };
6739 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006740 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006741 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6742 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006743 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006744 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006745 spvGroupOperands.push_back(scalar);
6746 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006747
Rex Xub7072052016-09-26 15:53:40 +08006748 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006749 }
6750
6751 // put the pieces together
6752 return builder.createCompositeConstruct(typeId, results);
6753}
Rex Xu2bbbe062016-08-23 15:41:05 +08006754
John Kessenich66011cb2018-03-06 16:12:04 -07006755// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006756spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6757 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006758{
6759 // Add the required capabilities.
6760 switch (op) {
6761 case glslang::EOpSubgroupElect:
6762 builder.addCapability(spv::CapabilityGroupNonUniform);
6763 break;
6764 case glslang::EOpSubgroupAll:
6765 case glslang::EOpSubgroupAny:
6766 case glslang::EOpSubgroupAllEqual:
6767 builder.addCapability(spv::CapabilityGroupNonUniform);
6768 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6769 break;
6770 case glslang::EOpSubgroupBroadcast:
6771 case glslang::EOpSubgroupBroadcastFirst:
6772 case glslang::EOpSubgroupBallot:
6773 case glslang::EOpSubgroupInverseBallot:
6774 case glslang::EOpSubgroupBallotBitExtract:
6775 case glslang::EOpSubgroupBallotBitCount:
6776 case glslang::EOpSubgroupBallotInclusiveBitCount:
6777 case glslang::EOpSubgroupBallotExclusiveBitCount:
6778 case glslang::EOpSubgroupBallotFindLSB:
6779 case glslang::EOpSubgroupBallotFindMSB:
6780 builder.addCapability(spv::CapabilityGroupNonUniform);
6781 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6782 break;
6783 case glslang::EOpSubgroupShuffle:
6784 case glslang::EOpSubgroupShuffleXor:
6785 builder.addCapability(spv::CapabilityGroupNonUniform);
6786 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6787 break;
6788 case glslang::EOpSubgroupShuffleUp:
6789 case glslang::EOpSubgroupShuffleDown:
6790 builder.addCapability(spv::CapabilityGroupNonUniform);
6791 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6792 break;
6793 case glslang::EOpSubgroupAdd:
6794 case glslang::EOpSubgroupMul:
6795 case glslang::EOpSubgroupMin:
6796 case glslang::EOpSubgroupMax:
6797 case glslang::EOpSubgroupAnd:
6798 case glslang::EOpSubgroupOr:
6799 case glslang::EOpSubgroupXor:
6800 case glslang::EOpSubgroupInclusiveAdd:
6801 case glslang::EOpSubgroupInclusiveMul:
6802 case glslang::EOpSubgroupInclusiveMin:
6803 case glslang::EOpSubgroupInclusiveMax:
6804 case glslang::EOpSubgroupInclusiveAnd:
6805 case glslang::EOpSubgroupInclusiveOr:
6806 case glslang::EOpSubgroupInclusiveXor:
6807 case glslang::EOpSubgroupExclusiveAdd:
6808 case glslang::EOpSubgroupExclusiveMul:
6809 case glslang::EOpSubgroupExclusiveMin:
6810 case glslang::EOpSubgroupExclusiveMax:
6811 case glslang::EOpSubgroupExclusiveAnd:
6812 case glslang::EOpSubgroupExclusiveOr:
6813 case glslang::EOpSubgroupExclusiveXor:
6814 builder.addCapability(spv::CapabilityGroupNonUniform);
6815 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6816 break;
6817 case glslang::EOpSubgroupClusteredAdd:
6818 case glslang::EOpSubgroupClusteredMul:
6819 case glslang::EOpSubgroupClusteredMin:
6820 case glslang::EOpSubgroupClusteredMax:
6821 case glslang::EOpSubgroupClusteredAnd:
6822 case glslang::EOpSubgroupClusteredOr:
6823 case glslang::EOpSubgroupClusteredXor:
6824 builder.addCapability(spv::CapabilityGroupNonUniform);
6825 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6826 break;
6827 case glslang::EOpSubgroupQuadBroadcast:
6828 case glslang::EOpSubgroupQuadSwapHorizontal:
6829 case glslang::EOpSubgroupQuadSwapVertical:
6830 case glslang::EOpSubgroupQuadSwapDiagonal:
6831 builder.addCapability(spv::CapabilityGroupNonUniform);
6832 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6833 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006834 case glslang::EOpSubgroupPartitionedAdd:
6835 case glslang::EOpSubgroupPartitionedMul:
6836 case glslang::EOpSubgroupPartitionedMin:
6837 case glslang::EOpSubgroupPartitionedMax:
6838 case glslang::EOpSubgroupPartitionedAnd:
6839 case glslang::EOpSubgroupPartitionedOr:
6840 case glslang::EOpSubgroupPartitionedXor:
6841 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6842 case glslang::EOpSubgroupPartitionedInclusiveMul:
6843 case glslang::EOpSubgroupPartitionedInclusiveMin:
6844 case glslang::EOpSubgroupPartitionedInclusiveMax:
6845 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6846 case glslang::EOpSubgroupPartitionedInclusiveOr:
6847 case glslang::EOpSubgroupPartitionedInclusiveXor:
6848 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6849 case glslang::EOpSubgroupPartitionedExclusiveMul:
6850 case glslang::EOpSubgroupPartitionedExclusiveMin:
6851 case glslang::EOpSubgroupPartitionedExclusiveMax:
6852 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6853 case glslang::EOpSubgroupPartitionedExclusiveOr:
6854 case glslang::EOpSubgroupPartitionedExclusiveXor:
6855 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6856 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6857 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006858 default: assert(0 && "Unhandled subgroup operation!");
6859 }
6860
Jeff Bolzc5b669e2019-09-08 08:49:18 -05006861
6862 const bool isUnsigned = isTypeUnsignedInt(typeProxy);
6863 const bool isFloat = isTypeFloat(typeProxy);
John Kessenich66011cb2018-03-06 16:12:04 -07006864 const bool isBool = typeProxy == glslang::EbtBool;
6865
6866 spv::Op opCode = spv::OpNop;
6867
6868 // Figure out which opcode to use.
6869 switch (op) {
6870 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6871 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6872 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6873 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6874 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6875 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6876 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6877 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6878 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6879 case glslang::EOpSubgroupBallotBitCount:
6880 case glslang::EOpSubgroupBallotInclusiveBitCount:
6881 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6882 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6883 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6884 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6885 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6886 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6887 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6888 case glslang::EOpSubgroupAdd:
6889 case glslang::EOpSubgroupInclusiveAdd:
6890 case glslang::EOpSubgroupExclusiveAdd:
6891 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006892 case glslang::EOpSubgroupPartitionedAdd:
6893 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6894 case glslang::EOpSubgroupPartitionedExclusiveAdd:
John Kessenich66011cb2018-03-06 16:12:04 -07006895 if (isFloat) {
6896 opCode = spv::OpGroupNonUniformFAdd;
6897 } else {
6898 opCode = spv::OpGroupNonUniformIAdd;
6899 }
6900 break;
6901 case glslang::EOpSubgroupMul:
6902 case glslang::EOpSubgroupInclusiveMul:
6903 case glslang::EOpSubgroupExclusiveMul:
6904 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006905 case glslang::EOpSubgroupPartitionedMul:
6906 case glslang::EOpSubgroupPartitionedInclusiveMul:
6907 case glslang::EOpSubgroupPartitionedExclusiveMul:
John Kessenich66011cb2018-03-06 16:12:04 -07006908 if (isFloat) {
6909 opCode = spv::OpGroupNonUniformFMul;
6910 } else {
6911 opCode = spv::OpGroupNonUniformIMul;
6912 }
6913 break;
6914 case glslang::EOpSubgroupMin:
6915 case glslang::EOpSubgroupInclusiveMin:
6916 case glslang::EOpSubgroupExclusiveMin:
6917 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006918 case glslang::EOpSubgroupPartitionedMin:
6919 case glslang::EOpSubgroupPartitionedInclusiveMin:
6920 case glslang::EOpSubgroupPartitionedExclusiveMin:
John Kessenich66011cb2018-03-06 16:12:04 -07006921 if (isFloat) {
6922 opCode = spv::OpGroupNonUniformFMin;
6923 } else if (isUnsigned) {
6924 opCode = spv::OpGroupNonUniformUMin;
6925 } else {
6926 opCode = spv::OpGroupNonUniformSMin;
6927 }
6928 break;
6929 case glslang::EOpSubgroupMax:
6930 case glslang::EOpSubgroupInclusiveMax:
6931 case glslang::EOpSubgroupExclusiveMax:
6932 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006933 case glslang::EOpSubgroupPartitionedMax:
6934 case glslang::EOpSubgroupPartitionedInclusiveMax:
6935 case glslang::EOpSubgroupPartitionedExclusiveMax:
John Kessenich66011cb2018-03-06 16:12:04 -07006936 if (isFloat) {
6937 opCode = spv::OpGroupNonUniformFMax;
6938 } else if (isUnsigned) {
6939 opCode = spv::OpGroupNonUniformUMax;
6940 } else {
6941 opCode = spv::OpGroupNonUniformSMax;
6942 }
6943 break;
6944 case glslang::EOpSubgroupAnd:
6945 case glslang::EOpSubgroupInclusiveAnd:
6946 case glslang::EOpSubgroupExclusiveAnd:
6947 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006948 case glslang::EOpSubgroupPartitionedAnd:
6949 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6950 case glslang::EOpSubgroupPartitionedExclusiveAnd:
John Kessenich66011cb2018-03-06 16:12:04 -07006951 if (isBool) {
6952 opCode = spv::OpGroupNonUniformLogicalAnd;
6953 } else {
6954 opCode = spv::OpGroupNonUniformBitwiseAnd;
6955 }
6956 break;
6957 case glslang::EOpSubgroupOr:
6958 case glslang::EOpSubgroupInclusiveOr:
6959 case glslang::EOpSubgroupExclusiveOr:
6960 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006961 case glslang::EOpSubgroupPartitionedOr:
6962 case glslang::EOpSubgroupPartitionedInclusiveOr:
6963 case glslang::EOpSubgroupPartitionedExclusiveOr:
John Kessenich66011cb2018-03-06 16:12:04 -07006964 if (isBool) {
6965 opCode = spv::OpGroupNonUniformLogicalOr;
6966 } else {
6967 opCode = spv::OpGroupNonUniformBitwiseOr;
6968 }
6969 break;
6970 case glslang::EOpSubgroupXor:
6971 case glslang::EOpSubgroupInclusiveXor:
6972 case glslang::EOpSubgroupExclusiveXor:
6973 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006974 case glslang::EOpSubgroupPartitionedXor:
6975 case glslang::EOpSubgroupPartitionedInclusiveXor:
6976 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07006977 if (isBool) {
6978 opCode = spv::OpGroupNonUniformLogicalXor;
6979 } else {
6980 opCode = spv::OpGroupNonUniformBitwiseXor;
6981 }
6982 break;
6983 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
6984 case glslang::EOpSubgroupQuadSwapHorizontal:
6985 case glslang::EOpSubgroupQuadSwapVertical:
6986 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
6987 default: assert(0 && "Unhandled subgroup operation!");
6988 }
6989
John Kessenich149afc32018-08-14 13:31:43 -06006990 // get the right Group Operation
6991 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07006992 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06006993 default:
6994 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006995 case glslang::EOpSubgroupBallotBitCount:
6996 case glslang::EOpSubgroupAdd:
6997 case glslang::EOpSubgroupMul:
6998 case glslang::EOpSubgroupMin:
6999 case glslang::EOpSubgroupMax:
7000 case glslang::EOpSubgroupAnd:
7001 case glslang::EOpSubgroupOr:
7002 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06007003 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007004 break;
7005 case glslang::EOpSubgroupBallotInclusiveBitCount:
7006 case glslang::EOpSubgroupInclusiveAdd:
7007 case glslang::EOpSubgroupInclusiveMul:
7008 case glslang::EOpSubgroupInclusiveMin:
7009 case glslang::EOpSubgroupInclusiveMax:
7010 case glslang::EOpSubgroupInclusiveAnd:
7011 case glslang::EOpSubgroupInclusiveOr:
7012 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007013 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007014 break;
7015 case glslang::EOpSubgroupBallotExclusiveBitCount:
7016 case glslang::EOpSubgroupExclusiveAdd:
7017 case glslang::EOpSubgroupExclusiveMul:
7018 case glslang::EOpSubgroupExclusiveMin:
7019 case glslang::EOpSubgroupExclusiveMax:
7020 case glslang::EOpSubgroupExclusiveAnd:
7021 case glslang::EOpSubgroupExclusiveOr:
7022 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007023 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007024 break;
7025 case glslang::EOpSubgroupClusteredAdd:
7026 case glslang::EOpSubgroupClusteredMul:
7027 case glslang::EOpSubgroupClusteredMin:
7028 case glslang::EOpSubgroupClusteredMax:
7029 case glslang::EOpSubgroupClusteredAnd:
7030 case glslang::EOpSubgroupClusteredOr:
7031 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06007032 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007033 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007034 case glslang::EOpSubgroupPartitionedAdd:
7035 case glslang::EOpSubgroupPartitionedMul:
7036 case glslang::EOpSubgroupPartitionedMin:
7037 case glslang::EOpSubgroupPartitionedMax:
7038 case glslang::EOpSubgroupPartitionedAnd:
7039 case glslang::EOpSubgroupPartitionedOr:
7040 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06007041 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007042 break;
7043 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7044 case glslang::EOpSubgroupPartitionedInclusiveMul:
7045 case glslang::EOpSubgroupPartitionedInclusiveMin:
7046 case glslang::EOpSubgroupPartitionedInclusiveMax:
7047 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7048 case glslang::EOpSubgroupPartitionedInclusiveOr:
7049 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007050 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007051 break;
7052 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7053 case glslang::EOpSubgroupPartitionedExclusiveMul:
7054 case glslang::EOpSubgroupPartitionedExclusiveMin:
7055 case glslang::EOpSubgroupPartitionedExclusiveMax:
7056 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7057 case glslang::EOpSubgroupPartitionedExclusiveOr:
7058 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007059 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007060 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007061 }
7062
John Kessenich149afc32018-08-14 13:31:43 -06007063 // build the instruction
7064 std::vector<spv::IdImmediate> spvGroupOperands;
7065
7066 // Every operation begins with the Execution Scope operand.
7067 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7068 spvGroupOperands.push_back(executionScope);
7069
7070 // Next, for all operations that use a Group Operation, push that as an operand.
7071 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007072 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007073 spvGroupOperands.push_back(groupOperand);
7074 }
7075
John Kessenich66011cb2018-03-06 16:12:04 -07007076 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06007077 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
7078 spv::IdImmediate operand = { true, *opIt };
7079 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07007080 }
7081
7082 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06007083 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07007084 switch (op) {
7085 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06007086 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
7087 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
7088 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
7089 }
7090 if (directionId != spv::NoResult) {
7091 spv::IdImmediate direction = { true, directionId };
7092 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007093 }
7094
7095 return builder.createOp(opCode, typeId, spvGroupOperands);
7096}
7097
John Kessenich5e4b1242015-08-06 22:53:06 -06007098spv::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 -06007099{
John Kessenich66011cb2018-03-06 16:12:04 -07007100 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7101 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007102
John Kessenich140f3df2015-06-26 16:58:36 -06007103 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007104 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007105 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007106 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007107 spv::Id typeId0 = 0;
7108 if (consumedOperands > 0)
7109 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007110 spv::Id typeId1 = 0;
7111 if (consumedOperands > 1)
7112 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007113 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007114
7115 switch (op) {
7116 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007117 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007118 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007119 else if (isUnsigned)
7120 libCall = spv::GLSLstd450UMin;
7121 else
7122 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007123 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007124 break;
7125 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007126 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007127 break;
7128 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007129 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007130 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007131 else if (isUnsigned)
7132 libCall = spv::GLSLstd450UMax;
7133 else
7134 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007135 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007136 break;
7137 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007138 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007139 break;
7140 case glslang::EOpDot:
7141 opCode = spv::OpDot;
7142 break;
7143 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007144 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007145 break;
7146
7147 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007148 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007149 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007150 else if (isUnsigned)
7151 libCall = spv::GLSLstd450UClamp;
7152 else
7153 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007154 builder.promoteScalar(precision, operands.front(), operands[1]);
7155 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007156 break;
7157 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007158 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7159 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007160 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007161 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007162 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007163 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007164 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007165 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007166 break;
7167 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007168 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007169 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007170 break;
7171 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007172 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007173 builder.promoteScalar(precision, operands[0], operands[2]);
7174 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007175 break;
7176
7177 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007178 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007179 break;
7180 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007181 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007182 break;
7183 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007184 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007185 break;
7186 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007187 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007188 break;
7189 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007190 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007191 break;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007192 case glslang::EOpBarrier:
7193 {
7194 // This is for the extended controlBarrier function, with four operands.
7195 // The unextended barrier() goes through createNoArgOperation.
7196 assert(operands.size() == 4);
7197 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7198 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7199 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
7200 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7201 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7202 spv::MemorySemanticsMakeVisibleKHRMask |
7203 spv::MemorySemanticsOutputMemoryKHRMask |
7204 spv::MemorySemanticsVolatileMask)) {
7205 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7206 }
7207 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
7208 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7209 }
7210 return 0;
7211 }
7212 break;
7213 case glslang::EOpMemoryBarrier:
7214 {
7215 // This is for the extended memoryBarrier function, with three operands.
7216 // The unextended memoryBarrier() goes through createNoArgOperation.
7217 assert(operands.size() == 3);
7218 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7219 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7220 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7221 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7222 spv::MemorySemanticsMakeVisibleKHRMask |
7223 spv::MemorySemanticsOutputMemoryKHRMask |
7224 spv::MemorySemanticsVolatileMask)) {
7225 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7226 }
7227 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7228 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7229 }
7230 return 0;
7231 }
7232 break;
7233
John Kessenicha28f7a72019-08-06 07:00:58 -06007234#ifndef GLSLANG_WEB
Rex Xu7a26c172015-12-08 17:12:09 +08007235 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007236 if (typeProxy == glslang::EbtFloat16)
7237 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007238 libCall = spv::GLSLstd450InterpolateAtSample;
7239 break;
7240 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007241 if (typeProxy == glslang::EbtFloat16)
7242 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007243 libCall = spv::GLSLstd450InterpolateAtOffset;
7244 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007245 case glslang::EOpAddCarry:
7246 opCode = spv::OpIAddCarry;
7247 typeId = builder.makeStructResultType(typeId0, typeId0);
7248 consumedOperands = 2;
7249 break;
7250 case glslang::EOpSubBorrow:
7251 opCode = spv::OpISubBorrow;
7252 typeId = builder.makeStructResultType(typeId0, typeId0);
7253 consumedOperands = 2;
7254 break;
7255 case glslang::EOpUMulExtended:
7256 opCode = spv::OpUMulExtended;
7257 typeId = builder.makeStructResultType(typeId0, typeId0);
7258 consumedOperands = 2;
7259 break;
7260 case glslang::EOpIMulExtended:
7261 opCode = spv::OpSMulExtended;
7262 typeId = builder.makeStructResultType(typeId0, typeId0);
7263 consumedOperands = 2;
7264 break;
7265 case glslang::EOpBitfieldExtract:
7266 if (isUnsigned)
7267 opCode = spv::OpBitFieldUExtract;
7268 else
7269 opCode = spv::OpBitFieldSExtract;
7270 break;
7271 case glslang::EOpBitfieldInsert:
7272 opCode = spv::OpBitFieldInsert;
7273 break;
7274
7275 case glslang::EOpFma:
7276 libCall = spv::GLSLstd450Fma;
7277 break;
7278 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007279 {
7280 libCall = spv::GLSLstd450FrexpStruct;
7281 assert(builder.isPointerType(typeId1));
7282 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007283 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007284 if (width == 16)
7285 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7286 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
Rex Xu470026f2017-03-29 17:12:40 +08007287 if (builder.getNumComponents(operands[0]) == 1)
7288 frexpIntType = builder.makeIntegerType(width, true);
7289 else
7290 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
7291 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7292 consumedOperands = 1;
7293 }
John Kessenich55e7d112015-11-15 21:33:39 -07007294 break;
7295 case glslang::EOpLdexp:
7296 libCall = spv::GLSLstd450Ldexp;
7297 break;
7298
Rex Xu574ab042016-04-14 16:53:07 +08007299 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007300 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007301
John Kessenich66011cb2018-03-06 16:12:04 -07007302 case glslang::EOpSubgroupBroadcast:
7303 case glslang::EOpSubgroupBallotBitExtract:
7304 case glslang::EOpSubgroupShuffle:
7305 case glslang::EOpSubgroupShuffleXor:
7306 case glslang::EOpSubgroupShuffleUp:
7307 case glslang::EOpSubgroupShuffleDown:
7308 case glslang::EOpSubgroupClusteredAdd:
7309 case glslang::EOpSubgroupClusteredMul:
7310 case glslang::EOpSubgroupClusteredMin:
7311 case glslang::EOpSubgroupClusteredMax:
7312 case glslang::EOpSubgroupClusteredAnd:
7313 case glslang::EOpSubgroupClusteredOr:
7314 case glslang::EOpSubgroupClusteredXor:
7315 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007316 case glslang::EOpSubgroupPartitionedAdd:
7317 case glslang::EOpSubgroupPartitionedMul:
7318 case glslang::EOpSubgroupPartitionedMin:
7319 case glslang::EOpSubgroupPartitionedMax:
7320 case glslang::EOpSubgroupPartitionedAnd:
7321 case glslang::EOpSubgroupPartitionedOr:
7322 case glslang::EOpSubgroupPartitionedXor:
7323 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7324 case glslang::EOpSubgroupPartitionedInclusiveMul:
7325 case glslang::EOpSubgroupPartitionedInclusiveMin:
7326 case glslang::EOpSubgroupPartitionedInclusiveMax:
7327 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7328 case glslang::EOpSubgroupPartitionedInclusiveOr:
7329 case glslang::EOpSubgroupPartitionedInclusiveXor:
7330 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7331 case glslang::EOpSubgroupPartitionedExclusiveMul:
7332 case glslang::EOpSubgroupPartitionedExclusiveMin:
7333 case glslang::EOpSubgroupPartitionedExclusiveMax:
7334 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7335 case glslang::EOpSubgroupPartitionedExclusiveOr:
7336 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007337 return createSubgroupOperation(op, typeId, operands, typeProxy);
7338
Rex Xu9d93a232016-05-05 12:30:44 +08007339 case glslang::EOpSwizzleInvocations:
7340 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7341 libCall = spv::SwizzleInvocationsAMD;
7342 break;
7343 case glslang::EOpSwizzleInvocationsMasked:
7344 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7345 libCall = spv::SwizzleInvocationsMaskedAMD;
7346 break;
7347 case glslang::EOpWriteInvocation:
7348 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7349 libCall = spv::WriteInvocationAMD;
7350 break;
7351
7352 case glslang::EOpMin3:
7353 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7354 if (isFloat)
7355 libCall = spv::FMin3AMD;
7356 else {
7357 if (isUnsigned)
7358 libCall = spv::UMin3AMD;
7359 else
7360 libCall = spv::SMin3AMD;
7361 }
7362 break;
7363 case glslang::EOpMax3:
7364 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7365 if (isFloat)
7366 libCall = spv::FMax3AMD;
7367 else {
7368 if (isUnsigned)
7369 libCall = spv::UMax3AMD;
7370 else
7371 libCall = spv::SMax3AMD;
7372 }
7373 break;
7374 case glslang::EOpMid3:
7375 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7376 if (isFloat)
7377 libCall = spv::FMid3AMD;
7378 else {
7379 if (isUnsigned)
7380 libCall = spv::UMid3AMD;
7381 else
7382 libCall = spv::SMid3AMD;
7383 }
7384 break;
7385
7386 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007387 if (typeProxy == glslang::EbtFloat16)
7388 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007389 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7390 libCall = spv::InterpolateAtVertexAMD;
7391 break;
Chao Chen3c366992018-09-19 11:41:59 -07007392
Chao Chenb50c02e2018-09-19 11:42:24 -07007393 case glslang::EOpReportIntersectionNV:
7394 {
7395 typeId = builder.makeBoolType();
Ashwin Leleff1783d2018-10-22 16:41:44 -07007396 opCode = spv::OpReportIntersectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07007397 }
7398 break;
7399 case glslang::EOpTraceNV:
7400 {
Ashwin Leleff1783d2018-10-22 16:41:44 -07007401 builder.createNoResultOp(spv::OpTraceNV, operands);
7402 return 0;
7403 }
7404 break;
7405 case glslang::EOpExecuteCallableNV:
7406 {
7407 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007408 return 0;
7409 }
7410 break;
Chao Chen3c366992018-09-19 11:41:59 -07007411 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7412 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7413 return 0;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007414 case glslang::EOpCooperativeMatrixMulAdd:
7415 opCode = spv::OpCooperativeMatrixMulAddNV;
7416 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007417#endif // GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007418 default:
7419 return 0;
7420 }
7421
7422 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007423 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007424 // Use an extended instruction from the standard library.
7425 // Construct the call arguments, without modifying the original operands vector.
7426 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7427 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007428 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007429 } else if (opCode == spv::OpDot && !isFloat) {
7430 // int dot(int, int)
7431 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7432 const int componentCount = builder.getNumComponents(operands[0]);
7433 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7434 builder.setPrecision(mulOp, precision);
7435 id = builder.createCompositeExtract(mulOp, typeId, 0);
7436 for (int i = 1; i < componentCount; ++i) {
7437 builder.setPrecision(id, precision);
7438 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(operands[0], typeId, i));
7439 }
John Kessenich2359bd02015-12-06 19:29:11 -07007440 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007441 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007442 case 0:
7443 // should all be handled by visitAggregate and createNoArgOperation
7444 assert(0);
7445 return 0;
7446 case 1:
7447 // should all be handled by createUnaryOperation
7448 assert(0);
7449 return 0;
7450 case 2:
7451 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7452 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007453 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007454 // anything 3 or over doesn't have l-value operands, so all should be consumed
7455 assert(consumedOperands == operands.size());
7456 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007457 break;
7458 }
7459 }
7460
John Kessenichb9197c82019-08-11 07:41:45 -06007461#ifndef GLSLANG_WEB
John Kessenich55e7d112015-11-15 21:33:39 -07007462 // Decode the return types that were structures
7463 switch (op) {
7464 case glslang::EOpAddCarry:
7465 case glslang::EOpSubBorrow:
7466 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7467 id = builder.createCompositeExtract(id, typeId0, 0);
7468 break;
7469 case glslang::EOpUMulExtended:
7470 case glslang::EOpIMulExtended:
7471 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7472 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7473 break;
7474 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007475 {
7476 assert(operands.size() == 2);
7477 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7478 // "exp" is floating-point type (from HLSL intrinsic)
7479 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7480 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7481 builder.createStore(member1, operands[1]);
7482 } else
7483 // "exp" is integer type (from GLSL built-in function)
7484 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7485 id = builder.createCompositeExtract(id, typeId0, 0);
7486 }
John Kessenich55e7d112015-11-15 21:33:39 -07007487 break;
7488 default:
7489 break;
7490 }
John Kessenichb9197c82019-08-11 07:41:45 -06007491#endif
John Kessenich55e7d112015-11-15 21:33:39 -07007492
John Kessenich32cfd492016-02-02 12:37:46 -07007493 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007494}
7495
Rex Xu9d93a232016-05-05 12:30:44 +08007496// Intrinsics with no arguments (or no return value, and no precision).
7497spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007498{
Jeff Bolz36831c92018-09-05 10:11:41 -05007499 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
7500 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007501
7502 switch (op) {
John Kessenich140f3df2015-06-26 16:58:36 -06007503 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007504 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007505 if (glslangIntermediate->usingVulkanMemoryModel()) {
7506 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7507 spv::MemorySemanticsOutputMemoryKHRMask |
7508 spv::MemorySemanticsAcquireReleaseMask);
7509 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7510 } else {
7511 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7512 }
John Kessenich82979362017-12-11 04:02:24 -07007513 } else {
7514 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7515 spv::MemorySemanticsWorkgroupMemoryMask |
7516 spv::MemorySemanticsAcquireReleaseMask);
7517 }
John Kessenich140f3df2015-06-26 16:58:36 -06007518 return 0;
7519 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007520 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7521 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007522 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007523 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007524 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7525 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007526 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007527 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007528 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7529 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007530 return 0;
7531 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007532 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7533 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007534 return 0;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007535#ifndef GLSLANG_WEB
7536 case glslang::EOpMemoryBarrierAtomicCounter:
7537 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7538 spv::MemorySemanticsAcquireReleaseMask);
7539 return 0;
7540 case glslang::EOpMemoryBarrierImage:
7541 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7542 spv::MemorySemanticsAcquireReleaseMask);
7543 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007544 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007545 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007546 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007547 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007548 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007549 case glslang::EOpDeviceMemoryBarrier:
7550 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7551 spv::MemorySemanticsImageMemoryMask |
7552 spv::MemorySemanticsAcquireReleaseMask);
7553 return 0;
7554 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7555 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7556 spv::MemorySemanticsImageMemoryMask |
7557 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007558 return 0;
7559 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007560 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7561 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007562 return 0;
7563 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007564 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7565 spv::MemorySemanticsWorkgroupMemoryMask |
7566 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007567 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007568 case glslang::EOpSubgroupBarrier:
7569 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7570 spv::MemorySemanticsAcquireReleaseMask);
7571 return spv::NoResult;
7572 case glslang::EOpSubgroupMemoryBarrier:
7573 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7574 spv::MemorySemanticsAcquireReleaseMask);
7575 return spv::NoResult;
7576 case glslang::EOpSubgroupMemoryBarrierBuffer:
7577 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7578 spv::MemorySemanticsAcquireReleaseMask);
7579 return spv::NoResult;
7580 case glslang::EOpSubgroupMemoryBarrierImage:
7581 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7582 spv::MemorySemanticsAcquireReleaseMask);
7583 return spv::NoResult;
7584 case glslang::EOpSubgroupMemoryBarrierShared:
7585 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7586 spv::MemorySemanticsAcquireReleaseMask);
7587 return spv::NoResult;
John Kessenichf8d1d742019-10-21 06:55:11 -06007588
7589 case glslang::EOpEmitVertex:
7590 builder.createNoResultOp(spv::OpEmitVertex);
7591 return 0;
7592 case glslang::EOpEndPrimitive:
7593 builder.createNoResultOp(spv::OpEndPrimitive);
7594 return 0;
7595
John Kessenich66011cb2018-03-06 16:12:04 -07007596 case glslang::EOpSubgroupElect: {
7597 std::vector<spv::Id> operands;
7598 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7599 }
Rex Xu9d93a232016-05-05 12:30:44 +08007600 case glslang::EOpTime:
7601 {
7602 std::vector<spv::Id> args; // Dummy arguments
7603 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7604 return builder.setPrecision(id, precision);
7605 }
Chao Chenb50c02e2018-09-19 11:42:24 -07007606 case glslang::EOpIgnoreIntersectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007607 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007608 return 0;
7609 case glslang::EOpTerminateRayNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007610 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007611 return 0;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05007612
7613 case glslang::EOpBeginInvocationInterlock:
7614 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
7615 return 0;
7616 case glslang::EOpEndInvocationInterlock:
7617 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
7618 return 0;
7619
Jeff Bolzba6170b2019-07-01 09:23:23 -05007620 case glslang::EOpIsHelperInvocation:
7621 {
7622 std::vector<spv::Id> args; // Dummy arguments
Rex Xubb7307b2019-07-15 14:57:20 +08007623 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
7624 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
7625 return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
Jeff Bolzba6170b2019-07-01 09:23:23 -05007626 }
7627
amhagan91fb0092019-07-10 21:14:38 -04007628 case glslang::EOpReadClockSubgroupKHR: {
7629 std::vector<spv::Id> args;
7630 args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
7631 builder.addExtension(spv::E_SPV_KHR_shader_clock);
7632 builder.addCapability(spv::CapabilityShaderClockKHR);
7633 return builder.createOp(spv::OpReadClockKHR, typeId, args);
7634 }
7635
7636 case glslang::EOpReadClockDeviceKHR: {
7637 std::vector<spv::Id> args;
7638 args.push_back(builder.makeUintConstant(spv::ScopeDevice));
7639 builder.addExtension(spv::E_SPV_KHR_shader_clock);
7640 builder.addCapability(spv::CapabilityShaderClockKHR);
7641 return builder.createOp(spv::OpReadClockKHR, typeId, args);
7642 }
John Kessenich3dd1ce52019-10-17 07:08:40 -06007643#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007644 default:
John Kessenich155d3512019-08-08 23:29:20 -06007645 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007646 }
John Kessenich155d3512019-08-08 23:29:20 -06007647
7648 logger->missingFunctionality("unknown operation with no arguments");
7649
7650 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007651}
7652
7653spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7654{
John Kessenich2f273362015-07-18 22:34:27 -06007655 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007656 spv::Id id;
7657 if (symbolValues.end() != iter) {
7658 id = iter->second;
7659 return id;
7660 }
7661
7662 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06007663 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
7664 auto forcedType = getForcedType(builtIn, symbol->getType());
7665 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06007666 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06007667 if (forcedType.second != spv::NoType)
7668 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06007669
Rex Xuc884b4a2016-06-29 15:03:44 +08007670 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007671 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7672 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7673 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenicha28f7a72019-08-06 07:00:58 -06007674#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07007675 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
John Kessenichb9197c82019-08-11 07:41:45 -06007676 if (symbol->getQualifier().hasComponent())
7677 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
7678 if (symbol->getQualifier().hasIndex())
7679 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
Chao Chen3c366992018-09-19 11:41:59 -07007680#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007681 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007682 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich91e4aa52016-07-07 17:46:42 -06007683 // atomic counters use this:
7684 if (symbol->getQualifier().hasOffset())
7685 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007686 }
7687
scygan2c864272016-05-18 18:09:17 +02007688 if (symbol->getQualifier().hasLocation())
7689 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007690 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007691 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007692 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007693 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007694 }
John Kessenich140f3df2015-06-26 16:58:36 -06007695 if (symbol->getQualifier().hasSet())
7696 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007697 else if (IsDescriptorResource(symbol->getType())) {
7698 // default to 0
7699 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7700 }
John Kessenich140f3df2015-06-26 16:58:36 -06007701 if (symbol->getQualifier().hasBinding())
7702 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06007703 else if (IsDescriptorResource(symbol->getType())) {
7704 // default to 0
7705 builder.addDecoration(id, spv::DecorationBinding, 0);
7706 }
John Kessenich6c292d32016-02-15 20:58:50 -07007707 if (symbol->getQualifier().hasAttachment())
7708 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06007709 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007710 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07007711 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007712 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007713 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7714 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7715 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7716 }
7717 if (symbol->getQualifier().hasXfbOffset())
7718 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007719 }
7720
John Kessenichb9197c82019-08-11 07:41:45 -06007721 // add built-in variable decoration
7722 if (builtIn != spv::BuiltInMax) {
7723 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
7724 }
7725
7726#ifndef GLSLANG_WEB
Rex Xu1da878f2016-02-21 20:59:01 +08007727 if (symbol->getType().isImage()) {
7728 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05007729 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007730 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007731 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007732 }
7733
John Kessenich5611c6d2018-04-05 11:25:02 -06007734 // nonuniform
7735 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7736
chaoc0ad6a4e2016-12-19 16:29:34 -08007737 if (builtIn == spv::BuiltInSampleMask) {
7738 spv::Decoration decoration;
7739 // GL_NV_sample_mask_override_coverage extension
7740 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007741 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007742 else
7743 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007744 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007745 if (decoration != spv::DecorationMax) {
Jason Macnakdbd4c3c2019-07-12 14:33:02 -07007746 builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
chaoc0ad6a4e2016-12-19 16:29:34 -08007747 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7748 }
7749 }
chaoc771d89f2017-01-13 01:10:53 -08007750 else if (builtIn == spv::BuiltInLayer) {
7751 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007752 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007753 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007754 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7755 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7756 }
John Kessenichb41bff62017-08-11 13:07:17 -06007757 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007758 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7759 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007760 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7761 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7762 }
7763 }
7764
chaoc6e5acae2016-12-20 13:28:52 -08007765 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007766 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007767 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007768 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7769 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007770 if (symbol->getQualifier().pervertexNV) {
7771 builder.addDecoration(id, spv::DecorationPerVertexNV);
7772 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7773 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7774 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007775
John Kessenich5d610ee2018-03-07 18:05:55 -07007776 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7777 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7778 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7779 symbol->getType().getQualifier().semanticName);
7780 }
7781
John Kessenich7015bd62019-08-01 03:28:08 -06007782 if (symbol->isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007783 builder.addDecoration(id, symbol->getType().getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
7784 }
John Kessenichb9197c82019-08-11 07:41:45 -06007785#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007786
John Kessenich140f3df2015-06-26 16:58:36 -06007787 return id;
7788}
7789
John Kessenicha28f7a72019-08-06 07:00:58 -06007790#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07007791// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7792void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7793{
7794 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07007795 if (qualifier.perPrimitiveNV) {
7796 // Need to add capability/extension for fragment shader.
7797 // Mesh shader already adds this by default.
7798 if (glslangIntermediate->getStage() == EShLangFragment) {
7799 builder.addCapability(spv::CapabilityMeshShadingNV);
7800 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7801 }
Chao Chen3c366992018-09-19 11:41:59 -07007802 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007803 }
Chao Chen3c366992018-09-19 11:41:59 -07007804 if (qualifier.perViewNV)
7805 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7806 if (qualifier.perTaskNV)
7807 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7808 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07007809 if (qualifier.perPrimitiveNV) {
7810 // Need to add capability/extension for fragment shader.
7811 // Mesh shader already adds this by default.
7812 if (glslangIntermediate->getStage() == EShLangFragment) {
7813 builder.addCapability(spv::CapabilityMeshShadingNV);
7814 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7815 }
Chao Chen3c366992018-09-19 11:41:59 -07007816 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007817 }
Chao Chen3c366992018-09-19 11:41:59 -07007818 if (qualifier.perViewNV)
7819 builder.addDecoration(id, spv::DecorationPerViewNV);
7820 if (qualifier.perTaskNV)
7821 builder.addDecoration(id, spv::DecorationPerTaskNV);
7822 }
7823}
7824#endif
7825
John Kessenich55e7d112015-11-15 21:33:39 -07007826// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07007827// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07007828//
7829// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7830//
7831// Recursively walk the nodes. The nodes form a tree whose leaves are
7832// regular constants, which themselves are trees that createSpvConstant()
7833// recursively walks. So, this function walks the "top" of the tree:
7834// - emit specialization constant-building instructions for specConstant
7835// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04007836spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07007837{
John Kessenich7cc0e282016-03-20 00:46:02 -06007838 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07007839
qining4f4bb812016-04-03 23:55:17 -04007840 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07007841 if (! node.getQualifier().specConstant) {
7842 // hand off to the non-spec-constant path
7843 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
7844 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04007845 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07007846 nextConst, false);
7847 }
7848
7849 // We now know we have a specialization constant to build
7850
John Kessenichd94c0032016-05-30 19:29:40 -06007851 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04007852 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
7853 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
7854 std::vector<spv::Id> dimConstId;
7855 for (int dim = 0; dim < 3; ++dim) {
7856 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
7857 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07007858 if (specConst) {
7859 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
7860 glslangIntermediate->getLocalSizeSpecId(dim));
7861 }
qining4f4bb812016-04-03 23:55:17 -04007862 }
7863 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
7864 }
7865
7866 // An AST node labelled as specialization constant should be a symbol node.
7867 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
7868 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007869 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04007870 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04007871 // Traverse the constant constructor sub tree like generating normal run-time instructions.
7872 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
7873 // will set the builder into spec constant op instruction generating mode.
7874 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007875 result = accessChainLoad(sub_tree->getType());
7876 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04007877 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007878 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05007879 } else {
7880 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05007881 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07007882 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007883 builder.addName(result, sn->getName().c_str());
7884 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07007885 }
qining4f4bb812016-04-03 23:55:17 -04007886
7887 // Neither a front-end constant node, nor a specialization constant node with constant union array or
7888 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04007889 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04007890 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07007891}
7892
John Kessenich140f3df2015-06-26 16:58:36 -06007893// Use 'consts' as the flattened glslang source of scalar constants to recursively
7894// build the aggregate SPIR-V constant.
7895//
7896// If there are not enough elements present in 'consts', 0 will be substituted;
7897// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
7898//
qining08408382016-03-21 09:51:37 -04007899spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06007900{
7901 // vector of constants for SPIR-V
7902 std::vector<spv::Id> spvConsts;
7903
7904 // Type is used for struct and array constants
7905 spv::Id typeId = convertGlslangToSpvType(glslangType);
7906
7907 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007908 glslang::TType elementType(glslangType, 0);
7909 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04007910 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007911 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007912 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06007913 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04007914 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007915 } else if (glslangType.isCoopMat()) {
7916 glslang::TType componentType(glslangType.getBasicType());
7917 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007918 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007919 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
7920 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04007921 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06007922 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06007923 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
7924 bool zero = nextConst >= consts.size();
7925 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06007926 case glslang::EbtInt:
7927 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
7928 break;
7929 case glslang::EbtUint:
7930 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
7931 break;
7932 case glslang::EbtFloat:
7933 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7934 break;
7935 case glslang::EbtBool:
7936 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7937 break;
7938#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07007939 case glslang::EbtInt8:
7940 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
7941 break;
7942 case glslang::EbtUint8:
7943 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
7944 break;
7945 case glslang::EbtInt16:
7946 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
7947 break;
7948 case glslang::EbtUint16:
7949 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
7950 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007951 case glslang::EbtInt64:
7952 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
7953 break;
7954 case glslang::EbtUint64:
7955 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
7956 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007957 case glslang::EbtDouble:
7958 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
7959 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007960 case glslang::EbtFloat16:
7961 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7962 break;
John Kessenich39697cd2019-08-08 10:35:51 -06007963#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007964 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007965 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007966 break;
7967 }
7968 ++nextConst;
7969 }
7970 } else {
7971 // we have a non-aggregate (scalar) constant
7972 bool zero = nextConst >= consts.size();
7973 spv::Id scalar = 0;
7974 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06007975 case glslang::EbtInt:
7976 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
7977 break;
7978 case glslang::EbtUint:
7979 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
7980 break;
7981 case glslang::EbtFloat:
7982 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7983 break;
7984 case glslang::EbtBool:
7985 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
7986 break;
7987#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07007988 case glslang::EbtInt8:
7989 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
7990 break;
7991 case glslang::EbtUint8:
7992 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
7993 break;
7994 case glslang::EbtInt16:
7995 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
7996 break;
7997 case glslang::EbtUint16:
7998 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
7999 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008000 case glslang::EbtInt64:
8001 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
8002 break;
8003 case glslang::EbtUint64:
8004 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8005 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008006 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07008007 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06008008 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008009 case glslang::EbtFloat16:
8010 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8011 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06008012 case glslang::EbtReference:
8013 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8014 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
8015 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008016#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008017 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008018 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008019 break;
8020 }
8021 ++nextConst;
8022 return scalar;
8023 }
8024
8025 return builder.makeCompositeConstant(typeId, spvConsts);
8026}
8027
John Kessenich7c1aa102015-10-15 13:29:11 -06008028// Return true if the node is a constant or symbol whose reading has no
8029// non-trivial observable cost or effect.
8030bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
8031{
8032 // don't know what this is
8033 if (node == nullptr)
8034 return false;
8035
8036 // a constant is safe
8037 if (node->getAsConstantUnion() != nullptr)
8038 return true;
8039
8040 // not a symbol means non-trivial
8041 if (node->getAsSymbolNode() == nullptr)
8042 return false;
8043
8044 // a symbol, depends on what's being read
8045 switch (node->getType().getQualifier().storage) {
8046 case glslang::EvqTemporary:
8047 case glslang::EvqGlobal:
8048 case glslang::EvqIn:
8049 case glslang::EvqInOut:
8050 case glslang::EvqConst:
8051 case glslang::EvqConstReadOnly:
8052 case glslang::EvqUniform:
8053 return true;
8054 default:
8055 return false;
8056 }
qining25262b32016-05-06 17:25:16 -04008057}
John Kessenich7c1aa102015-10-15 13:29:11 -06008058
8059// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06008060// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06008061// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06008062// Return true if trivial.
8063bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
8064{
8065 if (node == nullptr)
8066 return false;
8067
John Kessenich84cc15f2017-05-24 16:44:47 -06008068 // count non scalars as trivial, as well as anything coming from HLSL
8069 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06008070 return true;
8071
John Kessenich7c1aa102015-10-15 13:29:11 -06008072 // symbols and constants are trivial
8073 if (isTrivialLeaf(node))
8074 return true;
8075
8076 // otherwise, it needs to be a simple operation or one or two leaf nodes
8077
8078 // not a simple operation
8079 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
8080 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
8081 if (binaryNode == nullptr && unaryNode == nullptr)
8082 return false;
8083
8084 // not on leaf nodes
8085 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
8086 return false;
8087
8088 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
8089 return false;
8090 }
8091
8092 switch (node->getAsOperator()->getOp()) {
8093 case glslang::EOpLogicalNot:
8094 case glslang::EOpConvIntToBool:
8095 case glslang::EOpConvUintToBool:
8096 case glslang::EOpConvFloatToBool:
8097 case glslang::EOpConvDoubleToBool:
8098 case glslang::EOpEqual:
8099 case glslang::EOpNotEqual:
8100 case glslang::EOpLessThan:
8101 case glslang::EOpGreaterThan:
8102 case glslang::EOpLessThanEqual:
8103 case glslang::EOpGreaterThanEqual:
8104 case glslang::EOpIndexDirect:
8105 case glslang::EOpIndexDirectStruct:
8106 case glslang::EOpLogicalXor:
8107 case glslang::EOpAny:
8108 case glslang::EOpAll:
8109 return true;
8110 default:
8111 return false;
8112 }
8113}
8114
8115// Emit short-circuiting code, where 'right' is never evaluated unless
8116// the left side is true (for &&) or false (for ||).
8117spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
8118{
8119 spv::Id boolTypeId = builder.makeBoolType();
8120
8121 // emit left operand
8122 builder.clearAccessChain();
8123 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008124 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008125
8126 // Operands to accumulate OpPhi operands
8127 std::vector<spv::Id> phiOperands;
8128 // accumulate left operand's phi information
8129 phiOperands.push_back(leftId);
8130 phiOperands.push_back(builder.getBuildPoint()->getId());
8131
8132 // Make the two kinds of operation symmetric with a "!"
8133 // || => emit "if (! left) result = right"
8134 // && => emit "if ( left) result = right"
8135 //
8136 // TODO: this runtime "not" for || could be avoided by adding functionality
8137 // to 'builder' to have an "else" without an "then"
8138 if (op == glslang::EOpLogicalOr)
8139 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8140
8141 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008142 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008143
8144 // emit right operand as the "then" part of the "if"
8145 builder.clearAccessChain();
8146 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008147 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008148
8149 // accumulate left operand's phi information
8150 phiOperands.push_back(rightId);
8151 phiOperands.push_back(builder.getBuildPoint()->getId());
8152
8153 // finish the "if"
8154 ifBuilder.makeEndIf();
8155
8156 // phi together the two results
8157 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8158}
8159
John Kessenicha28f7a72019-08-06 07:00:58 -06008160#ifndef GLSLANG_WEB
Rex Xu9d93a232016-05-05 12:30:44 +08008161// Return type Id of the imported set of extended instructions corresponds to the name.
8162// Import this set if it has not been imported yet.
8163spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8164{
8165 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8166 return extBuiltinMap[name];
8167 else {
Rex Xu51596642016-09-21 18:56:12 +08008168 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008169 spv::Id extBuiltins = builder.import(name);
8170 extBuiltinMap[name] = extBuiltins;
8171 return extBuiltins;
8172 }
8173}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008174#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008175
John Kessenich140f3df2015-06-26 16:58:36 -06008176}; // end anonymous namespace
8177
8178namespace glslang {
8179
John Kessenich68d78fd2015-07-12 19:28:10 -06008180void GetSpirvVersion(std::string& version)
8181{
John Kessenich9e55f632015-07-15 10:03:39 -06008182 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008183 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008184 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008185 version = buf;
8186}
8187
John Kessenicha372a3e2017-11-02 22:32:14 -06008188// For low-order part of the generator's magic number. Bump up
8189// when there is a change in the style (e.g., if SSA form changes,
8190// or a different instruction sequence to do something gets used).
8191int GetSpirvGeneratorVersion()
8192{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008193 // return 1; // start
8194 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008195 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008196 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008197 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008198 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8199 // versions 4 and 6 each generate OpArrayLength as it has long been done
8200 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06008201}
8202
John Kessenich140f3df2015-06-26 16:58:36 -06008203// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008204void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008205{
8206 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008207 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008208 if (out.fail())
8209 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008210 for (int i = 0; i < (int)spirv.size(); ++i) {
8211 unsigned int word = spirv[i];
8212 out.write((const char*)&word, 4);
8213 }
8214 out.close();
8215}
8216
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008217// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008218void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008219{
John Kessenich155d3512019-08-08 23:29:20 -06008220#ifndef GLSLANG_WEB
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008221 std::ofstream out;
8222 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008223 if (out.fail())
8224 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07008225 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06008226 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07008227 std::endl;
Flavio15017db2017-02-15 14:29:33 -08008228 if (varName != nullptr) {
8229 out << "\t #pragma once" << std::endl;
8230 out << "const uint32_t " << varName << "[] = {" << std::endl;
8231 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008232 const int WORDS_PER_LINE = 8;
8233 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8234 out << "\t";
8235 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8236 const unsigned int word = spirv[i + j];
8237 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8238 if (i + j + 1 < (int)spirv.size()) {
8239 out << ",";
8240 }
8241 }
8242 out << std::endl;
8243 }
Flavio15017db2017-02-15 14:29:33 -08008244 if (varName != nullptr) {
8245 out << "};";
8246 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008247 out.close();
John Kessenich155d3512019-08-08 23:29:20 -06008248#endif
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008249}
8250
John Kessenich140f3df2015-06-26 16:58:36 -06008251//
8252// Set up the glslang traversal
8253//
John Kessenich4e11b612018-08-30 16:56:59 -06008254void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008255{
Lei Zhang17535f72016-05-04 15:55:59 -04008256 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008257 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008258}
8259
John Kessenich4e11b612018-08-30 16:56:59 -06008260void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008261 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008262{
John Kessenich140f3df2015-06-26 16:58:36 -06008263 TIntermNode* root = intermediate.getTreeRoot();
8264
8265 if (root == 0)
8266 return;
8267
John Kessenich4e11b612018-08-30 16:56:59 -06008268 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008269 if (options == nullptr)
8270 options = &defaultOptions;
8271
John Kessenich4e11b612018-08-30 16:56:59 -06008272 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008273
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008274 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008275 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008276 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008277 it.dumpSpv(spirv);
8278
GregFfb03a552018-03-29 11:49:14 -06008279#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008280 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8281 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008282 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
8283 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer) {
John Kesseniche7df8e02018-08-22 17:12:46 -06008284 SpirvToolsLegalize(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008285 prelegalization = false;
8286 }
John Kessenich717c80a2018-08-23 15:17:10 -06008287
John Kessenich4e11b612018-08-30 16:56:59 -06008288 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008289 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008290
John Kessenich717c80a2018-08-23 15:17:10 -06008291 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008292 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008293
GregFcd1f1692017-09-21 18:40:22 -06008294#endif
8295
John Kessenich4e11b612018-08-30 16:56:59 -06008296 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008297}
8298
8299}; // end namespace glslang