blob: c6dcef5ef7f01302fb95f4b883af8e267742a210 [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{
John Kessenichb9197c82019-08-11 07:41:45 -0600377#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -0500378 if (!useVulkanMemoryModel) {
379 if (qualifier.coherent)
380 memory.push_back(spv::DecorationCoherent);
381 if (qualifier.volatil) {
382 memory.push_back(spv::DecorationVolatile);
383 memory.push_back(spv::DecorationCoherent);
384 }
John Kessenich14b85d32018-06-04 15:36:03 -0600385 }
Rex Xu1da878f2016-02-21 20:59:01 +0800386 if (qualifier.restrict)
387 memory.push_back(spv::DecorationRestrict);
John Kessenichdeec1932019-08-13 08:00:30 -0600388 if (qualifier.isReadOnly())
Rex Xu1da878f2016-02-21 20:59:01 +0800389 memory.push_back(spv::DecorationNonWritable);
John Kessenichdeec1932019-08-13 08:00:30 -0600390 if (qualifier.isWriteOnly())
Rex Xu1da878f2016-02-21 20:59:01 +0800391 memory.push_back(spv::DecorationNonReadable);
John Kessenichb9197c82019-08-11 07:41:45 -0600392#endif
Rex Xu1da878f2016-02-21 20:59:01 +0800393}
394
John Kessenich140f3df2015-06-26 16:58:36 -0600395// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700396spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600397{
398 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700399 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600400 case glslang::ElmRowMajor:
401 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700402 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600403 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700404 default:
405 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600406 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600407 }
408 } else {
409 switch (type.getBasicType()) {
410 default:
John Kessenich4016e382016-07-15 11:53:56 -0600411 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600412 break;
413 case glslang::EbtBlock:
414 switch (type.getQualifier().storage) {
415 case glslang::EvqUniform:
416 case glslang::EvqBuffer:
417 switch (type.getQualifier().layoutPacking) {
418 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600419 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
420 default:
John Kessenich4016e382016-07-15 11:53:56 -0600421 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600422 }
423 case glslang::EvqVaryingIn:
424 case glslang::EvqVaryingOut:
Chao Chen3c366992018-09-19 11:41:59 -0700425 if (type.getQualifier().isTaskMemory()) {
426 switch (type.getQualifier().layoutPacking) {
427 case glslang::ElpShared: return spv::DecorationGLSLShared;
428 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
429 default: break;
430 }
431 } else {
432 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
433 }
John Kessenich4016e382016-07-15 11:53:56 -0600434 return spv::DecorationMax;
John Kessenicha28f7a72019-08-06 07:00:58 -0600435#ifndef GLSLANG_WEB
Chao Chenb50c02e2018-09-19 11:42:24 -0700436 case glslang::EvqPayloadNV:
437 case glslang::EvqPayloadInNV:
438 case glslang::EvqHitAttrNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700439 case glslang::EvqCallableDataNV:
440 case glslang::EvqCallableDataInNV:
Chao Chenb50c02e2018-09-19 11:42:24 -0700441 return spv::DecorationMax;
442#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600443 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700444 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600445 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600446 }
447 }
448 }
449}
450
451// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600452// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700453// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800454spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600455{
Rex Xubbceed72016-05-21 09:40:44 +0800456 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700457 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600458 return spv::DecorationMax;
John Kessenich7015bd62019-08-01 03:28:08 -0600459 else if (qualifier.isNonPerspective())
John Kessenich55e7d112015-11-15 21:33:39 -0700460 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700461 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600462 return spv::DecorationFlat;
John Kessenicha28f7a72019-08-06 07:00:58 -0600463 else if (qualifier.isExplicitInterpolation()) {
Rex Xu17ff3432016-10-14 17:41:45 +0800464 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800465 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800466 }
Rex Xubbceed72016-05-21 09:40:44 +0800467 else
John Kessenich4016e382016-07-15 11:53:56 -0600468 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800469}
470
471// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600472// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800473// should be applied.
474spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
475{
John Kessenichb9197c82019-08-11 07:41:45 -0600476 if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600477 return spv::DecorationCentroid;
John Kessenichb9197c82019-08-11 07:41:45 -0600478#ifndef GLSLANG_WEB
479 else if (qualifier.patch)
480 return spv::DecorationPatch;
John Kessenich5e801132016-02-15 11:09:46 -0700481 else if (qualifier.sample) {
482 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600483 return spv::DecorationSample;
John Kessenichb9197c82019-08-11 07:41:45 -0600484 }
485#endif
486
487 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600488}
489
John Kessenich92187592016-02-01 13:45:25 -0700490// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700491spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600492{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700493 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600494 return spv::DecorationInvariant;
495 else
John Kessenich4016e382016-07-15 11:53:56 -0600496 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600497}
498
qining9220dbb2016-05-04 17:34:38 -0400499// If glslang type is noContraction, return SPIR-V NoContraction decoration.
500spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
501{
John Kessenichb9197c82019-08-11 07:41:45 -0600502#ifndef GLSLANG_WEB
John Kessenicha28f7a72019-08-06 07:00:58 -0600503 if (qualifier.isNoContraction())
qining9220dbb2016-05-04 17:34:38 -0400504 return spv::DecorationNoContraction;
505 else
John Kessenichb9197c82019-08-11 07:41:45 -0600506#endif
John Kessenich4016e382016-07-15 11:53:56 -0600507 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400508}
509
John Kessenich5611c6d2018-04-05 11:25:02 -0600510// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
511spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
512{
John Kessenichb9197c82019-08-11 07:41:45 -0600513#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -0600514 if (qualifier.isNonUniform()) {
John Kessenich8317e6c2019-08-18 23:58:08 -0600515 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -0600516 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
517 return spv::DecorationNonUniformEXT;
518 } else
John Kessenichb9197c82019-08-11 07:41:45 -0600519#endif
John Kessenich5611c6d2018-04-05 11:25:02 -0600520 return spv::DecorationMax;
521}
522
John Kessenichb9197c82019-08-11 07:41:45 -0600523spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(
524 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500525{
Jeff Bolz36831c92018-09-05 10:11:41 -0500526 spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
John Kessenichb9197c82019-08-11 07:41:45 -0600527
528#ifndef GLSLANG_WEB
529 if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage)
530 return mask;
531
Jeff Bolz36831c92018-09-05 10:11:41 -0500532 if (coherentFlags.volatil ||
533 coherentFlags.coherent ||
534 coherentFlags.devicecoherent ||
535 coherentFlags.queuefamilycoherent ||
536 coherentFlags.workgroupcoherent ||
537 coherentFlags.subgroupcoherent) {
538 mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
539 spv::MemoryAccessMakePointerVisibleKHRMask;
540 }
541 if (coherentFlags.nonprivate) {
542 mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
543 }
544 if (coherentFlags.volatil) {
545 mask = mask | spv::MemoryAccessVolatileMask;
546 }
547 if (mask != spv::MemoryAccessMaskNone) {
548 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
549 }
John Kessenichb9197c82019-08-11 07:41:45 -0600550#endif
551
Jeff Bolz36831c92018-09-05 10:11:41 -0500552 return mask;
553}
554
John Kessenichb9197c82019-08-11 07:41:45 -0600555spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(
556 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500557{
Jeff Bolz36831c92018-09-05 10:11:41 -0500558 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenichb9197c82019-08-11 07:41:45 -0600559
560#ifndef GLSLANG_WEB
561 if (!glslangIntermediate->usingVulkanMemoryModel())
562 return mask;
563
Jeff Bolz36831c92018-09-05 10:11:41 -0500564 if (coherentFlags.volatil ||
565 coherentFlags.coherent ||
566 coherentFlags.devicecoherent ||
567 coherentFlags.queuefamilycoherent ||
568 coherentFlags.workgroupcoherent ||
569 coherentFlags.subgroupcoherent) {
570 mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
571 spv::ImageOperandsMakeTexelVisibleKHRMask;
572 }
573 if (coherentFlags.nonprivate) {
574 mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
575 }
576 if (coherentFlags.volatil) {
577 mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
578 }
579 if (mask != spv::ImageOperandsMaskNone) {
580 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
581 }
John Kessenichb9197c82019-08-11 07:41:45 -0600582#endif
583
Jeff Bolz36831c92018-09-05 10:11:41 -0500584 return mask;
585}
586
587spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
588{
John Kessenichb9197c82019-08-11 07:41:45 -0600589 spv::Builder::AccessChain::CoherentFlags flags = {};
590#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -0500591 flags.coherent = type.getQualifier().coherent;
592 flags.devicecoherent = type.getQualifier().devicecoherent;
593 flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
594 // shared variables are implicitly workgroupcoherent in GLSL.
595 flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
596 type.getQualifier().storage == glslang::EvqShared;
597 flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600598 flags.volatil = type.getQualifier().volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500599 // *coherent variables are implicitly nonprivate in GLSL
600 flags.nonprivate = type.getQualifier().nonprivate ||
Jeff Bolzab3c9652018-10-15 22:46:48 -0500601 flags.subgroupcoherent ||
602 flags.workgroupcoherent ||
603 flags.queuefamilycoherent ||
604 flags.devicecoherent ||
Jeff Bolz38cbad12019-03-05 14:40:07 -0600605 flags.coherent ||
606 flags.volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500607 flags.isImage = type.getBasicType() == glslang::EbtSampler;
John Kessenichb9197c82019-08-11 07:41:45 -0600608#endif
Jeff Bolz36831c92018-09-05 10:11:41 -0500609 return flags;
610}
611
John Kessenichb9197c82019-08-11 07:41:45 -0600612spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(
613 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500614{
John Kessenichb9197c82019-08-11 07:41:45 -0600615 spv::Scope scope = spv::ScopeMax;
616
617#ifndef GLSLANG_WEB
Jeff Bolz38cbad12019-03-05 14:40:07 -0600618 if (coherentFlags.volatil || coherentFlags.coherent) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500619 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
620 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
621 } else if (coherentFlags.devicecoherent) {
622 scope = spv::ScopeDevice;
623 } else if (coherentFlags.queuefamilycoherent) {
624 scope = spv::ScopeQueueFamilyKHR;
625 } else if (coherentFlags.workgroupcoherent) {
626 scope = spv::ScopeWorkgroup;
627 } else if (coherentFlags.subgroupcoherent) {
628 scope = spv::ScopeSubgroup;
Jeff Bolz36831c92018-09-05 10:11:41 -0500629 }
630 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
631 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
632 }
John Kessenichb9197c82019-08-11 07:41:45 -0600633#endif
634
Jeff Bolz36831c92018-09-05 10:11:41 -0500635 return scope;
636}
637
David Netoa901ffe2016-06-08 14:11:40 +0100638// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
639// associated capabilities when required. For some built-in variables, a capability
640// is generated only when using the variable in an executable instruction, but not when
641// just declaring a struct member variable with it. This is true for PointSize,
642// ClipDistance, and CullDistance.
643spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600644{
645 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700646 case glslang::EbvPointSize:
John Kessenich155d3512019-08-08 23:29:20 -0600647#ifndef GLSLANG_WEB
John Kessenich78a45572016-07-08 14:05:15 -0600648 // Defer adding the capability until the built-in is actually used.
649 if (! memberDeclaration) {
650 switch (glslangIntermediate->getStage()) {
651 case EShLangGeometry:
652 builder.addCapability(spv::CapabilityGeometryPointSize);
653 break;
654 case EShLangTessControl:
655 case EShLangTessEvaluation:
656 builder.addCapability(spv::CapabilityTessellationPointSize);
657 break;
658 default:
659 break;
660 }
John Kessenich92187592016-02-01 13:45:25 -0700661 }
John Kessenich155d3512019-08-08 23:29:20 -0600662#endif
John Kessenich92187592016-02-01 13:45:25 -0700663 return spv::BuiltInPointSize;
664
John Kessenicha28f7a72019-08-06 07:00:58 -0600665 case glslang::EbvPosition: return spv::BuiltInPosition;
666 case glslang::EbvVertexId: return spv::BuiltInVertexId;
667 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
668 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
669 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
670
671 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
672 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
673 case glslang::EbvFace: return spv::BuiltInFrontFacing;
674 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
675
John Kessenich3dd1ce52019-10-17 07:08:40 -0600676 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
677 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
678 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
679 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
680 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
681 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
682
John Kessenicha28f7a72019-08-06 07:00:58 -0600683#ifndef GLSLANG_WEB
John Kessenichebb50532016-05-16 19:22:05 -0600684 // These *Distance capabilities logically belong here, but if the member is declared and
685 // then never used, consumers of SPIR-V prefer the capability not be declared.
686 // They are now generated when used, rather than here when declared.
687 // Potentially, the specification should be more clear what the minimum
688 // use needed is to trigger the capability.
689 //
John Kessenich92187592016-02-01 13:45:25 -0700690 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100691 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800692 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700693 return spv::BuiltInClipDistance;
694
695 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100696 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800697 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700698 return spv::BuiltInCullDistance;
699
700 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600701 builder.addCapability(spv::CapabilityMultiViewport);
702 if (glslangIntermediate->getStage() == EShLangVertex ||
703 glslangIntermediate->getStage() == EShLangTessControl ||
704 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800705
John Kessenich8317e6c2019-08-18 23:58:08 -0600706 builder.addIncorporatedExtension(spv::E_SPV_EXT_shader_viewport_index_layer, spv::Spv_1_5);
John Kessenichba6a3c22017-09-13 13:22:50 -0600707 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800708 }
John Kessenich92187592016-02-01 13:45:25 -0700709 return spv::BuiltInViewportIndex;
710
John Kessenich5e801132016-02-15 11:09:46 -0700711 case glslang::EbvSampleId:
712 builder.addCapability(spv::CapabilitySampleRateShading);
713 return spv::BuiltInSampleId;
714
715 case glslang::EbvSamplePosition:
716 builder.addCapability(spv::CapabilitySampleRateShading);
717 return spv::BuiltInSamplePosition;
718
719 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700720 return spv::BuiltInSampleMask;
721
John Kessenich78a45572016-07-08 14:05:15 -0600722 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700723 if (glslangIntermediate->getStage() == EShLangMeshNV) {
724 return spv::BuiltInLayer;
725 }
John Kessenichba6a3c22017-09-13 13:22:50 -0600726 builder.addCapability(spv::CapabilityGeometry);
727 if (glslangIntermediate->getStage() == EShLangVertex ||
728 glslangIntermediate->getStage() == EShLangTessControl ||
729 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800730
John Kessenich8317e6c2019-08-18 23:58:08 -0600731 builder.addIncorporatedExtension(spv::E_SPV_EXT_shader_viewport_index_layer, spv::Spv_1_5);
John Kessenichba6a3c22017-09-13 13:22:50 -0600732 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800733 }
John Kessenich78a45572016-07-08 14:05:15 -0600734 return spv::BuiltInLayer;
735
John Kessenichda581a22015-10-14 14:10:30 -0600736 case glslang::EbvBaseVertex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600737 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800738 builder.addCapability(spv::CapabilityDrawParameters);
739 return spv::BuiltInBaseVertex;
740
John Kessenichda581a22015-10-14 14:10:30 -0600741 case glslang::EbvBaseInstance:
John Kessenich8317e6c2019-08-18 23:58:08 -0600742 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800743 builder.addCapability(spv::CapabilityDrawParameters);
744 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200745
John Kessenichda581a22015-10-14 14:10:30 -0600746 case glslang::EbvDrawId:
John Kessenich8317e6c2019-08-18 23:58:08 -0600747 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800748 builder.addCapability(spv::CapabilityDrawParameters);
749 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200750
751 case glslang::EbvPrimitiveId:
752 if (glslangIntermediate->getStage() == EShLangFragment)
753 builder.addCapability(spv::CapabilityGeometry);
754 return spv::BuiltInPrimitiveId;
755
Rex Xu37cdcee2017-06-29 17:46:34 +0800756 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800757 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
758 builder.addCapability(spv::CapabilityStencilExportEXT);
759 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800760
John Kessenich140f3df2015-06-26 16:58:36 -0600761 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600762 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
763 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
764 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
765 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
John Kessenich140f3df2015-06-26 16:58:36 -0600766 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
Rex Xu51596642016-09-21 18:56:12 +0800767
Rex Xu574ab042016-04-14 16:53:07 +0800768 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800769 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800770 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
771 return spv::BuiltInSubgroupSize;
772
Rex Xu574ab042016-04-14 16:53:07 +0800773 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800774 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800775 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
776 return spv::BuiltInSubgroupLocalInvocationId;
777
Rex Xu574ab042016-04-14 16:53:07 +0800778 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800779 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
780 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600781 return spv::BuiltInSubgroupEqMask;
Rex Xu51596642016-09-21 18:56:12 +0800782
Rex Xu574ab042016-04-14 16:53:07 +0800783 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800784 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
785 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600786 return spv::BuiltInSubgroupGeMask;
Rex Xu51596642016-09-21 18:56:12 +0800787
Rex Xu574ab042016-04-14 16:53:07 +0800788 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800789 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
790 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600791 return spv::BuiltInSubgroupGtMask;
Rex Xu51596642016-09-21 18:56:12 +0800792
Rex Xu574ab042016-04-14 16:53:07 +0800793 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800794 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
795 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600796 return spv::BuiltInSubgroupLeMask;
Rex Xu51596642016-09-21 18:56:12 +0800797
Rex Xu574ab042016-04-14 16:53:07 +0800798 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800799 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
800 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600801 return spv::BuiltInSubgroupLtMask;
Rex Xu51596642016-09-21 18:56:12 +0800802
John Kessenich66011cb2018-03-06 16:12:04 -0700803 case glslang::EbvNumSubgroups:
804 builder.addCapability(spv::CapabilityGroupNonUniform);
805 return spv::BuiltInNumSubgroups;
806
807 case glslang::EbvSubgroupID:
808 builder.addCapability(spv::CapabilityGroupNonUniform);
809 return spv::BuiltInSubgroupId;
810
811 case glslang::EbvSubgroupSize2:
812 builder.addCapability(spv::CapabilityGroupNonUniform);
813 return spv::BuiltInSubgroupSize;
814
815 case glslang::EbvSubgroupInvocation2:
816 builder.addCapability(spv::CapabilityGroupNonUniform);
817 return spv::BuiltInSubgroupLocalInvocationId;
818
819 case glslang::EbvSubgroupEqMask2:
820 builder.addCapability(spv::CapabilityGroupNonUniform);
821 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
822 return spv::BuiltInSubgroupEqMask;
823
824 case glslang::EbvSubgroupGeMask2:
825 builder.addCapability(spv::CapabilityGroupNonUniform);
826 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
827 return spv::BuiltInSubgroupGeMask;
828
829 case glslang::EbvSubgroupGtMask2:
830 builder.addCapability(spv::CapabilityGroupNonUniform);
831 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
832 return spv::BuiltInSubgroupGtMask;
833
834 case glslang::EbvSubgroupLeMask2:
835 builder.addCapability(spv::CapabilityGroupNonUniform);
836 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
837 return spv::BuiltInSubgroupLeMask;
838
839 case glslang::EbvSubgroupLtMask2:
840 builder.addCapability(spv::CapabilityGroupNonUniform);
841 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
842 return spv::BuiltInSubgroupLtMask;
John Kessenich9c14f772019-06-17 08:38:35 -0600843
Rex Xu17ff3432016-10-14 17:41:45 +0800844 case glslang::EbvBaryCoordNoPersp:
845 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
846 return spv::BuiltInBaryCoordNoPerspAMD;
847
848 case glslang::EbvBaryCoordNoPerspCentroid:
849 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
850 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
851
852 case glslang::EbvBaryCoordNoPerspSample:
853 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
854 return spv::BuiltInBaryCoordNoPerspSampleAMD;
855
856 case glslang::EbvBaryCoordSmooth:
857 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
858 return spv::BuiltInBaryCoordSmoothAMD;
859
860 case glslang::EbvBaryCoordSmoothCentroid:
861 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
862 return spv::BuiltInBaryCoordSmoothCentroidAMD;
863
864 case glslang::EbvBaryCoordSmoothSample:
865 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
866 return spv::BuiltInBaryCoordSmoothSampleAMD;
867
868 case glslang::EbvBaryCoordPullModel:
869 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
870 return spv::BuiltInBaryCoordPullModelAMD;
chaoc771d89f2017-01-13 01:10:53 -0800871
John Kessenich6c8aaac2017-02-27 01:20:51 -0700872 case glslang::EbvDeviceIndex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600873 builder.addIncorporatedExtension(spv::E_SPV_KHR_device_group, spv::Spv_1_3);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700874 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700875 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700876
877 case glslang::EbvViewIndex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600878 builder.addIncorporatedExtension(spv::E_SPV_KHR_multiview, spv::Spv_1_3);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700879 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700880 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700881
Daniel Koch5154db52018-11-26 10:01:58 -0500882 case glslang::EbvFragSizeEXT:
883 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
884 builder.addCapability(spv::CapabilityFragmentDensityEXT);
885 return spv::BuiltInFragSizeEXT;
886
887 case glslang::EbvFragInvocationCountEXT:
888 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
889 builder.addCapability(spv::CapabilityFragmentDensityEXT);
890 return spv::BuiltInFragInvocationCountEXT;
891
chaoc771d89f2017-01-13 01:10:53 -0800892 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800893 if (!memberDeclaration) {
894 builder.addExtension(spv::E_SPV_NV_viewport_array2);
895 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
896 }
chaoc771d89f2017-01-13 01:10:53 -0800897 return spv::BuiltInViewportMaskNV;
898 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800899 if (!memberDeclaration) {
900 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
901 builder.addCapability(spv::CapabilityShaderStereoViewNV);
902 }
chaoc771d89f2017-01-13 01:10:53 -0800903 return spv::BuiltInSecondaryPositionNV;
904 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800905 if (!memberDeclaration) {
906 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
907 builder.addCapability(spv::CapabilityShaderStereoViewNV);
908 }
chaoc771d89f2017-01-13 01:10:53 -0800909 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800910 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800911 if (!memberDeclaration) {
912 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
913 builder.addCapability(spv::CapabilityPerViewAttributesNV);
914 }
chaocdf3956c2017-02-14 14:52:34 -0800915 return spv::BuiltInPositionPerViewNV;
916 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800917 if (!memberDeclaration) {
918 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
919 builder.addCapability(spv::CapabilityPerViewAttributesNV);
920 }
chaocdf3956c2017-02-14 14:52:34 -0800921 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700922 case glslang::EbvFragFullyCoveredNV:
923 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
924 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
925 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700926 case glslang::EbvFragmentSizeNV:
927 builder.addExtension(spv::E_SPV_NV_shading_rate);
928 builder.addCapability(spv::CapabilityShadingRateNV);
929 return spv::BuiltInFragmentSizeNV;
930 case glslang::EbvInvocationsPerPixelNV:
931 builder.addExtension(spv::E_SPV_NV_shading_rate);
932 builder.addCapability(spv::CapabilityShadingRateNV);
933 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700934
Daniel Koch593a4e02019-05-27 16:46:31 -0400935 // ray tracing
Chao Chenb50c02e2018-09-19 11:42:24 -0700936 case glslang::EbvLaunchIdNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700937 return spv::BuiltInLaunchIdNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700938 case glslang::EbvLaunchSizeNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700939 return spv::BuiltInLaunchSizeNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700940 case glslang::EbvWorldRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700941 return spv::BuiltInWorldRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700942 case glslang::EbvWorldRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700943 return spv::BuiltInWorldRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700944 case glslang::EbvObjectRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700945 return spv::BuiltInObjectRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700946 case glslang::EbvObjectRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700947 return spv::BuiltInObjectRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700948 case glslang::EbvRayTminNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700949 return spv::BuiltInRayTminNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700950 case glslang::EbvRayTmaxNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700951 return spv::BuiltInRayTmaxNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700952 case glslang::EbvInstanceCustomIndexNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700953 return spv::BuiltInInstanceCustomIndexNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700954 case glslang::EbvHitTNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700955 return spv::BuiltInHitTNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700956 case glslang::EbvHitKindNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700957 return spv::BuiltInHitKindNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700958 case glslang::EbvObjectToWorldNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700959 return spv::BuiltInObjectToWorldNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700960 case glslang::EbvWorldToObjectNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700961 return spv::BuiltInWorldToObjectNV;
962 case glslang::EbvIncomingRayFlagsNV:
963 return spv::BuiltInIncomingRayFlagsNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400964
965 // barycentrics
Chao Chen9eada4b2018-09-19 11:39:56 -0700966 case glslang::EbvBaryCoordNV:
967 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
968 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
969 return spv::BuiltInBaryCoordNV;
970 case glslang::EbvBaryCoordNoPerspNV:
971 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
972 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
973 return spv::BuiltInBaryCoordNoPerspNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400974
975 // mesh shaders
976 case glslang::EbvTaskCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700977 return spv::BuiltInTaskCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400978 case glslang::EbvPrimitiveCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700979 return spv::BuiltInPrimitiveCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400980 case glslang::EbvPrimitiveIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -0700981 return spv::BuiltInPrimitiveIndicesNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400982 case glslang::EbvClipDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700983 return spv::BuiltInClipDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400984 case glslang::EbvCullDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700985 return spv::BuiltInCullDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400986 case glslang::EbvLayerPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700987 return spv::BuiltInLayerPerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400988 case glslang::EbvMeshViewCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700989 return spv::BuiltInMeshViewCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400990 case glslang::EbvMeshViewIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -0700991 return spv::BuiltInMeshViewIndicesNV;
Daniel Koch2cb2f192019-06-04 08:43:32 -0400992
993 // sm builtins
994 case glslang::EbvWarpsPerSM:
995 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
996 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
997 return spv::BuiltInWarpsPerSMNV;
998 case glslang::EbvSMCount:
999 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1000 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1001 return spv::BuiltInSMCountNV;
1002 case glslang::EbvWarpID:
1003 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1004 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1005 return spv::BuiltInWarpIDNV;
1006 case glslang::EbvSMID:
1007 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1008 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1009 return spv::BuiltInSMIDNV;
John Kessenicha28f7a72019-08-06 07:00:58 -06001010#endif
1011
Rex Xu3e783f92017-02-22 16:44:48 +08001012 default:
1013 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -06001014 }
1015}
1016
Rex Xufc618912015-09-09 16:42:49 +08001017// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -07001018spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +08001019{
1020 assert(type.getBasicType() == glslang::EbtSampler);
1021
John Kessenichb9197c82019-08-11 07:41:45 -06001022#ifdef GLSLANG_WEB
1023 return spv::ImageFormatUnknown;
1024#endif
1025
John Kessenich5d0fa972016-02-15 11:57:00 -07001026 // Check for capabilities
John Kessenich7015bd62019-08-01 03:28:08 -06001027 switch (type.getQualifier().getFormat()) {
John Kessenich5d0fa972016-02-15 11:57:00 -07001028 case glslang::ElfRg32f:
1029 case glslang::ElfRg16f:
1030 case glslang::ElfR11fG11fB10f:
1031 case glslang::ElfR16f:
1032 case glslang::ElfRgba16:
1033 case glslang::ElfRgb10A2:
1034 case glslang::ElfRg16:
1035 case glslang::ElfRg8:
1036 case glslang::ElfR16:
1037 case glslang::ElfR8:
1038 case glslang::ElfRgba16Snorm:
1039 case glslang::ElfRg16Snorm:
1040 case glslang::ElfRg8Snorm:
1041 case glslang::ElfR16Snorm:
1042 case glslang::ElfR8Snorm:
1043
1044 case glslang::ElfRg32i:
1045 case glslang::ElfRg16i:
1046 case glslang::ElfRg8i:
1047 case glslang::ElfR16i:
1048 case glslang::ElfR8i:
1049
1050 case glslang::ElfRgb10a2ui:
1051 case glslang::ElfRg32ui:
1052 case glslang::ElfRg16ui:
1053 case glslang::ElfRg8ui:
1054 case glslang::ElfR16ui:
1055 case glslang::ElfR8ui:
1056 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
1057 break;
1058
1059 default:
1060 break;
1061 }
1062
1063 // do the translation
John Kessenich7015bd62019-08-01 03:28:08 -06001064 switch (type.getQualifier().getFormat()) {
Rex Xufc618912015-09-09 16:42:49 +08001065 case glslang::ElfNone: return spv::ImageFormatUnknown;
1066 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
1067 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
1068 case glslang::ElfR32f: return spv::ImageFormatR32f;
1069 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
1070 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
1071 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1072 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1073 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1074 case glslang::ElfR16f: return spv::ImageFormatR16f;
1075 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1076 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1077 case glslang::ElfRg16: return spv::ImageFormatRg16;
1078 case glslang::ElfRg8: return spv::ImageFormatRg8;
1079 case glslang::ElfR16: return spv::ImageFormatR16;
1080 case glslang::ElfR8: return spv::ImageFormatR8;
1081 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1082 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1083 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1084 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1085 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1086 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1087 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1088 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1089 case glslang::ElfR32i: return spv::ImageFormatR32i;
1090 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1091 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1092 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1093 case glslang::ElfR16i: return spv::ImageFormatR16i;
1094 case glslang::ElfR8i: return spv::ImageFormatR8i;
1095 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1096 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1097 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1098 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1099 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1100 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1101 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1102 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1103 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1104 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001105 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001106 }
1107}
1108
John Kesseniche18fd202018-01-30 11:01:39 -07001109spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001110{
John Kesseniche18fd202018-01-30 11:01:39 -07001111 if (selectionNode.getFlatten())
1112 return spv::SelectionControlFlattenMask;
1113 if (selectionNode.getDontFlatten())
1114 return spv::SelectionControlDontFlattenMask;
1115 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001116}
1117
John Kesseniche18fd202018-01-30 11:01:39 -07001118spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -06001119{
John Kesseniche18fd202018-01-30 11:01:39 -07001120 if (switchNode.getFlatten())
1121 return spv::SelectionControlFlattenMask;
1122 if (switchNode.getDontFlatten())
1123 return spv::SelectionControlDontFlattenMask;
1124 return spv::SelectionControlMaskNone;
1125}
1126
John Kessenicha2858d92018-01-31 08:11:18 -07001127// return a non-0 dependency if the dependency argument must be set
1128spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
John Kessenich1f4d0462019-01-12 17:31:41 +07001129 std::vector<unsigned int>& operands) const
John Kesseniche18fd202018-01-30 11:01:39 -07001130{
1131 spv::LoopControlMask control = spv::LoopControlMaskNone;
1132
1133 if (loopNode.getDontUnroll())
1134 control = control | spv::LoopControlDontUnrollMask;
1135 if (loopNode.getUnroll())
1136 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001137 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001138 control = control | spv::LoopControlDependencyInfiniteMask;
1139 else if (loopNode.getLoopDependency() > 0) {
1140 control = control | spv::LoopControlDependencyLengthMask;
John Kessenich1f4d0462019-01-12 17:31:41 +07001141 operands.push_back((unsigned int)loopNode.getLoopDependency());
1142 }
1143 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
1144 if (loopNode.getMinIterations() > 0) {
1145 control = control | spv::LoopControlMinIterationsMask;
1146 operands.push_back(loopNode.getMinIterations());
1147 }
1148 if (loopNode.getMaxIterations() < glslang::TIntermLoop::iterationsInfinite) {
1149 control = control | spv::LoopControlMaxIterationsMask;
1150 operands.push_back(loopNode.getMaxIterations());
1151 }
1152 if (loopNode.getIterationMultiple() > 1) {
1153 control = control | spv::LoopControlIterationMultipleMask;
1154 operands.push_back(loopNode.getIterationMultiple());
1155 }
1156 if (loopNode.getPeelCount() > 0) {
1157 control = control | spv::LoopControlPeelCountMask;
1158 operands.push_back(loopNode.getPeelCount());
1159 }
1160 if (loopNode.getPartialCount() > 0) {
1161 control = control | spv::LoopControlPartialCountMask;
1162 operands.push_back(loopNode.getPartialCount());
1163 }
John Kessenicha2858d92018-01-31 08:11:18 -07001164 }
John Kesseniche18fd202018-01-30 11:01:39 -07001165
1166 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001167}
1168
John Kessenicha5c5fb62017-05-05 05:09:58 -06001169// Translate glslang type to SPIR-V storage class.
1170spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1171{
1172 if (type.getQualifier().isPipeInput())
1173 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001174 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001175 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001176
1177 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
John Kessenicha28f7a72019-08-06 07:00:58 -06001178 type.getQualifier().storage == glslang::EvqUniform) {
John Kessenichdeec1932019-08-13 08:00:30 -06001179 if (type.isAtomic())
John Kessenichbed4e4f2017-09-08 02:38:07 -06001180 return spv::StorageClassAtomicCounter;
1181 if (type.containsOpaque())
1182 return spv::StorageClassUniformConstant;
1183 }
1184
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001185 if (type.getQualifier().isUniformOrBuffer() &&
John Kessenichdeec1932019-08-13 08:00:30 -06001186 type.getQualifier().isShaderRecordNV()) {
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001187 return spv::StorageClassShaderRecordBufferNV;
1188 }
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001189
John Kessenichbed4e4f2017-09-08 02:38:07 -06001190 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001191 builder.addIncorporatedExtension(spv::E_SPV_KHR_storage_buffer_storage_class, spv::Spv_1_3);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001192 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001193 }
1194
1195 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich7015bd62019-08-01 03:28:08 -06001196 if (type.getQualifier().isPushConstant())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001197 return spv::StorageClassPushConstant;
1198 if (type.getBasicType() == glslang::EbtBlock)
1199 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001200 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001201 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001202
1203 switch (type.getQualifier().storage) {
John Kessenich3dd1ce52019-10-17 07:08:40 -06001204 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1205 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1206 case glslang::EvqTemporary: return spv::StorageClassFunction;
John Kessenichdeec1932019-08-13 08:00:30 -06001207 case glslang::EvqShared: return spv::StorageClassWorkgroup;
John Kessenich3dd1ce52019-10-17 07:08:40 -06001208#ifndef GLSLANG_WEB
Ashwin Leleff1783d2018-10-22 16:41:44 -07001209 case glslang::EvqPayloadNV: return spv::StorageClassRayPayloadNV;
1210 case glslang::EvqPayloadInNV: return spv::StorageClassIncomingRayPayloadNV;
1211 case glslang::EvqHitAttrNV: return spv::StorageClassHitAttributeNV;
1212 case glslang::EvqCallableDataNV: return spv::StorageClassCallableDataNV;
1213 case glslang::EvqCallableDataInNV: return spv::StorageClassIncomingCallableDataNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07001214#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001215 default:
1216 assert(0);
1217 break;
1218 }
1219
1220 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001221}
1222
John Kessenich5611c6d2018-04-05 11:25:02 -06001223// Add capabilities pertaining to how an array is indexed.
1224void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1225 const glslang::TType& indexType)
1226{
John Kessenichb9197c82019-08-11 07:41:45 -06001227#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06001228 if (indexType.getQualifier().isNonUniform()) {
1229 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001230 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001231 if (baseType.getBasicType() == glslang::EbtSampler) {
1232 if (baseType.getQualifier().hasAttachment())
1233 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001234 else if (baseType.isImage() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001235 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001236 else if (baseType.isTexture() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001237 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1238 else if (baseType.isImage())
1239 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1240 else if (baseType.isTexture())
1241 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1242 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1243 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1244 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1245 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1246 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1247 }
1248 } else {
1249 // assume a dynamically uniform index
1250 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001251 if (baseType.getQualifier().hasAttachment()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001252 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001253 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001254 } else if (baseType.isImage() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001255 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001256 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001257 } else if (baseType.isTexture() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001258 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001259 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001260 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001261 }
1262 }
John Kessenichb9197c82019-08-11 07:41:45 -06001263#endif
John Kessenich5611c6d2018-04-05 11:25:02 -06001264}
1265
qining25262b32016-05-06 17:25:16 -04001266// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001267// descriptor set.
1268bool IsDescriptorResource(const glslang::TType& type)
1269{
John Kessenichf7497e22016-03-08 21:36:22 -07001270 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001271 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001272 return type.getQualifier().isUniformOrBuffer() &&
John Kessenich7015bd62019-08-01 03:28:08 -06001273 ! type.getQualifier().isShaderRecordNV() &&
1274 ! type.getQualifier().isPushConstant();
John Kessenich6c292d32016-02-15 20:58:50 -07001275
1276 // non block...
1277 // basically samplerXXX/subpass/sampler/texture are all included
1278 // if they are the global-scope-class, not the function parameter
1279 // (or local, if they ever exist) class.
1280 if (type.getBasicType() == glslang::EbtSampler)
1281 return type.getQualifier().isUniformOrBuffer();
1282
1283 // None of the above.
1284 return false;
1285}
1286
John Kesseniche0b6cad2015-12-24 10:30:13 -07001287void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1288{
1289 if (child.layoutMatrix == glslang::ElmNone)
1290 child.layoutMatrix = parent.layoutMatrix;
1291
1292 if (parent.invariant)
1293 child.invariant = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001294 if (parent.flat)
1295 child.flat = true;
1296 if (parent.centroid)
1297 child.centroid = true;
John Kessenich7015bd62019-08-01 03:28:08 -06001298#ifndef GLSLANG_WEB
John Kesseniche0b6cad2015-12-24 10:30:13 -07001299 if (parent.nopersp)
1300 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001301 if (parent.explicitInterp)
1302 child.explicitInterp = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001303 if (parent.perPrimitiveNV)
1304 child.perPrimitiveNV = true;
1305 if (parent.perViewNV)
1306 child.perViewNV = true;
1307 if (parent.perTaskNV)
1308 child.perTaskNV = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001309 if (parent.patch)
1310 child.patch = true;
1311 if (parent.sample)
1312 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001313 if (parent.coherent)
1314 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001315 if (parent.devicecoherent)
1316 child.devicecoherent = true;
1317 if (parent.queuefamilycoherent)
1318 child.queuefamilycoherent = true;
1319 if (parent.workgroupcoherent)
1320 child.workgroupcoherent = true;
1321 if (parent.subgroupcoherent)
1322 child.subgroupcoherent = true;
1323 if (parent.nonprivate)
1324 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001325 if (parent.volatil)
1326 child.volatil = true;
1327 if (parent.restrict)
1328 child.restrict = true;
1329 if (parent.readonly)
1330 child.readonly = true;
1331 if (parent.writeonly)
1332 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001333#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001334}
1335
John Kessenichf2b7f332016-09-01 17:05:23 -06001336bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001337{
John Kessenich7b9fa252016-01-21 18:56:57 -07001338 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001339 // - struct members might inherit from a struct declaration
1340 // (note that non-block structs don't explicitly inherit,
1341 // only implicitly, meaning no decoration involved)
1342 // - affect decorations on the struct members
1343 // (note smooth does not, and expecting something like volatile
1344 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001345 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001346 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001347}
1348
John Kessenich140f3df2015-06-26 16:58:36 -06001349//
1350// Implement the TGlslangToSpvTraverser class.
1351//
1352
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001353TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001354 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1355 : TIntermTraverser(true, false, true),
1356 options(options),
1357 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001358 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001359 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001360 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich605afc72019-06-17 23:33:09 -06001361 glslangIntermediate(glslangIntermediate),
1362 nanMinMaxClamp(glslangIntermediate->getNanMinMaxClamp())
John Kessenich140f3df2015-06-26 16:58:36 -06001363{
1364 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1365
1366 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001367 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1368 glslangIntermediate->getVersion());
1369
John Kessenich121853f2017-05-31 17:11:16 -06001370 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001371 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001372 builder.setSourceFile(glslangIntermediate->getSourceFile());
1373
1374 // Set the source shader's text. If for SPV version 1.0, include
1375 // a preamble in comments stating the OpModuleProcessed instructions.
1376 // Otherwise, emit those as actual instructions.
1377 std::string text;
1378 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1379 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001380 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001381 text.append("// OpModuleProcessed ");
1382 text.append(processes[p]);
1383 text.append("\n");
1384 } else
1385 builder.addModuleProcessed(processes[p]);
1386 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001387 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001388 text.append("#line 1\n");
1389 text.append(glslangIntermediate->getSourceText());
1390 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001391 // Pass name and text for all included files
1392 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1393 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1394 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001395 }
John Kessenich140f3df2015-06-26 16:58:36 -06001396 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001397
1398 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1399 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1400
1401 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1402 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
John Kessenich1ff0c182019-10-10 12:01:13 -06001403 builder.addIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer, spv::Spv_1_5);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001404 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
1405 };
Jeff Bolz36831c92018-09-05 10:11:41 -05001406 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001407 memoryModel = spv::MemoryModelVulkanKHR;
1408 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
John Kessenich8317e6c2019-08-18 23:58:08 -06001409 builder.addIncorporatedExtension(spv::E_SPV_KHR_vulkan_memory_model, spv::Spv_1_5);
Jeff Bolz36831c92018-09-05 10:11:41 -05001410 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001411 builder.setMemoryModel(addressingModel, memoryModel);
1412
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001413 if (glslangIntermediate->usingVariablePointers()) {
1414 builder.addCapability(spv::CapabilityVariablePointers);
1415 }
1416
John Kessenicheee9d532016-09-19 18:09:30 -06001417 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1418 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001419
1420 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001421 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1422 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001423 builder.addSourceExtension(it->c_str());
1424
1425 // Add the top-level modes for this shader.
1426
John Kessenich92187592016-02-01 13:45:25 -07001427 if (glslangIntermediate->getXfbMode()) {
1428 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001429 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001430 }
John Kessenich140f3df2015-06-26 16:58:36 -06001431
1432 unsigned int mode;
1433 switch (glslangIntermediate->getStage()) {
1434 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001435 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001436 break;
1437
John Kessenicha28f7a72019-08-06 07:00:58 -06001438 case EShLangFragment:
1439 builder.addCapability(spv::CapabilityShader);
1440 if (glslangIntermediate->getPixelCenterInteger())
1441 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
1442
1443 if (glslangIntermediate->getOriginUpperLeft())
1444 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
1445 else
1446 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
1447
1448 if (glslangIntermediate->getEarlyFragmentTests())
1449 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1450
1451 if (glslangIntermediate->getPostDepthCoverage()) {
1452 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1453 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1454 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1455 }
1456
John Kessenichb9197c82019-08-11 07:41:45 -06001457 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1458 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
1459
1460#ifndef GLSLANG_WEB
John Kessenicha28f7a72019-08-06 07:00:58 -06001461 switch(glslangIntermediate->getDepth()) {
1462 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1463 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
1464 default: mode = spv::ExecutionModeMax; break;
1465 }
1466 if (mode != spv::ExecutionModeMax)
1467 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kessenicha28f7a72019-08-06 07:00:58 -06001468 switch (glslangIntermediate->getInterlockOrdering()) {
1469 case glslang::EioPixelInterlockOrdered: mode = spv::ExecutionModePixelInterlockOrderedEXT; break;
1470 case glslang::EioPixelInterlockUnordered: mode = spv::ExecutionModePixelInterlockUnorderedEXT; break;
1471 case glslang::EioSampleInterlockOrdered: mode = spv::ExecutionModeSampleInterlockOrderedEXT; break;
1472 case glslang::EioSampleInterlockUnordered: mode = spv::ExecutionModeSampleInterlockUnorderedEXT; break;
1473 case glslang::EioShadingRateInterlockOrdered: mode = spv::ExecutionModeShadingRateInterlockOrderedEXT; break;
1474 case glslang::EioShadingRateInterlockUnordered: mode = spv::ExecutionModeShadingRateInterlockUnorderedEXT; break;
1475 default: mode = spv::ExecutionModeMax; break;
1476 }
1477 if (mode != spv::ExecutionModeMax) {
1478 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1479 if (mode == spv::ExecutionModeShadingRateInterlockOrderedEXT ||
1480 mode == spv::ExecutionModeShadingRateInterlockUnorderedEXT) {
1481 builder.addCapability(spv::CapabilityFragmentShaderShadingRateInterlockEXT);
1482 } else if (mode == spv::ExecutionModePixelInterlockOrderedEXT ||
1483 mode == spv::ExecutionModePixelInterlockUnorderedEXT) {
1484 builder.addCapability(spv::CapabilityFragmentShaderPixelInterlockEXT);
1485 } else {
1486 builder.addCapability(spv::CapabilityFragmentShaderSampleInterlockEXT);
1487 }
1488 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
1489 }
John Kessenichb9197c82019-08-11 07:41:45 -06001490#endif
John Kessenicha28f7a72019-08-06 07:00:58 -06001491 break;
1492
John Kessenicha28f7a72019-08-06 07:00:58 -06001493 case EShLangCompute:
1494 builder.addCapability(spv::CapabilityShader);
1495 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1496 glslangIntermediate->getLocalSize(1),
1497 glslangIntermediate->getLocalSize(2));
John Kessenich51ed01c2019-10-10 11:40:11 -06001498#ifndef GLSLANG_WEB
John Kessenicha28f7a72019-08-06 07:00:58 -06001499 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1500 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1501 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1502 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1503 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1504 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1505 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1506 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1507 }
John Kessenich51ed01c2019-10-10 11:40:11 -06001508#endif
John Kessenicha28f7a72019-08-06 07:00:58 -06001509 break;
John Kessenich51ed01c2019-10-10 11:40:11 -06001510#ifndef GLSLANG_WEB
steve-lunarge7412492017-03-23 11:56:07 -06001511 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001512 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001513 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001514
steve-lunarge7412492017-03-23 11:56:07 -06001515 glslang::TLayoutGeometry primitive;
1516
1517 if (glslangIntermediate->getStage() == EShLangTessControl) {
1518 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1519 primitive = glslangIntermediate->getOutputPrimitive();
1520 } else {
1521 primitive = glslangIntermediate->getInputPrimitive();
1522 }
1523
1524 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001525 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1526 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1527 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001528 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001529 }
John Kessenich4016e382016-07-15 11:53:56 -06001530 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001531 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1532
John Kesseniche6903322015-10-13 16:29:02 -06001533 switch (glslangIntermediate->getVertexSpacing()) {
1534 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1535 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1536 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001537 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001538 }
John Kessenich4016e382016-07-15 11:53:56 -06001539 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001540 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1541
1542 switch (glslangIntermediate->getVertexOrder()) {
1543 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1544 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001545 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001546 }
John Kessenich4016e382016-07-15 11:53:56 -06001547 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001548 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1549
1550 if (glslangIntermediate->getPointMode())
1551 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001552 break;
1553
1554 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001555 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001556 switch (glslangIntermediate->getInputPrimitive()) {
1557 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1558 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1559 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001560 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001561 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001562 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001563 }
John Kessenich4016e382016-07-15 11:53:56 -06001564 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001565 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001566
John Kessenich140f3df2015-06-26 16:58:36 -06001567 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1568
1569 switch (glslangIntermediate->getOutputPrimitive()) {
1570 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1571 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1572 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001573 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001574 }
John Kessenich4016e382016-07-15 11:53:56 -06001575 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001576 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1577 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1578 break;
1579
Chao Chenb50c02e2018-09-19 11:42:24 -07001580 case EShLangRayGenNV:
1581 case EShLangIntersectNV:
1582 case EShLangAnyHitNV:
1583 case EShLangClosestHitNV:
1584 case EShLangMissNV:
1585 case EShLangCallableNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07001586 builder.addCapability(spv::CapabilityRayTracingNV);
1587 builder.addExtension("SPV_NV_ray_tracing");
Chao Chenb50c02e2018-09-19 11:42:24 -07001588 break;
Chao Chen3c366992018-09-19 11:41:59 -07001589 case EShLangTaskNV:
1590 case EShLangMeshNV:
1591 builder.addCapability(spv::CapabilityMeshShadingNV);
1592 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1593 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1594 glslangIntermediate->getLocalSize(1),
1595 glslangIntermediate->getLocalSize(2));
1596 if (glslangIntermediate->getStage() == EShLangMeshNV) {
1597 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1598 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV, glslangIntermediate->getPrimitives());
1599
1600 switch (glslangIntermediate->getOutputPrimitive()) {
1601 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1602 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1603 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1604 default: mode = spv::ExecutionModeMax; break;
1605 }
1606 if (mode != spv::ExecutionModeMax)
1607 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1608 }
1609 break;
1610#endif
1611
John Kessenich140f3df2015-06-26 16:58:36 -06001612 default:
1613 break;
1614 }
John Kessenich140f3df2015-06-26 16:58:36 -06001615}
1616
John Kessenichfca82622016-11-26 13:23:20 -07001617// Finish creating SPV, after the traversal is complete.
1618void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001619{
John Kessenichf04c51b2018-08-03 15:56:12 -06001620 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001621 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001622 builder.setBuildPoint(shaderEntry->getLastBlock());
1623 builder.leaveFunction();
1624 }
1625
John Kessenich7ba63412015-12-20 17:37:07 -07001626 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001627 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1628 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001629
John Kessenich23d27752019-07-28 02:12:10 -06001630#ifndef GLSLANG_WEB
John Kessenichf04c51b2018-08-03 15:56:12 -06001631 // Add capabilities, extensions, remove unneeded decorations, etc.,
1632 // based on the resulting SPIR-V.
1633 builder.postProcess();
John Kessenich23d27752019-07-28 02:12:10 -06001634#endif
John Kessenich7ba63412015-12-20 17:37:07 -07001635}
1636
John Kessenichfca82622016-11-26 13:23:20 -07001637// Write the SPV into 'out'.
1638void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001639{
John Kessenichfca82622016-11-26 13:23:20 -07001640 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001641}
1642
1643//
1644// Implement the traversal functions.
1645//
1646// Return true from interior nodes to have the external traversal
1647// continue on to children. Return false if children were
1648// already processed.
1649//
1650
1651//
qining25262b32016-05-06 17:25:16 -04001652// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001653// - uniform/input reads
1654// - output writes
1655// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1656// - something simple that degenerates into the last bullet
1657//
1658void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1659{
qining75d1d802016-04-06 14:42:01 -04001660 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1661 if (symbol->getType().getQualifier().isSpecConstant())
1662 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1663
John Kessenich140f3df2015-06-26 16:58:36 -06001664 // getSymbolId() will set up all the IO decorations on the first call.
1665 // Formal function parameters were mapped during makeFunctions().
1666 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001667
John Kessenich7ba63412015-12-20 17:37:07 -07001668 if (builder.isPointer(id)) {
John Kessenich9c14f772019-06-17 08:38:35 -06001669 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
John Kessenich7c7731e2019-01-04 16:47:06 +07001670 // Consider adding to the OpEntryPoint interface list.
1671 // Only looking at structures if they have at least one member.
1672 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1673 spv::StorageClass sc = builder.getStorageClass(id);
1674 // Before SPIR-V 1.4, we only want to include Input and Output.
1675 // Starting with SPIR-V 1.4, we want all globals.
1676 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && sc != spv::StorageClassFunction) ||
1677 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
John Kessenich5f77d862017-09-19 11:09:59 -06001678 iOSet.insert(id);
John Kessenich7c7731e2019-01-04 16:47:06 +07001679 }
John Kessenich5f77d862017-09-19 11:09:59 -06001680 }
John Kessenich9c14f772019-06-17 08:38:35 -06001681
1682 // If the SPIR-V type is required to be different than the AST type,
1683 // translate now from the SPIR-V type to the AST type, for the consuming
1684 // operation.
1685 // Note this turns it from an l-value to an r-value.
1686 // Currently, all symbols needing this are inputs; avoid the map lookup when non-input.
1687 if (symbol->getType().getQualifier().storage == glslang::EvqVaryingIn)
1688 id = translateForcedType(id);
John Kessenich7ba63412015-12-20 17:37:07 -07001689 }
1690
1691 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001692 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001693 // Prepare to generate code for the access
1694
1695 // L-value chains will be computed left to right. We're on the symbol now,
1696 // which is the left-most part of the access chain, so now is "clear" time,
1697 // followed by setting the base.
1698 builder.clearAccessChain();
1699
1700 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001701 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001702 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001703 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001704 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001705 // These are also pure R-values.
John Kessenich9c14f772019-06-17 08:38:35 -06001706 // C) R-Values from type translation, see above call to translateForcedType()
John Kessenich6c292d32016-02-15 20:58:50 -07001707 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich9c14f772019-06-17 08:38:35 -06001708 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end() ||
1709 !builder.isPointerType(builder.getTypeId(id)))
John Kessenich140f3df2015-06-26 16:58:36 -06001710 builder.setAccessChainRValue(id);
1711 else
1712 builder.setAccessChainLValue(id);
1713 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001714
John Kessenichb9197c82019-08-11 07:41:45 -06001715#ifdef ENABLE_HLSL
John Kessenich5d610ee2018-03-07 18:05:55 -07001716 // Process linkage-only nodes for any special additional interface work.
1717 if (linkageOnly) {
1718 if (glslangIntermediate->getHlslFunctionality1()) {
1719 // Map implicit counter buffers to their originating buffers, which should have been
1720 // seen by now, given earlier pruning of unused counters, and preservation of order
1721 // of declaration.
1722 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1723 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1724 // Save possible originating buffers for counter buffers, keyed by
1725 // making the potential counter-buffer name.
1726 std::string keyName = symbol->getName().c_str();
1727 keyName = glslangIntermediate->addCounterBufferName(keyName);
1728 counterOriginator[keyName] = symbol;
1729 } else {
1730 // Handle a counter buffer, by finding the saved originating buffer.
1731 std::string keyName = symbol->getName().c_str();
1732 auto it = counterOriginator.find(keyName);
1733 if (it != counterOriginator.end()) {
1734 id = getSymbolId(it->second);
1735 if (id != spv::NoResult) {
1736 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001737 if (counterId != spv::NoResult) {
1738 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001739 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001740 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001741 }
1742 }
1743 }
1744 }
1745 }
1746 }
John Kessenich155d3512019-08-08 23:29:20 -06001747#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001748}
1749
1750bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1751{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001752 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001753
qining40887662016-04-03 22:20:42 -04001754 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1755 if (node->getType().getQualifier().isSpecConstant())
1756 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1757
John Kessenich140f3df2015-06-26 16:58:36 -06001758 // First, handle special cases
1759 switch (node->getOp()) {
1760 case glslang::EOpAssign:
1761 case glslang::EOpAddAssign:
1762 case glslang::EOpSubAssign:
1763 case glslang::EOpMulAssign:
1764 case glslang::EOpVectorTimesMatrixAssign:
1765 case glslang::EOpVectorTimesScalarAssign:
1766 case glslang::EOpMatrixTimesScalarAssign:
1767 case glslang::EOpMatrixTimesMatrixAssign:
1768 case glslang::EOpDivAssign:
1769 case glslang::EOpModAssign:
1770 case glslang::EOpAndAssign:
1771 case glslang::EOpInclusiveOrAssign:
1772 case glslang::EOpExclusiveOrAssign:
1773 case glslang::EOpLeftShiftAssign:
1774 case glslang::EOpRightShiftAssign:
1775 // A bin-op assign "a += b" means the same thing as "a = a + b"
1776 // where a is evaluated before b. For a simple assignment, GLSL
1777 // says to evaluate the left before the right. So, always, left
1778 // node then right node.
1779 {
1780 // get the left l-value, save it away
1781 builder.clearAccessChain();
1782 node->getLeft()->traverse(this);
1783 spv::Builder::AccessChain lValue = builder.getAccessChain();
1784
1785 // evaluate the right
1786 builder.clearAccessChain();
1787 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001788 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001789
1790 if (node->getOp() != glslang::EOpAssign) {
1791 // the left is also an r-value
1792 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001793 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001794
1795 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001796 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001797 TranslateNoContractionDecoration(node->getType().getQualifier()),
1798 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001799 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001800 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1801 node->getType().getBasicType());
1802
1803 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001804 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001805 }
1806
1807 // store the result
1808 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001809 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001810
1811 // assignments are expressions having an rValue after they are evaluated...
1812 builder.clearAccessChain();
1813 builder.setAccessChainRValue(rValue);
1814 }
1815 return false;
1816 case glslang::EOpIndexDirect:
1817 case glslang::EOpIndexDirectStruct:
1818 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001819 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001820 // Get the left part of the access chain.
1821 node->getLeft()->traverse(this);
1822
1823 // Add the next element in the chain
1824
David Netoa901ffe2016-06-08 14:11:40 +01001825 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001826 if (! node->getLeft()->getType().isArray() &&
1827 node->getLeft()->getType().isVector() &&
1828 node->getOp() == glslang::EOpIndexDirect) {
1829 // This is essentially a hard-coded vector swizzle of size 1,
1830 // so short circuit the access-chain stuff with a swizzle.
1831 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001832 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001833 int dummySize;
1834 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1835 TranslateCoherent(node->getLeft()->getType()),
1836 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001837 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001838
1839 // Load through a block reference is performed with a dot operator that
1840 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1841 // do a load and reset the access chain.
John Kessenich7015bd62019-08-01 03:28:08 -06001842 if (node->getLeft()->isReference() &&
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001843 !node->getLeft()->getType().isArray() &&
1844 node->getOp() == glslang::EOpIndexDirectStruct)
1845 {
1846 spv::Id left = accessChainLoad(node->getLeft()->getType());
1847 builder.clearAccessChain();
1848 builder.setAccessChainLValue(left);
1849 }
1850
David Netoa901ffe2016-06-08 14:11:40 +01001851 int spvIndex = glslangIndex;
1852 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1853 node->getOp() == glslang::EOpIndexDirectStruct)
1854 {
1855 // This may be, e.g., an anonymous block-member selection, which generally need
1856 // index remapping due to hidden members in anonymous blocks.
1857 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1858 assert(remapper.size() > 0);
1859 spvIndex = remapper[glslangIndex];
1860 }
John Kessenichebb50532016-05-16 19:22:05 -06001861
David Netoa901ffe2016-06-08 14:11:40 +01001862 // normal case for indexing array or structure or block
Jeff Bolz7895e472019-03-06 13:34:10 -06001863 builder.accessChainPush(builder.makeIntConstant(spvIndex), TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001864
1865 // Add capabilities here for accessing PointSize and clip/cull distance.
1866 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001867 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001868 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001869 }
1870 }
1871 return false;
1872 case glslang::EOpIndexIndirect:
1873 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001874 // Array, matrix, or vector indirection with variable index.
1875 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06001876 // matrices are arrays of vectors, so will also work for a matrix.
1877 // Will use the access chain's 'component' for variable index into a vector.
1878
1879 // This adapter is building access chains left to right.
1880 // Set up the access chain to the left.
1881 node->getLeft()->traverse(this);
1882
1883 // save it so that computing the right side doesn't trash it
1884 spv::Builder::AccessChain partial = builder.getAccessChain();
1885
1886 // compute the next index in the chain
1887 builder.clearAccessChain();
1888 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001889 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001890
John Kessenich5611c6d2018-04-05 11:25:02 -06001891 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1892
John Kessenich140f3df2015-06-26 16:58:36 -06001893 // restore the saved access chain
1894 builder.setAccessChain(partial);
1895
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001896 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1897 int dummySize;
1898 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1899 TranslateCoherent(node->getLeft()->getType()),
1900 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
1901 } else
Jeff Bolz7895e472019-03-06 13:34:10 -06001902 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001903 }
1904 return false;
1905 case glslang::EOpVectorSwizzle:
1906 {
1907 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001908 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001909 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001910 int dummySize;
1911 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1912 TranslateCoherent(node->getLeft()->getType()),
1913 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001914 }
1915 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001916 case glslang::EOpMatrixSwizzle:
1917 logger->missingFunctionality("matrix swizzle");
1918 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001919 case glslang::EOpLogicalOr:
1920 case glslang::EOpLogicalAnd:
1921 {
1922
1923 // These may require short circuiting, but can sometimes be done as straight
1924 // binary operations. The right operand must be short circuited if it has
1925 // side effects, and should probably be if it is complex.
1926 if (isTrivial(node->getRight()->getAsTyped()))
1927 break; // handle below as a normal binary operation
1928 // otherwise, we need to do dynamic short circuiting on the right operand
1929 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1930 builder.clearAccessChain();
1931 builder.setAccessChainRValue(result);
1932 }
1933 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001934 default:
1935 break;
1936 }
1937
1938 // Assume generic binary op...
1939
John Kessenich32cfd492016-02-02 12:37:46 -07001940 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001941 builder.clearAccessChain();
1942 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001943 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001944
John Kessenich32cfd492016-02-02 12:37:46 -07001945 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001946 builder.clearAccessChain();
1947 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001948 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001949
John Kessenich32cfd492016-02-02 12:37:46 -07001950 // get result
John Kessenichead86222018-03-28 18:01:20 -06001951 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001952 TranslateNoContractionDecoration(node->getType().getQualifier()),
1953 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001954 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001955 convertGlslangToSpvType(node->getType()), left, right,
1956 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001957
John Kessenich50e57562015-12-21 21:21:11 -07001958 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001959 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001960 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001961 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001962 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001963 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001964 return false;
1965 }
John Kessenich140f3df2015-06-26 16:58:36 -06001966}
1967
John Kessenich9c14f772019-06-17 08:38:35 -06001968// Figure out what, if any, type changes are needed when accessing a specific built-in.
1969// Returns <the type SPIR-V requires for declarion, the type to translate to on use>.
1970// Also see comment for 'forceType', regarding tracking SPIR-V-required types.
1971std::pair<spv::Id, spv::Id> TGlslangToSpvTraverser::getForcedType(spv::BuiltIn builtIn,
1972 const glslang::TType& glslangType)
1973{
1974 switch(builtIn)
1975 {
1976 case spv::BuiltInSubgroupEqMask:
1977 case spv::BuiltInSubgroupGeMask:
1978 case spv::BuiltInSubgroupGtMask:
1979 case spv::BuiltInSubgroupLeMask:
1980 case spv::BuiltInSubgroupLtMask: {
1981 // these require changing a 64-bit scaler -> a vector of 32-bit components
1982 if (glslangType.isVector())
1983 break;
1984 std::pair<spv::Id, spv::Id> ret(builder.makeVectorType(builder.makeUintType(32), 4),
1985 builder.makeUintType(64));
1986 return ret;
1987 }
1988 default:
1989 break;
1990 }
1991
1992 std::pair<spv::Id, spv::Id> ret(spv::NoType, spv::NoType);
1993 return ret;
1994}
1995
1996// For an object previously identified (see getForcedType() and forceType)
1997// as needing type translations, do the translation needed for a load, turning
1998// an L-value into in R-value.
1999spv::Id TGlslangToSpvTraverser::translateForcedType(spv::Id object)
2000{
2001 const auto forceIt = forceType.find(object);
2002 if (forceIt == forceType.end())
2003 return object;
2004
2005 spv::Id desiredTypeId = forceIt->second;
2006 spv::Id objectTypeId = builder.getTypeId(object);
2007 assert(builder.isPointerType(objectTypeId));
2008 objectTypeId = builder.getContainedTypeId(objectTypeId);
2009 if (builder.isVectorType(objectTypeId) &&
2010 builder.getScalarTypeWidth(builder.getContainedTypeId(objectTypeId)) == 32) {
2011 if (builder.getScalarTypeWidth(desiredTypeId) == 64) {
2012 // handle 32-bit v.xy* -> 64-bit
2013 builder.clearAccessChain();
2014 builder.setAccessChainLValue(object);
2015 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2016 std::vector<spv::Id> components;
2017 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 0));
2018 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 1));
2019
2020 spv::Id vecType = builder.makeVectorType(builder.getContainedTypeId(objectTypeId), 2);
2021 return builder.createUnaryOp(spv::OpBitcast, desiredTypeId,
2022 builder.createCompositeConstruct(vecType, components));
2023 } else {
2024 logger->missingFunctionality("forcing 32-bit vector type to non 64-bit scalar");
2025 }
2026 } else {
2027 logger->missingFunctionality("forcing non 32-bit vector type");
2028 }
2029
2030 return object;
2031}
2032
John Kessenich140f3df2015-06-26 16:58:36 -06002033bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
2034{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002035 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002036
qining40887662016-04-03 22:20:42 -04002037 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2038 if (node->getType().getQualifier().isSpecConstant())
2039 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2040
John Kessenichfc51d282015-08-19 13:34:18 -06002041 spv::Id result = spv::NoResult;
2042
2043 // try texturing first
2044 result = createImageTextureFunctionCall(node);
2045 if (result != spv::NoResult) {
2046 builder.clearAccessChain();
2047 builder.setAccessChainRValue(result);
2048
2049 return false; // done with this node
2050 }
2051
2052 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06002053
2054 if (node->getOp() == glslang::EOpArrayLength) {
2055 // Quite special; won't want to evaluate the operand.
2056
John Kessenich5611c6d2018-04-05 11:25:02 -06002057 // Currently, the front-end does not allow .length() on an array until it is sized,
2058 // except for the last block membeor of an SSBO.
2059 // TODO: If this changes, link-time sized arrays might show up here, and need their
2060 // size extracted.
2061
John Kessenichc9a80832015-09-12 12:17:44 -06002062 // Normal .length() would have been constant folded by the front-end.
2063 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06002064 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06002065
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002066 spv::Id length;
2067 if (node->getOperand()->getType().isCoopMat()) {
2068 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2069
2070 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
2071 assert(builder.isCooperativeMatrixType(typeId));
2072
2073 length = builder.createCooperativeMatrixLength(typeId);
2074 } else {
2075 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
2076 block->traverse(this);
2077 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
2078 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
2079 }
John Kessenichc9a80832015-09-12 12:17:44 -06002080
John Kessenich8c869672018-11-28 07:01:37 -07002081 // GLSL semantics say the result of .length() is an int, while SPIR-V says
2082 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
2083 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002084 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
2085 if (builder.isInSpecConstCodeGenMode()) {
2086 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
2087 } else {
2088 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
2089 }
2090 }
John Kessenich8c869672018-11-28 07:01:37 -07002091
John Kessenichc9a80832015-09-12 12:17:44 -06002092 builder.clearAccessChain();
2093 builder.setAccessChainRValue(length);
2094
2095 return false;
2096 }
2097
John Kessenichfc51d282015-08-19 13:34:18 -06002098 // Start by evaluating the operand
2099
John Kessenich8c8505c2016-07-26 12:50:38 -06002100 // Does it need a swizzle inversion? If so, evaluation is inverted;
2101 // operate first on the swizzle base, then apply the swizzle.
2102 spv::Id invertedType = spv::NoType;
2103 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
2104 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
2105 invertedType = getInvertedSwizzleType(*node->getOperand());
2106
John Kessenich140f3df2015-06-26 16:58:36 -06002107 builder.clearAccessChain();
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002108 TIntermNode *operandNode;
John Kessenich8c8505c2016-07-26 12:50:38 -06002109 if (invertedType != spv::NoType)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002110 operandNode = node->getOperand()->getAsBinaryNode()->getLeft();
John Kessenich8c8505c2016-07-26 12:50:38 -06002111 else
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002112 operandNode = node->getOperand();
2113
2114 operandNode->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08002115
Rex Xufc618912015-09-09 16:42:49 +08002116 spv::Id operand = spv::NoResult;
2117
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002118 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2119
John Kessenichfb4f2332019-08-09 03:49:15 -06002120#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08002121 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
2122 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08002123 node->getOp() == glslang::EOpAtomicCounter ||
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002124 node->getOp() == glslang::EOpInterpolateAtCentroid) {
Rex Xufc618912015-09-09 16:42:49 +08002125 operand = builder.accessChainGetLValue(); // Special case l-value operands
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002126 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2127 lvalueCoherentFlags |= TranslateCoherent(operandNode->getAsTyped()->getType());
2128 } else
John Kessenichfb4f2332019-08-09 03:49:15 -06002129#endif
2130 {
John Kessenich32cfd492016-02-02 12:37:46 -07002131 operand = accessChainLoad(node->getOperand()->getType());
John Kessenichfb4f2332019-08-09 03:49:15 -06002132 }
John Kessenich140f3df2015-06-26 16:58:36 -06002133
John Kessenichead86222018-03-28 18:01:20 -06002134 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002135 TranslateNoContractionDecoration(node->getType().getQualifier()),
2136 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06002137
2138 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06002139 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06002140 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002141
2142 // if not, then possibly an operation
2143 if (! result)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002144 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType(), lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002145
2146 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06002147 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06002148 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenichb9197c82019-08-11 07:41:45 -06002149 decorations.addNonUniform(builder, result);
John Kessenich5611c6d2018-04-05 11:25:02 -06002150 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002151
John Kessenich140f3df2015-06-26 16:58:36 -06002152 builder.clearAccessChain();
2153 builder.setAccessChainRValue(result);
2154
2155 return false; // done with this node
2156 }
2157
2158 // it must be a special case, check...
2159 switch (node->getOp()) {
2160 case glslang::EOpPostIncrement:
2161 case glslang::EOpPostDecrement:
2162 case glslang::EOpPreIncrement:
2163 case glslang::EOpPreDecrement:
2164 {
2165 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08002166 spv::Id one = 0;
2167 if (node->getBasicType() == glslang::EbtFloat)
2168 one = builder.makeFloatConstant(1.0F);
John Kessenich39697cd2019-08-08 10:35:51 -06002169#ifndef GLSLANG_WEB
Rex Xuce31aea2016-07-29 16:13:04 +08002170 else if (node->getBasicType() == glslang::EbtDouble)
2171 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002172 else if (node->getBasicType() == glslang::EbtFloat16)
2173 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07002174 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
2175 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08002176 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
2177 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002178 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2179 one = builder.makeInt64Constant(1);
John Kessenich39697cd2019-08-08 10:35:51 -06002180#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08002181 else
2182 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002183 glslang::TOperator op;
2184 if (node->getOp() == glslang::EOpPreIncrement ||
2185 node->getOp() == glslang::EOpPostIncrement)
2186 op = glslang::EOpAdd;
2187 else
2188 op = glslang::EOpSub;
2189
John Kessenichead86222018-03-28 18:01:20 -06002190 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002191 convertGlslangToSpvType(node->getType()), operand, one,
2192 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002193 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002194
2195 // The result of operation is always stored, but conditionally the
2196 // consumed result. The consumed result is always an r-value.
2197 builder.accessChainStore(result);
2198 builder.clearAccessChain();
2199 if (node->getOp() == glslang::EOpPreIncrement ||
2200 node->getOp() == glslang::EOpPreDecrement)
2201 builder.setAccessChainRValue(result);
2202 else
2203 builder.setAccessChainRValue(operand);
2204 }
2205
2206 return false;
2207
John Kessenich155d3512019-08-08 23:29:20 -06002208#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06002209 case glslang::EOpEmitStreamVertex:
2210 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2211 return false;
2212 case glslang::EOpEndStreamPrimitive:
2213 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2214 return false;
John Kessenich155d3512019-08-08 23:29:20 -06002215#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002216
2217 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002218 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002219 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002220 }
John Kessenich140f3df2015-06-26 16:58:36 -06002221}
2222
Jeff Bolz53134492019-06-25 13:31:10 -05002223// Construct a composite object, recursively copying members if their types don't match
2224spv::Id TGlslangToSpvTraverser::createCompositeConstruct(spv::Id resultTypeId, std::vector<spv::Id> constituents)
2225{
2226 for (int c = 0; c < (int)constituents.size(); ++c) {
2227 spv::Id& constituent = constituents[c];
2228 spv::Id lType = builder.getContainedTypeId(resultTypeId, c);
2229 spv::Id rType = builder.getTypeId(constituent);
2230 if (lType != rType) {
2231 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
2232 constituent = builder.createUnaryOp(spv::OpCopyLogical, lType, constituent);
2233 } else if (builder.isStructType(rType)) {
2234 std::vector<spv::Id> rTypeConstituents;
2235 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2236 for (int i = 0; i < numrTypeConstituents; ++i) {
2237 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, builder.getContainedTypeId(rType, i), i));
2238 }
2239 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2240 } else {
2241 assert(builder.isArrayType(rType));
2242 std::vector<spv::Id> rTypeConstituents;
2243 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2244
2245 spv::Id elementRType = builder.getContainedTypeId(rType);
2246 for (int i = 0; i < numrTypeConstituents; ++i) {
2247 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, elementRType, i));
2248 }
2249 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2250 }
2251 }
2252 }
2253 return builder.createCompositeConstruct(resultTypeId, constituents);
2254}
2255
John Kessenich140f3df2015-06-26 16:58:36 -06002256bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2257{
qining27e04a02016-04-14 16:40:20 -04002258 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2259 if (node->getType().getQualifier().isSpecConstant())
2260 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2261
John Kessenichfc51d282015-08-19 13:34:18 -06002262 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06002263 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2264 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002265
2266 // try texturing
2267 result = createImageTextureFunctionCall(node);
2268 if (result != spv::NoResult) {
2269 builder.clearAccessChain();
2270 builder.setAccessChainRValue(result);
2271
2272 return false;
John Kessenicha28f7a72019-08-06 07:00:58 -06002273 }
2274#ifndef GLSLANG_WEB
2275 else if (node->getOp() == glslang::EOpImageStore ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002276 node->getOp() == glslang::EOpImageStoreLod ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002277 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002278 // "imageStore" is a special case, which has no result
2279 return false;
2280 }
John Kessenicha28f7a72019-08-06 07:00:58 -06002281#endif
John Kessenichfc51d282015-08-19 13:34:18 -06002282
John Kessenich140f3df2015-06-26 16:58:36 -06002283 glslang::TOperator binOp = glslang::EOpNull;
2284 bool reduceComparison = true;
2285 bool isMatrix = false;
2286 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002287 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002288
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002289 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2290
John Kessenich140f3df2015-06-26 16:58:36 -06002291 assert(node->getOp());
2292
John Kessenichf6640762016-08-01 19:44:00 -06002293 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002294
2295 switch (node->getOp()) {
2296 case glslang::EOpSequence:
2297 {
2298 if (preVisit)
2299 ++sequenceDepth;
2300 else
2301 --sequenceDepth;
2302
2303 if (sequenceDepth == 1) {
2304 // If this is the parent node of all the functions, we want to see them
2305 // early, so all call points have actual SPIR-V functions to reference.
2306 // In all cases, still let the traverser visit the children for us.
2307 makeFunctions(node->getAsAggregate()->getSequence());
2308
John Kessenich6fccb3c2016-09-19 16:01:41 -06002309 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002310 // anything else gets there, so visit out of order, doing them all now.
2311 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2312
John Kessenich6a60c2f2016-12-08 21:01:59 -07002313 // 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 -06002314 // so do them manually.
2315 visitFunctions(node->getAsAggregate()->getSequence());
2316
2317 return false;
2318 }
2319
2320 return true;
2321 }
2322 case glslang::EOpLinkerObjects:
2323 {
2324 if (visit == glslang::EvPreVisit)
2325 linkageOnly = true;
2326 else
2327 linkageOnly = false;
2328
2329 return true;
2330 }
2331 case glslang::EOpComma:
2332 {
2333 // processing from left to right naturally leaves the right-most
2334 // lying around in the access chain
2335 glslang::TIntermSequence& glslangOperands = node->getSequence();
2336 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2337 glslangOperands[i]->traverse(this);
2338
2339 return false;
2340 }
2341 case glslang::EOpFunction:
2342 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002343 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002344 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002345 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002346 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002347 } else {
2348 handleFunctionEntry(node);
2349 }
2350 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002351 if (inEntryPoint)
2352 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002353 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002354 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002355 }
2356
2357 return true;
2358 case glslang::EOpParameters:
2359 // Parameters will have been consumed by EOpFunction processing, but not
2360 // the body, so we still visited the function node's children, making this
2361 // child redundant.
2362 return false;
2363 case glslang::EOpFunctionCall:
2364 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002365 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002366 if (node->isUserDefined())
2367 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07002368 // 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 -07002369 if (result) {
2370 builder.clearAccessChain();
2371 builder.setAccessChainRValue(result);
2372 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002373 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002374
2375 return false;
2376 }
2377 case glslang::EOpConstructMat2x2:
2378 case glslang::EOpConstructMat2x3:
2379 case glslang::EOpConstructMat2x4:
2380 case glslang::EOpConstructMat3x2:
2381 case glslang::EOpConstructMat3x3:
2382 case glslang::EOpConstructMat3x4:
2383 case glslang::EOpConstructMat4x2:
2384 case glslang::EOpConstructMat4x3:
2385 case glslang::EOpConstructMat4x4:
2386 case glslang::EOpConstructDMat2x2:
2387 case glslang::EOpConstructDMat2x3:
2388 case glslang::EOpConstructDMat2x4:
2389 case glslang::EOpConstructDMat3x2:
2390 case glslang::EOpConstructDMat3x3:
2391 case glslang::EOpConstructDMat3x4:
2392 case glslang::EOpConstructDMat4x2:
2393 case glslang::EOpConstructDMat4x3:
2394 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002395 case glslang::EOpConstructIMat2x2:
2396 case glslang::EOpConstructIMat2x3:
2397 case glslang::EOpConstructIMat2x4:
2398 case glslang::EOpConstructIMat3x2:
2399 case glslang::EOpConstructIMat3x3:
2400 case glslang::EOpConstructIMat3x4:
2401 case glslang::EOpConstructIMat4x2:
2402 case glslang::EOpConstructIMat4x3:
2403 case glslang::EOpConstructIMat4x4:
2404 case glslang::EOpConstructUMat2x2:
2405 case glslang::EOpConstructUMat2x3:
2406 case glslang::EOpConstructUMat2x4:
2407 case glslang::EOpConstructUMat3x2:
2408 case glslang::EOpConstructUMat3x3:
2409 case glslang::EOpConstructUMat3x4:
2410 case glslang::EOpConstructUMat4x2:
2411 case glslang::EOpConstructUMat4x3:
2412 case glslang::EOpConstructUMat4x4:
2413 case glslang::EOpConstructBMat2x2:
2414 case glslang::EOpConstructBMat2x3:
2415 case glslang::EOpConstructBMat2x4:
2416 case glslang::EOpConstructBMat3x2:
2417 case glslang::EOpConstructBMat3x3:
2418 case glslang::EOpConstructBMat3x4:
2419 case glslang::EOpConstructBMat4x2:
2420 case glslang::EOpConstructBMat4x3:
2421 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002422 case glslang::EOpConstructF16Mat2x2:
2423 case glslang::EOpConstructF16Mat2x3:
2424 case glslang::EOpConstructF16Mat2x4:
2425 case glslang::EOpConstructF16Mat3x2:
2426 case glslang::EOpConstructF16Mat3x3:
2427 case glslang::EOpConstructF16Mat3x4:
2428 case glslang::EOpConstructF16Mat4x2:
2429 case glslang::EOpConstructF16Mat4x3:
2430 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002431 isMatrix = true;
2432 // fall through
2433 case glslang::EOpConstructFloat:
2434 case glslang::EOpConstructVec2:
2435 case glslang::EOpConstructVec3:
2436 case glslang::EOpConstructVec4:
2437 case glslang::EOpConstructDouble:
2438 case glslang::EOpConstructDVec2:
2439 case glslang::EOpConstructDVec3:
2440 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002441 case glslang::EOpConstructFloat16:
2442 case glslang::EOpConstructF16Vec2:
2443 case glslang::EOpConstructF16Vec3:
2444 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002445 case glslang::EOpConstructBool:
2446 case glslang::EOpConstructBVec2:
2447 case glslang::EOpConstructBVec3:
2448 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002449 case glslang::EOpConstructInt8:
2450 case glslang::EOpConstructI8Vec2:
2451 case glslang::EOpConstructI8Vec3:
2452 case glslang::EOpConstructI8Vec4:
2453 case glslang::EOpConstructUint8:
2454 case glslang::EOpConstructU8Vec2:
2455 case glslang::EOpConstructU8Vec3:
2456 case glslang::EOpConstructU8Vec4:
2457 case glslang::EOpConstructInt16:
2458 case glslang::EOpConstructI16Vec2:
2459 case glslang::EOpConstructI16Vec3:
2460 case glslang::EOpConstructI16Vec4:
2461 case glslang::EOpConstructUint16:
2462 case glslang::EOpConstructU16Vec2:
2463 case glslang::EOpConstructU16Vec3:
2464 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002465 case glslang::EOpConstructInt:
2466 case glslang::EOpConstructIVec2:
2467 case glslang::EOpConstructIVec3:
2468 case glslang::EOpConstructIVec4:
2469 case glslang::EOpConstructUint:
2470 case glslang::EOpConstructUVec2:
2471 case glslang::EOpConstructUVec3:
2472 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002473 case glslang::EOpConstructInt64:
2474 case glslang::EOpConstructI64Vec2:
2475 case glslang::EOpConstructI64Vec3:
2476 case glslang::EOpConstructI64Vec4:
2477 case glslang::EOpConstructUint64:
2478 case glslang::EOpConstructU64Vec2:
2479 case glslang::EOpConstructU64Vec3:
2480 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002481 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002482 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002483 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002484 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002485 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002486 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002487 std::vector<spv::Id> arguments;
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002488 translateArguments(*node, arguments, lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002489 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002490 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002491 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002492 else if (node->getOp() == glslang::EOpConstructStruct ||
2493 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2494 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002495 std::vector<spv::Id> constituents;
2496 for (int c = 0; c < (int)arguments.size(); ++c)
2497 constituents.push_back(arguments[c]);
Jeff Bolz53134492019-06-25 13:31:10 -05002498 constructed = createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002499 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002500 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002501 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002502 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002503
2504 builder.clearAccessChain();
2505 builder.setAccessChainRValue(constructed);
2506
2507 return false;
2508 }
2509
2510 // These six are component-wise compares with component-wise results.
2511 // Forward on to createBinaryOperation(), requesting a vector result.
2512 case glslang::EOpLessThan:
2513 case glslang::EOpGreaterThan:
2514 case glslang::EOpLessThanEqual:
2515 case glslang::EOpGreaterThanEqual:
2516 case glslang::EOpVectorEqual:
2517 case glslang::EOpVectorNotEqual:
2518 {
2519 // Map the operation to a binary
2520 binOp = node->getOp();
2521 reduceComparison = false;
2522 switch (node->getOp()) {
2523 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2524 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2525 default: binOp = node->getOp(); break;
2526 }
2527
2528 break;
2529 }
2530 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002531 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002532 binOp = glslang::EOpMul;
2533 break;
2534 case glslang::EOpOuterProduct:
2535 // two vectors multiplied to make a matrix
2536 binOp = glslang::EOpOuterProduct;
2537 break;
2538 case glslang::EOpDot:
2539 {
qining25262b32016-05-06 17:25:16 -04002540 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002541 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002542 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002543 binOp = glslang::EOpMul;
2544 break;
2545 }
2546 case glslang::EOpMod:
2547 // when an aggregate, this is the floating-point mod built-in function,
2548 // which can be emitted by the one in createBinaryOperation()
2549 binOp = glslang::EOpMod;
2550 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002551
John Kessenich140f3df2015-06-26 16:58:36 -06002552 case glslang::EOpEmitVertex:
2553 case glslang::EOpEndPrimitive:
2554 case glslang::EOpBarrier:
2555 case glslang::EOpMemoryBarrier:
2556 case glslang::EOpMemoryBarrierAtomicCounter:
2557 case glslang::EOpMemoryBarrierBuffer:
2558 case glslang::EOpMemoryBarrierImage:
2559 case glslang::EOpMemoryBarrierShared:
2560 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002561 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002562 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002563 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002564 case glslang::EOpWorkgroupMemoryBarrier:
2565 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002566 case glslang::EOpSubgroupBarrier:
2567 case glslang::EOpSubgroupMemoryBarrier:
2568 case glslang::EOpSubgroupMemoryBarrierBuffer:
2569 case glslang::EOpSubgroupMemoryBarrierImage:
2570 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002571 noReturnValue = true;
2572 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2573 break;
2574
John Kessenich3dd1ce52019-10-17 07:08:40 -06002575#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -05002576 case glslang::EOpAtomicStore:
2577 noReturnValue = true;
2578 // fallthrough
2579 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06002580 case glslang::EOpAtomicAdd:
2581 case glslang::EOpAtomicMin:
2582 case glslang::EOpAtomicMax:
2583 case glslang::EOpAtomicAnd:
2584 case glslang::EOpAtomicOr:
2585 case glslang::EOpAtomicXor:
2586 case glslang::EOpAtomicExchange:
2587 case glslang::EOpAtomicCompSwap:
2588 atomic = true;
2589 break;
2590
John Kessenich0d0c6d32017-07-23 16:08:26 -06002591 case glslang::EOpAtomicCounterAdd:
2592 case glslang::EOpAtomicCounterSubtract:
2593 case glslang::EOpAtomicCounterMin:
2594 case glslang::EOpAtomicCounterMax:
2595 case glslang::EOpAtomicCounterAnd:
2596 case glslang::EOpAtomicCounterOr:
2597 case glslang::EOpAtomicCounterXor:
2598 case glslang::EOpAtomicCounterExchange:
2599 case glslang::EOpAtomicCounterCompSwap:
2600 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2601 builder.addCapability(spv::CapabilityAtomicStorageOps);
2602 atomic = true;
2603 break;
2604
Chao Chenb50c02e2018-09-19 11:42:24 -07002605 case glslang::EOpIgnoreIntersectionNV:
2606 case glslang::EOpTerminateRayNV:
2607 case glslang::EOpTraceNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07002608 case glslang::EOpExecuteCallableNV:
Chao Chen3c366992018-09-19 11:41:59 -07002609 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2610 noReturnValue = true;
2611 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002612 case glslang::EOpCooperativeMatrixLoad:
2613 case glslang::EOpCooperativeMatrixStore:
2614 noReturnValue = true;
2615 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002616 case glslang::EOpBeginInvocationInterlock:
2617 case glslang::EOpEndInvocationInterlock:
2618 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2619 noReturnValue = true;
2620 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002621#endif
Chao Chen3c366992018-09-19 11:41:59 -07002622
John Kessenich140f3df2015-06-26 16:58:36 -06002623 default:
2624 break;
2625 }
2626
2627 //
2628 // See if it maps to a regular operation.
2629 //
John Kessenich140f3df2015-06-26 16:58:36 -06002630 if (binOp != glslang::EOpNull) {
2631 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2632 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2633 assert(left && right);
2634
2635 builder.clearAccessChain();
2636 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002637 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002638
2639 builder.clearAccessChain();
2640 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002641 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002642
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002643 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002644 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002645 TranslateNoContractionDecoration(node->getType().getQualifier()),
2646 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002647 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002648 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002649 left->getType().getBasicType(), reduceComparison);
2650
2651 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002652 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002653 builder.clearAccessChain();
2654 builder.setAccessChainRValue(result);
2655
2656 return false;
2657 }
2658
John Kessenich426394d2015-07-23 10:22:48 -06002659 //
2660 // Create the list of operands.
2661 //
John Kessenich140f3df2015-06-26 16:58:36 -06002662 glslang::TIntermSequence& glslangOperands = node->getSequence();
2663 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002664 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002665 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002666 // special case l-value operands; there are just a few
2667 bool lvalue = false;
2668 switch (node->getOp()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002669 case glslang::EOpModf:
2670 if (arg == 1)
2671 lvalue = true;
2672 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002673#ifndef GLSLANG_WEB
2674 case glslang::EOpFrexp:
2675 if (arg == 1)
2676 lvalue = true;
2677 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002678 case glslang::EOpInterpolateAtSample:
2679 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002680 case glslang::EOpInterpolateAtVertex:
John Kessenich8c8505c2016-07-26 12:50:38 -06002681 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002682 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002683
2684 // Does it need a swizzle inversion? If so, evaluation is inverted;
2685 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002686 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002687 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2688 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2689 }
Rex Xu7a26c172015-12-08 17:12:09 +08002690 break;
Rex Xud4782c12015-09-06 16:30:11 +08002691 case glslang::EOpAtomicAdd:
2692 case glslang::EOpAtomicMin:
2693 case glslang::EOpAtomicMax:
2694 case glslang::EOpAtomicAnd:
2695 case glslang::EOpAtomicOr:
2696 case glslang::EOpAtomicXor:
2697 case glslang::EOpAtomicExchange:
2698 case glslang::EOpAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05002699 case glslang::EOpAtomicLoad:
2700 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002701 case glslang::EOpAtomicCounterAdd:
2702 case glslang::EOpAtomicCounterSubtract:
2703 case glslang::EOpAtomicCounterMin:
2704 case glslang::EOpAtomicCounterMax:
2705 case glslang::EOpAtomicCounterAnd:
2706 case glslang::EOpAtomicCounterOr:
2707 case glslang::EOpAtomicCounterXor:
2708 case glslang::EOpAtomicCounterExchange:
2709 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002710 if (arg == 0)
2711 lvalue = true;
2712 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002713 case glslang::EOpAddCarry:
2714 case glslang::EOpSubBorrow:
2715 if (arg == 2)
2716 lvalue = true;
2717 break;
2718 case glslang::EOpUMulExtended:
2719 case glslang::EOpIMulExtended:
2720 if (arg >= 2)
2721 lvalue = true;
2722 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002723 case glslang::EOpCooperativeMatrixLoad:
2724 if (arg == 0 || arg == 1)
2725 lvalue = true;
2726 break;
2727 case glslang::EOpCooperativeMatrixStore:
2728 if (arg == 1)
2729 lvalue = true;
2730 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002731#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002732 default:
2733 break;
2734 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002735 builder.clearAccessChain();
2736 if (invertedType != spv::NoType && arg == 0)
2737 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2738 else
2739 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002740
John Kessenichb9197c82019-08-11 07:41:45 -06002741#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002742 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2743 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2744
2745 if (arg == 1) {
2746 // fold "element" parameter into the access chain
2747 spv::Builder::AccessChain save = builder.getAccessChain();
2748 builder.clearAccessChain();
2749 glslangOperands[2]->traverse(this);
2750
2751 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2752
2753 builder.setAccessChain(save);
2754
2755 // Point to the first element of the array.
2756 builder.accessChainPush(elementId, TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
Jeff Bolz7895e472019-03-06 13:34:10 -06002757 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002758
2759 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2760 unsigned int alignment = builder.getAccessChain().alignment;
2761
2762 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2763 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2764 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2765 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2766 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
2767 if (builder.getStorageClass(builder.getAccessChain().base) == spv::StorageClassPhysicalStorageBufferEXT) {
2768 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2769 }
2770
2771 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2772
2773 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2774 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2775 }
2776
2777 if (memoryAccess & (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2778 memoryAccessOperands.push_back(spv::IdImmediate(true, builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
2779 }
2780 } else if (arg == 2) {
2781 continue;
2782 }
2783 }
John Kessenichb9197c82019-08-11 07:41:45 -06002784#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002785
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002786 if (lvalue) {
John Kessenich140f3df2015-06-26 16:58:36 -06002787 operands.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002788 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2789 lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
2790 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002791 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich32cfd492016-02-02 12:37:46 -07002792 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002793 }
John Kessenich140f3df2015-06-26 16:58:36 -06002794 }
John Kessenich426394d2015-07-23 10:22:48 -06002795
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002796 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichb9197c82019-08-11 07:41:45 -06002797#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002798 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
2799 std::vector<spv::IdImmediate> idImmOps;
2800
2801 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2802 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2803 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2804 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2805 // get the pointee type
2806 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
2807 assert(builder.isCooperativeMatrixType(typeId));
2808 // do the op
2809 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
2810 // store the result to the pointer (out param 'm')
2811 builder.createStore(result, operands[0]);
2812 result = 0;
2813 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
2814 std::vector<spv::IdImmediate> idImmOps;
2815
2816 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2817 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
2818 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2819 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2820 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2821
2822 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
2823 result = 0;
2824 } else if (atomic) {
John Kessenich426394d2015-07-23 10:22:48 -06002825 // Handle all atomics
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002826 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(), lvalueCoherentFlags);
John Kessenichb9197c82019-08-11 07:41:45 -06002827 } else
2828#endif
2829 {
John Kessenich426394d2015-07-23 10:22:48 -06002830 // Pass through to generic operations.
2831 switch (glslangOperands.size()) {
2832 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002833 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002834 break;
2835 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002836 {
2837 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002838 TranslateNoContractionDecoration(node->getType().getQualifier()),
2839 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002840 result = createUnaryOperation(
2841 node->getOp(), decorations,
2842 resultType(), operands.front(),
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002843 glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -06002844 }
John Kessenich426394d2015-07-23 10:22:48 -06002845 break;
2846 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002847 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002848 break;
2849 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002850 if (invertedType)
2851 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002852 }
2853
2854 if (noReturnValue)
2855 return false;
2856
2857 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002858 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002859 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002860 } else {
2861 builder.clearAccessChain();
2862 builder.setAccessChainRValue(result);
2863 return false;
2864 }
2865}
2866
John Kessenich433e9ff2017-01-26 20:31:11 -07002867// This path handles both if-then-else and ?:
2868// The if-then-else has a node type of void, while
2869// ?: has either a void or a non-void node type
2870//
2871// Leaving the result, when not void:
2872// GLSL only has r-values as the result of a :?, but
2873// if we have an l-value, that can be more efficient if it will
2874// become the base of a complex r-value expression, because the
2875// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002876bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2877{
John Kessenich0c1e71a2019-01-10 18:23:06 +07002878 // see if OpSelect can handle it
2879 const auto isOpSelectable = [&]() {
2880 if (node->getBasicType() == glslang::EbtVoid)
2881 return false;
2882 // OpSelect can do all other types starting with SPV 1.4
2883 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
2884 // pre-1.4, only scalars and vectors can be handled
2885 if ((!node->getType().isScalar() && !node->getType().isVector()))
2886 return false;
2887 }
2888 return true;
2889 };
2890
John Kessenich4bee5312018-02-20 21:29:05 -07002891 // See if it simple and safe, or required, to execute both sides.
2892 // Crucially, side effects must be either semantically required or avoided,
2893 // and there are performance trade-offs.
2894 // Return true if required or a good idea (and safe) to execute both sides,
2895 // false otherwise.
2896 const auto bothSidesPolicy = [&]() -> bool {
2897 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002898 if (node->getTrueBlock() == nullptr ||
2899 node->getFalseBlock() == nullptr)
2900 return false;
2901
John Kessenich4bee5312018-02-20 21:29:05 -07002902 // required? (unless we write additional code to look for side effects
2903 // and make performance trade-offs if none are present)
2904 if (!node->getShortCircuit())
2905 return true;
2906
2907 // if not required to execute both, decide based on performance/practicality...
2908
John Kessenich0c1e71a2019-01-10 18:23:06 +07002909 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07002910 return false;
2911
John Kessenich433e9ff2017-01-26 20:31:11 -07002912 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2913 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2914
2915 // return true if a single operand to ? : is okay for OpSelect
2916 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002917 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002918 };
2919
2920 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2921 operandOkay(node->getFalseBlock()->getAsTyped());
2922 };
2923
John Kessenich4bee5312018-02-20 21:29:05 -07002924 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2925 // emit the condition before doing anything with selection
2926 node->getCondition()->traverse(this);
2927 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2928
2929 // Find a way of executing both sides and selecting the right result.
2930 const auto executeBothSides = [&]() -> void {
2931 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002932 node->getTrueBlock()->traverse(this);
2933 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2934 node->getFalseBlock()->traverse(this);
2935 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2936
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002937 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002938
John Kessenich4bee5312018-02-20 21:29:05 -07002939 // done if void
2940 if (node->getBasicType() == glslang::EbtVoid)
2941 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002942
John Kessenich4bee5312018-02-20 21:29:05 -07002943 // emit code to select between trueValue and falseValue
2944
2945 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07002946 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07002947 // Emit OpSelect for this selection.
2948
2949 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07002950 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
2951 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07002952 condition = builder.smearScalar(spv::NoPrecision, condition,
2953 builder.makeVectorType(builder.makeBoolType(),
2954 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07002955 }
John Kessenich4bee5312018-02-20 21:29:05 -07002956
2957 // OpSelect
2958 result = builder.createTriOp(spv::OpSelect,
2959 convertGlslangToSpvType(node->getType()), condition,
2960 trueValue, falseValue);
2961
2962 builder.clearAccessChain();
2963 builder.setAccessChainRValue(result);
2964 } else {
2965 // We need control flow to select the result.
2966 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2967 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2968
2969 // Selection control:
2970 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2971
2972 // make an "if" based on the value created by the condition
2973 spv::Builder::If ifBuilder(condition, control, builder);
2974
2975 // emit the "then" statement
2976 builder.createStore(trueValue, result);
2977 ifBuilder.makeBeginElse();
2978 // emit the "else" statement
2979 builder.createStore(falseValue, result);
2980
2981 // finish off the control flow
2982 ifBuilder.makeEndIf();
2983
2984 builder.clearAccessChain();
2985 builder.setAccessChainLValue(result);
2986 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002987 };
2988
John Kessenich4bee5312018-02-20 21:29:05 -07002989 // Execute the one side needed, as per the condition
2990 const auto executeOneSide = [&]() {
2991 // Always emit control flow.
2992 if (node->getBasicType() != glslang::EbtVoid)
2993 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002994
John Kessenich4bee5312018-02-20 21:29:05 -07002995 // Selection control:
2996 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2997
2998 // make an "if" based on the value created by the condition
2999 spv::Builder::If ifBuilder(condition, control, builder);
3000
3001 // emit the "then" statement
3002 if (node->getTrueBlock() != nullptr) {
3003 node->getTrueBlock()->traverse(this);
3004 if (result != spv::NoResult)
3005 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
3006 }
3007
3008 if (node->getFalseBlock() != nullptr) {
3009 ifBuilder.makeBeginElse();
3010 // emit the "else" statement
3011 node->getFalseBlock()->traverse(this);
3012 if (result != spv::NoResult)
3013 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
3014 }
3015
3016 // finish off the control flow
3017 ifBuilder.makeEndIf();
3018
3019 if (result != spv::NoResult) {
3020 builder.clearAccessChain();
3021 builder.setAccessChainLValue(result);
3022 }
3023 };
3024
3025 // Try for OpSelect (or a requirement to execute both sides)
3026 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003027 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
3028 if (node->getType().getQualifier().isSpecConstant())
3029 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07003030 executeBothSides();
3031 } else
3032 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06003033
3034 return false;
3035}
3036
3037bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
3038{
3039 // emit and get the condition before doing anything with switch
3040 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003041 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06003042
Rex Xu57e65922017-07-04 23:23:40 +08003043 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07003044 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08003045
John Kessenich140f3df2015-06-26 16:58:36 -06003046 // browse the children to sort out code segments
3047 int defaultSegment = -1;
3048 std::vector<TIntermNode*> codeSegments;
3049 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
3050 std::vector<int> caseValues;
3051 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
3052 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
3053 TIntermNode* child = *c;
3054 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02003055 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003056 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02003057 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003058 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
3059 } else
3060 codeSegments.push_back(child);
3061 }
3062
qining25262b32016-05-06 17:25:16 -04003063 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06003064 // statements between the last case and the end of the switch statement
3065 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
3066 (int)codeSegments.size() == defaultSegment)
3067 codeSegments.push_back(nullptr);
3068
3069 // make the switch statement
3070 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08003071 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06003072
3073 // emit all the code in the segments
3074 breakForLoop.push(false);
3075 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
3076 builder.nextSwitchSegment(segmentBlocks, s);
3077 if (codeSegments[s])
3078 codeSegments[s]->traverse(this);
3079 else
3080 builder.addSwitchBreak();
3081 }
3082 breakForLoop.pop();
3083
3084 builder.endSwitch(segmentBlocks);
3085
3086 return false;
3087}
3088
3089void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
3090{
3091 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003092 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06003093
3094 builder.clearAccessChain();
3095 builder.setAccessChainRValue(constant);
3096}
3097
3098bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
3099{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003100 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003101 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06003102
3103 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07003104 std::vector<unsigned int> operands;
3105 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06003106
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003107 // Spec requires back edges to target header blocks, and every header block
3108 // must dominate its merge block. Make a header block first to ensure these
3109 // conditions are met. By definition, it will contain OpLoopMerge, followed
3110 // by a block-ending branch. But we don't want to put any other body/test
3111 // instructions in it, since the body/test may have arbitrary instructions,
3112 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003113 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003114 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07003115 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003116 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003117 spv::Block& test = builder.makeNewBlock();
3118 builder.createBranch(&test);
3119
3120 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06003121 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06003122 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003123 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
3124
3125 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003126 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003127 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003128 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003129 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003130 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003131
3132 builder.setBuildPoint(&blocks.continue_target);
3133 if (node->getTerminal())
3134 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003135 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04003136 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003137 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003138 builder.createBranch(&blocks.body);
3139
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003140 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003141 builder.setBuildPoint(&blocks.body);
3142 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003143 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003144 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003145 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003146
3147 builder.setBuildPoint(&blocks.continue_target);
3148 if (node->getTerminal())
3149 node->getTerminal()->traverse(this);
3150 if (node->getTest()) {
3151 node->getTest()->traverse(this);
3152 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07003153 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003154 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003155 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05003156 // TODO: unless there was a break/return/discard instruction
3157 // somewhere in the body, this is an infinite loop, so we should
3158 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003159 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003160 }
John Kessenich140f3df2015-06-26 16:58:36 -06003161 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003162 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003163 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06003164 return false;
3165}
3166
3167bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
3168{
3169 if (node->getExpression())
3170 node->getExpression()->traverse(this);
3171
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003172 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003173
John Kessenich140f3df2015-06-26 16:58:36 -06003174 switch (node->getFlowOp()) {
3175 case glslang::EOpKill:
3176 builder.makeDiscard();
3177 break;
3178 case glslang::EOpBreak:
3179 if (breakForLoop.top())
3180 builder.createLoopExit();
3181 else
3182 builder.addSwitchBreak();
3183 break;
3184 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06003185 builder.createLoopContinue();
3186 break;
3187 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06003188 if (node->getExpression()) {
3189 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3190 spv::Id returnId = accessChainLoad(glslangReturnType);
3191 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
3192 builder.clearAccessChain();
3193 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
3194 builder.setAccessChainLValue(copyId);
3195 multiTypeStore(glslangReturnType, returnId);
3196 returnId = builder.createLoad(copyId);
3197 }
3198 builder.makeReturn(false, returnId);
3199 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003200 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003201
3202 builder.clearAccessChain();
3203 break;
3204
John Kessenichb9197c82019-08-11 07:41:45 -06003205#ifndef GLSLANG_WEB
Jeff Bolzba6170b2019-07-01 09:23:23 -05003206 case glslang::EOpDemote:
3207 builder.createNoResultOp(spv::OpDemoteToHelperInvocationEXT);
3208 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
3209 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
3210 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003211#endif
Jeff Bolzba6170b2019-07-01 09:23:23 -05003212
John Kessenich140f3df2015-06-26 16:58:36 -06003213 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003214 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003215 break;
3216 }
3217
3218 return false;
3219}
3220
John Kessenich9c14f772019-06-17 08:38:35 -06003221spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node, spv::Id forcedType)
John Kessenich140f3df2015-06-26 16:58:36 -06003222{
qining25262b32016-05-06 17:25:16 -04003223 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003224 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003225 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003226 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003227 spv::Id result = createSpvConstant(*node);
3228 if (result != spv::NoResult)
3229 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003230 }
3231
3232 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003233 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06003234 spv::Id spvType = forcedType == spv::NoType ? convertGlslangToSpvType(node->getType())
3235 : forcedType;
John Kessenich140f3df2015-06-26 16:58:36 -06003236
John Kessenichb9197c82019-08-11 07:41:45 -06003237 const bool contains16BitType = node->getType().contains16BitFloat() ||
3238 node->getType().contains16BitInt();
Rex Xuf89ad982017-04-07 23:22:33 +08003239 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003240 switch (storageClass) {
3241 case spv::StorageClassInput:
3242 case spv::StorageClassOutput:
John Kessenich8317e6c2019-08-18 23:58:08 -06003243 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003244 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003245 break;
John Kessenich18310872018-05-14 22:08:53 -06003246 case spv::StorageClassUniform:
John Kessenich8317e6c2019-08-18 23:58:08 -06003247 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003248 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3249 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003250 else
3251 builder.addCapability(spv::CapabilityStorageUniform16);
3252 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003253#ifndef GLSLANG_WEB
3254 case spv::StorageClassPushConstant:
John Kessenich8317e6c2019-08-18 23:58:08 -06003255 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenichb9197c82019-08-11 07:41:45 -06003256 builder.addCapability(spv::CapabilityStoragePushConstant16);
3257 break;
John Kessenich18310872018-05-14 22:08:53 -06003258 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003259 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich8317e6c2019-08-18 23:58:08 -06003260 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenich18310872018-05-14 22:08:53 -06003261 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3262 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003263#endif
John Kessenich18310872018-05-14 22:08:53 -06003264 default:
John Kessenichb9197c82019-08-11 07:41:45 -06003265 if (node->getType().contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003266 builder.addCapability(spv::CapabilityFloat16);
John Kessenichb9197c82019-08-11 07:41:45 -06003267 if (node->getType().contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003268 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06003269 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003270 }
3271 }
Rex Xuf89ad982017-04-07 23:22:33 +08003272
John Kessenichb9197c82019-08-11 07:41:45 -06003273 if (node->getType().contains8BitInt()) {
John Kessenich312dcfb2018-07-03 13:19:51 -06003274 if (storageClass == spv::StorageClassPushConstant) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003275 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003276 builder.addCapability(spv::CapabilityStoragePushConstant8);
3277 } else if (storageClass == spv::StorageClassUniform) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003278 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003279 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003280 } else if (storageClass == spv::StorageClassStorageBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003281 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
Neil Henningb6b01f02018-10-23 15:02:29 +01003282 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003283 } else {
3284 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06003285 }
3286 }
3287
John Kessenich140f3df2015-06-26 16:58:36 -06003288 const char* name = node->getName().c_str();
3289 if (glslang::IsAnonymous(name))
3290 name = "";
3291
3292 return builder.createVariable(storageClass, spvType, name);
3293}
3294
3295// Return type Id of the sampled type.
3296spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3297{
3298 switch (sampler.type) {
John Kessenicha28f7a72019-08-06 07:00:58 -06003299 case glslang::EbtInt: return builder.makeIntType(32);
3300 case glslang::EbtUint: return builder.makeUintType(32);
John Kessenich140f3df2015-06-26 16:58:36 -06003301 case glslang::EbtFloat: return builder.makeFloatType(32);
John Kessenicha28f7a72019-08-06 07:00:58 -06003302#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08003303 case glslang::EbtFloat16:
3304 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3305 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3306 return builder.makeFloatType(16);
3307#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003308 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003309 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003310 return builder.makeFloatType(32);
3311 }
3312}
3313
John Kessenich8c8505c2016-07-26 12:50:38 -06003314// If node is a swizzle operation, return the type that should be used if
3315// the swizzle base is first consumed by another operation, before the swizzle
3316// is applied.
3317spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3318{
John Kessenichecba76f2017-01-06 00:34:48 -07003319 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003320 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3321 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3322 else
3323 return spv::NoType;
3324}
3325
3326// When inverting a swizzle with a parent op, this function
3327// will apply the swizzle operation to a completed parent operation.
3328spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
3329{
3330 std::vector<unsigned> swizzle;
3331 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3332 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3333}
3334
John Kessenich8c8505c2016-07-26 12:50:38 -06003335// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3336void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3337{
3338 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3339 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3340 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3341}
3342
John Kessenich3ac051e2015-12-20 11:29:16 -07003343// Convert from a glslang type to an SPV type, by calling into a
3344// recursive version of this function. This establishes the inherited
3345// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003346spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003347{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003348 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003349}
3350
3351// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003352// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003353// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003354spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003355 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3356 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003357{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003358 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003359
3360 switch (type.getBasicType()) {
3361 case glslang::EbtVoid:
3362 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003363 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003364 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003365 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003366 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3367 // a 32-bit int where non-0 means true.
3368 if (explicitLayout != glslang::ElpNone)
3369 spvType = builder.makeUintType(32);
3370 else
3371 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003372 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003373 case glslang::EbtInt:
3374 spvType = builder.makeIntType(32);
3375 break;
3376 case glslang::EbtUint:
3377 spvType = builder.makeUintType(32);
3378 break;
3379 case glslang::EbtFloat:
3380 spvType = builder.makeFloatType(32);
3381 break;
3382#ifndef GLSLANG_WEB
3383 case glslang::EbtDouble:
3384 spvType = builder.makeFloatType(64);
3385 break;
3386 case glslang::EbtFloat16:
3387 spvType = builder.makeFloatType(16);
3388 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003389 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003390 spvType = builder.makeIntType(8);
3391 break;
3392 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003393 spvType = builder.makeUintType(8);
3394 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003395 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003396 spvType = builder.makeIntType(16);
3397 break;
3398 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003399 spvType = builder.makeUintType(16);
3400 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003401 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003402 spvType = builder.makeIntType(64);
3403 break;
3404 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003405 spvType = builder.makeUintType(64);
3406 break;
John Kessenich426394d2015-07-23 10:22:48 -06003407 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003408 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003409 spvType = builder.makeUintType(32);
3410 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003411 case glslang::EbtAccStructNV:
3412 spvType = builder.makeAccelerationStructureNVType();
3413 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003414 case glslang::EbtReference:
3415 {
3416 // Make the forward pointer, then recurse to convert the structure type, then
3417 // patch up the forward pointer with a real pointer type.
3418 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3419 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3420 forwardPointers[type.getReferentType()] = forwardId;
3421 }
3422 spvType = forwardPointers[type.getReferentType()];
3423 if (!forwardReferenceOnly) {
3424 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3425 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3426 forwardPointers[type.getReferentType()],
3427 referentType);
3428 }
3429 }
3430 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003431#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003432 case glslang::EbtSampler:
3433 {
3434 const glslang::TSampler& sampler = type.getSampler();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003435 if (sampler.isPureSampler()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003436 spvType = builder.makeSamplerType();
3437 } else {
3438 // an image is present, make its type
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003439 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler),
3440 sampler.isShadow(), sampler.isArrayed(), sampler.isMultiSample(),
3441 sampler.isImageClass() ? 2 : 1, TranslateImageFormat(type));
3442 if (sampler.isCombined()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003443 // already has both image and sampler, make the combined type
3444 spvType = builder.makeSampledImageType(spvType);
3445 }
John Kessenich55e7d112015-11-15 21:33:39 -07003446 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003447 }
John Kessenich140f3df2015-06-26 16:58:36 -06003448 break;
3449 case glslang::EbtStruct:
3450 case glslang::EbtBlock:
3451 {
3452 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003453 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003454
3455 // Try to share structs for different layouts, but not yet for other
3456 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003457 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003458 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003459 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003460 break;
3461
3462 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003463 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06003464 memberRemapper[glslangMembers].resize(glslangMembers->size());
3465 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003466 }
3467 break;
3468 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003469 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003470 break;
3471 }
3472
3473 if (type.isMatrix())
3474 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3475 else {
3476 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3477 if (type.getVectorSize() > 1)
3478 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3479 }
3480
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003481 if (type.isCoopMat()) {
3482 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3483 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3484 if (type.getBasicType() == glslang::EbtFloat16)
3485 builder.addCapability(spv::CapabilityFloat16);
Jeff Bolz387657e2019-08-22 20:28:00 -05003486 if (type.getBasicType() == glslang::EbtUint8 ||
3487 type.getBasicType() == glslang::EbtInt8) {
3488 builder.addCapability(spv::CapabilityInt8);
3489 }
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003490
3491 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3492 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3493 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3494
3495 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3496 }
3497
John Kessenich140f3df2015-06-26 16:58:36 -06003498 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003499 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3500
John Kessenichc9a80832015-09-12 12:17:44 -06003501 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003502 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003503 // We need to decorate array strides for types needing explicit layout, except blocks.
3504 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003505 // Use a dummy glslang type for querying internal strides of
3506 // arrays of arrays, but using just a one-dimensional array.
3507 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003508 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3509 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003510
3511 // Will compute the higher-order strides here, rather than making a whole
3512 // pile of types and doing repetitive recursion on their contents.
3513 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3514 }
John Kessenichf8842e52016-01-04 19:22:56 -07003515
3516 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003517 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003518 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003519 if (stride > 0)
3520 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003521 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003522 }
3523 } else {
3524 // single-dimensional array, and don't yet have stride
3525
John Kessenichf8842e52016-01-04 19:22:56 -07003526 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003527 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3528 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003529 }
John Kessenich31ed4832015-09-09 17:51:38 -06003530
John Kessenichead86222018-03-28 18:01:20 -06003531 // Do the outer dimension, which might not be known for a runtime-sized array.
3532 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3533 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003534 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003535 else {
John Kessenichb9197c82019-08-11 07:41:45 -06003536#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003537 if (!lastBufferBlockMember) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003538 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06003539 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3540 }
John Kessenichb9197c82019-08-11 07:41:45 -06003541#endif
John Kessenich3dd1ce52019-10-17 07:08:40 -06003542 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003543 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003544 if (stride > 0)
3545 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003546 }
3547
3548 return spvType;
3549}
3550
John Kessenich0e737842017-03-24 18:38:16 -06003551// TODO: this functionality should exist at a higher level, in creating the AST
3552//
3553// Identify interface members that don't have their required extension turned on.
3554//
3555bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3556{
John Kessenicha28f7a72019-08-06 07:00:58 -06003557#ifndef GLSLANG_WEB
John Kessenich0e737842017-03-24 18:38:16 -06003558 auto& extensions = glslangIntermediate->getRequestedExtensions();
3559
Rex Xubcf291a2017-03-29 23:01:36 +08003560 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3561 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3562 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003563 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3564 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3565 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003566
3567 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3568 if (member.getFieldName() == "gl_ViewportMask" &&
3569 extensions.find("GL_NV_viewport_array2") == extensions.end())
3570 return true;
3571 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3572 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3573 return true;
3574 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3575 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3576 return true;
3577 }
3578#endif
John Kessenich0e737842017-03-24 18:38:16 -06003579
3580 return false;
3581};
3582
John Kessenich6090df02016-06-30 21:18:02 -06003583// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3584// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3585// Mutually recursive with convertGlslangToSpvType().
3586spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3587 const glslang::TTypeList* glslangMembers,
3588 glslang::TLayoutPacking explicitLayout,
3589 const glslang::TQualifier& qualifier)
3590{
3591 // Create a vector of struct types for SPIR-V to consume
3592 std::vector<spv::Id> spvMembers;
3593 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 -06003594 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003595 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3596 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3597 if (glslangMember.hiddenMember()) {
3598 ++memberDelta;
3599 if (type.getBasicType() == glslang::EbtBlock)
3600 memberRemapper[glslangMembers][i] = -1;
3601 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003602 if (type.getBasicType() == glslang::EbtBlock) {
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003603 if (filterMember(glslangMember)) {
3604 memberDelta++;
3605 memberRemapper[glslangMembers][i] = -1;
John Kessenich0e737842017-03-24 18:38:16 -06003606 continue;
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003607 }
3608 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003609 }
John Kessenich6090df02016-06-30 21:18:02 -06003610 // modify just this child's view of the qualifier
3611 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3612 InheritQualifiers(memberQualifier, qualifier);
3613
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003614 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003615 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003616 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003617
3618 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003619 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3620 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003621
3622 // Make forward pointers for any pointer members, and create a list of members to
3623 // convert to spirv types after creating the struct.
John Kessenich7015bd62019-08-01 03:28:08 -06003624 if (glslangMember.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003625 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3626 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3627 }
3628 spvMembers.push_back(
3629 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, true));
3630 } else {
3631 spvMembers.push_back(
3632 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, false));
3633 }
John Kessenich6090df02016-06-30 21:18:02 -06003634 }
3635 }
3636
3637 // Make the SPIR-V type
3638 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003639 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003640 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3641
3642 // Decorate it
3643 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3644
John Kessenichd72f4882019-01-16 14:55:37 +07003645 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003646 auto it = deferredForwardPointers[i];
3647 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3648 }
3649
John Kessenich6090df02016-06-30 21:18:02 -06003650 return spvType;
3651}
3652
3653void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3654 const glslang::TTypeList* glslangMembers,
3655 glslang::TLayoutPacking explicitLayout,
3656 const glslang::TQualifier& qualifier,
3657 spv::Id spvType)
3658{
3659 // Name and decorate the non-hidden members
3660 int offset = -1;
3661 int locationOffset = 0; // for use within the members of this struct
3662 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3663 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3664 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003665 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003666 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06003667 if (filterMember(glslangMember))
3668 continue;
3669 }
John Kessenich6090df02016-06-30 21:18:02 -06003670
3671 // modify just this child's view of the qualifier
3672 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3673 InheritQualifiers(memberQualifier, qualifier);
3674
3675 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003676 if (member < 0)
3677 continue;
3678
3679 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3680 builder.addMemberDecoration(spvType, member,
3681 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3682 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3683 // Add interpolation and auxiliary storage decorations only to
3684 // top-level members of Input and Output storage classes
3685 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3686 type.getQualifier().storage == glslang::EvqVaryingOut) {
3687 if (type.getBasicType() == glslang::EbtBlock ||
3688 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3689 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3690 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenicha28f7a72019-08-06 07:00:58 -06003691#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07003692 addMeshNVDecoration(spvType, member, memberQualifier);
3693#endif
John Kessenich6090df02016-06-30 21:18:02 -06003694 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003695 }
3696 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003697
John Kessenichb9197c82019-08-11 07:41:45 -06003698#ifndef GLSLANG_WEB
John Kessenich5d610ee2018-03-07 18:05:55 -07003699 if (type.getBasicType() == glslang::EbtBlock &&
3700 qualifier.storage == glslang::EvqBuffer) {
3701 // Add memory decorations only to top-level members of shader storage block
3702 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003703 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003704 for (unsigned int i = 0; i < memory.size(); ++i)
3705 builder.addMemberDecoration(spvType, member, memory[i]);
3706 }
John Kessenichb9197c82019-08-11 07:41:45 -06003707#endif
John Kessenich6090df02016-06-30 21:18:02 -06003708
John Kessenich5d610ee2018-03-07 18:05:55 -07003709 // Location assignment was already completed correctly by the front end,
3710 // just track whether a member needs to be decorated.
3711 // Ignore member locations if the container is an array, as that's
3712 // ill-specified and decisions have been made to not allow this.
3713 if (! type.isArray() && memberQualifier.hasLocation())
3714 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003715
John Kessenich5d610ee2018-03-07 18:05:55 -07003716 if (qualifier.hasLocation()) // track for upcoming inheritance
3717 locationOffset += glslangIntermediate->computeTypeLocationSize(
3718 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003719
John Kessenich5d610ee2018-03-07 18:05:55 -07003720 // component, XFB, others
3721 if (glslangMember.getQualifier().hasComponent())
3722 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3723 glslangMember.getQualifier().layoutComponent);
3724 if (glslangMember.getQualifier().hasXfbOffset())
3725 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3726 glslangMember.getQualifier().layoutXfbOffset);
3727 else if (explicitLayout != glslang::ElpNone) {
3728 // figure out what to do with offset, which is accumulating
3729 int nextOffset;
3730 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3731 if (offset >= 0)
3732 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3733 offset = nextOffset;
3734 }
John Kessenich6090df02016-06-30 21:18:02 -06003735
John Kessenich5d610ee2018-03-07 18:05:55 -07003736 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3737 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3738 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003739
John Kessenich5d610ee2018-03-07 18:05:55 -07003740 // built-in variable decorations
3741 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3742 if (builtIn != spv::BuiltInMax)
3743 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003744
John Kessenichb9197c82019-08-11 07:41:45 -06003745#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003746 // nonuniform
3747 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3748
John Kessenichead86222018-03-28 18:01:20 -06003749 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3750 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3751 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3752 memberQualifier.semanticName);
3753 }
3754
John Kessenich5d610ee2018-03-07 18:05:55 -07003755 if (builtIn == spv::BuiltInLayer) {
3756 // SPV_NV_viewport_array2 extension
3757 if (glslangMember.getQualifier().layoutViewportRelative){
3758 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3759 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3760 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003761 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003762 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3763 builder.addMemberDecoration(spvType, member,
3764 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3765 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3766 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3767 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003768 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003769 }
3770 if (glslangMember.getQualifier().layoutPassthrough) {
3771 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3772 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3773 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3774 }
chaoc771d89f2017-01-13 01:10:53 -08003775#endif
John Kessenich6090df02016-06-30 21:18:02 -06003776 }
3777
3778 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003779 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3780 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003781}
3782
John Kessenich6c292d32016-02-15 20:58:50 -07003783// Turn the expression forming the array size into an id.
3784// This is not quite trivial, because of specialization constants.
3785// Sometimes, a raw constant is turned into an Id, and sometimes
3786// a specialization constant expression is.
3787spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3788{
3789 // First, see if this is sized with a node, meaning a specialization constant:
3790 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3791 if (specNode != nullptr) {
3792 builder.clearAccessChain();
3793 specNode->traverse(this);
3794 return accessChainLoad(specNode->getAsTyped()->getType());
3795 }
qining25262b32016-05-06 17:25:16 -04003796
John Kessenich6c292d32016-02-15 20:58:50 -07003797 // Otherwise, need a compile-time (front end) size, get it:
3798 int size = arraySizes.getDimSize(dim);
3799 assert(size > 0);
3800 return builder.makeUintConstant(size);
3801}
3802
John Kessenich103bef92016-02-08 21:38:15 -07003803// Wrap the builder's accessChainLoad to:
3804// - localize handling of RelaxedPrecision
3805// - use the SPIR-V inferred type instead of another conversion of the glslang type
3806// (avoids unnecessary work and possible type punning for structures)
3807// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003808spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3809{
John Kessenich103bef92016-02-08 21:38:15 -07003810 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003811
3812 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3813 coherentFlags |= TranslateCoherent(type);
3814
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003815 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003816 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003817
John Kessenich5611c6d2018-04-05 11:25:02 -06003818 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003819 TranslateNonUniformDecoration(type.getQualifier()),
3820 nominalTypeId,
3821 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003822 TranslateMemoryScope(coherentFlags),
3823 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07003824
3825 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003826 if (type.getBasicType() == glslang::EbtBool) {
3827 if (builder.isScalarType(nominalTypeId)) {
3828 // Conversion for bool
3829 spv::Id boolType = builder.makeBoolType();
3830 if (nominalTypeId != boolType)
3831 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3832 } else if (builder.isVectorType(nominalTypeId)) {
3833 // Conversion for bvec
3834 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3835 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3836 if (nominalTypeId != bvecType)
3837 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3838 }
3839 }
John Kessenich103bef92016-02-08 21:38:15 -07003840
3841 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003842}
3843
Rex Xu27253232016-02-23 17:51:09 +08003844// Wrap the builder's accessChainStore to:
3845// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003846//
3847// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003848void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3849{
3850 // Need to convert to abstract types when necessary
3851 if (type.getBasicType() == glslang::EbtBool) {
3852 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3853
3854 if (builder.isScalarType(nominalTypeId)) {
3855 // Conversion for bool
3856 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003857 if (nominalTypeId != boolType) {
3858 // keep these outside arguments, for determinant order-of-evaluation
3859 spv::Id one = builder.makeUintConstant(1);
3860 spv::Id zero = builder.makeUintConstant(0);
3861 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3862 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003863 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003864 } else if (builder.isVectorType(nominalTypeId)) {
3865 // Conversion for bvec
3866 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3867 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003868 if (nominalTypeId != bvecType) {
3869 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003870 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3871 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3872 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003873 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003874 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3875 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003876 }
3877 }
3878
Jeff Bolz36831c92018-09-05 10:11:41 -05003879 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3880 coherentFlags |= TranslateCoherent(type);
3881
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003882 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003883 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003884
Jeff Bolz36831c92018-09-05 10:11:41 -05003885 builder.accessChainStore(rvalue,
3886 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003887 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08003888}
3889
John Kessenich4bf71552016-09-02 11:20:21 -06003890// For storing when types match at the glslang level, but not might match at the
3891// SPIR-V level.
3892//
3893// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003894// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003895// as in a member-decorated way.
3896//
3897// NOTE: This function can handle any store request; if it's not special it
3898// simplifies to a simple OpStore.
3899//
3900// Implicitly uses the existing builder.accessChain as the storage target.
3901void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3902{
John Kessenichb3e24e42016-09-11 12:33:43 -06003903 // we only do the complex path here if it's an aggregate
3904 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003905 accessChainStore(type, rValue);
3906 return;
3907 }
3908
John Kessenichb3e24e42016-09-11 12:33:43 -06003909 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003910 spv::Id rType = builder.getTypeId(rValue);
3911 spv::Id lValue = builder.accessChainGetLValue();
3912 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3913 if (lType == rType) {
3914 accessChainStore(type, rValue);
3915 return;
3916 }
3917
John Kessenichb3e24e42016-09-11 12:33:43 -06003918 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003919 // where the two types were the same type in GLSL. This requires member
3920 // by member copy, recursively.
3921
John Kessenichfbb6bdf2019-01-15 21:48:27 +07003922 // SPIR-V 1.4 added an instruction to do help do this.
3923 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
3924 // However, bool in uniform space is changed to int, so
3925 // OpCopyLogical does not work for that.
3926 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
3927 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
3928 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
3929 if (lBool == rBool) {
3930 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
3931 accessChainStore(type, logicalCopy);
3932 return;
3933 }
3934 }
3935
John Kessenichb3e24e42016-09-11 12:33:43 -06003936 // If an array, copy element by element.
3937 if (type.isArray()) {
3938 glslang::TType glslangElementType(type, 0);
3939 spv::Id elementRType = builder.getContainedTypeId(rType);
3940 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3941 // get the source member
3942 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003943
John Kessenichb3e24e42016-09-11 12:33:43 -06003944 // set up the target storage
3945 builder.clearAccessChain();
3946 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003947 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06003948
John Kessenichb3e24e42016-09-11 12:33:43 -06003949 // store the member
3950 multiTypeStore(glslangElementType, elementRValue);
3951 }
3952 } else {
3953 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003954
John Kessenichb3e24e42016-09-11 12:33:43 -06003955 // loop over structure members
3956 const glslang::TTypeList& members = *type.getStruct();
3957 for (int m = 0; m < (int)members.size(); ++m) {
3958 const glslang::TType& glslangMemberType = *members[m].type;
3959
3960 // get the source member
3961 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3962 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3963
3964 // set up the target storage
3965 builder.clearAccessChain();
3966 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003967 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06003968
3969 // store the member
3970 multiTypeStore(glslangMemberType, memberRValue);
3971 }
John Kessenich4bf71552016-09-02 11:20:21 -06003972 }
3973}
3974
John Kessenichf85e8062015-12-19 13:57:10 -07003975// Decide whether or not this type should be
3976// decorated with offsets and strides, and if so
3977// whether std140 or std430 rules should be applied.
3978glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003979{
John Kessenichf85e8062015-12-19 13:57:10 -07003980 // has to be a block
3981 if (type.getBasicType() != glslang::EbtBlock)
3982 return glslang::ElpNone;
3983
Chao Chen3c366992018-09-19 11:41:59 -07003984 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07003985 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07003986 type.getQualifier().storage != glslang::EvqBuffer &&
3987 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07003988 return glslang::ElpNone;
3989
3990 // return the layout to use
3991 switch (type.getQualifier().layoutPacking) {
3992 case glslang::ElpStd140:
3993 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003994 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07003995 return type.getQualifier().layoutPacking;
3996 default:
3997 return glslang::ElpNone;
3998 }
John Kessenich31ed4832015-09-09 17:51:38 -06003999}
4000
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004001// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07004002int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004003{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004004 int size;
John Kessenich49987892015-12-29 17:11:44 -07004005 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004006 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07004007
4008 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004009}
4010
John Kessenich49987892015-12-29 17:11:44 -07004011// 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 -07004012// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07004013int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004014{
John Kessenich49987892015-12-29 17:11:44 -07004015 glslang::TType elementType;
4016 elementType.shallowCopy(matrixType);
4017 elementType.clearArraySizes();
4018
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004019 int size;
John Kessenich49987892015-12-29 17:11:44 -07004020 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004021 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07004022
4023 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004024}
4025
John Kessenich5e4b1242015-08-06 22:53:06 -06004026// Given a member type of a struct, realign the current offset for it, and compute
4027// the next (not yet aligned) offset for the next member, which will get aligned
4028// on the next call.
4029// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
4030// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
4031// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06004032void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07004033 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06004034{
4035 // this will get a positive value when deemed necessary
4036 nextOffset = -1;
4037
John Kessenich5e4b1242015-08-06 22:53:06 -06004038 // override anything in currentOffset with user-set offset
4039 if (memberType.getQualifier().hasOffset())
4040 currentOffset = memberType.getQualifier().layoutOffset;
4041
4042 // It could be that current linker usage in glslang updated all the layoutOffset,
4043 // in which case the following code does not matter. But, that's not quite right
4044 // once cross-compilation unit GLSL validation is done, as the original user
4045 // settings are needed in layoutOffset, and then the following will come into play.
4046
John Kessenichf85e8062015-12-19 13:57:10 -07004047 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06004048 if (! memberType.getQualifier().hasOffset())
4049 currentOffset = -1;
4050
4051 return;
4052 }
4053
John Kessenichf85e8062015-12-19 13:57:10 -07004054 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06004055 if (currentOffset < 0)
4056 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04004057
John Kessenich5e4b1242015-08-06 22:53:06 -06004058 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
4059 // but possibly not yet correctly aligned.
4060
4061 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07004062 int dummyStride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004063 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06004064
4065 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06004066 // TODO: make this consistent in early phases of code:
4067 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
4068 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
4069 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06004070 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06004071 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06004072 int dummySize;
4073 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
4074 if (componentAlignment <= 4)
4075 memberAlignment = componentAlignment;
4076 }
4077
4078 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06004079 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06004080
4081 // Bump up to vec4 if there is a bad straddle
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004082 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06004083 glslang::RoundToPow2(currentOffset, 16);
4084
John Kessenich5e4b1242015-08-06 22:53:06 -06004085 nextOffset = currentOffset + memberSize;
4086}
4087
David Netoa901ffe2016-06-08 14:11:40 +01004088void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06004089{
David Netoa901ffe2016-06-08 14:11:40 +01004090 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
4091 switch (glslangBuiltIn)
4092 {
John Kessenicha28f7a72019-08-06 07:00:58 -06004093 case glslang::EbvPointSize:
4094#ifndef GLSLANG_WEB
David Netoa901ffe2016-06-08 14:11:40 +01004095 case glslang::EbvClipDistance:
4096 case glslang::EbvCullDistance:
chaoc771d89f2017-01-13 01:10:53 -08004097 case glslang::EbvViewportMaskNV:
4098 case glslang::EbvSecondaryPositionNV:
4099 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08004100 case glslang::EbvPositionPerViewNV:
4101 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07004102 case glslang::EbvTaskCountNV:
4103 case glslang::EbvPrimitiveCountNV:
4104 case glslang::EbvPrimitiveIndicesNV:
4105 case glslang::EbvClipDistancePerViewNV:
4106 case glslang::EbvCullDistancePerViewNV:
4107 case glslang::EbvLayerPerViewNV:
4108 case glslang::EbvMeshViewCountNV:
4109 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004110#endif
David Netoa901ffe2016-06-08 14:11:40 +01004111 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4112 // Alternately, we could just call this for any glslang built-in, since the
4113 // capability already guards against duplicates.
4114 TranslateBuiltInDecoration(glslangBuiltIn, false);
4115 break;
4116 default:
4117 // Capabilities were already generated when the struct was declared.
4118 break;
4119 }
John Kessenichebb50532016-05-16 19:22:05 -06004120}
4121
John Kessenich6fccb3c2016-09-19 16:01:41 -06004122bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004123{
John Kessenicheee9d532016-09-19 18:09:30 -06004124 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004125}
4126
John Kessenichd41993d2017-09-10 15:21:05 -06004127// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004128// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4129// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004130bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004131{
John Kessenich6a14f782017-12-04 02:48:10 -07004132 assert(qualifier == glslang::EvqIn ||
4133 qualifier == glslang::EvqOut ||
4134 qualifier == glslang::EvqInOut ||
4135 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06004136 return qualifier != glslang::EvqConstReadOnly;
4137}
4138
4139// Is parameter pass-by-original?
4140bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4141 bool implicitThisParam)
4142{
4143 if (implicitThisParam) // implicit this
4144 return true;
4145 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004146 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004147 return paramType.containsOpaque() || // sampler, etc.
4148 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4149}
4150
John Kessenich140f3df2015-06-26 16:58:36 -06004151// Make all the functions, skeletally, without actually visiting their bodies.
4152void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4153{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004154 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004155 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4156 if (paramPrecision != spv::NoPrecision)
4157 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004158 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenich7015bd62019-08-01 03:28:08 -06004159 if (type.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004160 // Original and non-writable params pass the pointer directly and
4161 // use restrict/aliased, others are stored to a pointer in Function
4162 // memory and use RestrictPointer/AliasedPointer.
4163 if (originalParam(type.getQualifier().storage, type, false) ||
4164 !writableParam(type.getQualifier().storage)) {
4165 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrict : spv::DecorationAliased);
4166 } else {
4167 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
4168 }
4169 }
John Kessenichfad62972017-07-18 02:35:46 -06004170 };
4171
John Kessenich140f3df2015-06-26 16:58:36 -06004172 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4173 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004174 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004175 continue;
4176
4177 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004178 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004179 //
qining25262b32016-05-06 17:25:16 -04004180 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004181 // function. What it is an address of varies:
4182 //
John Kessenich4bf71552016-09-02 11:20:21 -06004183 // - "in" parameters not marked as "const" can be written to without modifying the calling
4184 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004185 //
4186 // - "const in" parameters can just be the r-value, as no writes need occur.
4187 //
John Kessenich4bf71552016-09-02 11:20:21 -06004188 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4189 // 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 -06004190
4191 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004192 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004193 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4194
John Kessenich155d3512019-08-08 23:29:20 -06004195#ifdef ENABLE_HLSL
John Kessenichfad62972017-07-18 02:35:46 -06004196 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4197 glslangIntermediate->implicitThisName;
John Kessenich155d3512019-08-08 23:29:20 -06004198#else
4199 bool implicitThis = false;
4200#endif
John Kessenich37789792017-03-21 23:56:40 -06004201
John Kessenichfad62972017-07-18 02:35:46 -06004202 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004203 for (int p = 0; p < (int)parameters.size(); ++p) {
4204 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4205 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004206 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004207 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004208 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004209 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4210 else
John Kessenich4bf71552016-09-02 11:20:21 -06004211 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004212 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004213 paramTypes.push_back(typeId);
4214 }
4215
4216 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004217 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4218 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004219 glslFunction->getName().c_str(), paramTypes,
4220 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004221 if (implicitThis)
4222 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004223
4224 // Track function to emit/call later
4225 functionMap[glslFunction->getName().c_str()] = function;
4226
4227 // Set the parameter id's
4228 for (int p = 0; p < (int)parameters.size(); ++p) {
4229 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4230 // give a name too
4231 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004232
4233 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
John Kessenichb9197c82019-08-11 07:41:45 -06004234 if (paramType.contains8BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004235 builder.addCapability(spv::CapabilityInt8);
John Kessenichb9197c82019-08-11 07:41:45 -06004236 if (paramType.contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004237 builder.addCapability(spv::CapabilityInt16);
John Kessenichb9197c82019-08-11 07:41:45 -06004238 if (paramType.contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004239 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004240 }
4241 }
4242}
4243
4244// Process all the initializers, while skipping the functions and link objects
4245void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4246{
4247 builder.setBuildPoint(shaderEntry->getLastBlock());
4248 for (int i = 0; i < (int)initializers.size(); ++i) {
4249 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
4250 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
4251
4252 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004253 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004254 initializer->traverse(this);
4255 }
4256 }
4257}
4258
4259// Process all the functions, while skipping initializers.
4260void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4261{
4262 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4263 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004264 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004265 node->traverse(this);
4266 }
4267}
4268
4269void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4270{
qining25262b32016-05-06 17:25:16 -04004271 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004272 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004273 currentFunction = functionMap[node->getName().c_str()];
4274 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004275 builder.setBuildPoint(functionBlock);
4276}
4277
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004278void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments, spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004279{
Rex Xufc618912015-09-09 16:42:49 +08004280 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004281
4282 glslang::TSampler sampler = {};
4283 bool cubeCompare = false;
John Kessenicha28f7a72019-08-06 07:00:58 -06004284#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004285 bool f16ShadowCompare = false;
4286#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004287 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004288 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4289 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
John Kessenicha28f7a72019-08-06 07:00:58 -06004290#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004291 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
4292#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004293 }
4294
John Kessenich140f3df2015-06-26 16:58:36 -06004295 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4296 builder.clearAccessChain();
4297 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004298
John Kessenicha28f7a72019-08-06 07:00:58 -06004299#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08004300 // Special case l-value operands
4301 bool lvalue = false;
4302 switch (node.getOp()) {
4303 case glslang::EOpImageAtomicAdd:
4304 case glslang::EOpImageAtomicMin:
4305 case glslang::EOpImageAtomicMax:
4306 case glslang::EOpImageAtomicAnd:
4307 case glslang::EOpImageAtomicOr:
4308 case glslang::EOpImageAtomicXor:
4309 case glslang::EOpImageAtomicExchange:
4310 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004311 case glslang::EOpImageAtomicLoad:
4312 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004313 if (i == 0)
4314 lvalue = true;
4315 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004316 case glslang::EOpSparseImageLoad:
4317 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4318 lvalue = true;
4319 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004320 case glslang::EOpSparseTexture:
4321 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4322 lvalue = true;
4323 break;
4324 case glslang::EOpSparseTextureClamp:
4325 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4326 lvalue = true;
4327 break;
4328 case glslang::EOpSparseTextureLod:
4329 case glslang::EOpSparseTextureOffset:
4330 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4331 lvalue = true;
4332 break;
Rex Xu48edadf2015-12-31 16:11:41 +08004333 case glslang::EOpSparseTextureFetch:
4334 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4335 lvalue = true;
4336 break;
4337 case glslang::EOpSparseTextureFetchOffset:
4338 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4339 lvalue = true;
4340 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004341 case glslang::EOpSparseTextureLodOffset:
4342 case glslang::EOpSparseTextureGrad:
4343 case glslang::EOpSparseTextureOffsetClamp:
4344 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4345 lvalue = true;
4346 break;
4347 case glslang::EOpSparseTextureGradOffset:
4348 case glslang::EOpSparseTextureGradClamp:
4349 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4350 lvalue = true;
4351 break;
4352 case glslang::EOpSparseTextureGradOffsetClamp:
4353 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4354 lvalue = true;
4355 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004356 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004357 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4358 lvalue = true;
4359 break;
4360 case glslang::EOpSparseTextureGatherOffset:
4361 case glslang::EOpSparseTextureGatherOffsets:
4362 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4363 lvalue = true;
4364 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004365 case glslang::EOpSparseTextureGatherLod:
4366 if (i == 3)
4367 lvalue = true;
4368 break;
4369 case glslang::EOpSparseTextureGatherLodOffset:
4370 case glslang::EOpSparseTextureGatherLodOffsets:
4371 if (i == 4)
4372 lvalue = true;
4373 break;
Rex Xu129799a2017-07-05 17:23:28 +08004374 case glslang::EOpSparseImageLoadLod:
4375 if (i == 3)
4376 lvalue = true;
4377 break;
Chao Chen3a137962018-09-19 11:41:27 -07004378 case glslang::EOpImageSampleFootprintNV:
4379 if (i == 4)
4380 lvalue = true;
4381 break;
4382 case glslang::EOpImageSampleFootprintClampNV:
4383 case glslang::EOpImageSampleFootprintLodNV:
4384 if (i == 5)
4385 lvalue = true;
4386 break;
4387 case glslang::EOpImageSampleFootprintGradNV:
4388 if (i == 6)
4389 lvalue = true;
4390 break;
4391 case glslang::EOpImageSampleFootprintGradClampNV:
4392 if (i == 7)
4393 lvalue = true;
4394 break;
Rex Xufc618912015-09-09 16:42:49 +08004395 default:
4396 break;
4397 }
4398
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004399 if (lvalue) {
Rex Xufc618912015-09-09 16:42:49 +08004400 arguments.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004401 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
4402 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4403 } else
John Kessenicha28f7a72019-08-06 07:00:58 -06004404#endif
John Kessenich32cfd492016-02-02 12:37:46 -07004405 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004406 }
4407}
4408
John Kessenichfc51d282015-08-19 13:34:18 -06004409void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004410{
John Kessenichfc51d282015-08-19 13:34:18 -06004411 builder.clearAccessChain();
4412 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004413 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004414}
John Kessenich140f3df2015-06-26 16:58:36 -06004415
John Kessenichfc51d282015-08-19 13:34:18 -06004416spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4417{
John Kesseniche485c7a2017-05-31 18:50:53 -06004418 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004419 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004420
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004421 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004422
John Kessenichfc51d282015-08-19 13:34:18 -06004423 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004424
John Kessenichf43c7392019-03-31 10:51:57 -06004425 const glslang::TType &imageType = node->getAsAggregate()
4426 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4427 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004428 const glslang::TSampler sampler = imageType.getSampler();
John Kessenicha28f7a72019-08-06 07:00:58 -06004429#ifdef GLSLANG_WEB
4430 const bool f16ShadowCompare = false;
4431#else
Rex Xu1e5d7b02016-11-29 17:36:31 +08004432 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004433 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4434 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004435#endif
4436
John Kessenichf43c7392019-03-31 10:51:57 -06004437 const auto signExtensionMask = [&]() {
4438 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4439 if (sampler.type == glslang::EbtUint)
4440 return spv::ImageOperandsZeroExtendMask;
4441 else if (sampler.type == glslang::EbtInt)
4442 return spv::ImageOperandsSignExtendMask;
4443 }
4444 return spv::ImageOperandsMaskNone;
4445 };
4446
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004447 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4448
John Kessenichfc51d282015-08-19 13:34:18 -06004449 std::vector<spv::Id> arguments;
4450 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004451 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004452 else
4453 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004454 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004455
4456 spv::Builder::TextureParameters params = { };
4457 params.sampler = arguments[0];
4458
Rex Xu04db3f52015-09-16 11:44:02 +08004459 glslang::TCrackedTextureOp cracked;
4460 node->crackTexture(sampler, cracked);
4461
amhagan05506bb2017-06-13 16:53:02 -04004462 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004463
John Kessenichfc51d282015-08-19 13:34:18 -06004464 // Check for queries
4465 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004466 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4467 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004468 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004469
John Kessenichfc51d282015-08-19 13:34:18 -06004470 switch (node->getOp()) {
4471 case glslang::EOpImageQuerySize:
4472 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004473 if (arguments.size() > 1) {
4474 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004475 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004476 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004477 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenicha28f7a72019-08-06 07:00:58 -06004478#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06004479 case glslang::EOpImageQuerySamples:
4480 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004481 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004482 case glslang::EOpTextureQueryLod:
4483 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004484 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004485 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004486 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004487 case glslang::EOpSparseTexelsResident:
4488 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenicha28f7a72019-08-06 07:00:58 -06004489#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004490 default:
4491 assert(0);
4492 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004493 }
John Kessenich140f3df2015-06-26 16:58:36 -06004494 }
4495
LoopDawg4425f242018-02-18 11:40:01 -07004496 int components = node->getType().getVectorSize();
4497
4498 if (node->getOp() == glslang::EOpTextureFetch) {
4499 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4500 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4501 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4502 // here around e.g. which ones return scalars or other types.
4503 components = 4;
4504 }
4505
4506 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4507
4508 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4509
Rex Xufc618912015-09-09 16:42:49 +08004510 // Check for image functions other than queries
4511 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004512 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004513 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004514 spv::IdImmediate image = { true, *(opIt++) };
4515 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004516
4517 // Handle subpass operations
4518 // TODO: GLSL should change to have the "MS" only on the type rather than the
4519 // built-in function.
4520 if (cracked.subpass) {
4521 // add on the (0,0) coordinate
4522 spv::Id zero = builder.makeIntConstant(0);
4523 std::vector<spv::Id> comps;
4524 comps.push_back(zero);
4525 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004526 spv::IdImmediate coord = { true,
4527 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4528 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004529 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4530 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004531 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004532 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4533 }
4534 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004535 operands.push_back(imageOperands);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004536 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004537 spv::IdImmediate imageOperand = { true, *(opIt++) };
4538 operands.push_back(imageOperand);
4539 }
John Kessenich6c292d32016-02-15 20:58:50 -07004540 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004541 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4542 builder.setPrecision(result, precision);
4543 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004544 }
4545
John Kessenich149afc32018-08-14 13:31:43 -06004546 spv::IdImmediate coord = { true, *(opIt++) };
4547 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004548 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004549 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004550 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004551 mask = mask | spv::ImageOperandsSampleMask;
4552 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004553 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004554 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4555 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004556 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004557 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004558 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4559 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004560 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004561 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004562 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4563 operands.push_back(imageOperands);
4564 }
4565 if (mask & spv::ImageOperandsSampleMask) {
4566 spv::IdImmediate imageOperand = { true, *opIt++ };
4567 operands.push_back(imageOperand);
4568 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004569 if (mask & spv::ImageOperandsLodMask) {
4570 spv::IdImmediate imageOperand = { true, *opIt++ };
4571 operands.push_back(imageOperand);
4572 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004573 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004574 spv::IdImmediate imageOperand = { true,
4575 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004576 operands.push_back(imageOperand);
4577 }
4578
John Kessenich149afc32018-08-14 13:31:43 -06004579 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004580 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004581
John Kessenich149afc32018-08-14 13:31:43 -06004582 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004583 builder.setPrecision(result[0], precision);
4584
4585 // If needed, add a conversion constructor to the proper size.
4586 if (components != node->getType().getVectorSize())
4587 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4588
4589 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004590 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004591
Jeff Bolz36831c92018-09-05 10:11:41 -05004592 // Push the texel value before the operands
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004593 if (sampler.isMultiSample() || cracked.lod) {
John Kessenich149afc32018-08-14 13:31:43 -06004594 spv::IdImmediate texel = { true, *(opIt + 1) };
4595 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004596 } else {
4597 spv::IdImmediate texel = { true, *opIt };
4598 operands.push_back(texel);
4599 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004600
4601 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004602 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004603 mask = mask | spv::ImageOperandsSampleMask;
4604 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004605 if (cracked.lod) {
4606 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4607 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4608 mask = mask | spv::ImageOperandsLodMask;
4609 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004610 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4611 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004612 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004613 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004614 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4615 operands.push_back(imageOperands);
4616 }
4617 if (mask & spv::ImageOperandsSampleMask) {
4618 spv::IdImmediate imageOperand = { true, *opIt++ };
4619 operands.push_back(imageOperand);
4620 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004621 if (mask & spv::ImageOperandsLodMask) {
4622 spv::IdImmediate imageOperand = { true, *opIt++ };
4623 operands.push_back(imageOperand);
4624 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004625 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004626 spv::IdImmediate imageOperand = { true,
4627 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004628 operands.push_back(imageOperand);
4629 }
4630
John Kessenich56bab042015-09-16 10:54:31 -06004631 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004632 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004633 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004634 return spv::NoResult;
John Kessenichf43c7392019-03-31 10:51:57 -06004635 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4636 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu5eafa472016-02-19 22:24:03 +08004637 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004638 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004639 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4640
Jeff Bolz36831c92018-09-05 10:11:41 -05004641 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004642 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004643 mask = mask | spv::ImageOperandsSampleMask;
4644 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004645 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004646 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4647 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4648
Jeff Bolz36831c92018-09-05 10:11:41 -05004649 mask = mask | spv::ImageOperandsLodMask;
4650 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004651 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4652 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004653 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004654 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004655 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004656 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004657 }
4658 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004659 spv::IdImmediate imageOperand = { true, *opIt++ };
4660 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004661 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004662 if (mask & spv::ImageOperandsLodMask) {
4663 spv::IdImmediate imageOperand = { true, *opIt++ };
4664 operands.push_back(imageOperand);
4665 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004666 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4667 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4668 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004669 }
4670
4671 // Create the return type that was a special structure
4672 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004673 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004674 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4675 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4676
4677 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4678
4679 // Decode the return type
4680 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4681 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004682 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004683 // Process image atomic operations
4684
4685 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4686 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004687 // For non-MS, the sample value should be 0
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004688 spv::IdImmediate sample = { true, sampler.isMultiSample() ? *(opIt++) : builder.makeUintConstant(0) };
John Kessenich149afc32018-08-14 13:31:43 -06004689 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004690
Jeff Bolz36831c92018-09-05 10:11:41 -05004691 spv::Id resultTypeId;
4692 // imageAtomicStore has a void return type so base the pointer type on
4693 // the type of the value operand.
4694 if (node->getOp() == glslang::EOpImageAtomicStore) {
4695 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
4696 } else {
4697 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4698 }
John Kessenich56bab042015-09-16 10:54:31 -06004699 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08004700
4701 std::vector<spv::Id> operands;
4702 operands.push_back(pointer);
4703 for (; opIt != arguments.end(); ++opIt)
4704 operands.push_back(*opIt);
4705
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004706 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(), lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08004707 }
4708 }
4709
John Kessenicha28f7a72019-08-06 07:00:58 -06004710#ifndef GLSLANG_WEB
amhagan05506bb2017-06-13 16:53:02 -04004711 // Check for fragment mask functions other than queries
4712 if (cracked.fragMask) {
4713 assert(sampler.ms);
4714
4715 auto opIt = arguments.begin();
4716 std::vector<spv::Id> operands;
4717
4718 // Extract the image if necessary
4719 if (builder.isSampledImage(params.sampler))
4720 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4721
4722 operands.push_back(params.sampler);
4723 ++opIt;
4724
4725 if (sampler.isSubpass()) {
4726 // add on the (0,0) coordinate
4727 spv::Id zero = builder.makeIntConstant(0);
4728 std::vector<spv::Id> comps;
4729 comps.push_back(zero);
4730 comps.push_back(zero);
4731 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
4732 }
4733
4734 for (; opIt != arguments.end(); ++opIt)
4735 operands.push_back(*opIt);
4736
4737 spv::Op fragMaskOp = spv::OpNop;
4738 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4739 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4740 else if (node->getOp() == glslang::EOpFragmentFetch)
4741 fragMaskOp = spv::OpFragmentFetchAMD;
4742
4743 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4744 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4745 return builder.createOp(fragMaskOp, resultType(), operands);
4746 }
4747#endif
4748
Rex Xufc618912015-09-09 16:42:49 +08004749 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004750 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004751 bool imageFootprint = node->isImageFootprint();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004752 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.isArrayed() && sampler.isShadow();
Rex Xu71519fe2015-11-11 15:35:47 +08004753
John Kessenichfc51d282015-08-19 13:34:18 -06004754 // check for bias argument
4755 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004756 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06004757 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004758 if (cracked.gather)
4759 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004760
4761 if (f16ShadowCompare)
4762 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06004763 if (cracked.offset)
4764 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004765 else if (cracked.offsets)
4766 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06004767 if (cracked.grad)
4768 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004769 if (cracked.lodClamp)
4770 ++nonBiasArgCount;
4771 if (sparse)
4772 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004773 if (imageFootprint)
4774 //Following three extra arguments
4775 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4776 nonBiasArgCount += 3;
John Kessenichfc51d282015-08-19 13:34:18 -06004777 if ((int)arguments.size() > nonBiasArgCount)
4778 bias = true;
4779 }
4780
John Kessenicha5c33d62016-06-02 23:45:21 -06004781 // See if the sampler param should really be just the SPV image part
4782 if (cracked.fetch) {
4783 // a fetch needs to have the image extracted first
4784 if (builder.isSampledImage(params.sampler))
4785 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4786 }
4787
John Kessenicha28f7a72019-08-06 07:00:58 -06004788#ifndef GLSLANG_WEB
Rex Xu225e0fc2016-11-17 17:47:59 +08004789 if (cracked.gather) {
4790 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4791 if (bias || cracked.lod ||
4792 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4793 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004794 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004795 }
4796 }
4797#endif
4798
John Kessenichfc51d282015-08-19 13:34:18 -06004799 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004800
John Kessenichfc51d282015-08-19 13:34:18 -06004801 params.coords = arguments[1];
4802 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004803 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004804
4805 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004806 if (cubeCompare || f16ShadowCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06004807 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004808 ++extraArgs;
4809 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004810 params.Dref = arguments[2];
4811 ++extraArgs;
4812 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004813 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004814 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004815 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004816 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004817 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004818 dRefComp = builder.getNumComponents(params.coords) - 1;
4819 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004820 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4821 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004822
4823 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004824 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004825 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004826 ++extraArgs;
John Kessenichb9197c82019-08-11 07:41:45 -06004827 } else if (glslangIntermediate->getStage() != EShLangFragment &&
4828 !(glslangIntermediate->getStage() == EShLangCompute &&
4829 glslangIntermediate->hasLayoutDerivativeModeNone())) {
John Kessenich019f08f2016-02-15 15:40:42 -07004830 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4831 noImplicitLod = true;
4832 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004833
4834 // multisample
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004835 if (sampler.isMultiSample()) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004836 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004837 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004838 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004839
4840 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004841 if (cracked.grad) {
4842 params.gradX = arguments[2 + extraArgs];
4843 params.gradY = arguments[3 + extraArgs];
4844 extraArgs += 2;
4845 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004846
4847 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004848 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004849 params.offset = arguments[2 + extraArgs];
4850 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004851 } else if (cracked.offsets) {
4852 params.offsets = arguments[2 + extraArgs];
4853 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004854 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004855
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004856#ifndef GLSLANG_WEB
John Kessenich76d4dfc2016-06-16 12:43:23 -06004857 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004858 if (cracked.lodClamp) {
4859 params.lodClamp = arguments[2 + extraArgs];
4860 ++extraArgs;
4861 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004862 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004863 if (sparse) {
4864 params.texelOut = arguments[2 + extraArgs];
4865 ++extraArgs;
4866 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004867 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004868 if (cracked.gather && ! sampler.shadow) {
4869 // default component is 0, if missing, otherwise an argument
4870 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004871 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004872 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004873 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004874 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004875 }
Chao Chen3a137962018-09-19 11:41:27 -07004876 spv::Id resultStruct = spv::NoResult;
4877 if (imageFootprint) {
4878 //Following three extra arguments
4879 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4880 params.granularity = arguments[2 + extraArgs];
4881 params.coarse = arguments[3 + extraArgs];
4882 resultStruct = arguments[4 + extraArgs];
4883 extraArgs += 3;
4884 }
4885#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004886 // bias
4887 if (bias) {
4888 params.bias = arguments[2 + extraArgs];
4889 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004890 }
John Kessenichfc51d282015-08-19 13:34:18 -06004891
John Kessenicha28f7a72019-08-06 07:00:58 -06004892#ifndef GLSLANG_WEB
Chao Chen3a137962018-09-19 11:41:27 -07004893 if (imageFootprint) {
4894 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
4895 builder.addCapability(spv::CapabilityImageFootprintNV);
4896
4897
4898 //resultStructType(OpenGL type) contains 5 elements:
4899 //struct gl_TextureFootprint2DNV {
4900 // uvec2 anchor;
4901 // uvec2 offset;
4902 // uvec2 mask;
4903 // uint lod;
4904 // uint granularity;
4905 //};
4906 //or
4907 //struct gl_TextureFootprint3DNV {
4908 // uvec3 anchor;
4909 // uvec3 offset;
4910 // uvec2 mask;
4911 // uint lod;
4912 // uint granularity;
4913 //};
4914 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
4915 assert(builder.isStructType(resultStructType));
4916
4917 //resType (SPIR-V type) contains 6 elements:
4918 //Member 0 must be a Boolean type scalar(LOD),
4919 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
4920 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
4921 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
4922 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
4923 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
4924 std::vector<spv::Id> members;
4925 members.push_back(resultType());
4926 for (int i = 0; i < 5; i++) {
4927 members.push_back(builder.getContainedTypeId(resultStructType, i));
4928 }
4929 spv::Id resType = builder.makeStructType(members, "ResType");
4930
4931 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06004932 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
4933 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07004934
4935 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
4936 for (int i = 0; i < 5; i++) {
4937 builder.clearAccessChain();
4938 builder.setAccessChainLValue(resultStruct);
4939
4940 //Accessing to a struct we created, no coherent flag is set
4941 spv::Builder::AccessChain::CoherentFlags flags;
4942 flags.clear();
4943
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004944 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
Chao Chen3a137962018-09-19 11:41:27 -07004945 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1), i+1));
4946 }
4947 return builder.createCompositeExtract(res, resultType(), 0);
4948 }
4949#endif
4950
John Kessenich65336482016-06-16 14:06:26 -06004951 // projective component (might not to move)
4952 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4953 // are divided by the last component of P."
4954 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4955 // unused components will appear after all used components."
4956 if (cracked.proj) {
4957 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4958 int projTargetComp;
4959 switch (sampler.dim) {
4960 case glslang::Esd1D: projTargetComp = 1; break;
4961 case glslang::Esd2D: projTargetComp = 2; break;
4962 case glslang::EsdRect: projTargetComp = 2; break;
4963 default: projTargetComp = projSourceComp; break;
4964 }
4965 // copy the projective coordinate if we have to
4966 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004967 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004968 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4969 projSourceComp);
4970 params.coords = builder.createCompositeInsert(projComp, params.coords,
4971 builder.getTypeId(params.coords), projTargetComp);
4972 }
4973 }
4974
Jeff Bolz36831c92018-09-05 10:11:41 -05004975 // nonprivate
4976 if (imageType.getQualifier().nonprivate) {
4977 params.nonprivate = true;
4978 }
4979
4980 // volatile
4981 if (imageType.getQualifier().volatil) {
4982 params.volatil = true;
4983 }
4984
St0fFa1184dd2018-04-09 21:08:14 +02004985 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06004986 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
4987 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02004988 );
LoopDawg4425f242018-02-18 11:40:01 -07004989
4990 if (components != node->getType().getVectorSize())
4991 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4992
4993 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06004994}
4995
4996spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
4997{
4998 // Grab the function's pointer from the previously created function
4999 spv::Function* function = functionMap[node->getName().c_str()];
5000 if (! function)
5001 return 0;
5002
5003 const glslang::TIntermSequence& glslangArgs = node->getSequence();
5004 const glslang::TQualifierList& qualifiers = node->getQualifierList();
5005
5006 // See comments in makeFunctions() for details about the semantics for parameter passing.
5007 //
5008 // These imply we need a four step process:
5009 // 1. Evaluate the arguments
5010 // 2. Allocate and make copies of in, out, and inout arguments
5011 // 3. Make the call
5012 // 4. Copy back the results
5013
John Kessenichd3ed90b2018-05-04 11:43:03 -06005014 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06005015 std::vector<spv::Builder::AccessChain> lValues;
5016 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07005017 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06005018 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005019 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06005020 // build l-value
5021 builder.clearAccessChain();
5022 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06005023 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06005024 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07005025 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005026 // save l-value
5027 lValues.push_back(builder.getAccessChain());
5028 } else {
5029 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07005030 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06005031 }
5032 }
5033
5034 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
5035 // copy the original into that space.
5036 //
5037 // Also, build up the list of actual arguments to pass in for the call
5038 int lValueCount = 0;
5039 int rValueCount = 0;
5040 std::vector<spv::Id> spvArgs;
5041 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
5042 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06005043 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07005044 builder.setAccessChain(lValues[lValueCount]);
5045 arg = builder.accessChainGetLValue();
5046 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06005047 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005048 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06005049 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06005050 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
5051 // need to copy the input into output space
5052 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07005053 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06005054 builder.clearAccessChain();
5055 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005056 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005057 }
5058 ++lValueCount;
5059 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005060 // process r-value, which involves a copy for a type mismatch
5061 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
5062 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
5063 builder.clearAccessChain();
5064 builder.setAccessChainLValue(argCopy);
5065 multiTypeStore(*argTypes[a], rValues[rValueCount]);
5066 arg = builder.createLoad(argCopy);
5067 } else
5068 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005069 ++rValueCount;
5070 }
5071 spvArgs.push_back(arg);
5072 }
5073
5074 // 3. Make the call.
5075 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005076 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06005077
5078 // 4. Copy back out an "out" arguments.
5079 lValueCount = 0;
5080 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005081 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005082 ++lValueCount;
5083 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005084 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
5085 spv::Id copy = builder.createLoad(spvArgs[a]);
5086 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005087 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005088 }
5089 ++lValueCount;
5090 }
5091 }
5092
5093 return result;
5094}
5095
5096// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005097spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005098 spv::Id typeId, spv::Id left, spv::Id right,
5099 glslang::TBasicType typeProxy, bool reduceComparison)
5100{
John Kessenich66011cb2018-03-06 16:12:04 -07005101 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5102 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005103 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005104
5105 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005106 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005107 bool comparison = false;
5108
5109 switch (op) {
5110 case glslang::EOpAdd:
5111 case glslang::EOpAddAssign:
5112 if (isFloat)
5113 binOp = spv::OpFAdd;
5114 else
5115 binOp = spv::OpIAdd;
5116 break;
5117 case glslang::EOpSub:
5118 case glslang::EOpSubAssign:
5119 if (isFloat)
5120 binOp = spv::OpFSub;
5121 else
5122 binOp = spv::OpISub;
5123 break;
5124 case glslang::EOpMul:
5125 case glslang::EOpMulAssign:
5126 if (isFloat)
5127 binOp = spv::OpFMul;
5128 else
5129 binOp = spv::OpIMul;
5130 break;
5131 case glslang::EOpVectorTimesScalar:
5132 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005133 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005134 if (builder.isVector(right))
5135 std::swap(left, right);
5136 assert(builder.isScalar(right));
5137 needMatchingVectors = false;
5138 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005139 } else if (isFloat)
5140 binOp = spv::OpFMul;
5141 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005142 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005143 break;
5144 case glslang::EOpVectorTimesMatrix:
5145 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005146 binOp = spv::OpVectorTimesMatrix;
5147 break;
5148 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005149 binOp = spv::OpMatrixTimesVector;
5150 break;
5151 case glslang::EOpMatrixTimesScalar:
5152 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005153 binOp = spv::OpMatrixTimesScalar;
5154 break;
5155 case glslang::EOpMatrixTimesMatrix:
5156 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005157 binOp = spv::OpMatrixTimesMatrix;
5158 break;
5159 case glslang::EOpOuterProduct:
5160 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005161 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005162 break;
5163
5164 case glslang::EOpDiv:
5165 case glslang::EOpDivAssign:
5166 if (isFloat)
5167 binOp = spv::OpFDiv;
5168 else if (isUnsigned)
5169 binOp = spv::OpUDiv;
5170 else
5171 binOp = spv::OpSDiv;
5172 break;
5173 case glslang::EOpMod:
5174 case glslang::EOpModAssign:
5175 if (isFloat)
5176 binOp = spv::OpFMod;
5177 else if (isUnsigned)
5178 binOp = spv::OpUMod;
5179 else
5180 binOp = spv::OpSMod;
5181 break;
5182 case glslang::EOpRightShift:
5183 case glslang::EOpRightShiftAssign:
5184 if (isUnsigned)
5185 binOp = spv::OpShiftRightLogical;
5186 else
5187 binOp = spv::OpShiftRightArithmetic;
5188 break;
5189 case glslang::EOpLeftShift:
5190 case glslang::EOpLeftShiftAssign:
5191 binOp = spv::OpShiftLeftLogical;
5192 break;
5193 case glslang::EOpAnd:
5194 case glslang::EOpAndAssign:
5195 binOp = spv::OpBitwiseAnd;
5196 break;
5197 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005198 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005199 binOp = spv::OpLogicalAnd;
5200 break;
5201 case glslang::EOpInclusiveOr:
5202 case glslang::EOpInclusiveOrAssign:
5203 binOp = spv::OpBitwiseOr;
5204 break;
5205 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005206 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005207 binOp = spv::OpLogicalOr;
5208 break;
5209 case glslang::EOpExclusiveOr:
5210 case glslang::EOpExclusiveOrAssign:
5211 binOp = spv::OpBitwiseXor;
5212 break;
5213 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005214 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005215 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005216 break;
5217
5218 case glslang::EOpLessThan:
5219 case glslang::EOpGreaterThan:
5220 case glslang::EOpLessThanEqual:
5221 case glslang::EOpGreaterThanEqual:
5222 case glslang::EOpEqual:
5223 case glslang::EOpNotEqual:
5224 case glslang::EOpVectorEqual:
5225 case glslang::EOpVectorNotEqual:
5226 comparison = true;
5227 break;
5228 default:
5229 break;
5230 }
5231
John Kessenich7c1aa102015-10-15 13:29:11 -06005232 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005233 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005234 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005235 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5236 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005237 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005238
5239 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005240 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005241 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005242
qining25262b32016-05-06 17:25:16 -04005243 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005244 decorations.addNoContraction(builder, result);
5245 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005246 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005247 }
5248
5249 if (! comparison)
5250 return 0;
5251
John Kessenich7c1aa102015-10-15 13:29:11 -06005252 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005253
John Kessenich4583b612016-08-07 19:14:22 -06005254 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005255 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5256 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenichb9197c82019-08-11 07:41:45 -06005257 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005258 return result;
5259 }
John Kessenich140f3df2015-06-26 16:58:36 -06005260
5261 switch (op) {
5262 case glslang::EOpLessThan:
5263 if (isFloat)
5264 binOp = spv::OpFOrdLessThan;
5265 else if (isUnsigned)
5266 binOp = spv::OpULessThan;
5267 else
5268 binOp = spv::OpSLessThan;
5269 break;
5270 case glslang::EOpGreaterThan:
5271 if (isFloat)
5272 binOp = spv::OpFOrdGreaterThan;
5273 else if (isUnsigned)
5274 binOp = spv::OpUGreaterThan;
5275 else
5276 binOp = spv::OpSGreaterThan;
5277 break;
5278 case glslang::EOpLessThanEqual:
5279 if (isFloat)
5280 binOp = spv::OpFOrdLessThanEqual;
5281 else if (isUnsigned)
5282 binOp = spv::OpULessThanEqual;
5283 else
5284 binOp = spv::OpSLessThanEqual;
5285 break;
5286 case glslang::EOpGreaterThanEqual:
5287 if (isFloat)
5288 binOp = spv::OpFOrdGreaterThanEqual;
5289 else if (isUnsigned)
5290 binOp = spv::OpUGreaterThanEqual;
5291 else
5292 binOp = spv::OpSGreaterThanEqual;
5293 break;
5294 case glslang::EOpEqual:
5295 case glslang::EOpVectorEqual:
5296 if (isFloat)
5297 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005298 else if (isBool)
5299 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005300 else
5301 binOp = spv::OpIEqual;
5302 break;
5303 case glslang::EOpNotEqual:
5304 case glslang::EOpVectorNotEqual:
5305 if (isFloat)
5306 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005307 else if (isBool)
5308 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005309 else
5310 binOp = spv::OpINotEqual;
5311 break;
5312 default:
5313 break;
5314 }
5315
qining25262b32016-05-06 17:25:16 -04005316 if (binOp != spv::OpNop) {
5317 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005318 decorations.addNoContraction(builder, result);
5319 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005320 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005321 }
John Kessenich140f3df2015-06-26 16:58:36 -06005322
5323 return 0;
5324}
5325
John Kessenich04bb8a02015-12-12 12:28:14 -07005326//
5327// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5328// These can be any of:
5329//
5330// matrix * scalar
5331// scalar * matrix
5332// matrix * matrix linear algebraic
5333// matrix * vector
5334// vector * matrix
5335// matrix * matrix componentwise
5336// matrix op matrix op in {+, -, /}
5337// matrix op scalar op in {+, -, /}
5338// scalar op matrix op in {+, -, /}
5339//
John Kessenichead86222018-03-28 18:01:20 -06005340spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5341 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005342{
5343 bool firstClass = true;
5344
5345 // First, handle first-class matrix operations (* and matrix/scalar)
5346 switch (op) {
5347 case spv::OpFDiv:
5348 if (builder.isMatrix(left) && builder.isScalar(right)) {
5349 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005350 spv::Id resultType = builder.getTypeId(right);
5351 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005352 op = spv::OpMatrixTimesScalar;
5353 } else
5354 firstClass = false;
5355 break;
5356 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005357 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005358 std::swap(left, right);
5359 assert(builder.isScalar(right));
5360 break;
5361 case spv::OpVectorTimesMatrix:
5362 assert(builder.isVector(left));
5363 assert(builder.isMatrix(right));
5364 break;
5365 case spv::OpMatrixTimesVector:
5366 assert(builder.isMatrix(left));
5367 assert(builder.isVector(right));
5368 break;
5369 case spv::OpMatrixTimesMatrix:
5370 assert(builder.isMatrix(left));
5371 assert(builder.isMatrix(right));
5372 break;
5373 default:
5374 firstClass = false;
5375 break;
5376 }
5377
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005378 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5379 firstClass = true;
5380
qining25262b32016-05-06 17:25:16 -04005381 if (firstClass) {
5382 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005383 decorations.addNoContraction(builder, result);
5384 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005385 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005386 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005387
LoopDawg592860c2016-06-09 08:57:35 -06005388 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005389 // The result type of all of them is the same type as the (a) matrix operand.
5390 // The algorithm is to:
5391 // - break the matrix(es) into vectors
5392 // - smear any scalar to a vector
5393 // - do vector operations
5394 // - make a matrix out the vector results
5395 switch (op) {
5396 case spv::OpFAdd:
5397 case spv::OpFSub:
5398 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005399 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005400 case spv::OpFMul:
5401 {
5402 // one time set up...
5403 bool leftMat = builder.isMatrix(left);
5404 bool rightMat = builder.isMatrix(right);
5405 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5406 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5407 spv::Id scalarType = builder.getScalarTypeId(typeId);
5408 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5409 std::vector<spv::Id> results;
5410 spv::Id smearVec = spv::NoResult;
5411 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005412 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005413 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005414 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005415
5416 // do each vector op
5417 for (unsigned int c = 0; c < numCols; ++c) {
5418 std::vector<unsigned int> indexes;
5419 indexes.push_back(c);
5420 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5421 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005422 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005423 decorations.addNoContraction(builder, result);
5424 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005425 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005426 }
5427
5428 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005429 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005430 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005431 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005432 }
5433 default:
5434 assert(0);
5435 return spv::NoResult;
5436 }
5437}
5438
John Kessenichead86222018-03-28 18:01:20 -06005439spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005440 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005441{
5442 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005443 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005444 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005445 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5446 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005447
5448 switch (op) {
5449 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005450 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005451 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005452 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005453 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005454 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005455 unaryOp = spv::OpSNegate;
5456 break;
5457
5458 case glslang::EOpLogicalNot:
5459 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005460 unaryOp = spv::OpLogicalNot;
5461 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005462 case glslang::EOpBitwiseNot:
5463 unaryOp = spv::OpNot;
5464 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005465
John Kessenich140f3df2015-06-26 16:58:36 -06005466 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005467 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005468 break;
5469 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005470 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005471 break;
5472 case glslang::EOpTranspose:
5473 unaryOp = spv::OpTranspose;
5474 break;
5475
5476 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005477 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005478 break;
5479 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005480 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005481 break;
5482 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005483 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005484 break;
5485 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005486 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005487 break;
5488 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005489 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005490 break;
5491 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005492 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005493 break;
5494 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005495 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005496 break;
5497 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005498 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005499 break;
5500
5501 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005502 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005503 break;
5504 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005505 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005506 break;
5507 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005508 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005509 break;
5510 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005511 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005512 break;
5513 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005514 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005515 break;
5516 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005517 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005518 break;
5519
5520 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005521 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005522 break;
5523 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005524 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005525 break;
5526
5527 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005528 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005529 break;
5530 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005531 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005532 break;
5533 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005534 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005535 break;
5536 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005537 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005538 break;
5539 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005540 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005541 break;
5542 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005543 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005544 break;
5545
5546 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005547 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005548 break;
5549 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005550 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005551 break;
5552 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005553 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005554 break;
5555 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005556 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005557 break;
5558 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005559 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005560 break;
5561 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005562 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005563 break;
5564
5565 case glslang::EOpIsNan:
5566 unaryOp = spv::OpIsNan;
5567 break;
5568 case glslang::EOpIsInf:
5569 unaryOp = spv::OpIsInf;
5570 break;
LoopDawg592860c2016-06-09 08:57:35 -06005571 case glslang::EOpIsFinite:
5572 unaryOp = spv::OpIsFinite;
5573 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005574
Rex Xucbc426e2015-12-15 16:03:10 +08005575 case glslang::EOpFloatBitsToInt:
5576 case glslang::EOpFloatBitsToUint:
5577 case glslang::EOpIntBitsToFloat:
5578 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005579 case glslang::EOpDoubleBitsToInt64:
5580 case glslang::EOpDoubleBitsToUint64:
5581 case glslang::EOpInt64BitsToDouble:
5582 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005583 case glslang::EOpFloat16BitsToInt16:
5584 case glslang::EOpFloat16BitsToUint16:
5585 case glslang::EOpInt16BitsToFloat16:
5586 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005587 unaryOp = spv::OpBitcast;
5588 break;
5589
John Kessenich140f3df2015-06-26 16:58:36 -06005590 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005591 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005592 break;
5593 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005594 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005595 break;
5596 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005597 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005598 break;
5599 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005600 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005601 break;
5602 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005603 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005604 break;
5605 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005606 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005607 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005608#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06005609 case glslang::EOpPackSnorm4x8:
5610 libCall = spv::GLSLstd450PackSnorm4x8;
5611 break;
5612 case glslang::EOpUnpackSnorm4x8:
5613 libCall = spv::GLSLstd450UnpackSnorm4x8;
5614 break;
5615 case glslang::EOpPackUnorm4x8:
5616 libCall = spv::GLSLstd450PackUnorm4x8;
5617 break;
5618 case glslang::EOpUnpackUnorm4x8:
5619 libCall = spv::GLSLstd450UnpackUnorm4x8;
5620 break;
5621 case glslang::EOpPackDouble2x32:
5622 libCall = spv::GLSLstd450PackDouble2x32;
5623 break;
5624 case glslang::EOpUnpackDouble2x32:
5625 libCall = spv::GLSLstd450UnpackDouble2x32;
5626 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005627#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005628
Rex Xu8ff43de2016-04-22 16:51:45 +08005629 case glslang::EOpPackInt2x32:
5630 case glslang::EOpUnpackInt2x32:
5631 case glslang::EOpPackUint2x32:
5632 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005633 case glslang::EOpPack16:
5634 case glslang::EOpPack32:
5635 case glslang::EOpPack64:
5636 case glslang::EOpUnpack32:
5637 case glslang::EOpUnpack16:
5638 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005639 case glslang::EOpPackInt2x16:
5640 case glslang::EOpUnpackInt2x16:
5641 case glslang::EOpPackUint2x16:
5642 case glslang::EOpUnpackUint2x16:
5643 case glslang::EOpPackInt4x16:
5644 case glslang::EOpUnpackInt4x16:
5645 case glslang::EOpPackUint4x16:
5646 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005647 case glslang::EOpPackFloat2x16:
5648 case glslang::EOpUnpackFloat2x16:
5649 unaryOp = spv::OpBitcast;
5650 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005651
John Kessenich140f3df2015-06-26 16:58:36 -06005652 case glslang::EOpDPdx:
5653 unaryOp = spv::OpDPdx;
5654 break;
5655 case glslang::EOpDPdy:
5656 unaryOp = spv::OpDPdy;
5657 break;
5658 case glslang::EOpFwidth:
5659 unaryOp = spv::OpFwidth;
5660 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005661
John Kessenich140f3df2015-06-26 16:58:36 -06005662 case glslang::EOpAny:
5663 unaryOp = spv::OpAny;
5664 break;
5665 case glslang::EOpAll:
5666 unaryOp = spv::OpAll;
5667 break;
5668
5669 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005670 if (isFloat)
5671 libCall = spv::GLSLstd450FAbs;
5672 else
5673 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005674 break;
5675 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005676 if (isFloat)
5677 libCall = spv::GLSLstd450FSign;
5678 else
5679 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005680 break;
5681
John Kessenicha28f7a72019-08-06 07:00:58 -06005682#ifndef GLSLANG_WEB
5683 case glslang::EOpDPdxFine:
5684 unaryOp = spv::OpDPdxFine;
5685 break;
5686 case glslang::EOpDPdyFine:
5687 unaryOp = spv::OpDPdyFine;
5688 break;
5689 case glslang::EOpFwidthFine:
5690 unaryOp = spv::OpFwidthFine;
5691 break;
5692 case glslang::EOpDPdxCoarse:
5693 unaryOp = spv::OpDPdxCoarse;
5694 break;
5695 case glslang::EOpDPdyCoarse:
5696 unaryOp = spv::OpDPdyCoarse;
5697 break;
5698 case glslang::EOpFwidthCoarse:
5699 unaryOp = spv::OpFwidthCoarse;
5700 break;
5701 case glslang::EOpInterpolateAtCentroid:
5702 if (typeProxy == glslang::EbtFloat16)
5703 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5704 libCall = spv::GLSLstd450InterpolateAtCentroid;
5705 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005706 case glslang::EOpAtomicCounterIncrement:
5707 case glslang::EOpAtomicCounterDecrement:
5708 case glslang::EOpAtomicCounter:
5709 {
5710 // Handle all of the atomics in one place, in createAtomicOperation()
5711 std::vector<spv::Id> operands;
5712 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005713 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06005714 }
5715
John Kessenichfc51d282015-08-19 13:34:18 -06005716 case glslang::EOpBitFieldReverse:
5717 unaryOp = spv::OpBitReverse;
5718 break;
5719 case glslang::EOpBitCount:
5720 unaryOp = spv::OpBitCount;
5721 break;
5722 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005723 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005724 break;
5725 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005726 if (isUnsigned)
5727 libCall = spv::GLSLstd450FindUMsb;
5728 else
5729 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005730 break;
5731
Rex Xu574ab042016-04-14 16:53:07 +08005732 case glslang::EOpBallot:
5733 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005734 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005735 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005736 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005737 case glslang::EOpMinInvocations:
5738 case glslang::EOpMaxInvocations:
5739 case glslang::EOpAddInvocations:
5740 case glslang::EOpMinInvocationsNonUniform:
5741 case glslang::EOpMaxInvocationsNonUniform:
5742 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005743 case glslang::EOpMinInvocationsInclusiveScan:
5744 case glslang::EOpMaxInvocationsInclusiveScan:
5745 case glslang::EOpAddInvocationsInclusiveScan:
5746 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5747 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5748 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5749 case glslang::EOpMinInvocationsExclusiveScan:
5750 case glslang::EOpMaxInvocationsExclusiveScan:
5751 case glslang::EOpAddInvocationsExclusiveScan:
5752 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5753 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5754 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu51596642016-09-21 18:56:12 +08005755 {
5756 std::vector<spv::Id> operands;
5757 operands.push_back(operand);
5758 return createInvocationsOperation(op, typeId, operands, typeProxy);
5759 }
John Kessenich66011cb2018-03-06 16:12:04 -07005760 case glslang::EOpSubgroupAll:
5761 case glslang::EOpSubgroupAny:
5762 case glslang::EOpSubgroupAllEqual:
5763 case glslang::EOpSubgroupBroadcastFirst:
5764 case glslang::EOpSubgroupBallot:
5765 case glslang::EOpSubgroupInverseBallot:
5766 case glslang::EOpSubgroupBallotBitCount:
5767 case glslang::EOpSubgroupBallotInclusiveBitCount:
5768 case glslang::EOpSubgroupBallotExclusiveBitCount:
5769 case glslang::EOpSubgroupBallotFindLSB:
5770 case glslang::EOpSubgroupBallotFindMSB:
5771 case glslang::EOpSubgroupAdd:
5772 case glslang::EOpSubgroupMul:
5773 case glslang::EOpSubgroupMin:
5774 case glslang::EOpSubgroupMax:
5775 case glslang::EOpSubgroupAnd:
5776 case glslang::EOpSubgroupOr:
5777 case glslang::EOpSubgroupXor:
5778 case glslang::EOpSubgroupInclusiveAdd:
5779 case glslang::EOpSubgroupInclusiveMul:
5780 case glslang::EOpSubgroupInclusiveMin:
5781 case glslang::EOpSubgroupInclusiveMax:
5782 case glslang::EOpSubgroupInclusiveAnd:
5783 case glslang::EOpSubgroupInclusiveOr:
5784 case glslang::EOpSubgroupInclusiveXor:
5785 case glslang::EOpSubgroupExclusiveAdd:
5786 case glslang::EOpSubgroupExclusiveMul:
5787 case glslang::EOpSubgroupExclusiveMin:
5788 case glslang::EOpSubgroupExclusiveMax:
5789 case glslang::EOpSubgroupExclusiveAnd:
5790 case glslang::EOpSubgroupExclusiveOr:
5791 case glslang::EOpSubgroupExclusiveXor:
5792 case glslang::EOpSubgroupQuadSwapHorizontal:
5793 case glslang::EOpSubgroupQuadSwapVertical:
5794 case glslang::EOpSubgroupQuadSwapDiagonal: {
5795 std::vector<spv::Id> operands;
5796 operands.push_back(operand);
5797 return createSubgroupOperation(op, typeId, operands, typeProxy);
5798 }
Rex Xu9d93a232016-05-05 12:30:44 +08005799 case glslang::EOpMbcnt:
5800 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5801 libCall = spv::MbcntAMD;
5802 break;
5803
5804 case glslang::EOpCubeFaceIndex:
5805 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5806 libCall = spv::CubeFaceIndexAMD;
5807 break;
5808
5809 case glslang::EOpCubeFaceCoord:
5810 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5811 libCall = spv::CubeFaceCoordAMD;
5812 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005813 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005814 unaryOp = spv::OpGroupNonUniformPartitionNV;
5815 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005816 case glslang::EOpConstructReference:
5817 unaryOp = spv::OpBitcast;
5818 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005819#endif
Jeff Bolz88220d52019-05-08 10:24:46 -05005820
5821 case glslang::EOpCopyObject:
5822 unaryOp = spv::OpCopyObject;
5823 break;
5824
John Kessenich140f3df2015-06-26 16:58:36 -06005825 default:
5826 return 0;
5827 }
5828
5829 spv::Id id;
5830 if (libCall >= 0) {
5831 std::vector<spv::Id> args;
5832 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005833 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005834 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005835 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005836 }
John Kessenich140f3df2015-06-26 16:58:36 -06005837
John Kessenichb9197c82019-08-11 07:41:45 -06005838 decorations.addNoContraction(builder, id);
5839 decorations.addNonUniform(builder, id);
John Kessenichead86222018-03-28 18:01:20 -06005840 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005841}
5842
John Kessenich7a53f762016-01-20 11:19:27 -07005843// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005844spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5845 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005846{
5847 // Handle unary operations vector by vector.
5848 // The result type is the same type as the original type.
5849 // The algorithm is to:
5850 // - break the matrix into vectors
5851 // - apply the operation to each vector
5852 // - make a matrix out the vector results
5853
5854 // get the types sorted out
5855 int numCols = builder.getNumColumns(operand);
5856 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005857 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5858 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005859 std::vector<spv::Id> results;
5860
5861 // do each vector op
5862 for (int c = 0; c < numCols; ++c) {
5863 std::vector<unsigned int> indexes;
5864 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005865 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5866 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005867 decorations.addNoContraction(builder, destVec);
5868 decorations.addNonUniform(builder, destVec);
John Kessenichead86222018-03-28 18:01:20 -06005869 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005870 }
5871
5872 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005873 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005874 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005875 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005876}
5877
John Kessenichad7645f2018-06-04 19:11:25 -06005878// For converting integers where both the bitwidth and the signedness could
5879// change, but only do the width change here. The caller is still responsible
5880// for the signedness conversion.
5881spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005882{
John Kessenichad7645f2018-06-04 19:11:25 -06005883 // Get the result type width, based on the type to convert to.
5884 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005885 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005886 case glslang::EOpConvInt16ToUint8:
5887 case glslang::EOpConvIntToUint8:
5888 case glslang::EOpConvInt64ToUint8:
5889 case glslang::EOpConvUint16ToInt8:
5890 case glslang::EOpConvUintToInt8:
5891 case glslang::EOpConvUint64ToInt8:
5892 width = 8;
5893 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005894 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005895 case glslang::EOpConvIntToUint16:
5896 case glslang::EOpConvInt64ToUint16:
5897 case glslang::EOpConvUint8ToInt16:
5898 case glslang::EOpConvUintToInt16:
5899 case glslang::EOpConvUint64ToInt16:
5900 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005901 break;
5902 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005903 case glslang::EOpConvInt16ToUint:
5904 case glslang::EOpConvInt64ToUint:
5905 case glslang::EOpConvUint8ToInt:
5906 case glslang::EOpConvUint16ToInt:
5907 case glslang::EOpConvUint64ToInt:
5908 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005909 break;
5910 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005911 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005912 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005913 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005914 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005915 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005916 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005917 break;
5918
5919 default:
5920 assert(false && "Default missing");
5921 break;
5922 }
5923
John Kessenichad7645f2018-06-04 19:11:25 -06005924 // Get the conversion operation and result type,
5925 // based on the target width, but the source type.
5926 spv::Id type = spv::NoType;
5927 spv::Op convOp = spv::OpNop;
5928 switch(op) {
5929 case glslang::EOpConvInt8ToUint16:
5930 case glslang::EOpConvInt8ToUint:
5931 case glslang::EOpConvInt8ToUint64:
5932 case glslang::EOpConvInt16ToUint8:
5933 case glslang::EOpConvInt16ToUint:
5934 case glslang::EOpConvInt16ToUint64:
5935 case glslang::EOpConvIntToUint8:
5936 case glslang::EOpConvIntToUint16:
5937 case glslang::EOpConvIntToUint64:
5938 case glslang::EOpConvInt64ToUint8:
5939 case glslang::EOpConvInt64ToUint16:
5940 case glslang::EOpConvInt64ToUint:
5941 convOp = spv::OpSConvert;
5942 type = builder.makeIntType(width);
5943 break;
5944 default:
5945 convOp = spv::OpUConvert;
5946 type = builder.makeUintType(width);
5947 break;
5948 }
5949
John Kessenich66011cb2018-03-06 16:12:04 -07005950 if (vectorSize > 0)
5951 type = builder.makeVectorType(type, vectorSize);
5952
John Kessenichad7645f2018-06-04 19:11:25 -06005953 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005954}
5955
John Kessenichead86222018-03-28 18:01:20 -06005956spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5957 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005958{
5959 spv::Op convOp = spv::OpNop;
5960 spv::Id zero = 0;
5961 spv::Id one = 0;
5962
5963 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5964
5965 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005966 case glslang::EOpConvIntToBool:
5967 case glslang::EOpConvUintToBool:
5968 zero = builder.makeUintConstant(0);
5969 zero = makeSmearedConstant(zero, vectorSize);
5970 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06005971 case glslang::EOpConvFloatToBool:
5972 zero = builder.makeFloatConstant(0.0F);
5973 zero = makeSmearedConstant(zero, vectorSize);
5974 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06005975 case glslang::EOpConvBoolToFloat:
5976 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005977 zero = builder.makeFloatConstant(0.0F);
5978 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06005979 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005980
John Kessenich140f3df2015-06-26 16:58:36 -06005981 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005982 case glslang::EOpConvBoolToInt64:
John Kessenichb9197c82019-08-11 07:41:45 -06005983#ifndef GLSLANG_WEB
5984 if (op == glslang::EOpConvBoolToInt64) {
Rex Xucabbb782017-03-24 13:41:14 +08005985 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005986 one = builder.makeInt64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06005987 } else
5988#endif
5989 {
5990 zero = builder.makeIntConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005991 one = builder.makeIntConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06005992 }
Rex Xucabbb782017-03-24 13:41:14 +08005993
John Kessenich140f3df2015-06-26 16:58:36 -06005994 convOp = spv::OpSelect;
5995 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005996
John Kessenich140f3df2015-06-26 16:58:36 -06005997 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005998 case glslang::EOpConvBoolToUint64:
John Kessenichb9197c82019-08-11 07:41:45 -06005999#ifndef GLSLANG_WEB
6000 if (op == glslang::EOpConvBoolToUint64) {
Rex Xucabbb782017-03-24 13:41:14 +08006001 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006002 one = builder.makeUint64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006003 } else
6004#endif
6005 {
6006 zero = builder.makeUintConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006007 one = builder.makeUintConstant(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;
6012
John Kessenich66011cb2018-03-06 16:12:04 -07006013 case glslang::EOpConvInt8ToFloat16:
6014 case glslang::EOpConvInt8ToFloat:
6015 case glslang::EOpConvInt8ToDouble:
6016 case glslang::EOpConvInt16ToFloat16:
6017 case glslang::EOpConvInt16ToFloat:
6018 case glslang::EOpConvInt16ToDouble:
6019 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006020 case glslang::EOpConvIntToFloat:
6021 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006022 case glslang::EOpConvInt64ToFloat:
6023 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006024 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006025 convOp = spv::OpConvertSToF;
6026 break;
6027
John Kessenich66011cb2018-03-06 16:12:04 -07006028 case glslang::EOpConvUint8ToFloat16:
6029 case glslang::EOpConvUint8ToFloat:
6030 case glslang::EOpConvUint8ToDouble:
6031 case glslang::EOpConvUint16ToFloat16:
6032 case glslang::EOpConvUint16ToFloat:
6033 case glslang::EOpConvUint16ToDouble:
6034 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006035 case glslang::EOpConvUintToFloat:
6036 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006037 case glslang::EOpConvUint64ToFloat:
6038 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006039 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006040 convOp = spv::OpConvertUToF;
6041 break;
6042
John Kessenich66011cb2018-03-06 16:12:04 -07006043 case glslang::EOpConvFloat16ToInt8:
6044 case glslang::EOpConvFloatToInt8:
6045 case glslang::EOpConvDoubleToInt8:
6046 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006047 case glslang::EOpConvFloatToInt16:
6048 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006049 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006050 case glslang::EOpConvFloatToInt:
6051 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006052 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006053 case glslang::EOpConvFloatToInt64:
6054 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006055 convOp = spv::OpConvertFToS;
6056 break;
6057
John Kessenich66011cb2018-03-06 16:12:04 -07006058 case glslang::EOpConvUint8ToInt8:
6059 case glslang::EOpConvInt8ToUint8:
6060 case glslang::EOpConvUint16ToInt16:
6061 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006062 case glslang::EOpConvUintToInt:
6063 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006064 case glslang::EOpConvUint64ToInt64:
6065 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006066 if (builder.isInSpecConstCodeGenMode()) {
6067 // Build zero scalar or vector for OpIAdd.
John Kessenich39697cd2019-08-08 10:35:51 -06006068#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07006069 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6070 zero = builder.makeUint8Constant(0);
6071 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006072 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006073 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6074 zero = builder.makeUint64Constant(0);
John Kessenich39697cd2019-08-08 10:35:51 -06006075 } else
6076#endif
6077 {
Rex Xucabbb782017-03-24 13:41:14 +08006078 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006079 }
qining189b2032016-04-12 23:16:20 -04006080 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006081 // Use OpIAdd, instead of OpBitcast to do the conversion when
6082 // generating for OpSpecConstantOp instruction.
6083 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6084 }
6085 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006086 convOp = spv::OpBitcast;
6087 break;
6088
John Kessenich66011cb2018-03-06 16:12:04 -07006089 case glslang::EOpConvFloat16ToUint8:
6090 case glslang::EOpConvFloatToUint8:
6091 case glslang::EOpConvDoubleToUint8:
6092 case glslang::EOpConvFloat16ToUint16:
6093 case glslang::EOpConvFloatToUint16:
6094 case glslang::EOpConvDoubleToUint16:
6095 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006096 case glslang::EOpConvFloatToUint:
6097 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006098 case glslang::EOpConvFloatToUint64:
6099 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006100 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006101 convOp = spv::OpConvertFToU;
6102 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006103
John Kessenich39697cd2019-08-08 10:35:51 -06006104#ifndef GLSLANG_WEB
6105 case glslang::EOpConvInt8ToBool:
6106 case glslang::EOpConvUint8ToBool:
6107 zero = builder.makeUint8Constant(0);
6108 zero = makeSmearedConstant(zero, vectorSize);
6109 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6110 case glslang::EOpConvInt16ToBool:
6111 case glslang::EOpConvUint16ToBool:
6112 zero = builder.makeUint16Constant(0);
6113 zero = makeSmearedConstant(zero, vectorSize);
6114 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6115 case glslang::EOpConvInt64ToBool:
6116 case glslang::EOpConvUint64ToBool:
6117 zero = builder.makeUint64Constant(0);
6118 zero = makeSmearedConstant(zero, vectorSize);
6119 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6120 case glslang::EOpConvDoubleToBool:
6121 zero = builder.makeDoubleConstant(0.0);
6122 zero = makeSmearedConstant(zero, vectorSize);
6123 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6124 case glslang::EOpConvFloat16ToBool:
6125 zero = builder.makeFloat16Constant(0.0F);
6126 zero = makeSmearedConstant(zero, vectorSize);
6127 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6128 case glslang::EOpConvBoolToDouble:
6129 convOp = spv::OpSelect;
6130 zero = builder.makeDoubleConstant(0.0);
6131 one = builder.makeDoubleConstant(1.0);
6132 break;
6133 case glslang::EOpConvBoolToFloat16:
6134 convOp = spv::OpSelect;
6135 zero = builder.makeFloat16Constant(0.0F);
6136 one = builder.makeFloat16Constant(1.0F);
6137 break;
6138 case glslang::EOpConvBoolToInt8:
6139 zero = builder.makeInt8Constant(0);
6140 one = builder.makeInt8Constant(1);
6141 convOp = spv::OpSelect;
6142 break;
6143 case glslang::EOpConvBoolToUint8:
6144 zero = builder.makeUint8Constant(0);
6145 one = builder.makeUint8Constant(1);
6146 convOp = spv::OpSelect;
6147 break;
6148 case glslang::EOpConvBoolToInt16:
6149 zero = builder.makeInt16Constant(0);
6150 one = builder.makeInt16Constant(1);
6151 convOp = spv::OpSelect;
6152 break;
6153 case glslang::EOpConvBoolToUint16:
6154 zero = builder.makeUint16Constant(0);
6155 one = builder.makeUint16Constant(1);
6156 convOp = spv::OpSelect;
6157 break;
6158 case glslang::EOpConvDoubleToFloat:
6159 case glslang::EOpConvFloatToDouble:
6160 case glslang::EOpConvDoubleToFloat16:
6161 case glslang::EOpConvFloat16ToDouble:
6162 case glslang::EOpConvFloatToFloat16:
6163 case glslang::EOpConvFloat16ToFloat:
6164 convOp = spv::OpFConvert;
6165 if (builder.isMatrixType(destType))
6166 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
6167 break;
6168
John Kessenich66011cb2018-03-06 16:12:04 -07006169 case glslang::EOpConvInt8ToInt16:
6170 case glslang::EOpConvInt8ToInt:
6171 case glslang::EOpConvInt8ToInt64:
6172 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006173 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006174 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006175 case glslang::EOpConvIntToInt8:
6176 case glslang::EOpConvIntToInt16:
6177 case glslang::EOpConvIntToInt64:
6178 case glslang::EOpConvInt64ToInt8:
6179 case glslang::EOpConvInt64ToInt16:
6180 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006181 convOp = spv::OpSConvert;
6182 break;
6183
John Kessenich66011cb2018-03-06 16:12:04 -07006184 case glslang::EOpConvUint8ToUint16:
6185 case glslang::EOpConvUint8ToUint:
6186 case glslang::EOpConvUint8ToUint64:
6187 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006188 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006189 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006190 case glslang::EOpConvUintToUint8:
6191 case glslang::EOpConvUintToUint16:
6192 case glslang::EOpConvUintToUint64:
6193 case glslang::EOpConvUint64ToUint8:
6194 case glslang::EOpConvUint64ToUint16:
6195 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006196 convOp = spv::OpUConvert;
6197 break;
6198
John Kessenich66011cb2018-03-06 16:12:04 -07006199 case glslang::EOpConvInt8ToUint16:
6200 case glslang::EOpConvInt8ToUint:
6201 case glslang::EOpConvInt8ToUint64:
6202 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006203 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006204 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006205 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006206 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006207 case glslang::EOpConvIntToUint64:
6208 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006209 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006210 case glslang::EOpConvInt64ToUint:
6211 case glslang::EOpConvUint8ToInt16:
6212 case glslang::EOpConvUint8ToInt:
6213 case glslang::EOpConvUint8ToInt64:
6214 case glslang::EOpConvUint16ToInt8:
6215 case glslang::EOpConvUint16ToInt:
6216 case glslang::EOpConvUint16ToInt64:
6217 case glslang::EOpConvUintToInt8:
6218 case glslang::EOpConvUintToInt16:
6219 case glslang::EOpConvUintToInt64:
6220 case glslang::EOpConvUint64ToInt8:
6221 case glslang::EOpConvUint64ToInt16:
6222 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006223 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006224 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006225
6226 if (builder.isInSpecConstCodeGenMode()) {
6227 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006228 switch(op) {
6229 case glslang::EOpConvInt16ToUint8:
6230 case glslang::EOpConvIntToUint8:
6231 case glslang::EOpConvInt64ToUint8:
6232 case glslang::EOpConvUint16ToInt8:
6233 case glslang::EOpConvUintToInt8:
6234 case glslang::EOpConvUint64ToInt8:
6235 zero = builder.makeUint8Constant(0);
6236 break;
6237 case glslang::EOpConvInt8ToUint16:
6238 case glslang::EOpConvIntToUint16:
6239 case glslang::EOpConvInt64ToUint16:
6240 case glslang::EOpConvUint8ToInt16:
6241 case glslang::EOpConvUintToInt16:
6242 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006243 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006244 break;
6245 case glslang::EOpConvInt8ToUint:
6246 case glslang::EOpConvInt16ToUint:
6247 case glslang::EOpConvInt64ToUint:
6248 case glslang::EOpConvUint8ToInt:
6249 case glslang::EOpConvUint16ToInt:
6250 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006251 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006252 break;
6253 case glslang::EOpConvInt8ToUint64:
6254 case glslang::EOpConvInt16ToUint64:
6255 case glslang::EOpConvIntToUint64:
6256 case glslang::EOpConvUint8ToInt64:
6257 case glslang::EOpConvUint16ToInt64:
6258 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006259 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006260 break;
6261 default:
6262 assert(false && "Default missing");
6263 break;
6264 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006265 zero = makeSmearedConstant(zero, vectorSize);
6266 // Use OpIAdd, instead of OpBitcast to do the conversion when
6267 // generating for OpSpecConstantOp instruction.
6268 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6269 }
6270 // For normal run-time conversion instruction, use OpBitcast.
6271 convOp = spv::OpBitcast;
6272 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006273 case glslang::EOpConvUint64ToPtr:
6274 convOp = spv::OpConvertUToPtr;
6275 break;
6276 case glslang::EOpConvPtrToUint64:
6277 convOp = spv::OpConvertPtrToU;
6278 break;
John Kessenich90e402f2019-09-17 23:19:38 -06006279 case glslang::EOpConvPtrToUvec2:
6280 case glslang::EOpConvUvec2ToPtr:
John Kessenichee8e9c12019-10-10 20:54:21 -06006281 if (builder.isVector(operand))
6282 builder.promoteIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer,
6283 spv::E_SPV_KHR_physical_storage_buffer, spv::Spv_1_5);
John Kessenich90e402f2019-09-17 23:19:38 -06006284 convOp = spv::OpBitcast;
6285 break;
John Kessenich39697cd2019-08-08 10:35:51 -06006286#endif
6287
John Kessenich140f3df2015-06-26 16:58:36 -06006288 default:
6289 break;
6290 }
6291
6292 spv::Id result = 0;
6293 if (convOp == spv::OpNop)
6294 return result;
6295
6296 if (convOp == spv::OpSelect) {
6297 zero = makeSmearedConstant(zero, vectorSize);
6298 one = makeSmearedConstant(one, vectorSize);
6299 result = builder.createTriOp(convOp, destType, operand, one, zero);
6300 } else
6301 result = builder.createUnaryOp(convOp, destType, operand);
6302
John Kessenichead86222018-03-28 18:01:20 -06006303 result = builder.setPrecision(result, decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006304 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006305 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006306}
6307
6308spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6309{
6310 if (vectorSize == 0)
6311 return constant;
6312
6313 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6314 std::vector<spv::Id> components;
6315 for (int c = 0; c < vectorSize; ++c)
6316 components.push_back(constant);
6317 return builder.makeCompositeConstant(vectorTypeId, components);
6318}
6319
John Kessenich426394d2015-07-23 10:22:48 -06006320// For glslang ops that map to SPV atomic opCodes
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006321spv::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 -06006322{
6323 spv::Op opCode = spv::OpNop;
6324
6325 switch (op) {
6326 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006327 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006328 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006329 opCode = spv::OpAtomicIAdd;
6330 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006331 case glslang::EOpAtomicCounterSubtract:
6332 opCode = spv::OpAtomicISub;
6333 break;
John Kessenich426394d2015-07-23 10:22:48 -06006334 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006335 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006336 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08006337 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006338 break;
6339 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006340 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006341 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08006342 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006343 break;
6344 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006345 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006346 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006347 opCode = spv::OpAtomicAnd;
6348 break;
6349 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006350 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006351 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006352 opCode = spv::OpAtomicOr;
6353 break;
6354 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006355 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006356 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006357 opCode = spv::OpAtomicXor;
6358 break;
6359 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006360 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006361 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006362 opCode = spv::OpAtomicExchange;
6363 break;
6364 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006365 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006366 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006367 opCode = spv::OpAtomicCompareExchange;
6368 break;
6369 case glslang::EOpAtomicCounterIncrement:
6370 opCode = spv::OpAtomicIIncrement;
6371 break;
6372 case glslang::EOpAtomicCounterDecrement:
6373 opCode = spv::OpAtomicIDecrement;
6374 break;
6375 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006376 case glslang::EOpImageAtomicLoad:
6377 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006378 opCode = spv::OpAtomicLoad;
6379 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006380 case glslang::EOpAtomicStore:
6381 case glslang::EOpImageAtomicStore:
6382 opCode = spv::OpAtomicStore;
6383 break;
John Kessenich426394d2015-07-23 10:22:48 -06006384 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006385 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006386 break;
6387 }
6388
Rex Xue8fe8b02017-09-26 15:42:56 +08006389 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6390 builder.addCapability(spv::CapabilityInt64Atomics);
6391
John Kessenich426394d2015-07-23 10:22:48 -06006392 // Sort out the operands
6393 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006394 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006395 // - compare-exchange swaps the value and comparator
6396 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006397 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006398 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6399 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6400 spv::Id scopeId;
6401 if (glslangIntermediate->usingVulkanMemoryModel()) {
6402 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6403 } else {
6404 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6405 }
6406 // semantics default to relaxed
Jeff Bolz016ddee2019-10-17 11:22:57 -05006407 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.isVolatile() && glslangIntermediate->usingVulkanMemoryModel() ?
John Kessenichb9197c82019-08-11 07:41:45 -06006408 spv::MemorySemanticsVolatileMask :
6409 spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006410 spv::Id semanticsId2 = semanticsId;
6411
6412 pointerId = operands[0];
6413 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6414 // no additional operands
6415 } else if (opCode == spv::OpAtomicCompareExchange) {
6416 compareId = operands[1];
6417 valueId = operands[2];
6418 if (operands.size() > 3) {
6419 scopeId = operands[3];
6420 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6421 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
6422 }
6423 } else if (opCode == spv::OpAtomicLoad) {
6424 if (operands.size() > 1) {
6425 scopeId = operands[1];
6426 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
6427 }
6428 } else {
6429 // atomic store or RMW
6430 valueId = operands[1];
6431 if (operands.size() > 2) {
6432 scopeId = operands[2];
6433 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
6434 }
Rex Xu04db3f52015-09-16 11:44:02 +08006435 }
John Kessenich426394d2015-07-23 10:22:48 -06006436
Jeff Bolz36831c92018-09-05 10:11:41 -05006437 // Check for capabilities
6438 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006439 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6440 spv::MemorySemanticsMakeVisibleKHRMask |
6441 spv::MemorySemanticsOutputMemoryKHRMask |
6442 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006443 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6444 }
John Kessenich426394d2015-07-23 10:22:48 -06006445
Jeff Bolz36831c92018-09-05 10:11:41 -05006446 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6447 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6448 }
John Kessenich48d6e792017-10-06 21:21:48 -06006449
Jeff Bolz36831c92018-09-05 10:11:41 -05006450 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6451 spvAtomicOperands.push_back(pointerId);
6452 spvAtomicOperands.push_back(scopeId);
6453 spvAtomicOperands.push_back(semanticsId);
6454 if (opCode == spv::OpAtomicCompareExchange) {
6455 spvAtomicOperands.push_back(semanticsId2);
6456 spvAtomicOperands.push_back(valueId);
6457 spvAtomicOperands.push_back(compareId);
6458 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6459 spvAtomicOperands.push_back(valueId);
6460 }
John Kessenich48d6e792017-10-06 21:21:48 -06006461
Jeff Bolz36831c92018-09-05 10:11:41 -05006462 if (opCode == spv::OpAtomicStore) {
6463 builder.createNoResultOp(opCode, spvAtomicOperands);
6464 return 0;
6465 } else {
6466 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6467
6468 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6469 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6470 if (op == glslang::EOpAtomicCounterDecrement)
6471 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6472
6473 return resultId;
6474 }
John Kessenich426394d2015-07-23 10:22:48 -06006475}
6476
John Kessenich91cef522016-05-05 16:45:40 -06006477// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08006478spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006479{
John Kessenich66011cb2018-03-06 16:12:04 -07006480 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6481 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08006482
Rex Xu51596642016-09-21 18:56:12 +08006483 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006484 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006485 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6486
chaocf200da82016-12-20 12:44:35 -08006487 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6488 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006489 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6490 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006491 } else if (op == glslang::EOpAnyInvocation ||
6492 op == glslang::EOpAllInvocations ||
6493 op == glslang::EOpAllInvocationsEqual) {
6494 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6495 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006496 } else {
6497 builder.addCapability(spv::CapabilityGroups);
Rex Xu17ff3432016-10-14 17:41:45 +08006498 if (op == glslang::EOpMinInvocationsNonUniform ||
6499 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006500 op == glslang::EOpAddInvocationsNonUniform ||
6501 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6502 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6503 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6504 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6505 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6506 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006507 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +08006508
Rex Xu430ef402016-10-14 17:22:23 +08006509 switch (op) {
6510 case glslang::EOpMinInvocations:
6511 case glslang::EOpMaxInvocations:
6512 case glslang::EOpAddInvocations:
6513 case glslang::EOpMinInvocationsNonUniform:
6514 case glslang::EOpMaxInvocationsNonUniform:
6515 case glslang::EOpAddInvocationsNonUniform:
6516 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006517 break;
6518 case glslang::EOpMinInvocationsInclusiveScan:
6519 case glslang::EOpMaxInvocationsInclusiveScan:
6520 case glslang::EOpAddInvocationsInclusiveScan:
6521 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6522 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6523 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6524 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006525 break;
6526 case glslang::EOpMinInvocationsExclusiveScan:
6527 case glslang::EOpMaxInvocationsExclusiveScan:
6528 case glslang::EOpAddInvocationsExclusiveScan:
6529 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6530 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6531 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6532 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006533 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006534 default:
6535 break;
Rex Xu430ef402016-10-14 17:22:23 +08006536 }
John Kessenich149afc32018-08-14 13:31:43 -06006537 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6538 spvGroupOperands.push_back(scope);
6539 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006540 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006541 spvGroupOperands.push_back(groupOp);
6542 }
Rex Xu51596642016-09-21 18:56:12 +08006543 }
6544
John Kessenich149afc32018-08-14 13:31:43 -06006545 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6546 spv::IdImmediate op = { true, *opIt };
6547 spvGroupOperands.push_back(op);
6548 }
John Kessenich91cef522016-05-05 16:45:40 -06006549
6550 switch (op) {
6551 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006552 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006553 break;
John Kessenich91cef522016-05-05 16:45:40 -06006554 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006555 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006556 break;
John Kessenich91cef522016-05-05 16:45:40 -06006557 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006558 opCode = spv::OpSubgroupAllEqualKHR;
6559 break;
Rex Xu51596642016-09-21 18:56:12 +08006560 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006561 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006562 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006563 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006564 break;
6565 case glslang::EOpReadFirstInvocation:
6566 opCode = spv::OpSubgroupFirstInvocationKHR;
6567 break;
6568 case glslang::EOpBallot:
6569 {
6570 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6571 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6572 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6573 //
6574 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6575 //
6576 spv::Id uintType = builder.makeUintType(32);
6577 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6578 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6579
6580 std::vector<spv::Id> components;
6581 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6582 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6583
6584 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6585 return builder.createUnaryOp(spv::OpBitcast, typeId,
6586 builder.createCompositeConstruct(uvec2Type, components));
6587 }
6588
Rex Xu9d93a232016-05-05 12:30:44 +08006589 case glslang::EOpMinInvocations:
6590 case glslang::EOpMaxInvocations:
6591 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006592 case glslang::EOpMinInvocationsInclusiveScan:
6593 case glslang::EOpMaxInvocationsInclusiveScan:
6594 case glslang::EOpAddInvocationsInclusiveScan:
6595 case glslang::EOpMinInvocationsExclusiveScan:
6596 case glslang::EOpMaxInvocationsExclusiveScan:
6597 case glslang::EOpAddInvocationsExclusiveScan:
6598 if (op == glslang::EOpMinInvocations ||
6599 op == glslang::EOpMinInvocationsInclusiveScan ||
6600 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006601 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006602 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006603 else {
6604 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006605 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006606 else
Rex Xu51596642016-09-21 18:56:12 +08006607 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006608 }
Rex Xu430ef402016-10-14 17:22:23 +08006609 } else if (op == glslang::EOpMaxInvocations ||
6610 op == glslang::EOpMaxInvocationsInclusiveScan ||
6611 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006612 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006613 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006614 else {
6615 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006616 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006617 else
Rex Xu51596642016-09-21 18:56:12 +08006618 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006619 }
6620 } else {
6621 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006622 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006623 else
Rex Xu51596642016-09-21 18:56:12 +08006624 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006625 }
6626
Rex Xu2bbbe062016-08-23 15:41:05 +08006627 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006628 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006629
6630 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006631 case glslang::EOpMinInvocationsNonUniform:
6632 case glslang::EOpMaxInvocationsNonUniform:
6633 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006634 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6635 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6636 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6637 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6638 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6639 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6640 if (op == glslang::EOpMinInvocationsNonUniform ||
6641 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6642 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006643 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006644 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006645 else {
6646 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006647 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006648 else
Rex Xu51596642016-09-21 18:56:12 +08006649 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006650 }
6651 }
Rex Xu430ef402016-10-14 17:22:23 +08006652 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6653 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6654 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006655 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006656 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006657 else {
6658 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006659 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006660 else
Rex Xu51596642016-09-21 18:56:12 +08006661 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006662 }
6663 }
6664 else {
6665 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006666 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006667 else
Rex Xu51596642016-09-21 18:56:12 +08006668 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006669 }
6670
Rex Xu2bbbe062016-08-23 15:41:05 +08006671 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006672 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006673
6674 break;
John Kessenich91cef522016-05-05 16:45:40 -06006675 default:
6676 logger->missingFunctionality("invocation operation");
6677 return spv::NoResult;
6678 }
Rex Xu51596642016-09-21 18:56:12 +08006679
6680 assert(opCode != spv::OpNop);
6681 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006682}
6683
Rex Xu2bbbe062016-08-23 15:41:05 +08006684// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006685spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6686 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006687{
6688 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6689 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006690 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006691 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006692 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
6693 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
6694 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
6695
6696 // Handle group invocation operations scalar by scalar.
6697 // The result type is the same type as the original type.
6698 // The algorithm is to:
6699 // - break the vector into scalars
6700 // - apply the operation to each scalar
6701 // - make a vector out the scalar results
6702
6703 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006704 int numComponents = builder.getNumComponents(operands[0]);
6705 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006706 std::vector<spv::Id> results;
6707
6708 // do each scalar op
6709 for (int comp = 0; comp < numComponents; ++comp) {
6710 std::vector<unsigned int> indexes;
6711 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006712 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6713 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006714 if (op == spv::OpSubgroupReadInvocationKHR) {
6715 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006716 spv::IdImmediate operand = { true, operands[1] };
6717 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006718 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006719 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6720 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006721 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006722 spv::IdImmediate operand = { true, operands[1] };
6723 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006724 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006725 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6726 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006727 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006728 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006729 spvGroupOperands.push_back(scalar);
6730 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006731
Rex Xub7072052016-09-26 15:53:40 +08006732 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006733 }
6734
6735 // put the pieces together
6736 return builder.createCompositeConstruct(typeId, results);
6737}
Rex Xu2bbbe062016-08-23 15:41:05 +08006738
John Kessenich66011cb2018-03-06 16:12:04 -07006739// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006740spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6741 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006742{
6743 // Add the required capabilities.
6744 switch (op) {
6745 case glslang::EOpSubgroupElect:
6746 builder.addCapability(spv::CapabilityGroupNonUniform);
6747 break;
6748 case glslang::EOpSubgroupAll:
6749 case glslang::EOpSubgroupAny:
6750 case glslang::EOpSubgroupAllEqual:
6751 builder.addCapability(spv::CapabilityGroupNonUniform);
6752 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6753 break;
6754 case glslang::EOpSubgroupBroadcast:
6755 case glslang::EOpSubgroupBroadcastFirst:
6756 case glslang::EOpSubgroupBallot:
6757 case glslang::EOpSubgroupInverseBallot:
6758 case glslang::EOpSubgroupBallotBitExtract:
6759 case glslang::EOpSubgroupBallotBitCount:
6760 case glslang::EOpSubgroupBallotInclusiveBitCount:
6761 case glslang::EOpSubgroupBallotExclusiveBitCount:
6762 case glslang::EOpSubgroupBallotFindLSB:
6763 case glslang::EOpSubgroupBallotFindMSB:
6764 builder.addCapability(spv::CapabilityGroupNonUniform);
6765 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6766 break;
6767 case glslang::EOpSubgroupShuffle:
6768 case glslang::EOpSubgroupShuffleXor:
6769 builder.addCapability(spv::CapabilityGroupNonUniform);
6770 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6771 break;
6772 case glslang::EOpSubgroupShuffleUp:
6773 case glslang::EOpSubgroupShuffleDown:
6774 builder.addCapability(spv::CapabilityGroupNonUniform);
6775 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6776 break;
6777 case glslang::EOpSubgroupAdd:
6778 case glslang::EOpSubgroupMul:
6779 case glslang::EOpSubgroupMin:
6780 case glslang::EOpSubgroupMax:
6781 case glslang::EOpSubgroupAnd:
6782 case glslang::EOpSubgroupOr:
6783 case glslang::EOpSubgroupXor:
6784 case glslang::EOpSubgroupInclusiveAdd:
6785 case glslang::EOpSubgroupInclusiveMul:
6786 case glslang::EOpSubgroupInclusiveMin:
6787 case glslang::EOpSubgroupInclusiveMax:
6788 case glslang::EOpSubgroupInclusiveAnd:
6789 case glslang::EOpSubgroupInclusiveOr:
6790 case glslang::EOpSubgroupInclusiveXor:
6791 case glslang::EOpSubgroupExclusiveAdd:
6792 case glslang::EOpSubgroupExclusiveMul:
6793 case glslang::EOpSubgroupExclusiveMin:
6794 case glslang::EOpSubgroupExclusiveMax:
6795 case glslang::EOpSubgroupExclusiveAnd:
6796 case glslang::EOpSubgroupExclusiveOr:
6797 case glslang::EOpSubgroupExclusiveXor:
6798 builder.addCapability(spv::CapabilityGroupNonUniform);
6799 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6800 break;
6801 case glslang::EOpSubgroupClusteredAdd:
6802 case glslang::EOpSubgroupClusteredMul:
6803 case glslang::EOpSubgroupClusteredMin:
6804 case glslang::EOpSubgroupClusteredMax:
6805 case glslang::EOpSubgroupClusteredAnd:
6806 case glslang::EOpSubgroupClusteredOr:
6807 case glslang::EOpSubgroupClusteredXor:
6808 builder.addCapability(spv::CapabilityGroupNonUniform);
6809 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6810 break;
6811 case glslang::EOpSubgroupQuadBroadcast:
6812 case glslang::EOpSubgroupQuadSwapHorizontal:
6813 case glslang::EOpSubgroupQuadSwapVertical:
6814 case glslang::EOpSubgroupQuadSwapDiagonal:
6815 builder.addCapability(spv::CapabilityGroupNonUniform);
6816 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6817 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006818 case glslang::EOpSubgroupPartitionedAdd:
6819 case glslang::EOpSubgroupPartitionedMul:
6820 case glslang::EOpSubgroupPartitionedMin:
6821 case glslang::EOpSubgroupPartitionedMax:
6822 case glslang::EOpSubgroupPartitionedAnd:
6823 case glslang::EOpSubgroupPartitionedOr:
6824 case glslang::EOpSubgroupPartitionedXor:
6825 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6826 case glslang::EOpSubgroupPartitionedInclusiveMul:
6827 case glslang::EOpSubgroupPartitionedInclusiveMin:
6828 case glslang::EOpSubgroupPartitionedInclusiveMax:
6829 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6830 case glslang::EOpSubgroupPartitionedInclusiveOr:
6831 case glslang::EOpSubgroupPartitionedInclusiveXor:
6832 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6833 case glslang::EOpSubgroupPartitionedExclusiveMul:
6834 case glslang::EOpSubgroupPartitionedExclusiveMin:
6835 case glslang::EOpSubgroupPartitionedExclusiveMax:
6836 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6837 case glslang::EOpSubgroupPartitionedExclusiveOr:
6838 case glslang::EOpSubgroupPartitionedExclusiveXor:
6839 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6840 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6841 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006842 default: assert(0 && "Unhandled subgroup operation!");
6843 }
6844
Jeff Bolzc5b669e2019-09-08 08:49:18 -05006845
6846 const bool isUnsigned = isTypeUnsignedInt(typeProxy);
6847 const bool isFloat = isTypeFloat(typeProxy);
John Kessenich66011cb2018-03-06 16:12:04 -07006848 const bool isBool = typeProxy == glslang::EbtBool;
6849
6850 spv::Op opCode = spv::OpNop;
6851
6852 // Figure out which opcode to use.
6853 switch (op) {
6854 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6855 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6856 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6857 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6858 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6859 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6860 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6861 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6862 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6863 case glslang::EOpSubgroupBallotBitCount:
6864 case glslang::EOpSubgroupBallotInclusiveBitCount:
6865 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6866 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6867 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6868 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6869 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6870 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6871 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6872 case glslang::EOpSubgroupAdd:
6873 case glslang::EOpSubgroupInclusiveAdd:
6874 case glslang::EOpSubgroupExclusiveAdd:
6875 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006876 case glslang::EOpSubgroupPartitionedAdd:
6877 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6878 case glslang::EOpSubgroupPartitionedExclusiveAdd:
John Kessenich66011cb2018-03-06 16:12:04 -07006879 if (isFloat) {
6880 opCode = spv::OpGroupNonUniformFAdd;
6881 } else {
6882 opCode = spv::OpGroupNonUniformIAdd;
6883 }
6884 break;
6885 case glslang::EOpSubgroupMul:
6886 case glslang::EOpSubgroupInclusiveMul:
6887 case glslang::EOpSubgroupExclusiveMul:
6888 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006889 case glslang::EOpSubgroupPartitionedMul:
6890 case glslang::EOpSubgroupPartitionedInclusiveMul:
6891 case glslang::EOpSubgroupPartitionedExclusiveMul:
John Kessenich66011cb2018-03-06 16:12:04 -07006892 if (isFloat) {
6893 opCode = spv::OpGroupNonUniformFMul;
6894 } else {
6895 opCode = spv::OpGroupNonUniformIMul;
6896 }
6897 break;
6898 case glslang::EOpSubgroupMin:
6899 case glslang::EOpSubgroupInclusiveMin:
6900 case glslang::EOpSubgroupExclusiveMin:
6901 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006902 case glslang::EOpSubgroupPartitionedMin:
6903 case glslang::EOpSubgroupPartitionedInclusiveMin:
6904 case glslang::EOpSubgroupPartitionedExclusiveMin:
John Kessenich66011cb2018-03-06 16:12:04 -07006905 if (isFloat) {
6906 opCode = spv::OpGroupNonUniformFMin;
6907 } else if (isUnsigned) {
6908 opCode = spv::OpGroupNonUniformUMin;
6909 } else {
6910 opCode = spv::OpGroupNonUniformSMin;
6911 }
6912 break;
6913 case glslang::EOpSubgroupMax:
6914 case glslang::EOpSubgroupInclusiveMax:
6915 case glslang::EOpSubgroupExclusiveMax:
6916 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006917 case glslang::EOpSubgroupPartitionedMax:
6918 case glslang::EOpSubgroupPartitionedInclusiveMax:
6919 case glslang::EOpSubgroupPartitionedExclusiveMax:
John Kessenich66011cb2018-03-06 16:12:04 -07006920 if (isFloat) {
6921 opCode = spv::OpGroupNonUniformFMax;
6922 } else if (isUnsigned) {
6923 opCode = spv::OpGroupNonUniformUMax;
6924 } else {
6925 opCode = spv::OpGroupNonUniformSMax;
6926 }
6927 break;
6928 case glslang::EOpSubgroupAnd:
6929 case glslang::EOpSubgroupInclusiveAnd:
6930 case glslang::EOpSubgroupExclusiveAnd:
6931 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006932 case glslang::EOpSubgroupPartitionedAnd:
6933 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6934 case glslang::EOpSubgroupPartitionedExclusiveAnd:
John Kessenich66011cb2018-03-06 16:12:04 -07006935 if (isBool) {
6936 opCode = spv::OpGroupNonUniformLogicalAnd;
6937 } else {
6938 opCode = spv::OpGroupNonUniformBitwiseAnd;
6939 }
6940 break;
6941 case glslang::EOpSubgroupOr:
6942 case glslang::EOpSubgroupInclusiveOr:
6943 case glslang::EOpSubgroupExclusiveOr:
6944 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006945 case glslang::EOpSubgroupPartitionedOr:
6946 case glslang::EOpSubgroupPartitionedInclusiveOr:
6947 case glslang::EOpSubgroupPartitionedExclusiveOr:
John Kessenich66011cb2018-03-06 16:12:04 -07006948 if (isBool) {
6949 opCode = spv::OpGroupNonUniformLogicalOr;
6950 } else {
6951 opCode = spv::OpGroupNonUniformBitwiseOr;
6952 }
6953 break;
6954 case glslang::EOpSubgroupXor:
6955 case glslang::EOpSubgroupInclusiveXor:
6956 case glslang::EOpSubgroupExclusiveXor:
6957 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006958 case glslang::EOpSubgroupPartitionedXor:
6959 case glslang::EOpSubgroupPartitionedInclusiveXor:
6960 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07006961 if (isBool) {
6962 opCode = spv::OpGroupNonUniformLogicalXor;
6963 } else {
6964 opCode = spv::OpGroupNonUniformBitwiseXor;
6965 }
6966 break;
6967 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
6968 case glslang::EOpSubgroupQuadSwapHorizontal:
6969 case glslang::EOpSubgroupQuadSwapVertical:
6970 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
6971 default: assert(0 && "Unhandled subgroup operation!");
6972 }
6973
John Kessenich149afc32018-08-14 13:31:43 -06006974 // get the right Group Operation
6975 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07006976 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06006977 default:
6978 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006979 case glslang::EOpSubgroupBallotBitCount:
6980 case glslang::EOpSubgroupAdd:
6981 case glslang::EOpSubgroupMul:
6982 case glslang::EOpSubgroupMin:
6983 case glslang::EOpSubgroupMax:
6984 case glslang::EOpSubgroupAnd:
6985 case glslang::EOpSubgroupOr:
6986 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06006987 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006988 break;
6989 case glslang::EOpSubgroupBallotInclusiveBitCount:
6990 case glslang::EOpSubgroupInclusiveAdd:
6991 case glslang::EOpSubgroupInclusiveMul:
6992 case glslang::EOpSubgroupInclusiveMin:
6993 case glslang::EOpSubgroupInclusiveMax:
6994 case glslang::EOpSubgroupInclusiveAnd:
6995 case glslang::EOpSubgroupInclusiveOr:
6996 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006997 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006998 break;
6999 case glslang::EOpSubgroupBallotExclusiveBitCount:
7000 case glslang::EOpSubgroupExclusiveAdd:
7001 case glslang::EOpSubgroupExclusiveMul:
7002 case glslang::EOpSubgroupExclusiveMin:
7003 case glslang::EOpSubgroupExclusiveMax:
7004 case glslang::EOpSubgroupExclusiveAnd:
7005 case glslang::EOpSubgroupExclusiveOr:
7006 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007007 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007008 break;
7009 case glslang::EOpSubgroupClusteredAdd:
7010 case glslang::EOpSubgroupClusteredMul:
7011 case glslang::EOpSubgroupClusteredMin:
7012 case glslang::EOpSubgroupClusteredMax:
7013 case glslang::EOpSubgroupClusteredAnd:
7014 case glslang::EOpSubgroupClusteredOr:
7015 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06007016 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007017 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007018 case glslang::EOpSubgroupPartitionedAdd:
7019 case glslang::EOpSubgroupPartitionedMul:
7020 case glslang::EOpSubgroupPartitionedMin:
7021 case glslang::EOpSubgroupPartitionedMax:
7022 case glslang::EOpSubgroupPartitionedAnd:
7023 case glslang::EOpSubgroupPartitionedOr:
7024 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06007025 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007026 break;
7027 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7028 case glslang::EOpSubgroupPartitionedInclusiveMul:
7029 case glslang::EOpSubgroupPartitionedInclusiveMin:
7030 case glslang::EOpSubgroupPartitionedInclusiveMax:
7031 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7032 case glslang::EOpSubgroupPartitionedInclusiveOr:
7033 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007034 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007035 break;
7036 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7037 case glslang::EOpSubgroupPartitionedExclusiveMul:
7038 case glslang::EOpSubgroupPartitionedExclusiveMin:
7039 case glslang::EOpSubgroupPartitionedExclusiveMax:
7040 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7041 case glslang::EOpSubgroupPartitionedExclusiveOr:
7042 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007043 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007044 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007045 }
7046
John Kessenich149afc32018-08-14 13:31:43 -06007047 // build the instruction
7048 std::vector<spv::IdImmediate> spvGroupOperands;
7049
7050 // Every operation begins with the Execution Scope operand.
7051 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7052 spvGroupOperands.push_back(executionScope);
7053
7054 // Next, for all operations that use a Group Operation, push that as an operand.
7055 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007056 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007057 spvGroupOperands.push_back(groupOperand);
7058 }
7059
John Kessenich66011cb2018-03-06 16:12:04 -07007060 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06007061 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
7062 spv::IdImmediate operand = { true, *opIt };
7063 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07007064 }
7065
7066 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06007067 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07007068 switch (op) {
7069 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06007070 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
7071 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
7072 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
7073 }
7074 if (directionId != spv::NoResult) {
7075 spv::IdImmediate direction = { true, directionId };
7076 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007077 }
7078
7079 return builder.createOp(opCode, typeId, spvGroupOperands);
7080}
7081
John Kessenich5e4b1242015-08-06 22:53:06 -06007082spv::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 -06007083{
John Kessenich66011cb2018-03-06 16:12:04 -07007084 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7085 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007086
John Kessenich140f3df2015-06-26 16:58:36 -06007087 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007088 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007089 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007090 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007091 spv::Id typeId0 = 0;
7092 if (consumedOperands > 0)
7093 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007094 spv::Id typeId1 = 0;
7095 if (consumedOperands > 1)
7096 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007097 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007098
7099 switch (op) {
7100 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007101 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007102 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007103 else if (isUnsigned)
7104 libCall = spv::GLSLstd450UMin;
7105 else
7106 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007107 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007108 break;
7109 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007110 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007111 break;
7112 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007113 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007114 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007115 else if (isUnsigned)
7116 libCall = spv::GLSLstd450UMax;
7117 else
7118 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007119 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007120 break;
7121 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007122 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007123 break;
7124 case glslang::EOpDot:
7125 opCode = spv::OpDot;
7126 break;
7127 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007128 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007129 break;
7130
7131 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007132 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007133 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007134 else if (isUnsigned)
7135 libCall = spv::GLSLstd450UClamp;
7136 else
7137 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007138 builder.promoteScalar(precision, operands.front(), operands[1]);
7139 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007140 break;
7141 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007142 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7143 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007144 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007145 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007146 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007147 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007148 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007149 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007150 break;
7151 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007152 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007153 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007154 break;
7155 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007156 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007157 builder.promoteScalar(precision, operands[0], operands[2]);
7158 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007159 break;
7160
7161 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007162 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007163 break;
7164 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007165 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007166 break;
7167 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007168 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007169 break;
7170 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007171 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007172 break;
7173 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007174 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007175 break;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007176 case glslang::EOpBarrier:
7177 {
7178 // This is for the extended controlBarrier function, with four operands.
7179 // The unextended barrier() goes through createNoArgOperation.
7180 assert(operands.size() == 4);
7181 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7182 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7183 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
7184 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7185 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7186 spv::MemorySemanticsMakeVisibleKHRMask |
7187 spv::MemorySemanticsOutputMemoryKHRMask |
7188 spv::MemorySemanticsVolatileMask)) {
7189 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7190 }
7191 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
7192 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7193 }
7194 return 0;
7195 }
7196 break;
7197 case glslang::EOpMemoryBarrier:
7198 {
7199 // This is for the extended memoryBarrier function, with three operands.
7200 // The unextended memoryBarrier() goes through createNoArgOperation.
7201 assert(operands.size() == 3);
7202 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7203 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7204 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7205 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7206 spv::MemorySemanticsMakeVisibleKHRMask |
7207 spv::MemorySemanticsOutputMemoryKHRMask |
7208 spv::MemorySemanticsVolatileMask)) {
7209 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7210 }
7211 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7212 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7213 }
7214 return 0;
7215 }
7216 break;
7217
John Kessenicha28f7a72019-08-06 07:00:58 -06007218#ifndef GLSLANG_WEB
Rex Xu7a26c172015-12-08 17:12:09 +08007219 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007220 if (typeProxy == glslang::EbtFloat16)
7221 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007222 libCall = spv::GLSLstd450InterpolateAtSample;
7223 break;
7224 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007225 if (typeProxy == glslang::EbtFloat16)
7226 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007227 libCall = spv::GLSLstd450InterpolateAtOffset;
7228 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007229 case glslang::EOpAddCarry:
7230 opCode = spv::OpIAddCarry;
7231 typeId = builder.makeStructResultType(typeId0, typeId0);
7232 consumedOperands = 2;
7233 break;
7234 case glslang::EOpSubBorrow:
7235 opCode = spv::OpISubBorrow;
7236 typeId = builder.makeStructResultType(typeId0, typeId0);
7237 consumedOperands = 2;
7238 break;
7239 case glslang::EOpUMulExtended:
7240 opCode = spv::OpUMulExtended;
7241 typeId = builder.makeStructResultType(typeId0, typeId0);
7242 consumedOperands = 2;
7243 break;
7244 case glslang::EOpIMulExtended:
7245 opCode = spv::OpSMulExtended;
7246 typeId = builder.makeStructResultType(typeId0, typeId0);
7247 consumedOperands = 2;
7248 break;
7249 case glslang::EOpBitfieldExtract:
7250 if (isUnsigned)
7251 opCode = spv::OpBitFieldUExtract;
7252 else
7253 opCode = spv::OpBitFieldSExtract;
7254 break;
7255 case glslang::EOpBitfieldInsert:
7256 opCode = spv::OpBitFieldInsert;
7257 break;
7258
7259 case glslang::EOpFma:
7260 libCall = spv::GLSLstd450Fma;
7261 break;
7262 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007263 {
7264 libCall = spv::GLSLstd450FrexpStruct;
7265 assert(builder.isPointerType(typeId1));
7266 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007267 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007268 if (width == 16)
7269 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7270 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
Rex Xu470026f2017-03-29 17:12:40 +08007271 if (builder.getNumComponents(operands[0]) == 1)
7272 frexpIntType = builder.makeIntegerType(width, true);
7273 else
7274 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
7275 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7276 consumedOperands = 1;
7277 }
John Kessenich55e7d112015-11-15 21:33:39 -07007278 break;
7279 case glslang::EOpLdexp:
7280 libCall = spv::GLSLstd450Ldexp;
7281 break;
7282
Rex Xu574ab042016-04-14 16:53:07 +08007283 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007284 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007285
John Kessenich66011cb2018-03-06 16:12:04 -07007286 case glslang::EOpSubgroupBroadcast:
7287 case glslang::EOpSubgroupBallotBitExtract:
7288 case glslang::EOpSubgroupShuffle:
7289 case glslang::EOpSubgroupShuffleXor:
7290 case glslang::EOpSubgroupShuffleUp:
7291 case glslang::EOpSubgroupShuffleDown:
7292 case glslang::EOpSubgroupClusteredAdd:
7293 case glslang::EOpSubgroupClusteredMul:
7294 case glslang::EOpSubgroupClusteredMin:
7295 case glslang::EOpSubgroupClusteredMax:
7296 case glslang::EOpSubgroupClusteredAnd:
7297 case glslang::EOpSubgroupClusteredOr:
7298 case glslang::EOpSubgroupClusteredXor:
7299 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007300 case glslang::EOpSubgroupPartitionedAdd:
7301 case glslang::EOpSubgroupPartitionedMul:
7302 case glslang::EOpSubgroupPartitionedMin:
7303 case glslang::EOpSubgroupPartitionedMax:
7304 case glslang::EOpSubgroupPartitionedAnd:
7305 case glslang::EOpSubgroupPartitionedOr:
7306 case glslang::EOpSubgroupPartitionedXor:
7307 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7308 case glslang::EOpSubgroupPartitionedInclusiveMul:
7309 case glslang::EOpSubgroupPartitionedInclusiveMin:
7310 case glslang::EOpSubgroupPartitionedInclusiveMax:
7311 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7312 case glslang::EOpSubgroupPartitionedInclusiveOr:
7313 case glslang::EOpSubgroupPartitionedInclusiveXor:
7314 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7315 case glslang::EOpSubgroupPartitionedExclusiveMul:
7316 case glslang::EOpSubgroupPartitionedExclusiveMin:
7317 case glslang::EOpSubgroupPartitionedExclusiveMax:
7318 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7319 case glslang::EOpSubgroupPartitionedExclusiveOr:
7320 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007321 return createSubgroupOperation(op, typeId, operands, typeProxy);
7322
Rex Xu9d93a232016-05-05 12:30:44 +08007323 case glslang::EOpSwizzleInvocations:
7324 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7325 libCall = spv::SwizzleInvocationsAMD;
7326 break;
7327 case glslang::EOpSwizzleInvocationsMasked:
7328 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7329 libCall = spv::SwizzleInvocationsMaskedAMD;
7330 break;
7331 case glslang::EOpWriteInvocation:
7332 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7333 libCall = spv::WriteInvocationAMD;
7334 break;
7335
7336 case glslang::EOpMin3:
7337 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7338 if (isFloat)
7339 libCall = spv::FMin3AMD;
7340 else {
7341 if (isUnsigned)
7342 libCall = spv::UMin3AMD;
7343 else
7344 libCall = spv::SMin3AMD;
7345 }
7346 break;
7347 case glslang::EOpMax3:
7348 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7349 if (isFloat)
7350 libCall = spv::FMax3AMD;
7351 else {
7352 if (isUnsigned)
7353 libCall = spv::UMax3AMD;
7354 else
7355 libCall = spv::SMax3AMD;
7356 }
7357 break;
7358 case glslang::EOpMid3:
7359 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7360 if (isFloat)
7361 libCall = spv::FMid3AMD;
7362 else {
7363 if (isUnsigned)
7364 libCall = spv::UMid3AMD;
7365 else
7366 libCall = spv::SMid3AMD;
7367 }
7368 break;
7369
7370 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007371 if (typeProxy == glslang::EbtFloat16)
7372 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007373 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7374 libCall = spv::InterpolateAtVertexAMD;
7375 break;
Chao Chen3c366992018-09-19 11:41:59 -07007376
Chao Chenb50c02e2018-09-19 11:42:24 -07007377 case glslang::EOpReportIntersectionNV:
7378 {
7379 typeId = builder.makeBoolType();
Ashwin Leleff1783d2018-10-22 16:41:44 -07007380 opCode = spv::OpReportIntersectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07007381 }
7382 break;
7383 case glslang::EOpTraceNV:
7384 {
Ashwin Leleff1783d2018-10-22 16:41:44 -07007385 builder.createNoResultOp(spv::OpTraceNV, operands);
7386 return 0;
7387 }
7388 break;
7389 case glslang::EOpExecuteCallableNV:
7390 {
7391 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007392 return 0;
7393 }
7394 break;
Chao Chen3c366992018-09-19 11:41:59 -07007395 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7396 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7397 return 0;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007398 case glslang::EOpCooperativeMatrixMulAdd:
7399 opCode = spv::OpCooperativeMatrixMulAddNV;
7400 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007401#endif // GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007402 default:
7403 return 0;
7404 }
7405
7406 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007407 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007408 // Use an extended instruction from the standard library.
7409 // Construct the call arguments, without modifying the original operands vector.
7410 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7411 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007412 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007413 } else if (opCode == spv::OpDot && !isFloat) {
7414 // int dot(int, int)
7415 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7416 const int componentCount = builder.getNumComponents(operands[0]);
7417 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7418 builder.setPrecision(mulOp, precision);
7419 id = builder.createCompositeExtract(mulOp, typeId, 0);
7420 for (int i = 1; i < componentCount; ++i) {
7421 builder.setPrecision(id, precision);
7422 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(operands[0], typeId, i));
7423 }
John Kessenich2359bd02015-12-06 19:29:11 -07007424 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007425 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007426 case 0:
7427 // should all be handled by visitAggregate and createNoArgOperation
7428 assert(0);
7429 return 0;
7430 case 1:
7431 // should all be handled by createUnaryOperation
7432 assert(0);
7433 return 0;
7434 case 2:
7435 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7436 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007437 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007438 // anything 3 or over doesn't have l-value operands, so all should be consumed
7439 assert(consumedOperands == operands.size());
7440 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007441 break;
7442 }
7443 }
7444
John Kessenichb9197c82019-08-11 07:41:45 -06007445#ifndef GLSLANG_WEB
John Kessenich55e7d112015-11-15 21:33:39 -07007446 // Decode the return types that were structures
7447 switch (op) {
7448 case glslang::EOpAddCarry:
7449 case glslang::EOpSubBorrow:
7450 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7451 id = builder.createCompositeExtract(id, typeId0, 0);
7452 break;
7453 case glslang::EOpUMulExtended:
7454 case glslang::EOpIMulExtended:
7455 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7456 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7457 break;
7458 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007459 {
7460 assert(operands.size() == 2);
7461 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7462 // "exp" is floating-point type (from HLSL intrinsic)
7463 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7464 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7465 builder.createStore(member1, operands[1]);
7466 } else
7467 // "exp" is integer type (from GLSL built-in function)
7468 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7469 id = builder.createCompositeExtract(id, typeId0, 0);
7470 }
John Kessenich55e7d112015-11-15 21:33:39 -07007471 break;
7472 default:
7473 break;
7474 }
John Kessenichb9197c82019-08-11 07:41:45 -06007475#endif
John Kessenich55e7d112015-11-15 21:33:39 -07007476
John Kessenich32cfd492016-02-02 12:37:46 -07007477 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007478}
7479
Rex Xu9d93a232016-05-05 12:30:44 +08007480// Intrinsics with no arguments (or no return value, and no precision).
7481spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007482{
Jeff Bolz36831c92018-09-05 10:11:41 -05007483 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
7484 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007485
7486 switch (op) {
John Kessenich3dd1ce52019-10-17 07:08:40 -06007487#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007488 case glslang::EOpEmitVertex:
7489 builder.createNoResultOp(spv::OpEmitVertex);
7490 return 0;
7491 case glslang::EOpEndPrimitive:
7492 builder.createNoResultOp(spv::OpEndPrimitive);
7493 return 0;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007494#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007495 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007496 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007497 if (glslangIntermediate->usingVulkanMemoryModel()) {
7498 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7499 spv::MemorySemanticsOutputMemoryKHRMask |
7500 spv::MemorySemanticsAcquireReleaseMask);
7501 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7502 } else {
7503 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7504 }
John Kessenich82979362017-12-11 04:02:24 -07007505 } else {
7506 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7507 spv::MemorySemanticsWorkgroupMemoryMask |
7508 spv::MemorySemanticsAcquireReleaseMask);
7509 }
John Kessenich140f3df2015-06-26 16:58:36 -06007510 return 0;
7511 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007512 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7513 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007514 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007515 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007516 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7517 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007518 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007519 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007520 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7521 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007522 return 0;
7523 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007524 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7525 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007526 return 0;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007527#ifndef GLSLANG_WEB
7528 case glslang::EOpMemoryBarrierAtomicCounter:
7529 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7530 spv::MemorySemanticsAcquireReleaseMask);
7531 return 0;
7532 case glslang::EOpMemoryBarrierImage:
7533 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7534 spv::MemorySemanticsAcquireReleaseMask);
7535 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007536 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007537 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007538 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007539 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007540 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007541 case glslang::EOpDeviceMemoryBarrier:
7542 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7543 spv::MemorySemanticsImageMemoryMask |
7544 spv::MemorySemanticsAcquireReleaseMask);
7545 return 0;
7546 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7547 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7548 spv::MemorySemanticsImageMemoryMask |
7549 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007550 return 0;
7551 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007552 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7553 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007554 return 0;
7555 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007556 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7557 spv::MemorySemanticsWorkgroupMemoryMask |
7558 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007559 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007560 case glslang::EOpSubgroupBarrier:
7561 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7562 spv::MemorySemanticsAcquireReleaseMask);
7563 return spv::NoResult;
7564 case glslang::EOpSubgroupMemoryBarrier:
7565 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7566 spv::MemorySemanticsAcquireReleaseMask);
7567 return spv::NoResult;
7568 case glslang::EOpSubgroupMemoryBarrierBuffer:
7569 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7570 spv::MemorySemanticsAcquireReleaseMask);
7571 return spv::NoResult;
7572 case glslang::EOpSubgroupMemoryBarrierImage:
7573 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7574 spv::MemorySemanticsAcquireReleaseMask);
7575 return spv::NoResult;
7576 case glslang::EOpSubgroupMemoryBarrierShared:
7577 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7578 spv::MemorySemanticsAcquireReleaseMask);
7579 return spv::NoResult;
7580 case glslang::EOpSubgroupElect: {
7581 std::vector<spv::Id> operands;
7582 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7583 }
Rex Xu9d93a232016-05-05 12:30:44 +08007584 case glslang::EOpTime:
7585 {
7586 std::vector<spv::Id> args; // Dummy arguments
7587 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7588 return builder.setPrecision(id, precision);
7589 }
Chao Chenb50c02e2018-09-19 11:42:24 -07007590 case glslang::EOpIgnoreIntersectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007591 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007592 return 0;
7593 case glslang::EOpTerminateRayNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007594 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007595 return 0;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05007596
7597 case glslang::EOpBeginInvocationInterlock:
7598 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
7599 return 0;
7600 case glslang::EOpEndInvocationInterlock:
7601 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
7602 return 0;
7603
Jeff Bolzba6170b2019-07-01 09:23:23 -05007604 case glslang::EOpIsHelperInvocation:
7605 {
7606 std::vector<spv::Id> args; // Dummy arguments
Rex Xubb7307b2019-07-15 14:57:20 +08007607 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
7608 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
7609 return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
Jeff Bolzba6170b2019-07-01 09:23:23 -05007610 }
7611
amhagan91fb0092019-07-10 21:14:38 -04007612 case glslang::EOpReadClockSubgroupKHR: {
7613 std::vector<spv::Id> args;
7614 args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
7615 builder.addExtension(spv::E_SPV_KHR_shader_clock);
7616 builder.addCapability(spv::CapabilityShaderClockKHR);
7617 return builder.createOp(spv::OpReadClockKHR, typeId, args);
7618 }
7619
7620 case glslang::EOpReadClockDeviceKHR: {
7621 std::vector<spv::Id> args;
7622 args.push_back(builder.makeUintConstant(spv::ScopeDevice));
7623 builder.addExtension(spv::E_SPV_KHR_shader_clock);
7624 builder.addCapability(spv::CapabilityShaderClockKHR);
7625 return builder.createOp(spv::OpReadClockKHR, typeId, args);
7626 }
John Kessenich3dd1ce52019-10-17 07:08:40 -06007627#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007628 default:
John Kessenich155d3512019-08-08 23:29:20 -06007629 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007630 }
John Kessenich155d3512019-08-08 23:29:20 -06007631
7632 logger->missingFunctionality("unknown operation with no arguments");
7633
7634 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007635}
7636
7637spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7638{
John Kessenich2f273362015-07-18 22:34:27 -06007639 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007640 spv::Id id;
7641 if (symbolValues.end() != iter) {
7642 id = iter->second;
7643 return id;
7644 }
7645
7646 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06007647 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
7648 auto forcedType = getForcedType(builtIn, symbol->getType());
7649 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06007650 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06007651 if (forcedType.second != spv::NoType)
7652 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06007653
Rex Xuc884b4a2016-06-29 15:03:44 +08007654 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007655 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7656 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7657 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenicha28f7a72019-08-06 07:00:58 -06007658#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07007659 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
John Kessenichb9197c82019-08-11 07:41:45 -06007660 if (symbol->getQualifier().hasComponent())
7661 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
7662 if (symbol->getQualifier().hasIndex())
7663 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
Chao Chen3c366992018-09-19 11:41:59 -07007664#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007665 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007666 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich91e4aa52016-07-07 17:46:42 -06007667 // atomic counters use this:
7668 if (symbol->getQualifier().hasOffset())
7669 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007670 }
7671
scygan2c864272016-05-18 18:09:17 +02007672 if (symbol->getQualifier().hasLocation())
7673 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007674 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007675 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007676 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007677 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007678 }
John Kessenich140f3df2015-06-26 16:58:36 -06007679 if (symbol->getQualifier().hasSet())
7680 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007681 else if (IsDescriptorResource(symbol->getType())) {
7682 // default to 0
7683 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7684 }
John Kessenich140f3df2015-06-26 16:58:36 -06007685 if (symbol->getQualifier().hasBinding())
7686 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06007687 else if (IsDescriptorResource(symbol->getType())) {
7688 // default to 0
7689 builder.addDecoration(id, spv::DecorationBinding, 0);
7690 }
John Kessenich6c292d32016-02-15 20:58:50 -07007691 if (symbol->getQualifier().hasAttachment())
7692 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06007693 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007694 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07007695 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007696 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007697 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7698 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7699 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7700 }
7701 if (symbol->getQualifier().hasXfbOffset())
7702 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007703 }
7704
John Kessenichb9197c82019-08-11 07:41:45 -06007705 // add built-in variable decoration
7706 if (builtIn != spv::BuiltInMax) {
7707 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
7708 }
7709
7710#ifndef GLSLANG_WEB
Rex Xu1da878f2016-02-21 20:59:01 +08007711 if (symbol->getType().isImage()) {
7712 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05007713 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007714 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007715 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007716 }
7717
John Kessenich5611c6d2018-04-05 11:25:02 -06007718 // nonuniform
7719 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7720
chaoc0ad6a4e2016-12-19 16:29:34 -08007721 if (builtIn == spv::BuiltInSampleMask) {
7722 spv::Decoration decoration;
7723 // GL_NV_sample_mask_override_coverage extension
7724 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007725 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007726 else
7727 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007728 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007729 if (decoration != spv::DecorationMax) {
Jason Macnakdbd4c3c2019-07-12 14:33:02 -07007730 builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
chaoc0ad6a4e2016-12-19 16:29:34 -08007731 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7732 }
7733 }
chaoc771d89f2017-01-13 01:10:53 -08007734 else if (builtIn == spv::BuiltInLayer) {
7735 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007736 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007737 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007738 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7739 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7740 }
John Kessenichb41bff62017-08-11 13:07:17 -06007741 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007742 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7743 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007744 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7745 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7746 }
7747 }
7748
chaoc6e5acae2016-12-20 13:28:52 -08007749 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007750 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007751 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007752 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7753 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007754 if (symbol->getQualifier().pervertexNV) {
7755 builder.addDecoration(id, spv::DecorationPerVertexNV);
7756 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7757 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7758 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007759
John Kessenich5d610ee2018-03-07 18:05:55 -07007760 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7761 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7762 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7763 symbol->getType().getQualifier().semanticName);
7764 }
7765
John Kessenich7015bd62019-08-01 03:28:08 -06007766 if (symbol->isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007767 builder.addDecoration(id, symbol->getType().getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
7768 }
John Kessenichb9197c82019-08-11 07:41:45 -06007769#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007770
John Kessenich140f3df2015-06-26 16:58:36 -06007771 return id;
7772}
7773
John Kessenicha28f7a72019-08-06 07:00:58 -06007774#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07007775// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7776void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7777{
7778 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07007779 if (qualifier.perPrimitiveNV) {
7780 // Need to add capability/extension for fragment shader.
7781 // Mesh shader already adds this by default.
7782 if (glslangIntermediate->getStage() == EShLangFragment) {
7783 builder.addCapability(spv::CapabilityMeshShadingNV);
7784 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7785 }
Chao Chen3c366992018-09-19 11:41:59 -07007786 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007787 }
Chao Chen3c366992018-09-19 11:41:59 -07007788 if (qualifier.perViewNV)
7789 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7790 if (qualifier.perTaskNV)
7791 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7792 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07007793 if (qualifier.perPrimitiveNV) {
7794 // Need to add capability/extension for fragment shader.
7795 // Mesh shader already adds this by default.
7796 if (glslangIntermediate->getStage() == EShLangFragment) {
7797 builder.addCapability(spv::CapabilityMeshShadingNV);
7798 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7799 }
Chao Chen3c366992018-09-19 11:41:59 -07007800 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007801 }
Chao Chen3c366992018-09-19 11:41:59 -07007802 if (qualifier.perViewNV)
7803 builder.addDecoration(id, spv::DecorationPerViewNV);
7804 if (qualifier.perTaskNV)
7805 builder.addDecoration(id, spv::DecorationPerTaskNV);
7806 }
7807}
7808#endif
7809
John Kessenich55e7d112015-11-15 21:33:39 -07007810// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07007811// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07007812//
7813// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7814//
7815// Recursively walk the nodes. The nodes form a tree whose leaves are
7816// regular constants, which themselves are trees that createSpvConstant()
7817// recursively walks. So, this function walks the "top" of the tree:
7818// - emit specialization constant-building instructions for specConstant
7819// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04007820spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07007821{
John Kessenich7cc0e282016-03-20 00:46:02 -06007822 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07007823
qining4f4bb812016-04-03 23:55:17 -04007824 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07007825 if (! node.getQualifier().specConstant) {
7826 // hand off to the non-spec-constant path
7827 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
7828 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04007829 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07007830 nextConst, false);
7831 }
7832
7833 // We now know we have a specialization constant to build
7834
John Kessenichd94c0032016-05-30 19:29:40 -06007835 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04007836 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
7837 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
7838 std::vector<spv::Id> dimConstId;
7839 for (int dim = 0; dim < 3; ++dim) {
7840 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
7841 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07007842 if (specConst) {
7843 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
7844 glslangIntermediate->getLocalSizeSpecId(dim));
7845 }
qining4f4bb812016-04-03 23:55:17 -04007846 }
7847 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
7848 }
7849
7850 // An AST node labelled as specialization constant should be a symbol node.
7851 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
7852 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007853 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04007854 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04007855 // Traverse the constant constructor sub tree like generating normal run-time instructions.
7856 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
7857 // will set the builder into spec constant op instruction generating mode.
7858 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007859 result = accessChainLoad(sub_tree->getType());
7860 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04007861 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007862 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05007863 } else {
7864 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05007865 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07007866 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007867 builder.addName(result, sn->getName().c_str());
7868 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07007869 }
qining4f4bb812016-04-03 23:55:17 -04007870
7871 // Neither a front-end constant node, nor a specialization constant node with constant union array or
7872 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04007873 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04007874 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07007875}
7876
John Kessenich140f3df2015-06-26 16:58:36 -06007877// Use 'consts' as the flattened glslang source of scalar constants to recursively
7878// build the aggregate SPIR-V constant.
7879//
7880// If there are not enough elements present in 'consts', 0 will be substituted;
7881// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
7882//
qining08408382016-03-21 09:51:37 -04007883spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06007884{
7885 // vector of constants for SPIR-V
7886 std::vector<spv::Id> spvConsts;
7887
7888 // Type is used for struct and array constants
7889 spv::Id typeId = convertGlslangToSpvType(glslangType);
7890
7891 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007892 glslang::TType elementType(glslangType, 0);
7893 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04007894 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007895 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007896 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06007897 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04007898 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007899 } else if (glslangType.isCoopMat()) {
7900 glslang::TType componentType(glslangType.getBasicType());
7901 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007902 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007903 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
7904 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04007905 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06007906 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06007907 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
7908 bool zero = nextConst >= consts.size();
7909 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06007910 case glslang::EbtInt:
7911 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
7912 break;
7913 case glslang::EbtUint:
7914 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
7915 break;
7916 case glslang::EbtFloat:
7917 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7918 break;
7919 case glslang::EbtBool:
7920 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7921 break;
7922#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07007923 case glslang::EbtInt8:
7924 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
7925 break;
7926 case glslang::EbtUint8:
7927 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
7928 break;
7929 case glslang::EbtInt16:
7930 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
7931 break;
7932 case glslang::EbtUint16:
7933 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
7934 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007935 case glslang::EbtInt64:
7936 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
7937 break;
7938 case glslang::EbtUint64:
7939 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
7940 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007941 case glslang::EbtDouble:
7942 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
7943 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007944 case glslang::EbtFloat16:
7945 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7946 break;
John Kessenich39697cd2019-08-08 10:35:51 -06007947#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007948 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007949 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007950 break;
7951 }
7952 ++nextConst;
7953 }
7954 } else {
7955 // we have a non-aggregate (scalar) constant
7956 bool zero = nextConst >= consts.size();
7957 spv::Id scalar = 0;
7958 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06007959 case glslang::EbtInt:
7960 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
7961 break;
7962 case glslang::EbtUint:
7963 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
7964 break;
7965 case glslang::EbtFloat:
7966 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7967 break;
7968 case glslang::EbtBool:
7969 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
7970 break;
7971#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07007972 case glslang::EbtInt8:
7973 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
7974 break;
7975 case glslang::EbtUint8:
7976 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
7977 break;
7978 case glslang::EbtInt16:
7979 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
7980 break;
7981 case glslang::EbtUint16:
7982 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
7983 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007984 case glslang::EbtInt64:
7985 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
7986 break;
7987 case glslang::EbtUint64:
7988 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7989 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007990 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07007991 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007992 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007993 case glslang::EbtFloat16:
7994 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7995 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06007996 case glslang::EbtReference:
7997 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7998 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
7999 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008000#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008001 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008002 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008003 break;
8004 }
8005 ++nextConst;
8006 return scalar;
8007 }
8008
8009 return builder.makeCompositeConstant(typeId, spvConsts);
8010}
8011
John Kessenich7c1aa102015-10-15 13:29:11 -06008012// Return true if the node is a constant or symbol whose reading has no
8013// non-trivial observable cost or effect.
8014bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
8015{
8016 // don't know what this is
8017 if (node == nullptr)
8018 return false;
8019
8020 // a constant is safe
8021 if (node->getAsConstantUnion() != nullptr)
8022 return true;
8023
8024 // not a symbol means non-trivial
8025 if (node->getAsSymbolNode() == nullptr)
8026 return false;
8027
8028 // a symbol, depends on what's being read
8029 switch (node->getType().getQualifier().storage) {
8030 case glslang::EvqTemporary:
8031 case glslang::EvqGlobal:
8032 case glslang::EvqIn:
8033 case glslang::EvqInOut:
8034 case glslang::EvqConst:
8035 case glslang::EvqConstReadOnly:
8036 case glslang::EvqUniform:
8037 return true;
8038 default:
8039 return false;
8040 }
qining25262b32016-05-06 17:25:16 -04008041}
John Kessenich7c1aa102015-10-15 13:29:11 -06008042
8043// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06008044// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06008045// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06008046// Return true if trivial.
8047bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
8048{
8049 if (node == nullptr)
8050 return false;
8051
John Kessenich84cc15f2017-05-24 16:44:47 -06008052 // count non scalars as trivial, as well as anything coming from HLSL
8053 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06008054 return true;
8055
John Kessenich7c1aa102015-10-15 13:29:11 -06008056 // symbols and constants are trivial
8057 if (isTrivialLeaf(node))
8058 return true;
8059
8060 // otherwise, it needs to be a simple operation or one or two leaf nodes
8061
8062 // not a simple operation
8063 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
8064 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
8065 if (binaryNode == nullptr && unaryNode == nullptr)
8066 return false;
8067
8068 // not on leaf nodes
8069 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
8070 return false;
8071
8072 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
8073 return false;
8074 }
8075
8076 switch (node->getAsOperator()->getOp()) {
8077 case glslang::EOpLogicalNot:
8078 case glslang::EOpConvIntToBool:
8079 case glslang::EOpConvUintToBool:
8080 case glslang::EOpConvFloatToBool:
8081 case glslang::EOpConvDoubleToBool:
8082 case glslang::EOpEqual:
8083 case glslang::EOpNotEqual:
8084 case glslang::EOpLessThan:
8085 case glslang::EOpGreaterThan:
8086 case glslang::EOpLessThanEqual:
8087 case glslang::EOpGreaterThanEqual:
8088 case glslang::EOpIndexDirect:
8089 case glslang::EOpIndexDirectStruct:
8090 case glslang::EOpLogicalXor:
8091 case glslang::EOpAny:
8092 case glslang::EOpAll:
8093 return true;
8094 default:
8095 return false;
8096 }
8097}
8098
8099// Emit short-circuiting code, where 'right' is never evaluated unless
8100// the left side is true (for &&) or false (for ||).
8101spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
8102{
8103 spv::Id boolTypeId = builder.makeBoolType();
8104
8105 // emit left operand
8106 builder.clearAccessChain();
8107 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008108 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008109
8110 // Operands to accumulate OpPhi operands
8111 std::vector<spv::Id> phiOperands;
8112 // accumulate left operand's phi information
8113 phiOperands.push_back(leftId);
8114 phiOperands.push_back(builder.getBuildPoint()->getId());
8115
8116 // Make the two kinds of operation symmetric with a "!"
8117 // || => emit "if (! left) result = right"
8118 // && => emit "if ( left) result = right"
8119 //
8120 // TODO: this runtime "not" for || could be avoided by adding functionality
8121 // to 'builder' to have an "else" without an "then"
8122 if (op == glslang::EOpLogicalOr)
8123 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8124
8125 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008126 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008127
8128 // emit right operand as the "then" part of the "if"
8129 builder.clearAccessChain();
8130 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008131 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008132
8133 // accumulate left operand's phi information
8134 phiOperands.push_back(rightId);
8135 phiOperands.push_back(builder.getBuildPoint()->getId());
8136
8137 // finish the "if"
8138 ifBuilder.makeEndIf();
8139
8140 // phi together the two results
8141 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8142}
8143
John Kessenicha28f7a72019-08-06 07:00:58 -06008144#ifndef GLSLANG_WEB
Rex Xu9d93a232016-05-05 12:30:44 +08008145// Return type Id of the imported set of extended instructions corresponds to the name.
8146// Import this set if it has not been imported yet.
8147spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8148{
8149 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8150 return extBuiltinMap[name];
8151 else {
Rex Xu51596642016-09-21 18:56:12 +08008152 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008153 spv::Id extBuiltins = builder.import(name);
8154 extBuiltinMap[name] = extBuiltins;
8155 return extBuiltins;
8156 }
8157}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008158#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008159
John Kessenich140f3df2015-06-26 16:58:36 -06008160}; // end anonymous namespace
8161
8162namespace glslang {
8163
John Kessenich68d78fd2015-07-12 19:28:10 -06008164void GetSpirvVersion(std::string& version)
8165{
John Kessenich9e55f632015-07-15 10:03:39 -06008166 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008167 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008168 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008169 version = buf;
8170}
8171
John Kessenicha372a3e2017-11-02 22:32:14 -06008172// For low-order part of the generator's magic number. Bump up
8173// when there is a change in the style (e.g., if SSA form changes,
8174// or a different instruction sequence to do something gets used).
8175int GetSpirvGeneratorVersion()
8176{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008177 // return 1; // start
8178 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008179 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008180 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008181 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008182 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8183 // versions 4 and 6 each generate OpArrayLength as it has long been done
8184 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06008185}
8186
John Kessenich140f3df2015-06-26 16:58:36 -06008187// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008188void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008189{
8190 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008191 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008192 if (out.fail())
8193 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008194 for (int i = 0; i < (int)spirv.size(); ++i) {
8195 unsigned int word = spirv[i];
8196 out.write((const char*)&word, 4);
8197 }
8198 out.close();
8199}
8200
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008201// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008202void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008203{
John Kessenich155d3512019-08-08 23:29:20 -06008204#ifndef GLSLANG_WEB
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008205 std::ofstream out;
8206 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008207 if (out.fail())
8208 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07008209 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06008210 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07008211 std::endl;
Flavio15017db2017-02-15 14:29:33 -08008212 if (varName != nullptr) {
8213 out << "\t #pragma once" << std::endl;
8214 out << "const uint32_t " << varName << "[] = {" << std::endl;
8215 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008216 const int WORDS_PER_LINE = 8;
8217 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8218 out << "\t";
8219 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8220 const unsigned int word = spirv[i + j];
8221 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8222 if (i + j + 1 < (int)spirv.size()) {
8223 out << ",";
8224 }
8225 }
8226 out << std::endl;
8227 }
Flavio15017db2017-02-15 14:29:33 -08008228 if (varName != nullptr) {
8229 out << "};";
8230 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008231 out.close();
John Kessenich155d3512019-08-08 23:29:20 -06008232#endif
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008233}
8234
John Kessenich140f3df2015-06-26 16:58:36 -06008235//
8236// Set up the glslang traversal
8237//
John Kessenich4e11b612018-08-30 16:56:59 -06008238void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008239{
Lei Zhang17535f72016-05-04 15:55:59 -04008240 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008241 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008242}
8243
John Kessenich4e11b612018-08-30 16:56:59 -06008244void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008245 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008246{
John Kessenich140f3df2015-06-26 16:58:36 -06008247 TIntermNode* root = intermediate.getTreeRoot();
8248
8249 if (root == 0)
8250 return;
8251
John Kessenich4e11b612018-08-30 16:56:59 -06008252 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008253 if (options == nullptr)
8254 options = &defaultOptions;
8255
John Kessenich4e11b612018-08-30 16:56:59 -06008256 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008257
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008258 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008259 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008260 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008261 it.dumpSpv(spirv);
8262
GregFfb03a552018-03-29 11:49:14 -06008263#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008264 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8265 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008266 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
8267 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer) {
John Kesseniche7df8e02018-08-22 17:12:46 -06008268 SpirvToolsLegalize(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008269 prelegalization = false;
8270 }
John Kessenich717c80a2018-08-23 15:17:10 -06008271
John Kessenich4e11b612018-08-30 16:56:59 -06008272 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008273 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008274
John Kessenich717c80a2018-08-23 15:17:10 -06008275 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008276 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008277
GregFcd1f1692017-09-21 18:40:22 -06008278#endif
8279
John Kessenich4e11b612018-08-30 16:56:59 -06008280 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008281}
8282
8283}; // end namespace glslang