blob: ccf112d36ee94d4c062221385ec09816e4b80b1f [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 Kessenich56364b62020-03-01 04:51:40 -07003// Copyright (C) 2015-2020 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):
Roy05a5b532020-01-03 16:21:34 +0800248 std::unordered_map<int, std::vector<int>> memberRemapper;
249 // for mapping glslang symbol struct to symbol Id
250 std::unordered_map<const glslang::TTypeList*, int> glslangTypeToIdMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600251 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700252 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600253 // Map pointee types for EbtReference to their forward pointers
254 std::map<const glslang::TType *, spv::Id> forwardPointers;
John Kessenich9c14f772019-06-17 08:38:35 -0600255 // Type forcing, for when SPIR-V wants a different type than the AST,
256 // requiring local translation to and from SPIR-V type on every access.
257 // Maps <builtin-variable-id -> AST-required-type-id>
258 std::unordered_map<spv::Id, spv::Id> forceType;
John Kessenich140f3df2015-06-26 16:58:36 -0600259};
260
261//
262// Helper functions for translating glslang representations to SPIR-V enumerants.
263//
264
265// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700266spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600267{
John Kessenich155d3512019-08-08 23:29:20 -0600268#ifdef GLSLANG_WEB
269 return spv::SourceLanguageESSL;
270#endif
271
John Kessenich66e2faf2016-03-12 18:34:36 -0700272 switch (source) {
273 case glslang::EShSourceGlsl:
274 switch (profile) {
275 case ENoProfile:
276 case ECoreProfile:
277 case ECompatibilityProfile:
278 return spv::SourceLanguageGLSL;
279 case EEsProfile:
280 return spv::SourceLanguageESSL;
281 default:
282 return spv::SourceLanguageUnknown;
283 }
284 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600285 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600286 default:
287 return spv::SourceLanguageUnknown;
288 }
289}
290
291// Translate glslang language (stage) to SPIR-V execution model.
292spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
293{
294 switch (stage) {
295 case EShLangVertex: return spv::ExecutionModelVertex;
John Kessenicha28f7a72019-08-06 07:00:58 -0600296 case EShLangFragment: return spv::ExecutionModelFragment;
John Kessenicha28f7a72019-08-06 07:00:58 -0600297 case EShLangCompute: return spv::ExecutionModelGLCompute;
John Kessenich51ed01c2019-10-10 11:40:11 -0600298#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -0600299 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
300 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
301 case EShLangGeometry: return spv::ExecutionModelGeometry;
Ashwin Leleff1783d2018-10-22 16:41:44 -0700302 case EShLangRayGenNV: return spv::ExecutionModelRayGenerationNV;
303 case EShLangIntersectNV: return spv::ExecutionModelIntersectionNV;
304 case EShLangAnyHitNV: return spv::ExecutionModelAnyHitNV;
305 case EShLangClosestHitNV: return spv::ExecutionModelClosestHitNV;
306 case EShLangMissNV: return spv::ExecutionModelMissNV;
307 case EShLangCallableNV: return spv::ExecutionModelCallableNV;
Chao Chen3c366992018-09-19 11:41:59 -0700308 case EShLangTaskNV: return spv::ExecutionModelTaskNV;
309 case EShLangMeshNV: return spv::ExecutionModelMeshNV;
310#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600311 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700312 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600313 return spv::ExecutionModelFragment;
314 }
315}
316
John Kessenich140f3df2015-06-26 16:58:36 -0600317// Translate glslang sampler type to SPIR-V dimensionality.
318spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
319{
320 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700321 case glslang::Esd1D: return spv::Dim1D;
322 case glslang::Esd2D: return spv::Dim2D;
323 case glslang::Esd3D: return spv::Dim3D;
324 case glslang::EsdCube: return spv::DimCube;
325 case glslang::EsdRect: return spv::DimRect;
326 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700327 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600328 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700329 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600330 return spv::Dim2D;
331 }
332}
333
John Kessenichf6640762016-08-01 19:44:00 -0600334// Translate glslang precision to SPIR-V precision decorations.
335spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600336{
John Kessenichf6640762016-08-01 19:44:00 -0600337 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700338 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600339 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600340 default:
341 return spv::NoPrecision;
342 }
343}
344
John Kessenichf6640762016-08-01 19:44:00 -0600345// Translate glslang type to SPIR-V precision decorations.
346spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
347{
348 return TranslatePrecisionDecoration(type.getQualifier().precision);
349}
350
John Kessenich140f3df2015-06-26 16:58:36 -0600351// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600352spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600353{
354 if (type.getBasicType() == glslang::EbtBlock) {
355 switch (type.getQualifier().storage) {
356 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600357 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600358 case glslang::EvqVaryingIn: return spv::DecorationBlock;
359 case glslang::EvqVaryingOut: return spv::DecorationBlock;
John Kessenicha28f7a72019-08-06 07:00:58 -0600360#ifndef GLSLANG_WEB
Chao Chenb50c02e2018-09-19 11:42:24 -0700361 case glslang::EvqPayloadNV: return spv::DecorationBlock;
362 case glslang::EvqPayloadInNV: return spv::DecorationBlock;
363 case glslang::EvqHitAttrNV: return spv::DecorationBlock;
Ashwin Leleff1783d2018-10-22 16:41:44 -0700364 case glslang::EvqCallableDataNV: return spv::DecorationBlock;
365 case glslang::EvqCallableDataInNV: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700366#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600367 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700368 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600369 break;
370 }
371 }
372
John Kessenich4016e382016-07-15 11:53:56 -0600373 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600374}
375
Rex Xu1da878f2016-02-21 20:59:01 +0800376// Translate glslang type to SPIR-V memory decorations.
Jeff Bolz36831c92018-09-05 10:11:41 -0500377void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory, bool useVulkanMemoryModel)
Rex Xu1da878f2016-02-21 20:59:01 +0800378{
Jeff Bolz36831c92018-09-05 10:11:41 -0500379 if (!useVulkanMemoryModel) {
John Kessenichf8d1d742019-10-21 06:55:11 -0600380 if (qualifier.isCoherent())
Jeff Bolz36831c92018-09-05 10:11:41 -0500381 memory.push_back(spv::DecorationCoherent);
John Kessenichf8d1d742019-10-21 06:55:11 -0600382 if (qualifier.isVolatile()) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500383 memory.push_back(spv::DecorationVolatile);
384 memory.push_back(spv::DecorationCoherent);
385 }
John Kessenich14b85d32018-06-04 15:36:03 -0600386 }
John Kessenichf8d1d742019-10-21 06:55:11 -0600387 if (qualifier.isRestrict())
Rex Xu1da878f2016-02-21 20:59:01 +0800388 memory.push_back(spv::DecorationRestrict);
John Kessenichdeec1932019-08-13 08:00:30 -0600389 if (qualifier.isReadOnly())
Rex Xu1da878f2016-02-21 20:59:01 +0800390 memory.push_back(spv::DecorationNonWritable);
John Kessenichdeec1932019-08-13 08:00:30 -0600391 if (qualifier.isWriteOnly())
Rex Xu1da878f2016-02-21 20:59:01 +0800392 memory.push_back(spv::DecorationNonReadable);
393}
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 Kessenichf8d1d742019-10-21 06:55:11 -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()) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001469 case glslang::EioPixelInterlockOrdered: mode = spv::ExecutionModePixelInterlockOrderedEXT;
1470 break;
1471 case glslang::EioPixelInterlockUnordered: mode = spv::ExecutionModePixelInterlockUnorderedEXT;
1472 break;
1473 case glslang::EioSampleInterlockOrdered: mode = spv::ExecutionModeSampleInterlockOrderedEXT;
1474 break;
1475 case glslang::EioSampleInterlockUnordered: mode = spv::ExecutionModeSampleInterlockUnorderedEXT;
1476 break;
1477 case glslang::EioShadingRateInterlockOrdered: mode = spv::ExecutionModeShadingRateInterlockOrderedEXT;
1478 break;
1479 case glslang::EioShadingRateInterlockUnordered: mode = spv::ExecutionModeShadingRateInterlockUnorderedEXT;
1480 break;
1481 default: mode = spv::ExecutionModeMax;
1482 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06001483 }
1484 if (mode != spv::ExecutionModeMax) {
1485 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1486 if (mode == spv::ExecutionModeShadingRateInterlockOrderedEXT ||
1487 mode == spv::ExecutionModeShadingRateInterlockUnorderedEXT) {
1488 builder.addCapability(spv::CapabilityFragmentShaderShadingRateInterlockEXT);
1489 } else if (mode == spv::ExecutionModePixelInterlockOrderedEXT ||
1490 mode == spv::ExecutionModePixelInterlockUnorderedEXT) {
1491 builder.addCapability(spv::CapabilityFragmentShaderPixelInterlockEXT);
1492 } else {
1493 builder.addCapability(spv::CapabilityFragmentShaderSampleInterlockEXT);
1494 }
1495 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
1496 }
John Kessenichb9197c82019-08-11 07:41:45 -06001497#endif
John Kessenicha28f7a72019-08-06 07:00:58 -06001498 break;
1499
John Kessenicha28f7a72019-08-06 07:00:58 -06001500 case EShLangCompute:
1501 builder.addCapability(spv::CapabilityShader);
1502 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1503 glslangIntermediate->getLocalSize(1),
1504 glslangIntermediate->getLocalSize(2));
1505 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1506 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1507 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1508 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1509 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1510 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1511 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1512 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1513 }
1514 break;
John Kessenich51ed01c2019-10-10 11:40:11 -06001515#ifndef GLSLANG_WEB
steve-lunarge7412492017-03-23 11:56:07 -06001516 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001517 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001518 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001519
steve-lunarge7412492017-03-23 11:56:07 -06001520 glslang::TLayoutGeometry primitive;
1521
1522 if (glslangIntermediate->getStage() == EShLangTessControl) {
1523 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1524 primitive = glslangIntermediate->getOutputPrimitive();
1525 } else {
1526 primitive = glslangIntermediate->getInputPrimitive();
1527 }
1528
1529 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001530 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1531 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1532 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001533 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001534 }
John Kessenich4016e382016-07-15 11:53:56 -06001535 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001536 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1537
John Kesseniche6903322015-10-13 16:29:02 -06001538 switch (glslangIntermediate->getVertexSpacing()) {
1539 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1540 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1541 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001542 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001543 }
John Kessenich4016e382016-07-15 11:53:56 -06001544 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001545 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1546
1547 switch (glslangIntermediate->getVertexOrder()) {
1548 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1549 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001550 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001551 }
John Kessenich4016e382016-07-15 11:53:56 -06001552 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001553 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1554
1555 if (glslangIntermediate->getPointMode())
1556 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001557 break;
1558
1559 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001560 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001561 switch (glslangIntermediate->getInputPrimitive()) {
1562 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1563 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1564 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001565 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001566 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001567 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001568 }
John Kessenich4016e382016-07-15 11:53:56 -06001569 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001570 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001571
John Kessenich140f3df2015-06-26 16:58:36 -06001572 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1573
1574 switch (glslangIntermediate->getOutputPrimitive()) {
1575 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1576 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1577 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001578 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001579 }
John Kessenich4016e382016-07-15 11:53:56 -06001580 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001581 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1582 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1583 break;
1584
Chao Chenb50c02e2018-09-19 11:42:24 -07001585 case EShLangRayGenNV:
1586 case EShLangIntersectNV:
1587 case EShLangAnyHitNV:
1588 case EShLangClosestHitNV:
1589 case EShLangMissNV:
1590 case EShLangCallableNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07001591 builder.addCapability(spv::CapabilityRayTracingNV);
1592 builder.addExtension("SPV_NV_ray_tracing");
Chao Chenb50c02e2018-09-19 11:42:24 -07001593 break;
Chao Chen3c366992018-09-19 11:41:59 -07001594 case EShLangTaskNV:
1595 case EShLangMeshNV:
1596 builder.addCapability(spv::CapabilityMeshShadingNV);
1597 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1598 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1599 glslangIntermediate->getLocalSize(1),
1600 glslangIntermediate->getLocalSize(2));
1601 if (glslangIntermediate->getStage() == EShLangMeshNV) {
1602 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1603 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV, glslangIntermediate->getPrimitives());
1604
1605 switch (glslangIntermediate->getOutputPrimitive()) {
1606 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1607 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1608 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1609 default: mode = spv::ExecutionModeMax; break;
1610 }
1611 if (mode != spv::ExecutionModeMax)
1612 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1613 }
1614 break;
1615#endif
1616
John Kessenich140f3df2015-06-26 16:58:36 -06001617 default:
1618 break;
1619 }
John Kessenich140f3df2015-06-26 16:58:36 -06001620}
1621
John Kessenichfca82622016-11-26 13:23:20 -07001622// Finish creating SPV, after the traversal is complete.
1623void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001624{
John Kessenichf04c51b2018-08-03 15:56:12 -06001625 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001626 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001627 builder.setBuildPoint(shaderEntry->getLastBlock());
1628 builder.leaveFunction();
1629 }
1630
John Kessenich7ba63412015-12-20 17:37:07 -07001631 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001632 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1633 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001634
David Neto8c3d5b42019-10-21 14:50:31 -04001635 // Add capabilities, extensions, remove unneeded decorations, etc.,
John Kessenichf04c51b2018-08-03 15:56:12 -06001636 // based on the resulting SPIR-V.
David Neto8c3d5b42019-10-21 14:50:31 -04001637 // Note: WebGPU code generation must have the opportunity to aggressively
1638 // prune unreachable merge blocks and continue targets.
John Kessenichf04c51b2018-08-03 15:56:12 -06001639 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001640}
1641
John Kessenichfca82622016-11-26 13:23:20 -07001642// Write the SPV into 'out'.
1643void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001644{
John Kessenichfca82622016-11-26 13:23:20 -07001645 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001646}
1647
1648//
1649// Implement the traversal functions.
1650//
1651// Return true from interior nodes to have the external traversal
1652// continue on to children. Return false if children were
1653// already processed.
1654//
1655
1656//
qining25262b32016-05-06 17:25:16 -04001657// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001658// - uniform/input reads
1659// - output writes
1660// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1661// - something simple that degenerates into the last bullet
1662//
1663void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1664{
qining75d1d802016-04-06 14:42:01 -04001665 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
Roy05a5b532020-01-03 16:21:34 +08001666 if (symbol->getType().isStruct())
1667 glslangTypeToIdMap[symbol->getType().getStruct()] = symbol->getId();
1668
qining75d1d802016-04-06 14:42:01 -04001669 if (symbol->getType().getQualifier().isSpecConstant())
1670 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1671
John Kessenich140f3df2015-06-26 16:58:36 -06001672 // getSymbolId() will set up all the IO decorations on the first call.
1673 // Formal function parameters were mapped during makeFunctions().
1674 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001675
John Kessenich7ba63412015-12-20 17:37:07 -07001676 if (builder.isPointer(id)) {
John Kessenich9c14f772019-06-17 08:38:35 -06001677 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
John Kessenich7c7731e2019-01-04 16:47:06 +07001678 // Consider adding to the OpEntryPoint interface list.
1679 // Only looking at structures if they have at least one member.
1680 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1681 spv::StorageClass sc = builder.getStorageClass(id);
1682 // Before SPIR-V 1.4, we only want to include Input and Output.
1683 // Starting with SPIR-V 1.4, we want all globals.
1684 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && sc != spv::StorageClassFunction) ||
1685 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
John Kessenich5f77d862017-09-19 11:09:59 -06001686 iOSet.insert(id);
John Kessenich7c7731e2019-01-04 16:47:06 +07001687 }
John Kessenich5f77d862017-09-19 11:09:59 -06001688 }
John Kessenich9c14f772019-06-17 08:38:35 -06001689
1690 // If the SPIR-V type is required to be different than the AST type,
1691 // translate now from the SPIR-V type to the AST type, for the consuming
1692 // operation.
1693 // Note this turns it from an l-value to an r-value.
1694 // Currently, all symbols needing this are inputs; avoid the map lookup when non-input.
1695 if (symbol->getType().getQualifier().storage == glslang::EvqVaryingIn)
1696 id = translateForcedType(id);
John Kessenich7ba63412015-12-20 17:37:07 -07001697 }
1698
1699 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001700 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001701 // Prepare to generate code for the access
1702
1703 // L-value chains will be computed left to right. We're on the symbol now,
1704 // which is the left-most part of the access chain, so now is "clear" time,
1705 // followed by setting the base.
1706 builder.clearAccessChain();
1707
1708 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001709 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001710 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001711 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001712 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001713 // These are also pure R-values.
John Kessenich9c14f772019-06-17 08:38:35 -06001714 // C) R-Values from type translation, see above call to translateForcedType()
John Kessenich6c292d32016-02-15 20:58:50 -07001715 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich9c14f772019-06-17 08:38:35 -06001716 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end() ||
1717 !builder.isPointerType(builder.getTypeId(id)))
John Kessenich140f3df2015-06-26 16:58:36 -06001718 builder.setAccessChainRValue(id);
1719 else
1720 builder.setAccessChainLValue(id);
1721 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001722
John Kessenichb9197c82019-08-11 07:41:45 -06001723#ifdef ENABLE_HLSL
John Kessenich5d610ee2018-03-07 18:05:55 -07001724 // Process linkage-only nodes for any special additional interface work.
1725 if (linkageOnly) {
1726 if (glslangIntermediate->getHlslFunctionality1()) {
1727 // Map implicit counter buffers to their originating buffers, which should have been
1728 // seen by now, given earlier pruning of unused counters, and preservation of order
1729 // of declaration.
1730 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1731 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1732 // Save possible originating buffers for counter buffers, keyed by
1733 // making the potential counter-buffer name.
1734 std::string keyName = symbol->getName().c_str();
1735 keyName = glslangIntermediate->addCounterBufferName(keyName);
1736 counterOriginator[keyName] = symbol;
1737 } else {
1738 // Handle a counter buffer, by finding the saved originating buffer.
1739 std::string keyName = symbol->getName().c_str();
1740 auto it = counterOriginator.find(keyName);
1741 if (it != counterOriginator.end()) {
1742 id = getSymbolId(it->second);
1743 if (id != spv::NoResult) {
1744 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001745 if (counterId != spv::NoResult) {
1746 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001747 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001748 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001749 }
1750 }
1751 }
1752 }
1753 }
1754 }
John Kessenich155d3512019-08-08 23:29:20 -06001755#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001756}
1757
1758bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1759{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001760 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Roy05a5b532020-01-03 16:21:34 +08001761 if (node->getLeft()->getAsSymbolNode() != nullptr && node->getLeft()->getType().isStruct()) {
1762 glslangTypeToIdMap[node->getLeft()->getType().getStruct()] = node->getLeft()->getAsSymbolNode()->getId();
1763 }
1764 if (node->getRight()->getAsSymbolNode() != nullptr && node->getRight()->getType().isStruct()) {
1765 glslangTypeToIdMap[node->getRight()->getType().getStruct()] = node->getRight()->getAsSymbolNode()->getId();
1766 }
John Kesseniche485c7a2017-05-31 18:50:53 -06001767
qining40887662016-04-03 22:20:42 -04001768 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1769 if (node->getType().getQualifier().isSpecConstant())
1770 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1771
John Kessenich140f3df2015-06-26 16:58:36 -06001772 // First, handle special cases
1773 switch (node->getOp()) {
1774 case glslang::EOpAssign:
1775 case glslang::EOpAddAssign:
1776 case glslang::EOpSubAssign:
1777 case glslang::EOpMulAssign:
1778 case glslang::EOpVectorTimesMatrixAssign:
1779 case glslang::EOpVectorTimesScalarAssign:
1780 case glslang::EOpMatrixTimesScalarAssign:
1781 case glslang::EOpMatrixTimesMatrixAssign:
1782 case glslang::EOpDivAssign:
1783 case glslang::EOpModAssign:
1784 case glslang::EOpAndAssign:
1785 case glslang::EOpInclusiveOrAssign:
1786 case glslang::EOpExclusiveOrAssign:
1787 case glslang::EOpLeftShiftAssign:
1788 case glslang::EOpRightShiftAssign:
1789 // A bin-op assign "a += b" means the same thing as "a = a + b"
1790 // where a is evaluated before b. For a simple assignment, GLSL
1791 // says to evaluate the left before the right. So, always, left
1792 // node then right node.
1793 {
1794 // get the left l-value, save it away
1795 builder.clearAccessChain();
1796 node->getLeft()->traverse(this);
1797 spv::Builder::AccessChain lValue = builder.getAccessChain();
1798
1799 // evaluate the right
1800 builder.clearAccessChain();
1801 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001802 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001803
1804 if (node->getOp() != glslang::EOpAssign) {
1805 // the left is also an r-value
1806 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001807 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001808
1809 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001810 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001811 TranslateNoContractionDecoration(node->getType().getQualifier()),
1812 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001813 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001814 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1815 node->getType().getBasicType());
1816
1817 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001818 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001819 }
1820
1821 // store the result
1822 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001823 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001824
1825 // assignments are expressions having an rValue after they are evaluated...
1826 builder.clearAccessChain();
1827 builder.setAccessChainRValue(rValue);
1828 }
1829 return false;
1830 case glslang::EOpIndexDirect:
1831 case glslang::EOpIndexDirectStruct:
1832 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001833 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001834 // Get the left part of the access chain.
1835 node->getLeft()->traverse(this);
1836
1837 // Add the next element in the chain
1838
David Netoa901ffe2016-06-08 14:11:40 +01001839 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001840 if (! node->getLeft()->getType().isArray() &&
1841 node->getLeft()->getType().isVector() &&
1842 node->getOp() == glslang::EOpIndexDirect) {
1843 // This is essentially a hard-coded vector swizzle of size 1,
1844 // so short circuit the access-chain stuff with a swizzle.
1845 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001846 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001847 int dummySize;
1848 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1849 TranslateCoherent(node->getLeft()->getType()),
1850 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001851 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001852
1853 // Load through a block reference is performed with a dot operator that
1854 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1855 // do a load and reset the access chain.
John Kessenich7015bd62019-08-01 03:28:08 -06001856 if (node->getLeft()->isReference() &&
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001857 !node->getLeft()->getType().isArray() &&
1858 node->getOp() == glslang::EOpIndexDirectStruct)
1859 {
1860 spv::Id left = accessChainLoad(node->getLeft()->getType());
1861 builder.clearAccessChain();
1862 builder.setAccessChainLValue(left);
1863 }
1864
David Netoa901ffe2016-06-08 14:11:40 +01001865 int spvIndex = glslangIndex;
1866 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1867 node->getOp() == glslang::EOpIndexDirectStruct)
1868 {
1869 // This may be, e.g., an anonymous block-member selection, which generally need
1870 // index remapping due to hidden members in anonymous blocks.
Roy05a5b532020-01-03 16:21:34 +08001871 int glslangId = glslangTypeToIdMap[node->getLeft()->getType().getStruct()];
1872 if (memberRemapper.find(glslangId) != memberRemapper.end()) {
1873 std::vector<int>& remapper = memberRemapper[glslangId];
1874 assert(remapper.size() > 0);
1875 spvIndex = remapper[glslangIndex];
1876 }
David Netoa901ffe2016-06-08 14:11:40 +01001877 }
John Kessenichebb50532016-05-16 19:22:05 -06001878
David Netoa901ffe2016-06-08 14:11:40 +01001879 // normal case for indexing array or structure or block
Jeff Bolz7895e472019-03-06 13:34:10 -06001880 builder.accessChainPush(builder.makeIntConstant(spvIndex), TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001881
1882 // Add capabilities here for accessing PointSize and clip/cull distance.
1883 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001884 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001885 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001886 }
1887 }
1888 return false;
1889 case glslang::EOpIndexIndirect:
1890 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001891 // Array, matrix, or vector indirection with variable index.
1892 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06001893 // matrices are arrays of vectors, so will also work for a matrix.
1894 // Will use the access chain's 'component' for variable index into a vector.
1895
1896 // This adapter is building access chains left to right.
1897 // Set up the access chain to the left.
1898 node->getLeft()->traverse(this);
1899
1900 // save it so that computing the right side doesn't trash it
1901 spv::Builder::AccessChain partial = builder.getAccessChain();
1902
1903 // compute the next index in the chain
1904 builder.clearAccessChain();
1905 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001906 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001907
John Kessenich5611c6d2018-04-05 11:25:02 -06001908 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1909
John Kessenich140f3df2015-06-26 16:58:36 -06001910 // restore the saved access chain
1911 builder.setAccessChain(partial);
1912
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001913 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1914 int dummySize;
1915 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1916 TranslateCoherent(node->getLeft()->getType()),
1917 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
1918 } else
Jeff Bolz7895e472019-03-06 13:34:10 -06001919 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001920 }
1921 return false;
1922 case glslang::EOpVectorSwizzle:
1923 {
1924 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001925 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001926 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001927 int dummySize;
1928 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1929 TranslateCoherent(node->getLeft()->getType()),
1930 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001931 }
1932 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001933 case glslang::EOpMatrixSwizzle:
1934 logger->missingFunctionality("matrix swizzle");
1935 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001936 case glslang::EOpLogicalOr:
1937 case glslang::EOpLogicalAnd:
1938 {
1939
1940 // These may require short circuiting, but can sometimes be done as straight
1941 // binary operations. The right operand must be short circuited if it has
1942 // side effects, and should probably be if it is complex.
1943 if (isTrivial(node->getRight()->getAsTyped()))
1944 break; // handle below as a normal binary operation
1945 // otherwise, we need to do dynamic short circuiting on the right operand
1946 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1947 builder.clearAccessChain();
1948 builder.setAccessChainRValue(result);
1949 }
1950 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001951 default:
1952 break;
1953 }
1954
1955 // Assume generic binary op...
1956
John Kessenich32cfd492016-02-02 12:37:46 -07001957 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001958 builder.clearAccessChain();
1959 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001960 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001961
John Kessenich32cfd492016-02-02 12:37:46 -07001962 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001963 builder.clearAccessChain();
1964 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001965 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001966
John Kessenich32cfd492016-02-02 12:37:46 -07001967 // get result
John Kessenichead86222018-03-28 18:01:20 -06001968 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001969 TranslateNoContractionDecoration(node->getType().getQualifier()),
1970 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001971 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001972 convertGlslangToSpvType(node->getType()), left, right,
1973 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001974
John Kessenich50e57562015-12-21 21:21:11 -07001975 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001976 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001977 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001978 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001979 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001980 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001981 return false;
1982 }
John Kessenich140f3df2015-06-26 16:58:36 -06001983}
1984
John Kessenich9c14f772019-06-17 08:38:35 -06001985// Figure out what, if any, type changes are needed when accessing a specific built-in.
1986// Returns <the type SPIR-V requires for declarion, the type to translate to on use>.
1987// Also see comment for 'forceType', regarding tracking SPIR-V-required types.
1988std::pair<spv::Id, spv::Id> TGlslangToSpvTraverser::getForcedType(spv::BuiltIn builtIn,
1989 const glslang::TType& glslangType)
1990{
1991 switch(builtIn)
1992 {
1993 case spv::BuiltInSubgroupEqMask:
1994 case spv::BuiltInSubgroupGeMask:
1995 case spv::BuiltInSubgroupGtMask:
1996 case spv::BuiltInSubgroupLeMask:
1997 case spv::BuiltInSubgroupLtMask: {
1998 // these require changing a 64-bit scaler -> a vector of 32-bit components
1999 if (glslangType.isVector())
2000 break;
2001 std::pair<spv::Id, spv::Id> ret(builder.makeVectorType(builder.makeUintType(32), 4),
2002 builder.makeUintType(64));
2003 return ret;
2004 }
2005 default:
2006 break;
2007 }
2008
2009 std::pair<spv::Id, spv::Id> ret(spv::NoType, spv::NoType);
2010 return ret;
2011}
2012
2013// For an object previously identified (see getForcedType() and forceType)
2014// as needing type translations, do the translation needed for a load, turning
2015// an L-value into in R-value.
2016spv::Id TGlslangToSpvTraverser::translateForcedType(spv::Id object)
2017{
2018 const auto forceIt = forceType.find(object);
2019 if (forceIt == forceType.end())
2020 return object;
2021
2022 spv::Id desiredTypeId = forceIt->second;
2023 spv::Id objectTypeId = builder.getTypeId(object);
2024 assert(builder.isPointerType(objectTypeId));
2025 objectTypeId = builder.getContainedTypeId(objectTypeId);
2026 if (builder.isVectorType(objectTypeId) &&
2027 builder.getScalarTypeWidth(builder.getContainedTypeId(objectTypeId)) == 32) {
2028 if (builder.getScalarTypeWidth(desiredTypeId) == 64) {
2029 // handle 32-bit v.xy* -> 64-bit
2030 builder.clearAccessChain();
2031 builder.setAccessChainLValue(object);
2032 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2033 std::vector<spv::Id> components;
2034 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 0));
2035 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 1));
2036
2037 spv::Id vecType = builder.makeVectorType(builder.getContainedTypeId(objectTypeId), 2);
2038 return builder.createUnaryOp(spv::OpBitcast, desiredTypeId,
2039 builder.createCompositeConstruct(vecType, components));
2040 } else {
2041 logger->missingFunctionality("forcing 32-bit vector type to non 64-bit scalar");
2042 }
2043 } else {
2044 logger->missingFunctionality("forcing non 32-bit vector type");
2045 }
2046
2047 return object;
2048}
2049
John Kessenich140f3df2015-06-26 16:58:36 -06002050bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
2051{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002052 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002053
qining40887662016-04-03 22:20:42 -04002054 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2055 if (node->getType().getQualifier().isSpecConstant())
2056 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2057
John Kessenichfc51d282015-08-19 13:34:18 -06002058 spv::Id result = spv::NoResult;
2059
2060 // try texturing first
2061 result = createImageTextureFunctionCall(node);
2062 if (result != spv::NoResult) {
2063 builder.clearAccessChain();
2064 builder.setAccessChainRValue(result);
2065
2066 return false; // done with this node
2067 }
2068
2069 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06002070
2071 if (node->getOp() == glslang::EOpArrayLength) {
2072 // Quite special; won't want to evaluate the operand.
2073
John Kessenich5611c6d2018-04-05 11:25:02 -06002074 // Currently, the front-end does not allow .length() on an array until it is sized,
2075 // except for the last block membeor of an SSBO.
2076 // TODO: If this changes, link-time sized arrays might show up here, and need their
2077 // size extracted.
2078
John Kessenichc9a80832015-09-12 12:17:44 -06002079 // Normal .length() would have been constant folded by the front-end.
2080 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06002081 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06002082
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002083 spv::Id length;
2084 if (node->getOperand()->getType().isCoopMat()) {
2085 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2086
2087 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
2088 assert(builder.isCooperativeMatrixType(typeId));
2089
2090 length = builder.createCooperativeMatrixLength(typeId);
2091 } else {
2092 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
2093 block->traverse(this);
2094 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
2095 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
2096 }
John Kessenichc9a80832015-09-12 12:17:44 -06002097
John Kessenich8c869672018-11-28 07:01:37 -07002098 // GLSL semantics say the result of .length() is an int, while SPIR-V says
2099 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
2100 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002101 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
2102 if (builder.isInSpecConstCodeGenMode()) {
2103 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
2104 } else {
2105 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
2106 }
2107 }
John Kessenich8c869672018-11-28 07:01:37 -07002108
John Kessenichc9a80832015-09-12 12:17:44 -06002109 builder.clearAccessChain();
2110 builder.setAccessChainRValue(length);
2111
2112 return false;
2113 }
2114
John Kessenichfc51d282015-08-19 13:34:18 -06002115 // Start by evaluating the operand
2116
John Kessenich8c8505c2016-07-26 12:50:38 -06002117 // Does it need a swizzle inversion? If so, evaluation is inverted;
2118 // operate first on the swizzle base, then apply the swizzle.
2119 spv::Id invertedType = spv::NoType;
2120 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
2121 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
2122 invertedType = getInvertedSwizzleType(*node->getOperand());
2123
John Kessenich140f3df2015-06-26 16:58:36 -06002124 builder.clearAccessChain();
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002125 TIntermNode *operandNode;
John Kessenich8c8505c2016-07-26 12:50:38 -06002126 if (invertedType != spv::NoType)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002127 operandNode = node->getOperand()->getAsBinaryNode()->getLeft();
John Kessenich8c8505c2016-07-26 12:50:38 -06002128 else
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002129 operandNode = node->getOperand();
2130
2131 operandNode->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08002132
Rex Xufc618912015-09-09 16:42:49 +08002133 spv::Id operand = spv::NoResult;
2134
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002135 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2136
John Kessenichfb4f2332019-08-09 03:49:15 -06002137#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08002138 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
2139 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08002140 node->getOp() == glslang::EOpAtomicCounter ||
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002141 node->getOp() == glslang::EOpInterpolateAtCentroid) {
Rex Xufc618912015-09-09 16:42:49 +08002142 operand = builder.accessChainGetLValue(); // Special case l-value operands
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002143 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2144 lvalueCoherentFlags |= TranslateCoherent(operandNode->getAsTyped()->getType());
2145 } else
John Kessenichfb4f2332019-08-09 03:49:15 -06002146#endif
2147 {
John Kessenich32cfd492016-02-02 12:37:46 -07002148 operand = accessChainLoad(node->getOperand()->getType());
John Kessenichfb4f2332019-08-09 03:49:15 -06002149 }
John Kessenich140f3df2015-06-26 16:58:36 -06002150
John Kessenichead86222018-03-28 18:01:20 -06002151 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002152 TranslateNoContractionDecoration(node->getType().getQualifier()),
2153 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06002154
2155 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06002156 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06002157 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002158
2159 // if not, then possibly an operation
2160 if (! result)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002161 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType(), lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002162
2163 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06002164 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06002165 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenichb9197c82019-08-11 07:41:45 -06002166 decorations.addNonUniform(builder, result);
John Kessenich5611c6d2018-04-05 11:25:02 -06002167 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002168
John Kessenich140f3df2015-06-26 16:58:36 -06002169 builder.clearAccessChain();
2170 builder.setAccessChainRValue(result);
2171
2172 return false; // done with this node
2173 }
2174
2175 // it must be a special case, check...
2176 switch (node->getOp()) {
2177 case glslang::EOpPostIncrement:
2178 case glslang::EOpPostDecrement:
2179 case glslang::EOpPreIncrement:
2180 case glslang::EOpPreDecrement:
2181 {
2182 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08002183 spv::Id one = 0;
2184 if (node->getBasicType() == glslang::EbtFloat)
2185 one = builder.makeFloatConstant(1.0F);
John Kessenich39697cd2019-08-08 10:35:51 -06002186#ifndef GLSLANG_WEB
Rex Xuce31aea2016-07-29 16:13:04 +08002187 else if (node->getBasicType() == glslang::EbtDouble)
2188 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002189 else if (node->getBasicType() == glslang::EbtFloat16)
2190 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07002191 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
2192 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08002193 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
2194 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002195 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2196 one = builder.makeInt64Constant(1);
John Kessenich39697cd2019-08-08 10:35:51 -06002197#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08002198 else
2199 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002200 glslang::TOperator op;
2201 if (node->getOp() == glslang::EOpPreIncrement ||
2202 node->getOp() == glslang::EOpPostIncrement)
2203 op = glslang::EOpAdd;
2204 else
2205 op = glslang::EOpSub;
2206
John Kessenichead86222018-03-28 18:01:20 -06002207 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002208 convertGlslangToSpvType(node->getType()), operand, one,
2209 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002210 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002211
2212 // The result of operation is always stored, but conditionally the
2213 // consumed result. The consumed result is always an r-value.
2214 builder.accessChainStore(result);
2215 builder.clearAccessChain();
2216 if (node->getOp() == glslang::EOpPreIncrement ||
2217 node->getOp() == glslang::EOpPreDecrement)
2218 builder.setAccessChainRValue(result);
2219 else
2220 builder.setAccessChainRValue(operand);
2221 }
2222
2223 return false;
2224
John Kessenich155d3512019-08-08 23:29:20 -06002225#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06002226 case glslang::EOpEmitStreamVertex:
2227 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2228 return false;
2229 case glslang::EOpEndStreamPrimitive:
2230 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2231 return false;
John Kessenich155d3512019-08-08 23:29:20 -06002232#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002233
2234 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002235 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002236 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002237 }
John Kessenich140f3df2015-06-26 16:58:36 -06002238}
2239
Jeff Bolz53134492019-06-25 13:31:10 -05002240// Construct a composite object, recursively copying members if their types don't match
2241spv::Id TGlslangToSpvTraverser::createCompositeConstruct(spv::Id resultTypeId, std::vector<spv::Id> constituents)
2242{
2243 for (int c = 0; c < (int)constituents.size(); ++c) {
2244 spv::Id& constituent = constituents[c];
2245 spv::Id lType = builder.getContainedTypeId(resultTypeId, c);
2246 spv::Id rType = builder.getTypeId(constituent);
2247 if (lType != rType) {
2248 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
2249 constituent = builder.createUnaryOp(spv::OpCopyLogical, lType, constituent);
2250 } else if (builder.isStructType(rType)) {
2251 std::vector<spv::Id> rTypeConstituents;
2252 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2253 for (int i = 0; i < numrTypeConstituents; ++i) {
2254 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, builder.getContainedTypeId(rType, i), i));
2255 }
2256 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2257 } else {
2258 assert(builder.isArrayType(rType));
2259 std::vector<spv::Id> rTypeConstituents;
2260 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2261
2262 spv::Id elementRType = builder.getContainedTypeId(rType);
2263 for (int i = 0; i < numrTypeConstituents; ++i) {
2264 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, elementRType, i));
2265 }
2266 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2267 }
2268 }
2269 }
2270 return builder.createCompositeConstruct(resultTypeId, constituents);
2271}
2272
John Kessenich140f3df2015-06-26 16:58:36 -06002273bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2274{
qining27e04a02016-04-14 16:40:20 -04002275 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2276 if (node->getType().getQualifier().isSpecConstant())
2277 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2278
John Kessenichfc51d282015-08-19 13:34:18 -06002279 spv::Id result = spv::NoResult;
John Kessenichbbbd9a22020-03-03 07:21:37 -07002280 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2281 spv::Builder::AccessChain complexLvalue; // for holding swizzling l-values too complex for SPIR-V, for at out parameter
2282 spv::Id temporaryLvalue = spv::NoResult; // temporary to pass, as proxy for complexLValue
2283
John Kessenich8c8505c2016-07-26 12:50:38 -06002284 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002285
2286 // try texturing
2287 result = createImageTextureFunctionCall(node);
2288 if (result != spv::NoResult) {
2289 builder.clearAccessChain();
2290 builder.setAccessChainRValue(result);
2291
2292 return false;
John Kessenicha28f7a72019-08-06 07:00:58 -06002293 }
2294#ifndef GLSLANG_WEB
2295 else if (node->getOp() == glslang::EOpImageStore ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002296 node->getOp() == glslang::EOpImageStoreLod ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002297 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002298 // "imageStore" is a special case, which has no result
2299 return false;
2300 }
John Kessenicha28f7a72019-08-06 07:00:58 -06002301#endif
John Kessenichfc51d282015-08-19 13:34:18 -06002302
John Kessenich140f3df2015-06-26 16:58:36 -06002303 glslang::TOperator binOp = glslang::EOpNull;
2304 bool reduceComparison = true;
2305 bool isMatrix = false;
2306 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002307 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002308
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002309 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2310
John Kessenich140f3df2015-06-26 16:58:36 -06002311 assert(node->getOp());
2312
John Kessenichf6640762016-08-01 19:44:00 -06002313 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002314
2315 switch (node->getOp()) {
2316 case glslang::EOpSequence:
2317 {
2318 if (preVisit)
2319 ++sequenceDepth;
2320 else
2321 --sequenceDepth;
2322
2323 if (sequenceDepth == 1) {
2324 // If this is the parent node of all the functions, we want to see them
2325 // early, so all call points have actual SPIR-V functions to reference.
2326 // In all cases, still let the traverser visit the children for us.
2327 makeFunctions(node->getAsAggregate()->getSequence());
2328
John Kessenich6fccb3c2016-09-19 16:01:41 -06002329 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002330 // anything else gets there, so visit out of order, doing them all now.
2331 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2332
John Kessenich6a60c2f2016-12-08 21:01:59 -07002333 // 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 -06002334 // so do them manually.
2335 visitFunctions(node->getAsAggregate()->getSequence());
2336
2337 return false;
2338 }
2339
2340 return true;
2341 }
2342 case glslang::EOpLinkerObjects:
2343 {
2344 if (visit == glslang::EvPreVisit)
2345 linkageOnly = true;
2346 else
2347 linkageOnly = false;
2348
2349 return true;
2350 }
2351 case glslang::EOpComma:
2352 {
2353 // processing from left to right naturally leaves the right-most
2354 // lying around in the access chain
2355 glslang::TIntermSequence& glslangOperands = node->getSequence();
2356 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2357 glslangOperands[i]->traverse(this);
2358
2359 return false;
2360 }
2361 case glslang::EOpFunction:
2362 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002363 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002364 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002365 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002366 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002367 } else {
2368 handleFunctionEntry(node);
2369 }
2370 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002371 if (inEntryPoint)
2372 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002373 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002374 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002375 }
2376
2377 return true;
2378 case glslang::EOpParameters:
2379 // Parameters will have been consumed by EOpFunction processing, but not
2380 // the body, so we still visited the function node's children, making this
2381 // child redundant.
2382 return false;
2383 case glslang::EOpFunctionCall:
2384 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002385 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002386 if (node->isUserDefined())
2387 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07002388 // 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 -07002389 if (result) {
2390 builder.clearAccessChain();
2391 builder.setAccessChainRValue(result);
2392 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002393 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002394
2395 return false;
2396 }
2397 case glslang::EOpConstructMat2x2:
2398 case glslang::EOpConstructMat2x3:
2399 case glslang::EOpConstructMat2x4:
2400 case glslang::EOpConstructMat3x2:
2401 case glslang::EOpConstructMat3x3:
2402 case glslang::EOpConstructMat3x4:
2403 case glslang::EOpConstructMat4x2:
2404 case glslang::EOpConstructMat4x3:
2405 case glslang::EOpConstructMat4x4:
2406 case glslang::EOpConstructDMat2x2:
2407 case glslang::EOpConstructDMat2x3:
2408 case glslang::EOpConstructDMat2x4:
2409 case glslang::EOpConstructDMat3x2:
2410 case glslang::EOpConstructDMat3x3:
2411 case glslang::EOpConstructDMat3x4:
2412 case glslang::EOpConstructDMat4x2:
2413 case glslang::EOpConstructDMat4x3:
2414 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002415 case glslang::EOpConstructIMat2x2:
2416 case glslang::EOpConstructIMat2x3:
2417 case glslang::EOpConstructIMat2x4:
2418 case glslang::EOpConstructIMat3x2:
2419 case glslang::EOpConstructIMat3x3:
2420 case glslang::EOpConstructIMat3x4:
2421 case glslang::EOpConstructIMat4x2:
2422 case glslang::EOpConstructIMat4x3:
2423 case glslang::EOpConstructIMat4x4:
2424 case glslang::EOpConstructUMat2x2:
2425 case glslang::EOpConstructUMat2x3:
2426 case glslang::EOpConstructUMat2x4:
2427 case glslang::EOpConstructUMat3x2:
2428 case glslang::EOpConstructUMat3x3:
2429 case glslang::EOpConstructUMat3x4:
2430 case glslang::EOpConstructUMat4x2:
2431 case glslang::EOpConstructUMat4x3:
2432 case glslang::EOpConstructUMat4x4:
2433 case glslang::EOpConstructBMat2x2:
2434 case glslang::EOpConstructBMat2x3:
2435 case glslang::EOpConstructBMat2x4:
2436 case glslang::EOpConstructBMat3x2:
2437 case glslang::EOpConstructBMat3x3:
2438 case glslang::EOpConstructBMat3x4:
2439 case glslang::EOpConstructBMat4x2:
2440 case glslang::EOpConstructBMat4x3:
2441 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002442 case glslang::EOpConstructF16Mat2x2:
2443 case glslang::EOpConstructF16Mat2x3:
2444 case glslang::EOpConstructF16Mat2x4:
2445 case glslang::EOpConstructF16Mat3x2:
2446 case glslang::EOpConstructF16Mat3x3:
2447 case glslang::EOpConstructF16Mat3x4:
2448 case glslang::EOpConstructF16Mat4x2:
2449 case glslang::EOpConstructF16Mat4x3:
2450 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002451 isMatrix = true;
2452 // fall through
2453 case glslang::EOpConstructFloat:
2454 case glslang::EOpConstructVec2:
2455 case glslang::EOpConstructVec3:
2456 case glslang::EOpConstructVec4:
2457 case glslang::EOpConstructDouble:
2458 case glslang::EOpConstructDVec2:
2459 case glslang::EOpConstructDVec3:
2460 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002461 case glslang::EOpConstructFloat16:
2462 case glslang::EOpConstructF16Vec2:
2463 case glslang::EOpConstructF16Vec3:
2464 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002465 case glslang::EOpConstructBool:
2466 case glslang::EOpConstructBVec2:
2467 case glslang::EOpConstructBVec3:
2468 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002469 case glslang::EOpConstructInt8:
2470 case glslang::EOpConstructI8Vec2:
2471 case glslang::EOpConstructI8Vec3:
2472 case glslang::EOpConstructI8Vec4:
2473 case glslang::EOpConstructUint8:
2474 case glslang::EOpConstructU8Vec2:
2475 case glslang::EOpConstructU8Vec3:
2476 case glslang::EOpConstructU8Vec4:
2477 case glslang::EOpConstructInt16:
2478 case glslang::EOpConstructI16Vec2:
2479 case glslang::EOpConstructI16Vec3:
2480 case glslang::EOpConstructI16Vec4:
2481 case glslang::EOpConstructUint16:
2482 case glslang::EOpConstructU16Vec2:
2483 case glslang::EOpConstructU16Vec3:
2484 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002485 case glslang::EOpConstructInt:
2486 case glslang::EOpConstructIVec2:
2487 case glslang::EOpConstructIVec3:
2488 case glslang::EOpConstructIVec4:
2489 case glslang::EOpConstructUint:
2490 case glslang::EOpConstructUVec2:
2491 case glslang::EOpConstructUVec3:
2492 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002493 case glslang::EOpConstructInt64:
2494 case glslang::EOpConstructI64Vec2:
2495 case glslang::EOpConstructI64Vec3:
2496 case glslang::EOpConstructI64Vec4:
2497 case glslang::EOpConstructUint64:
2498 case glslang::EOpConstructU64Vec2:
2499 case glslang::EOpConstructU64Vec3:
2500 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002501 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002502 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002503 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002504 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002505 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002506 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002507 std::vector<spv::Id> arguments;
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002508 translateArguments(*node, arguments, lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002509 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002510 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002511 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002512 else if (node->getOp() == glslang::EOpConstructStruct ||
2513 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2514 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002515 std::vector<spv::Id> constituents;
2516 for (int c = 0; c < (int)arguments.size(); ++c)
2517 constituents.push_back(arguments[c]);
Jeff Bolz53134492019-06-25 13:31:10 -05002518 constructed = createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002519 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002520 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002521 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002522 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002523
2524 builder.clearAccessChain();
2525 builder.setAccessChainRValue(constructed);
2526
2527 return false;
2528 }
2529
2530 // These six are component-wise compares with component-wise results.
2531 // Forward on to createBinaryOperation(), requesting a vector result.
2532 case glslang::EOpLessThan:
2533 case glslang::EOpGreaterThan:
2534 case glslang::EOpLessThanEqual:
2535 case glslang::EOpGreaterThanEqual:
2536 case glslang::EOpVectorEqual:
2537 case glslang::EOpVectorNotEqual:
2538 {
2539 // Map the operation to a binary
2540 binOp = node->getOp();
2541 reduceComparison = false;
2542 switch (node->getOp()) {
2543 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2544 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2545 default: binOp = node->getOp(); break;
2546 }
2547
2548 break;
2549 }
2550 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002551 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002552 binOp = glslang::EOpMul;
2553 break;
2554 case glslang::EOpOuterProduct:
2555 // two vectors multiplied to make a matrix
2556 binOp = glslang::EOpOuterProduct;
2557 break;
2558 case glslang::EOpDot:
2559 {
qining25262b32016-05-06 17:25:16 -04002560 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002561 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002562 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002563 binOp = glslang::EOpMul;
2564 break;
2565 }
2566 case glslang::EOpMod:
2567 // when an aggregate, this is the floating-point mod built-in function,
2568 // which can be emitted by the one in createBinaryOperation()
2569 binOp = glslang::EOpMod;
2570 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002571
John Kessenich140f3df2015-06-26 16:58:36 -06002572 case glslang::EOpEmitVertex:
2573 case glslang::EOpEndPrimitive:
2574 case glslang::EOpBarrier:
2575 case glslang::EOpMemoryBarrier:
2576 case glslang::EOpMemoryBarrierAtomicCounter:
2577 case glslang::EOpMemoryBarrierBuffer:
2578 case glslang::EOpMemoryBarrierImage:
2579 case glslang::EOpMemoryBarrierShared:
2580 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002581 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002582 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002583 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002584 case glslang::EOpWorkgroupMemoryBarrier:
2585 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002586 case glslang::EOpSubgroupBarrier:
2587 case glslang::EOpSubgroupMemoryBarrier:
2588 case glslang::EOpSubgroupMemoryBarrierBuffer:
2589 case glslang::EOpSubgroupMemoryBarrierImage:
2590 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002591 noReturnValue = true;
2592 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2593 break;
2594
John Kessenich426394d2015-07-23 10:22:48 -06002595 case glslang::EOpAtomicAdd:
2596 case glslang::EOpAtomicMin:
2597 case glslang::EOpAtomicMax:
2598 case glslang::EOpAtomicAnd:
2599 case glslang::EOpAtomicOr:
2600 case glslang::EOpAtomicXor:
2601 case glslang::EOpAtomicExchange:
2602 case glslang::EOpAtomicCompSwap:
2603 atomic = true;
2604 break;
2605
John Kesseniche5eee8f2019-10-18 01:03:11 -06002606#ifndef GLSLANG_WEB
2607 case glslang::EOpAtomicStore:
2608 noReturnValue = true;
2609 // fallthrough
2610 case glslang::EOpAtomicLoad:
2611 atomic = true;
2612 break;
2613
John Kessenich0d0c6d32017-07-23 16:08:26 -06002614 case glslang::EOpAtomicCounterAdd:
2615 case glslang::EOpAtomicCounterSubtract:
2616 case glslang::EOpAtomicCounterMin:
2617 case glslang::EOpAtomicCounterMax:
2618 case glslang::EOpAtomicCounterAnd:
2619 case glslang::EOpAtomicCounterOr:
2620 case glslang::EOpAtomicCounterXor:
2621 case glslang::EOpAtomicCounterExchange:
2622 case glslang::EOpAtomicCounterCompSwap:
2623 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2624 builder.addCapability(spv::CapabilityAtomicStorageOps);
2625 atomic = true;
2626 break;
2627
Ian Romanickb3bd4022019-01-21 08:57:25 -08002628 case glslang::EOpAbsDifference:
2629 case glslang::EOpAddSaturate:
2630 case glslang::EOpSubSaturate:
2631 case glslang::EOpAverage:
2632 case glslang::EOpAverageRounded:
2633 case glslang::EOpMul32x16:
2634 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
2635 builder.addExtension("SPV_INTEL_shader_integer_functions2");
2636 binOp = node->getOp();
2637 break;
2638
Chao Chenb50c02e2018-09-19 11:42:24 -07002639 case glslang::EOpIgnoreIntersectionNV:
2640 case glslang::EOpTerminateRayNV:
2641 case glslang::EOpTraceNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07002642 case glslang::EOpExecuteCallableNV:
Chao Chen3c366992018-09-19 11:41:59 -07002643 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2644 noReturnValue = true;
2645 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002646 case glslang::EOpCooperativeMatrixLoad:
2647 case glslang::EOpCooperativeMatrixStore:
2648 noReturnValue = true;
2649 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002650 case glslang::EOpBeginInvocationInterlock:
2651 case glslang::EOpEndInvocationInterlock:
2652 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2653 noReturnValue = true;
2654 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002655#endif
Chao Chen3c366992018-09-19 11:41:59 -07002656
John Kessenich140f3df2015-06-26 16:58:36 -06002657 default:
2658 break;
2659 }
2660
2661 //
2662 // See if it maps to a regular operation.
2663 //
John Kessenich140f3df2015-06-26 16:58:36 -06002664 if (binOp != glslang::EOpNull) {
2665 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2666 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2667 assert(left && right);
2668
2669 builder.clearAccessChain();
2670 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002671 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002672
2673 builder.clearAccessChain();
2674 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002675 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002676
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002677 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002678 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002679 TranslateNoContractionDecoration(node->getType().getQualifier()),
2680 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002681 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002682 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002683 left->getType().getBasicType(), reduceComparison);
2684
2685 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002686 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002687 builder.clearAccessChain();
2688 builder.setAccessChainRValue(result);
2689
2690 return false;
2691 }
2692
John Kessenich426394d2015-07-23 10:22:48 -06002693 //
2694 // Create the list of operands.
2695 //
John Kessenich140f3df2015-06-26 16:58:36 -06002696 glslang::TIntermSequence& glslangOperands = node->getSequence();
2697 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002698 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002699 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002700 // special case l-value operands; there are just a few
2701 bool lvalue = false;
2702 switch (node->getOp()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002703 case glslang::EOpModf:
2704 if (arg == 1)
2705 lvalue = true;
2706 break;
John Kesseniche5eee8f2019-10-18 01:03:11 -06002707
2708 case glslang::EOpAtomicAdd:
2709 case glslang::EOpAtomicMin:
2710 case glslang::EOpAtomicMax:
2711 case glslang::EOpAtomicAnd:
2712 case glslang::EOpAtomicOr:
2713 case glslang::EOpAtomicXor:
2714 case glslang::EOpAtomicExchange:
2715 case glslang::EOpAtomicCompSwap:
2716 if (arg == 0)
2717 lvalue = true;
2718 break;
2719
John Kessenicha28f7a72019-08-06 07:00:58 -06002720#ifndef GLSLANG_WEB
2721 case glslang::EOpFrexp:
2722 if (arg == 1)
2723 lvalue = true;
2724 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002725 case glslang::EOpInterpolateAtSample:
2726 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002727 case glslang::EOpInterpolateAtVertex:
John Kessenich8c8505c2016-07-26 12:50:38 -06002728 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002729 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002730
2731 // Does it need a swizzle inversion? If so, evaluation is inverted;
2732 // operate first on the swizzle base, then apply the swizzle.
John Kessenichbbbd9a22020-03-03 07:21:37 -07002733 // That is, we transform
2734 //
2735 // interpolate(v.zy) -> interpolate(v).zy
2736 //
John Kessenichecba76f2017-01-06 00:34:48 -07002737 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002738 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2739 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2740 }
Rex Xu7a26c172015-12-08 17:12:09 +08002741 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05002742 case glslang::EOpAtomicLoad:
2743 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002744 case glslang::EOpAtomicCounterAdd:
2745 case glslang::EOpAtomicCounterSubtract:
2746 case glslang::EOpAtomicCounterMin:
2747 case glslang::EOpAtomicCounterMax:
2748 case glslang::EOpAtomicCounterAnd:
2749 case glslang::EOpAtomicCounterOr:
2750 case glslang::EOpAtomicCounterXor:
2751 case glslang::EOpAtomicCounterExchange:
2752 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002753 if (arg == 0)
2754 lvalue = true;
2755 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002756 case glslang::EOpAddCarry:
2757 case glslang::EOpSubBorrow:
2758 if (arg == 2)
2759 lvalue = true;
2760 break;
2761 case glslang::EOpUMulExtended:
2762 case glslang::EOpIMulExtended:
2763 if (arg >= 2)
2764 lvalue = true;
2765 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002766 case glslang::EOpCooperativeMatrixLoad:
2767 if (arg == 0 || arg == 1)
2768 lvalue = true;
2769 break;
2770 case glslang::EOpCooperativeMatrixStore:
2771 if (arg == 1)
2772 lvalue = true;
2773 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002774#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002775 default:
2776 break;
2777 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002778 builder.clearAccessChain();
2779 if (invertedType != spv::NoType && arg == 0)
2780 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2781 else
2782 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002783
John Kessenichb9197c82019-08-11 07:41:45 -06002784#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002785 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2786 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2787
2788 if (arg == 1) {
2789 // fold "element" parameter into the access chain
2790 spv::Builder::AccessChain save = builder.getAccessChain();
2791 builder.clearAccessChain();
2792 glslangOperands[2]->traverse(this);
2793
2794 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2795
2796 builder.setAccessChain(save);
2797
2798 // Point to the first element of the array.
2799 builder.accessChainPush(elementId, TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
Jeff Bolz7895e472019-03-06 13:34:10 -06002800 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002801
2802 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2803 unsigned int alignment = builder.getAccessChain().alignment;
2804
2805 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2806 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2807 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2808 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2809 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
2810 if (builder.getStorageClass(builder.getAccessChain().base) == spv::StorageClassPhysicalStorageBufferEXT) {
2811 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2812 }
2813
2814 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2815
2816 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2817 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2818 }
2819
2820 if (memoryAccess & (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2821 memoryAccessOperands.push_back(spv::IdImmediate(true, builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
2822 }
2823 } else if (arg == 2) {
2824 continue;
2825 }
2826 }
John Kessenichb9197c82019-08-11 07:41:45 -06002827#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002828
John Kessenichbbbd9a22020-03-03 07:21:37 -07002829 // for l-values, pass the address, for r-values, pass the value
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002830 if (lvalue) {
John Kessenichbbbd9a22020-03-03 07:21:37 -07002831 if (invertedType == spv::NoType && !builder.isSpvLvalue()) {
2832 // SPIR-V cannot represent an l-value containing a swizzle that doesn't
2833 // reduce to a simple access chain. So, we need a temporary vector to
2834 // receive the result, and must later swizzle that into the original
2835 // l-value.
2836 complexLvalue = builder.getAccessChain();
2837 temporaryLvalue = builder.createVariable(spv::StorageClassFunction, builder.accessChainGetInferredType(), "swizzleTemp");
2838 operands.push_back(temporaryLvalue);
2839 } else {
2840 operands.push_back(builder.accessChainGetLValue());
2841 }
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002842 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2843 lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
2844 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002845 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich32cfd492016-02-02 12:37:46 -07002846 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002847 }
John Kessenich140f3df2015-06-26 16:58:36 -06002848 }
John Kessenich426394d2015-07-23 10:22:48 -06002849
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002850 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichb9197c82019-08-11 07:41:45 -06002851#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002852 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
2853 std::vector<spv::IdImmediate> idImmOps;
2854
2855 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2856 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2857 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2858 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2859 // get the pointee type
2860 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
2861 assert(builder.isCooperativeMatrixType(typeId));
2862 // do the op
2863 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
2864 // store the result to the pointer (out param 'm')
2865 builder.createStore(result, operands[0]);
2866 result = 0;
2867 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
2868 std::vector<spv::IdImmediate> idImmOps;
2869
2870 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2871 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
2872 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2873 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2874 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2875
2876 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
2877 result = 0;
John Kessenichb9197c82019-08-11 07:41:45 -06002878 } else
2879#endif
John Kesseniche5eee8f2019-10-18 01:03:11 -06002880 if (atomic) {
2881 // Handle all atomics
2882 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(), lvalueCoherentFlags);
2883 } else {
John Kessenich426394d2015-07-23 10:22:48 -06002884 // Pass through to generic operations.
2885 switch (glslangOperands.size()) {
2886 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002887 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002888 break;
2889 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002890 {
2891 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002892 TranslateNoContractionDecoration(node->getType().getQualifier()),
2893 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002894 result = createUnaryOperation(
2895 node->getOp(), decorations,
2896 resultType(), operands.front(),
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002897 glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -06002898 }
John Kessenich426394d2015-07-23 10:22:48 -06002899 break;
2900 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002901 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002902 break;
2903 }
John Kessenichbbbd9a22020-03-03 07:21:37 -07002904 if (invertedType != spv::NoResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06002905 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenichbbbd9a22020-03-03 07:21:37 -07002906 else if (temporaryLvalue != spv::NoResult) {
2907 builder.setAccessChain(complexLvalue);
2908 builder.accessChainStore(builder.createLoad(temporaryLvalue));
2909 }
John Kessenich140f3df2015-06-26 16:58:36 -06002910 }
2911
2912 if (noReturnValue)
2913 return false;
2914
2915 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002916 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002917 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002918 } else {
2919 builder.clearAccessChain();
2920 builder.setAccessChainRValue(result);
2921 return false;
2922 }
2923}
2924
John Kessenich433e9ff2017-01-26 20:31:11 -07002925// This path handles both if-then-else and ?:
2926// The if-then-else has a node type of void, while
2927// ?: has either a void or a non-void node type
2928//
2929// Leaving the result, when not void:
2930// GLSL only has r-values as the result of a :?, but
2931// if we have an l-value, that can be more efficient if it will
2932// become the base of a complex r-value expression, because the
2933// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002934bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2935{
John Kessenich0c1e71a2019-01-10 18:23:06 +07002936 // see if OpSelect can handle it
2937 const auto isOpSelectable = [&]() {
2938 if (node->getBasicType() == glslang::EbtVoid)
2939 return false;
2940 // OpSelect can do all other types starting with SPV 1.4
2941 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
2942 // pre-1.4, only scalars and vectors can be handled
2943 if ((!node->getType().isScalar() && !node->getType().isVector()))
2944 return false;
2945 }
2946 return true;
2947 };
2948
John Kessenich4bee5312018-02-20 21:29:05 -07002949 // See if it simple and safe, or required, to execute both sides.
2950 // Crucially, side effects must be either semantically required or avoided,
2951 // and there are performance trade-offs.
2952 // Return true if required or a good idea (and safe) to execute both sides,
2953 // false otherwise.
2954 const auto bothSidesPolicy = [&]() -> bool {
2955 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002956 if (node->getTrueBlock() == nullptr ||
2957 node->getFalseBlock() == nullptr)
2958 return false;
2959
John Kessenich4bee5312018-02-20 21:29:05 -07002960 // required? (unless we write additional code to look for side effects
2961 // and make performance trade-offs if none are present)
2962 if (!node->getShortCircuit())
2963 return true;
2964
2965 // if not required to execute both, decide based on performance/practicality...
2966
John Kessenich0c1e71a2019-01-10 18:23:06 +07002967 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07002968 return false;
2969
John Kessenich433e9ff2017-01-26 20:31:11 -07002970 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2971 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2972
2973 // return true if a single operand to ? : is okay for OpSelect
2974 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002975 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002976 };
2977
2978 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2979 operandOkay(node->getFalseBlock()->getAsTyped());
2980 };
2981
John Kessenich4bee5312018-02-20 21:29:05 -07002982 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2983 // emit the condition before doing anything with selection
2984 node->getCondition()->traverse(this);
2985 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2986
2987 // Find a way of executing both sides and selecting the right result.
2988 const auto executeBothSides = [&]() -> void {
2989 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002990 node->getTrueBlock()->traverse(this);
2991 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2992 node->getFalseBlock()->traverse(this);
2993 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2994
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002995 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002996
John Kessenich4bee5312018-02-20 21:29:05 -07002997 // done if void
2998 if (node->getBasicType() == glslang::EbtVoid)
2999 return;
John Kesseniche434ad92017-03-30 10:09:28 -06003000
John Kessenich4bee5312018-02-20 21:29:05 -07003001 // emit code to select between trueValue and falseValue
3002
3003 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07003004 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07003005 // Emit OpSelect for this selection.
3006
3007 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07003008 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
3009 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07003010 condition = builder.smearScalar(spv::NoPrecision, condition,
3011 builder.makeVectorType(builder.makeBoolType(),
3012 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07003013 }
John Kessenich4bee5312018-02-20 21:29:05 -07003014
3015 // OpSelect
3016 result = builder.createTriOp(spv::OpSelect,
3017 convertGlslangToSpvType(node->getType()), condition,
3018 trueValue, falseValue);
3019
3020 builder.clearAccessChain();
3021 builder.setAccessChainRValue(result);
3022 } else {
3023 // We need control flow to select the result.
3024 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
3025 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
3026
3027 // Selection control:
3028 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3029
3030 // make an "if" based on the value created by the condition
3031 spv::Builder::If ifBuilder(condition, control, builder);
3032
3033 // emit the "then" statement
3034 builder.createStore(trueValue, result);
3035 ifBuilder.makeBeginElse();
3036 // emit the "else" statement
3037 builder.createStore(falseValue, result);
3038
3039 // finish off the control flow
3040 ifBuilder.makeEndIf();
3041
3042 builder.clearAccessChain();
3043 builder.setAccessChainLValue(result);
3044 }
John Kessenich433e9ff2017-01-26 20:31:11 -07003045 };
3046
John Kessenich4bee5312018-02-20 21:29:05 -07003047 // Execute the one side needed, as per the condition
3048 const auto executeOneSide = [&]() {
3049 // Always emit control flow.
3050 if (node->getBasicType() != glslang::EbtVoid)
3051 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07003052
John Kessenich4bee5312018-02-20 21:29:05 -07003053 // Selection control:
3054 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3055
3056 // make an "if" based on the value created by the condition
3057 spv::Builder::If ifBuilder(condition, control, builder);
3058
3059 // emit the "then" statement
3060 if (node->getTrueBlock() != nullptr) {
3061 node->getTrueBlock()->traverse(this);
3062 if (result != spv::NoResult)
3063 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
3064 }
3065
3066 if (node->getFalseBlock() != nullptr) {
3067 ifBuilder.makeBeginElse();
3068 // emit the "else" statement
3069 node->getFalseBlock()->traverse(this);
3070 if (result != spv::NoResult)
3071 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
3072 }
3073
3074 // finish off the control flow
3075 ifBuilder.makeEndIf();
3076
3077 if (result != spv::NoResult) {
3078 builder.clearAccessChain();
3079 builder.setAccessChainLValue(result);
3080 }
3081 };
3082
3083 // Try for OpSelect (or a requirement to execute both sides)
3084 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003085 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
3086 if (node->getType().getQualifier().isSpecConstant())
3087 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07003088 executeBothSides();
3089 } else
3090 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06003091
3092 return false;
3093}
3094
3095bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
3096{
3097 // emit and get the condition before doing anything with switch
3098 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003099 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06003100
Rex Xu57e65922017-07-04 23:23:40 +08003101 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07003102 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08003103
John Kessenich140f3df2015-06-26 16:58:36 -06003104 // browse the children to sort out code segments
3105 int defaultSegment = -1;
3106 std::vector<TIntermNode*> codeSegments;
3107 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
3108 std::vector<int> caseValues;
3109 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
3110 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
3111 TIntermNode* child = *c;
3112 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02003113 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003114 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02003115 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003116 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
3117 } else
3118 codeSegments.push_back(child);
3119 }
3120
qining25262b32016-05-06 17:25:16 -04003121 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06003122 // statements between the last case and the end of the switch statement
3123 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
3124 (int)codeSegments.size() == defaultSegment)
3125 codeSegments.push_back(nullptr);
3126
3127 // make the switch statement
3128 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08003129 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06003130
3131 // emit all the code in the segments
3132 breakForLoop.push(false);
3133 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
3134 builder.nextSwitchSegment(segmentBlocks, s);
3135 if (codeSegments[s])
3136 codeSegments[s]->traverse(this);
3137 else
3138 builder.addSwitchBreak();
3139 }
3140 breakForLoop.pop();
3141
3142 builder.endSwitch(segmentBlocks);
3143
3144 return false;
3145}
3146
3147void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
3148{
3149 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003150 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06003151
3152 builder.clearAccessChain();
3153 builder.setAccessChainRValue(constant);
3154}
3155
3156bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
3157{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003158 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003159 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06003160
3161 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07003162 std::vector<unsigned int> operands;
3163 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06003164
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003165 // Spec requires back edges to target header blocks, and every header block
3166 // must dominate its merge block. Make a header block first to ensure these
3167 // conditions are met. By definition, it will contain OpLoopMerge, followed
3168 // by a block-ending branch. But we don't want to put any other body/test
3169 // instructions in it, since the body/test may have arbitrary instructions,
3170 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003171 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003172 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07003173 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003174 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003175 spv::Block& test = builder.makeNewBlock();
3176 builder.createBranch(&test);
3177
3178 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06003179 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06003180 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003181 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
3182
3183 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003184 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003185 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003186 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003187 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003188 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003189
3190 builder.setBuildPoint(&blocks.continue_target);
3191 if (node->getTerminal())
3192 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003193 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04003194 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003195 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003196 builder.createBranch(&blocks.body);
3197
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003198 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003199 builder.setBuildPoint(&blocks.body);
3200 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003201 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003202 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003203 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003204
3205 builder.setBuildPoint(&blocks.continue_target);
3206 if (node->getTerminal())
3207 node->getTerminal()->traverse(this);
3208 if (node->getTest()) {
3209 node->getTest()->traverse(this);
3210 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07003211 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003212 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003213 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05003214 // TODO: unless there was a break/return/discard instruction
3215 // somewhere in the body, this is an infinite loop, so we should
3216 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003217 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003218 }
John Kessenich140f3df2015-06-26 16:58:36 -06003219 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003220 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003221 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06003222 return false;
3223}
3224
3225bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
3226{
3227 if (node->getExpression())
3228 node->getExpression()->traverse(this);
3229
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003230 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003231
John Kessenich140f3df2015-06-26 16:58:36 -06003232 switch (node->getFlowOp()) {
3233 case glslang::EOpKill:
3234 builder.makeDiscard();
3235 break;
3236 case glslang::EOpBreak:
3237 if (breakForLoop.top())
3238 builder.createLoopExit();
3239 else
3240 builder.addSwitchBreak();
3241 break;
3242 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06003243 builder.createLoopContinue();
3244 break;
3245 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06003246 if (node->getExpression()) {
3247 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3248 spv::Id returnId = accessChainLoad(glslangReturnType);
3249 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
3250 builder.clearAccessChain();
3251 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
3252 builder.setAccessChainLValue(copyId);
3253 multiTypeStore(glslangReturnType, returnId);
3254 returnId = builder.createLoad(copyId);
3255 }
3256 builder.makeReturn(false, returnId);
3257 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003258 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003259
3260 builder.clearAccessChain();
3261 break;
3262
John Kessenichb9197c82019-08-11 07:41:45 -06003263#ifndef GLSLANG_WEB
Jeff Bolzba6170b2019-07-01 09:23:23 -05003264 case glslang::EOpDemote:
3265 builder.createNoResultOp(spv::OpDemoteToHelperInvocationEXT);
3266 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
3267 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
3268 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003269#endif
Jeff Bolzba6170b2019-07-01 09:23:23 -05003270
John Kessenich140f3df2015-06-26 16:58:36 -06003271 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003272 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003273 break;
3274 }
3275
3276 return false;
3277}
3278
John Kessenich9c14f772019-06-17 08:38:35 -06003279spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node, spv::Id forcedType)
John Kessenich140f3df2015-06-26 16:58:36 -06003280{
qining25262b32016-05-06 17:25:16 -04003281 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003282 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003283 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003284 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003285 spv::Id result = createSpvConstant(*node);
3286 if (result != spv::NoResult)
3287 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003288 }
3289
3290 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003291 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06003292 spv::Id spvType = forcedType == spv::NoType ? convertGlslangToSpvType(node->getType())
3293 : forcedType;
John Kessenich140f3df2015-06-26 16:58:36 -06003294
John Kessenichb9197c82019-08-11 07:41:45 -06003295 const bool contains16BitType = node->getType().contains16BitFloat() ||
3296 node->getType().contains16BitInt();
Rex Xuf89ad982017-04-07 23:22:33 +08003297 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003298 switch (storageClass) {
3299 case spv::StorageClassInput:
3300 case spv::StorageClassOutput:
John Kessenich8317e6c2019-08-18 23:58:08 -06003301 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003302 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003303 break;
John Kessenich18310872018-05-14 22:08:53 -06003304 case spv::StorageClassUniform:
John Kessenich8317e6c2019-08-18 23:58:08 -06003305 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003306 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3307 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003308 else
3309 builder.addCapability(spv::CapabilityStorageUniform16);
3310 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003311#ifndef GLSLANG_WEB
3312 case spv::StorageClassPushConstant:
John Kessenich8317e6c2019-08-18 23:58:08 -06003313 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenichb9197c82019-08-11 07:41:45 -06003314 builder.addCapability(spv::CapabilityStoragePushConstant16);
3315 break;
John Kessenich18310872018-05-14 22:08:53 -06003316 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003317 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich8317e6c2019-08-18 23:58:08 -06003318 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenich18310872018-05-14 22:08:53 -06003319 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3320 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003321#endif
John Kessenich18310872018-05-14 22:08:53 -06003322 default:
John Kessenichb9197c82019-08-11 07:41:45 -06003323 if (node->getType().contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003324 builder.addCapability(spv::CapabilityFloat16);
John Kessenichb9197c82019-08-11 07:41:45 -06003325 if (node->getType().contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003326 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06003327 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003328 }
3329 }
Rex Xuf89ad982017-04-07 23:22:33 +08003330
John Kessenichb9197c82019-08-11 07:41:45 -06003331 if (node->getType().contains8BitInt()) {
John Kessenich312dcfb2018-07-03 13:19:51 -06003332 if (storageClass == spv::StorageClassPushConstant) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003333 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003334 builder.addCapability(spv::CapabilityStoragePushConstant8);
3335 } else if (storageClass == spv::StorageClassUniform) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003336 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003337 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003338 } else if (storageClass == spv::StorageClassStorageBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003339 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
Neil Henningb6b01f02018-10-23 15:02:29 +01003340 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003341 } else {
3342 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06003343 }
3344 }
3345
John Kessenich140f3df2015-06-26 16:58:36 -06003346 const char* name = node->getName().c_str();
3347 if (glslang::IsAnonymous(name))
3348 name = "";
3349
3350 return builder.createVariable(storageClass, spvType, name);
3351}
3352
3353// Return type Id of the sampled type.
3354spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3355{
3356 switch (sampler.type) {
John Kessenicha28f7a72019-08-06 07:00:58 -06003357 case glslang::EbtInt: return builder.makeIntType(32);
3358 case glslang::EbtUint: return builder.makeUintType(32);
John Kessenich140f3df2015-06-26 16:58:36 -06003359 case glslang::EbtFloat: return builder.makeFloatType(32);
John Kessenicha28f7a72019-08-06 07:00:58 -06003360#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08003361 case glslang::EbtFloat16:
3362 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3363 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3364 return builder.makeFloatType(16);
3365#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003366 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003367 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003368 return builder.makeFloatType(32);
3369 }
3370}
3371
John Kessenich8c8505c2016-07-26 12:50:38 -06003372// If node is a swizzle operation, return the type that should be used if
3373// the swizzle base is first consumed by another operation, before the swizzle
3374// is applied.
3375spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3376{
John Kessenichecba76f2017-01-06 00:34:48 -07003377 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003378 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3379 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3380 else
3381 return spv::NoType;
3382}
3383
3384// When inverting a swizzle with a parent op, this function
3385// will apply the swizzle operation to a completed parent operation.
3386spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
3387{
3388 std::vector<unsigned> swizzle;
3389 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3390 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3391}
3392
John Kessenich8c8505c2016-07-26 12:50:38 -06003393// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3394void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3395{
3396 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3397 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3398 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3399}
3400
John Kessenich3ac051e2015-12-20 11:29:16 -07003401// Convert from a glslang type to an SPV type, by calling into a
3402// recursive version of this function. This establishes the inherited
3403// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003404spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003405{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003406 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003407}
3408
3409// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003410// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003411// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003412spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003413 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3414 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003415{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003416 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003417
3418 switch (type.getBasicType()) {
3419 case glslang::EbtVoid:
3420 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003421 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003422 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003423 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003424 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3425 // a 32-bit int where non-0 means true.
3426 if (explicitLayout != glslang::ElpNone)
3427 spvType = builder.makeUintType(32);
3428 else
3429 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003430 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003431 case glslang::EbtInt:
3432 spvType = builder.makeIntType(32);
3433 break;
3434 case glslang::EbtUint:
3435 spvType = builder.makeUintType(32);
3436 break;
3437 case glslang::EbtFloat:
3438 spvType = builder.makeFloatType(32);
3439 break;
3440#ifndef GLSLANG_WEB
3441 case glslang::EbtDouble:
3442 spvType = builder.makeFloatType(64);
3443 break;
3444 case glslang::EbtFloat16:
3445 spvType = builder.makeFloatType(16);
3446 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003447 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003448 spvType = builder.makeIntType(8);
3449 break;
3450 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003451 spvType = builder.makeUintType(8);
3452 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003453 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003454 spvType = builder.makeIntType(16);
3455 break;
3456 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003457 spvType = builder.makeUintType(16);
3458 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003459 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003460 spvType = builder.makeIntType(64);
3461 break;
3462 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003463 spvType = builder.makeUintType(64);
3464 break;
John Kessenich426394d2015-07-23 10:22:48 -06003465 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003466 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003467 spvType = builder.makeUintType(32);
3468 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003469 case glslang::EbtAccStructNV:
3470 spvType = builder.makeAccelerationStructureNVType();
3471 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003472 case glslang::EbtReference:
3473 {
3474 // Make the forward pointer, then recurse to convert the structure type, then
3475 // patch up the forward pointer with a real pointer type.
3476 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3477 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3478 forwardPointers[type.getReferentType()] = forwardId;
3479 }
3480 spvType = forwardPointers[type.getReferentType()];
3481 if (!forwardReferenceOnly) {
3482 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3483 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3484 forwardPointers[type.getReferentType()],
3485 referentType);
3486 }
3487 }
3488 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003489#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003490 case glslang::EbtSampler:
3491 {
3492 const glslang::TSampler& sampler = type.getSampler();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003493 if (sampler.isPureSampler()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003494 spvType = builder.makeSamplerType();
3495 } else {
3496 // an image is present, make its type
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003497 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler),
3498 sampler.isShadow(), sampler.isArrayed(), sampler.isMultiSample(),
3499 sampler.isImageClass() ? 2 : 1, TranslateImageFormat(type));
3500 if (sampler.isCombined()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003501 // already has both image and sampler, make the combined type
3502 spvType = builder.makeSampledImageType(spvType);
3503 }
John Kessenich55e7d112015-11-15 21:33:39 -07003504 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003505 }
John Kessenich140f3df2015-06-26 16:58:36 -06003506 break;
3507 case glslang::EbtStruct:
3508 case glslang::EbtBlock:
3509 {
3510 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003511 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003512
3513 // Try to share structs for different layouts, but not yet for other
3514 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003515 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003516 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003517 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003518 break;
3519
3520 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003521 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003522 memberRemapper[glslangTypeToIdMap[glslangMembers]].resize(glslangMembers->size());
John Kessenich6090df02016-06-30 21:18:02 -06003523 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003524 }
3525 break;
3526 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003527 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003528 break;
3529 }
3530
3531 if (type.isMatrix())
3532 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3533 else {
3534 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3535 if (type.getVectorSize() > 1)
3536 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3537 }
3538
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003539 if (type.isCoopMat()) {
3540 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3541 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3542 if (type.getBasicType() == glslang::EbtFloat16)
3543 builder.addCapability(spv::CapabilityFloat16);
Jeff Bolz387657e2019-08-22 20:28:00 -05003544 if (type.getBasicType() == glslang::EbtUint8 ||
3545 type.getBasicType() == glslang::EbtInt8) {
3546 builder.addCapability(spv::CapabilityInt8);
3547 }
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003548
3549 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3550 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3551 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3552
3553 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3554 }
3555
John Kessenich140f3df2015-06-26 16:58:36 -06003556 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003557 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3558
John Kessenichc9a80832015-09-12 12:17:44 -06003559 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003560 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003561 // We need to decorate array strides for types needing explicit layout, except blocks.
3562 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003563 // Use a dummy glslang type for querying internal strides of
3564 // arrays of arrays, but using just a one-dimensional array.
3565 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003566 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3567 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003568
3569 // Will compute the higher-order strides here, rather than making a whole
3570 // pile of types and doing repetitive recursion on their contents.
3571 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3572 }
John Kessenichf8842e52016-01-04 19:22:56 -07003573
3574 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003575 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003576 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003577 if (stride > 0)
3578 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003579 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003580 }
3581 } else {
3582 // single-dimensional array, and don't yet have stride
3583
John Kessenichf8842e52016-01-04 19:22:56 -07003584 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003585 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3586 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003587 }
John Kessenich31ed4832015-09-09 17:51:38 -06003588
John Kessenichead86222018-03-28 18:01:20 -06003589 // Do the outer dimension, which might not be known for a runtime-sized array.
3590 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3591 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003592 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003593 else {
John Kessenichb9197c82019-08-11 07:41:45 -06003594#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003595 if (!lastBufferBlockMember) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003596 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06003597 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3598 }
John Kessenichb9197c82019-08-11 07:41:45 -06003599#endif
John Kessenich3dd1ce52019-10-17 07:08:40 -06003600 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003601 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003602 if (stride > 0)
3603 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003604 }
3605
3606 return spvType;
3607}
3608
John Kessenich0e737842017-03-24 18:38:16 -06003609// TODO: this functionality should exist at a higher level, in creating the AST
3610//
3611// Identify interface members that don't have their required extension turned on.
3612//
3613bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3614{
John Kessenicha28f7a72019-08-06 07:00:58 -06003615#ifndef GLSLANG_WEB
John Kessenich0e737842017-03-24 18:38:16 -06003616 auto& extensions = glslangIntermediate->getRequestedExtensions();
3617
Rex Xubcf291a2017-03-29 23:01:36 +08003618 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3619 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3620 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003621 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3622 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3623 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003624
3625 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3626 if (member.getFieldName() == "gl_ViewportMask" &&
3627 extensions.find("GL_NV_viewport_array2") == extensions.end())
3628 return true;
3629 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3630 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3631 return true;
3632 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3633 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3634 return true;
3635 }
3636#endif
John Kessenich0e737842017-03-24 18:38:16 -06003637
3638 return false;
3639};
3640
John Kessenich6090df02016-06-30 21:18:02 -06003641// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3642// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3643// Mutually recursive with convertGlslangToSpvType().
3644spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3645 const glslang::TTypeList* glslangMembers,
3646 glslang::TLayoutPacking explicitLayout,
3647 const glslang::TQualifier& qualifier)
3648{
3649 // Create a vector of struct types for SPIR-V to consume
3650 std::vector<spv::Id> spvMembers;
3651 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 -06003652 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003653 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3654 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3655 if (glslangMember.hiddenMember()) {
3656 ++memberDelta;
3657 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003658 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich6090df02016-06-30 21:18:02 -06003659 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003660 if (type.getBasicType() == glslang::EbtBlock) {
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003661 if (filterMember(glslangMember)) {
3662 memberDelta++;
Roy05a5b532020-01-03 16:21:34 +08003663 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich0e737842017-03-24 18:38:16 -06003664 continue;
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003665 }
Roy05a5b532020-01-03 16:21:34 +08003666 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003667 }
John Kessenich6090df02016-06-30 21:18:02 -06003668 // modify just this child's view of the qualifier
3669 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3670 InheritQualifiers(memberQualifier, qualifier);
3671
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003672 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003673 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003674 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003675
3676 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003677 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3678 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003679
3680 // Make forward pointers for any pointer members, and create a list of members to
3681 // convert to spirv types after creating the struct.
John Kessenich7015bd62019-08-01 03:28:08 -06003682 if (glslangMember.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003683 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3684 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3685 }
3686 spvMembers.push_back(
3687 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, true));
3688 } else {
3689 spvMembers.push_back(
3690 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, false));
3691 }
John Kessenich6090df02016-06-30 21:18:02 -06003692 }
3693 }
3694
3695 // Make the SPIR-V type
3696 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003697 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003698 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3699
3700 // Decorate it
3701 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3702
John Kessenichd72f4882019-01-16 14:55:37 +07003703 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003704 auto it = deferredForwardPointers[i];
3705 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3706 }
3707
John Kessenich6090df02016-06-30 21:18:02 -06003708 return spvType;
3709}
3710
3711void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3712 const glslang::TTypeList* glslangMembers,
3713 glslang::TLayoutPacking explicitLayout,
3714 const glslang::TQualifier& qualifier,
3715 spv::Id spvType)
3716{
3717 // Name and decorate the non-hidden members
3718 int offset = -1;
3719 int locationOffset = 0; // for use within the members of this struct
3720 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3721 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3722 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003723 if (type.getBasicType() == glslang::EbtBlock) {
Roy05a5b532020-01-03 16:21:34 +08003724 member = memberRemapper[glslangTypeToIdMap[glslangMembers]][i];
John Kessenich0e737842017-03-24 18:38:16 -06003725 if (filterMember(glslangMember))
3726 continue;
3727 }
John Kessenich6090df02016-06-30 21:18:02 -06003728
3729 // modify just this child's view of the qualifier
3730 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3731 InheritQualifiers(memberQualifier, qualifier);
3732
3733 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003734 if (member < 0)
3735 continue;
3736
3737 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3738 builder.addMemberDecoration(spvType, member,
3739 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3740 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3741 // Add interpolation and auxiliary storage decorations only to
3742 // top-level members of Input and Output storage classes
3743 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3744 type.getQualifier().storage == glslang::EvqVaryingOut) {
3745 if (type.getBasicType() == glslang::EbtBlock ||
3746 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3747 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3748 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenicha28f7a72019-08-06 07:00:58 -06003749#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07003750 addMeshNVDecoration(spvType, member, memberQualifier);
3751#endif
John Kessenich6090df02016-06-30 21:18:02 -06003752 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003753 }
3754 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003755
John Kessenichb9197c82019-08-11 07:41:45 -06003756#ifndef GLSLANG_WEB
John Kessenich5d610ee2018-03-07 18:05:55 -07003757 if (type.getBasicType() == glslang::EbtBlock &&
3758 qualifier.storage == glslang::EvqBuffer) {
3759 // Add memory decorations only to top-level members of shader storage block
3760 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003761 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003762 for (unsigned int i = 0; i < memory.size(); ++i)
3763 builder.addMemberDecoration(spvType, member, memory[i]);
3764 }
John Kessenichf8d1d742019-10-21 06:55:11 -06003765
John Kessenichb9197c82019-08-11 07:41:45 -06003766#endif
John Kessenich6090df02016-06-30 21:18:02 -06003767
John Kessenich5d610ee2018-03-07 18:05:55 -07003768 // Location assignment was already completed correctly by the front end,
3769 // just track whether a member needs to be decorated.
3770 // Ignore member locations if the container is an array, as that's
3771 // ill-specified and decisions have been made to not allow this.
3772 if (! type.isArray() && memberQualifier.hasLocation())
3773 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003774
John Kessenich5d610ee2018-03-07 18:05:55 -07003775 if (qualifier.hasLocation()) // track for upcoming inheritance
3776 locationOffset += glslangIntermediate->computeTypeLocationSize(
3777 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003778
John Kessenich5d610ee2018-03-07 18:05:55 -07003779 // component, XFB, others
3780 if (glslangMember.getQualifier().hasComponent())
3781 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3782 glslangMember.getQualifier().layoutComponent);
3783 if (glslangMember.getQualifier().hasXfbOffset())
3784 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3785 glslangMember.getQualifier().layoutXfbOffset);
3786 else if (explicitLayout != glslang::ElpNone) {
3787 // figure out what to do with offset, which is accumulating
3788 int nextOffset;
3789 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3790 if (offset >= 0)
3791 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3792 offset = nextOffset;
3793 }
John Kessenich6090df02016-06-30 21:18:02 -06003794
John Kessenich5d610ee2018-03-07 18:05:55 -07003795 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3796 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3797 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003798
John Kessenich5d610ee2018-03-07 18:05:55 -07003799 // built-in variable decorations
3800 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3801 if (builtIn != spv::BuiltInMax)
3802 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003803
John Kessenichb9197c82019-08-11 07:41:45 -06003804#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003805 // nonuniform
3806 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3807
John Kessenichead86222018-03-28 18:01:20 -06003808 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3809 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3810 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3811 memberQualifier.semanticName);
3812 }
3813
John Kessenich5d610ee2018-03-07 18:05:55 -07003814 if (builtIn == spv::BuiltInLayer) {
3815 // SPV_NV_viewport_array2 extension
3816 if (glslangMember.getQualifier().layoutViewportRelative){
3817 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3818 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3819 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003820 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003821 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3822 builder.addMemberDecoration(spvType, member,
3823 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3824 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3825 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3826 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003827 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003828 }
3829 if (glslangMember.getQualifier().layoutPassthrough) {
3830 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3831 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3832 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3833 }
chaoc771d89f2017-01-13 01:10:53 -08003834#endif
John Kessenich6090df02016-06-30 21:18:02 -06003835 }
3836
3837 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003838 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3839 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003840}
3841
John Kessenich6c292d32016-02-15 20:58:50 -07003842// Turn the expression forming the array size into an id.
3843// This is not quite trivial, because of specialization constants.
3844// Sometimes, a raw constant is turned into an Id, and sometimes
3845// a specialization constant expression is.
3846spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3847{
3848 // First, see if this is sized with a node, meaning a specialization constant:
3849 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3850 if (specNode != nullptr) {
3851 builder.clearAccessChain();
3852 specNode->traverse(this);
3853 return accessChainLoad(specNode->getAsTyped()->getType());
3854 }
qining25262b32016-05-06 17:25:16 -04003855
John Kessenich6c292d32016-02-15 20:58:50 -07003856 // Otherwise, need a compile-time (front end) size, get it:
3857 int size = arraySizes.getDimSize(dim);
3858 assert(size > 0);
3859 return builder.makeUintConstant(size);
3860}
3861
John Kessenich103bef92016-02-08 21:38:15 -07003862// Wrap the builder's accessChainLoad to:
3863// - localize handling of RelaxedPrecision
3864// - use the SPIR-V inferred type instead of another conversion of the glslang type
3865// (avoids unnecessary work and possible type punning for structures)
3866// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003867spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3868{
John Kessenich103bef92016-02-08 21:38:15 -07003869 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003870
3871 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3872 coherentFlags |= TranslateCoherent(type);
3873
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003874 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003875 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003876
John Kessenich5611c6d2018-04-05 11:25:02 -06003877 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003878 TranslateNonUniformDecoration(type.getQualifier()),
3879 nominalTypeId,
3880 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003881 TranslateMemoryScope(coherentFlags),
3882 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07003883
3884 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003885 if (type.getBasicType() == glslang::EbtBool) {
3886 if (builder.isScalarType(nominalTypeId)) {
3887 // Conversion for bool
3888 spv::Id boolType = builder.makeBoolType();
3889 if (nominalTypeId != boolType)
3890 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3891 } else if (builder.isVectorType(nominalTypeId)) {
3892 // Conversion for bvec
3893 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3894 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3895 if (nominalTypeId != bvecType)
3896 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3897 }
3898 }
John Kessenich103bef92016-02-08 21:38:15 -07003899
3900 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003901}
3902
Rex Xu27253232016-02-23 17:51:09 +08003903// Wrap the builder's accessChainStore to:
3904// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003905//
3906// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003907void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3908{
3909 // Need to convert to abstract types when necessary
3910 if (type.getBasicType() == glslang::EbtBool) {
3911 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3912
3913 if (builder.isScalarType(nominalTypeId)) {
3914 // Conversion for bool
3915 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003916 if (nominalTypeId != boolType) {
3917 // keep these outside arguments, for determinant order-of-evaluation
3918 spv::Id one = builder.makeUintConstant(1);
3919 spv::Id zero = builder.makeUintConstant(0);
3920 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3921 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003922 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003923 } else if (builder.isVectorType(nominalTypeId)) {
3924 // Conversion for bvec
3925 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3926 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003927 if (nominalTypeId != bvecType) {
3928 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003929 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3930 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3931 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003932 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003933 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3934 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003935 }
3936 }
3937
Jeff Bolz36831c92018-09-05 10:11:41 -05003938 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3939 coherentFlags |= TranslateCoherent(type);
3940
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003941 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003942 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003943
Jeff Bolz36831c92018-09-05 10:11:41 -05003944 builder.accessChainStore(rvalue,
3945 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003946 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08003947}
3948
John Kessenich4bf71552016-09-02 11:20:21 -06003949// For storing when types match at the glslang level, but not might match at the
3950// SPIR-V level.
3951//
3952// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003953// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003954// as in a member-decorated way.
3955//
3956// NOTE: This function can handle any store request; if it's not special it
3957// simplifies to a simple OpStore.
3958//
3959// Implicitly uses the existing builder.accessChain as the storage target.
3960void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3961{
John Kessenichb3e24e42016-09-11 12:33:43 -06003962 // we only do the complex path here if it's an aggregate
3963 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003964 accessChainStore(type, rValue);
3965 return;
3966 }
3967
John Kessenichb3e24e42016-09-11 12:33:43 -06003968 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003969 spv::Id rType = builder.getTypeId(rValue);
3970 spv::Id lValue = builder.accessChainGetLValue();
3971 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3972 if (lType == rType) {
3973 accessChainStore(type, rValue);
3974 return;
3975 }
3976
John Kessenichb3e24e42016-09-11 12:33:43 -06003977 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003978 // where the two types were the same type in GLSL. This requires member
3979 // by member copy, recursively.
3980
John Kessenichfbb6bdf2019-01-15 21:48:27 +07003981 // SPIR-V 1.4 added an instruction to do help do this.
3982 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
3983 // However, bool in uniform space is changed to int, so
3984 // OpCopyLogical does not work for that.
3985 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
3986 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
3987 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
3988 if (lBool == rBool) {
3989 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
3990 accessChainStore(type, logicalCopy);
3991 return;
3992 }
3993 }
3994
John Kessenichb3e24e42016-09-11 12:33:43 -06003995 // If an array, copy element by element.
3996 if (type.isArray()) {
3997 glslang::TType glslangElementType(type, 0);
3998 spv::Id elementRType = builder.getContainedTypeId(rType);
3999 for (int index = 0; index < type.getOuterArraySize(); ++index) {
4000 // get the source member
4001 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06004002
John Kessenichb3e24e42016-09-11 12:33:43 -06004003 // set up the target storage
4004 builder.clearAccessChain();
4005 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06004006 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06004007
John Kessenichb3e24e42016-09-11 12:33:43 -06004008 // store the member
4009 multiTypeStore(glslangElementType, elementRValue);
4010 }
4011 } else {
4012 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06004013
John Kessenichb3e24e42016-09-11 12:33:43 -06004014 // loop over structure members
4015 const glslang::TTypeList& members = *type.getStruct();
4016 for (int m = 0; m < (int)members.size(); ++m) {
4017 const glslang::TType& glslangMemberType = *members[m].type;
4018
4019 // get the source member
4020 spv::Id memberRType = builder.getContainedTypeId(rType, m);
4021 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
4022
4023 // set up the target storage
4024 builder.clearAccessChain();
4025 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06004026 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06004027
4028 // store the member
4029 multiTypeStore(glslangMemberType, memberRValue);
4030 }
John Kessenich4bf71552016-09-02 11:20:21 -06004031 }
4032}
4033
John Kessenichf85e8062015-12-19 13:57:10 -07004034// Decide whether or not this type should be
4035// decorated with offsets and strides, and if so
4036// whether std140 or std430 rules should be applied.
4037glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06004038{
John Kessenichf85e8062015-12-19 13:57:10 -07004039 // has to be a block
4040 if (type.getBasicType() != glslang::EbtBlock)
4041 return glslang::ElpNone;
4042
Chao Chen3c366992018-09-19 11:41:59 -07004043 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07004044 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07004045 type.getQualifier().storage != glslang::EvqBuffer &&
4046 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07004047 return glslang::ElpNone;
4048
4049 // return the layout to use
4050 switch (type.getQualifier().layoutPacking) {
4051 case glslang::ElpStd140:
4052 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004053 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07004054 return type.getQualifier().layoutPacking;
4055 default:
4056 return glslang::ElpNone;
4057 }
John Kessenich31ed4832015-09-09 17:51:38 -06004058}
4059
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004060// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07004061int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004062{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004063 int size;
John Kessenich49987892015-12-29 17:11:44 -07004064 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004065 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07004066
4067 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004068}
4069
John Kessenich49987892015-12-29 17:11:44 -07004070// 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 -07004071// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07004072int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004073{
John Kessenich49987892015-12-29 17:11:44 -07004074 glslang::TType elementType;
4075 elementType.shallowCopy(matrixType);
4076 elementType.clearArraySizes();
4077
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004078 int size;
John Kessenich49987892015-12-29 17:11:44 -07004079 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004080 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07004081
4082 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004083}
4084
John Kessenich5e4b1242015-08-06 22:53:06 -06004085// Given a member type of a struct, realign the current offset for it, and compute
4086// the next (not yet aligned) offset for the next member, which will get aligned
4087// on the next call.
4088// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
4089// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
4090// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06004091void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07004092 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06004093{
4094 // this will get a positive value when deemed necessary
4095 nextOffset = -1;
4096
John Kessenich5e4b1242015-08-06 22:53:06 -06004097 // override anything in currentOffset with user-set offset
4098 if (memberType.getQualifier().hasOffset())
4099 currentOffset = memberType.getQualifier().layoutOffset;
4100
4101 // It could be that current linker usage in glslang updated all the layoutOffset,
4102 // in which case the following code does not matter. But, that's not quite right
4103 // once cross-compilation unit GLSL validation is done, as the original user
4104 // settings are needed in layoutOffset, and then the following will come into play.
4105
John Kessenichf85e8062015-12-19 13:57:10 -07004106 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06004107 if (! memberType.getQualifier().hasOffset())
4108 currentOffset = -1;
4109
4110 return;
4111 }
4112
John Kessenichf85e8062015-12-19 13:57:10 -07004113 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06004114 if (currentOffset < 0)
4115 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04004116
John Kessenich5e4b1242015-08-06 22:53:06 -06004117 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
4118 // but possibly not yet correctly aligned.
4119
4120 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07004121 int dummyStride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004122 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06004123
4124 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06004125 // TODO: make this consistent in early phases of code:
4126 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
4127 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
4128 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06004129 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06004130 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06004131 int dummySize;
4132 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
4133 if (componentAlignment <= 4)
4134 memberAlignment = componentAlignment;
4135 }
4136
4137 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06004138 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06004139
4140 // Bump up to vec4 if there is a bad straddle
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004141 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06004142 glslang::RoundToPow2(currentOffset, 16);
4143
John Kessenich5e4b1242015-08-06 22:53:06 -06004144 nextOffset = currentOffset + memberSize;
4145}
4146
David Netoa901ffe2016-06-08 14:11:40 +01004147void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06004148{
David Netoa901ffe2016-06-08 14:11:40 +01004149 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
4150 switch (glslangBuiltIn)
4151 {
John Kessenicha28f7a72019-08-06 07:00:58 -06004152 case glslang::EbvPointSize:
4153#ifndef GLSLANG_WEB
David Netoa901ffe2016-06-08 14:11:40 +01004154 case glslang::EbvClipDistance:
4155 case glslang::EbvCullDistance:
chaoc771d89f2017-01-13 01:10:53 -08004156 case glslang::EbvViewportMaskNV:
4157 case glslang::EbvSecondaryPositionNV:
4158 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08004159 case glslang::EbvPositionPerViewNV:
4160 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07004161 case glslang::EbvTaskCountNV:
4162 case glslang::EbvPrimitiveCountNV:
4163 case glslang::EbvPrimitiveIndicesNV:
4164 case glslang::EbvClipDistancePerViewNV:
4165 case glslang::EbvCullDistancePerViewNV:
4166 case glslang::EbvLayerPerViewNV:
4167 case glslang::EbvMeshViewCountNV:
4168 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004169#endif
David Netoa901ffe2016-06-08 14:11:40 +01004170 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4171 // Alternately, we could just call this for any glslang built-in, since the
4172 // capability already guards against duplicates.
4173 TranslateBuiltInDecoration(glslangBuiltIn, false);
4174 break;
4175 default:
4176 // Capabilities were already generated when the struct was declared.
4177 break;
4178 }
John Kessenichebb50532016-05-16 19:22:05 -06004179}
4180
John Kessenich6fccb3c2016-09-19 16:01:41 -06004181bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004182{
John Kessenicheee9d532016-09-19 18:09:30 -06004183 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004184}
4185
John Kessenichd41993d2017-09-10 15:21:05 -06004186// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004187// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4188// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004189bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004190{
John Kessenich6a14f782017-12-04 02:48:10 -07004191 assert(qualifier == glslang::EvqIn ||
4192 qualifier == glslang::EvqOut ||
4193 qualifier == glslang::EvqInOut ||
4194 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06004195 return qualifier != glslang::EvqConstReadOnly;
4196}
4197
4198// Is parameter pass-by-original?
4199bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4200 bool implicitThisParam)
4201{
4202 if (implicitThisParam) // implicit this
4203 return true;
4204 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004205 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004206 return paramType.containsOpaque() || // sampler, etc.
4207 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4208}
4209
John Kessenich140f3df2015-06-26 16:58:36 -06004210// Make all the functions, skeletally, without actually visiting their bodies.
4211void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4212{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004213 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004214 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4215 if (paramPrecision != spv::NoPrecision)
4216 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004217 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenich7015bd62019-08-01 03:28:08 -06004218 if (type.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004219 // Original and non-writable params pass the pointer directly and
4220 // use restrict/aliased, others are stored to a pointer in Function
4221 // memory and use RestrictPointer/AliasedPointer.
4222 if (originalParam(type.getQualifier().storage, type, false) ||
4223 !writableParam(type.getQualifier().storage)) {
John Kessenichf8d1d742019-10-21 06:55:11 -06004224 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrict :
4225 spv::DecorationAliased);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004226 } else {
John Kessenichf8d1d742019-10-21 06:55:11 -06004227 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrictPointerEXT :
4228 spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004229 }
4230 }
John Kessenichfad62972017-07-18 02:35:46 -06004231 };
4232
John Kessenich140f3df2015-06-26 16:58:36 -06004233 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4234 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004235 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004236 continue;
4237
4238 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004239 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004240 //
qining25262b32016-05-06 17:25:16 -04004241 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004242 // function. What it is an address of varies:
4243 //
John Kessenich4bf71552016-09-02 11:20:21 -06004244 // - "in" parameters not marked as "const" can be written to without modifying the calling
4245 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004246 //
4247 // - "const in" parameters can just be the r-value, as no writes need occur.
4248 //
John Kessenich4bf71552016-09-02 11:20:21 -06004249 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4250 // 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 -06004251
4252 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004253 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004254 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4255
John Kessenich155d3512019-08-08 23:29:20 -06004256#ifdef ENABLE_HLSL
John Kessenichfad62972017-07-18 02:35:46 -06004257 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4258 glslangIntermediate->implicitThisName;
John Kessenich155d3512019-08-08 23:29:20 -06004259#else
4260 bool implicitThis = false;
4261#endif
John Kessenich37789792017-03-21 23:56:40 -06004262
John Kessenichfad62972017-07-18 02:35:46 -06004263 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004264 for (int p = 0; p < (int)parameters.size(); ++p) {
4265 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4266 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004267 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004268 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004269 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004270 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4271 else
John Kessenich4bf71552016-09-02 11:20:21 -06004272 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004273 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004274 paramTypes.push_back(typeId);
4275 }
4276
4277 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004278 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4279 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004280 glslFunction->getName().c_str(), paramTypes,
4281 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004282 if (implicitThis)
4283 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004284
4285 // Track function to emit/call later
4286 functionMap[glslFunction->getName().c_str()] = function;
4287
4288 // Set the parameter id's
4289 for (int p = 0; p < (int)parameters.size(); ++p) {
4290 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4291 // give a name too
4292 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004293
4294 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
John Kessenichb9197c82019-08-11 07:41:45 -06004295 if (paramType.contains8BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004296 builder.addCapability(spv::CapabilityInt8);
John Kessenichb9197c82019-08-11 07:41:45 -06004297 if (paramType.contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004298 builder.addCapability(spv::CapabilityInt16);
John Kessenichb9197c82019-08-11 07:41:45 -06004299 if (paramType.contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004300 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004301 }
4302 }
4303}
4304
4305// Process all the initializers, while skipping the functions and link objects
4306void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4307{
4308 builder.setBuildPoint(shaderEntry->getLastBlock());
4309 for (int i = 0; i < (int)initializers.size(); ++i) {
4310 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
4311 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
4312
4313 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004314 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004315 initializer->traverse(this);
4316 }
4317 }
4318}
4319
4320// Process all the functions, while skipping initializers.
4321void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4322{
4323 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4324 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004325 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004326 node->traverse(this);
4327 }
4328}
4329
4330void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4331{
qining25262b32016-05-06 17:25:16 -04004332 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004333 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004334 currentFunction = functionMap[node->getName().c_str()];
4335 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004336 builder.setBuildPoint(functionBlock);
4337}
4338
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004339void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments, spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004340{
Rex Xufc618912015-09-09 16:42:49 +08004341 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004342
4343 glslang::TSampler sampler = {};
4344 bool cubeCompare = false;
John Kessenicha28f7a72019-08-06 07:00:58 -06004345#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004346 bool f16ShadowCompare = false;
4347#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004348 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004349 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4350 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
John Kessenicha28f7a72019-08-06 07:00:58 -06004351#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004352 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
4353#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004354 }
4355
John Kessenich140f3df2015-06-26 16:58:36 -06004356 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4357 builder.clearAccessChain();
4358 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004359
John Kessenicha28f7a72019-08-06 07:00:58 -06004360#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08004361 // Special case l-value operands
4362 bool lvalue = false;
4363 switch (node.getOp()) {
4364 case glslang::EOpImageAtomicAdd:
4365 case glslang::EOpImageAtomicMin:
4366 case glslang::EOpImageAtomicMax:
4367 case glslang::EOpImageAtomicAnd:
4368 case glslang::EOpImageAtomicOr:
4369 case glslang::EOpImageAtomicXor:
4370 case glslang::EOpImageAtomicExchange:
4371 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004372 case glslang::EOpImageAtomicLoad:
4373 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004374 if (i == 0)
4375 lvalue = true;
4376 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004377 case glslang::EOpSparseImageLoad:
4378 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4379 lvalue = true;
4380 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004381 case glslang::EOpSparseTexture:
4382 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4383 lvalue = true;
4384 break;
4385 case glslang::EOpSparseTextureClamp:
4386 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4387 lvalue = true;
4388 break;
4389 case glslang::EOpSparseTextureLod:
4390 case glslang::EOpSparseTextureOffset:
4391 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4392 lvalue = true;
4393 break;
Rex Xu48edadf2015-12-31 16:11:41 +08004394 case glslang::EOpSparseTextureFetch:
4395 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4396 lvalue = true;
4397 break;
4398 case glslang::EOpSparseTextureFetchOffset:
4399 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4400 lvalue = true;
4401 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004402 case glslang::EOpSparseTextureLodOffset:
4403 case glslang::EOpSparseTextureGrad:
4404 case glslang::EOpSparseTextureOffsetClamp:
4405 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4406 lvalue = true;
4407 break;
4408 case glslang::EOpSparseTextureGradOffset:
4409 case glslang::EOpSparseTextureGradClamp:
4410 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4411 lvalue = true;
4412 break;
4413 case glslang::EOpSparseTextureGradOffsetClamp:
4414 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4415 lvalue = true;
4416 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004417 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004418 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4419 lvalue = true;
4420 break;
4421 case glslang::EOpSparseTextureGatherOffset:
4422 case glslang::EOpSparseTextureGatherOffsets:
4423 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4424 lvalue = true;
4425 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004426 case glslang::EOpSparseTextureGatherLod:
4427 if (i == 3)
4428 lvalue = true;
4429 break;
4430 case glslang::EOpSparseTextureGatherLodOffset:
4431 case glslang::EOpSparseTextureGatherLodOffsets:
4432 if (i == 4)
4433 lvalue = true;
4434 break;
Rex Xu129799a2017-07-05 17:23:28 +08004435 case glslang::EOpSparseImageLoadLod:
4436 if (i == 3)
4437 lvalue = true;
4438 break;
Chao Chen3a137962018-09-19 11:41:27 -07004439 case glslang::EOpImageSampleFootprintNV:
4440 if (i == 4)
4441 lvalue = true;
4442 break;
4443 case glslang::EOpImageSampleFootprintClampNV:
4444 case glslang::EOpImageSampleFootprintLodNV:
4445 if (i == 5)
4446 lvalue = true;
4447 break;
4448 case glslang::EOpImageSampleFootprintGradNV:
4449 if (i == 6)
4450 lvalue = true;
4451 break;
4452 case glslang::EOpImageSampleFootprintGradClampNV:
4453 if (i == 7)
4454 lvalue = true;
4455 break;
Rex Xufc618912015-09-09 16:42:49 +08004456 default:
4457 break;
4458 }
4459
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004460 if (lvalue) {
Rex Xufc618912015-09-09 16:42:49 +08004461 arguments.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004462 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
4463 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4464 } else
John Kessenicha28f7a72019-08-06 07:00:58 -06004465#endif
John Kessenich32cfd492016-02-02 12:37:46 -07004466 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004467 }
4468}
4469
John Kessenichfc51d282015-08-19 13:34:18 -06004470void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004471{
John Kessenichfc51d282015-08-19 13:34:18 -06004472 builder.clearAccessChain();
4473 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004474 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004475}
John Kessenich140f3df2015-06-26 16:58:36 -06004476
John Kessenichfc51d282015-08-19 13:34:18 -06004477spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4478{
John Kesseniche485c7a2017-05-31 18:50:53 -06004479 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004480 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004481
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004482 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004483
John Kessenichfc51d282015-08-19 13:34:18 -06004484 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004485
John Kessenichf43c7392019-03-31 10:51:57 -06004486 const glslang::TType &imageType = node->getAsAggregate()
4487 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4488 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004489 const glslang::TSampler sampler = imageType.getSampler();
John Kessenicha28f7a72019-08-06 07:00:58 -06004490#ifdef GLSLANG_WEB
4491 const bool f16ShadowCompare = false;
4492#else
Rex Xu1e5d7b02016-11-29 17:36:31 +08004493 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004494 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4495 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004496#endif
4497
John Kessenichf43c7392019-03-31 10:51:57 -06004498 const auto signExtensionMask = [&]() {
4499 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4500 if (sampler.type == glslang::EbtUint)
4501 return spv::ImageOperandsZeroExtendMask;
4502 else if (sampler.type == glslang::EbtInt)
4503 return spv::ImageOperandsSignExtendMask;
4504 }
4505 return spv::ImageOperandsMaskNone;
4506 };
4507
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004508 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4509
John Kessenichfc51d282015-08-19 13:34:18 -06004510 std::vector<spv::Id> arguments;
4511 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004512 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004513 else
4514 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004515 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004516
4517 spv::Builder::TextureParameters params = { };
4518 params.sampler = arguments[0];
4519
Rex Xu04db3f52015-09-16 11:44:02 +08004520 glslang::TCrackedTextureOp cracked;
4521 node->crackTexture(sampler, cracked);
4522
amhagan05506bb2017-06-13 16:53:02 -04004523 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004524
John Kessenichfc51d282015-08-19 13:34:18 -06004525 // Check for queries
4526 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004527 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4528 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004529 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004530
John Kessenichfc51d282015-08-19 13:34:18 -06004531 switch (node->getOp()) {
4532 case glslang::EOpImageQuerySize:
4533 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004534 if (arguments.size() > 1) {
4535 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004536 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004537 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004538 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenicha28f7a72019-08-06 07:00:58 -06004539#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06004540 case glslang::EOpImageQuerySamples:
4541 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004542 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004543 case glslang::EOpTextureQueryLod:
4544 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004545 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004546 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004547 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004548 case glslang::EOpSparseTexelsResident:
4549 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenicha28f7a72019-08-06 07:00:58 -06004550#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004551 default:
4552 assert(0);
4553 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004554 }
John Kessenich140f3df2015-06-26 16:58:36 -06004555 }
4556
LoopDawg4425f242018-02-18 11:40:01 -07004557 int components = node->getType().getVectorSize();
4558
4559 if (node->getOp() == glslang::EOpTextureFetch) {
4560 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4561 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4562 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4563 // here around e.g. which ones return scalars or other types.
4564 components = 4;
4565 }
4566
4567 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4568
4569 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4570
Rex Xufc618912015-09-09 16:42:49 +08004571 // Check for image functions other than queries
4572 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004573 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004574 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004575 spv::IdImmediate image = { true, *(opIt++) };
4576 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004577
4578 // Handle subpass operations
4579 // TODO: GLSL should change to have the "MS" only on the type rather than the
4580 // built-in function.
4581 if (cracked.subpass) {
4582 // add on the (0,0) coordinate
4583 spv::Id zero = builder.makeIntConstant(0);
4584 std::vector<spv::Id> comps;
4585 comps.push_back(zero);
4586 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004587 spv::IdImmediate coord = { true,
4588 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4589 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004590 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4591 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004592 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004593 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4594 }
4595 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004596 operands.push_back(imageOperands);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004597 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004598 spv::IdImmediate imageOperand = { true, *(opIt++) };
4599 operands.push_back(imageOperand);
4600 }
John Kessenich6c292d32016-02-15 20:58:50 -07004601 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004602 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4603 builder.setPrecision(result, precision);
4604 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004605 }
4606
John Kessenich149afc32018-08-14 13:31:43 -06004607 spv::IdImmediate coord = { true, *(opIt++) };
4608 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004609 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004610 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004611 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004612 mask = mask | spv::ImageOperandsSampleMask;
4613 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004614 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004615 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4616 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004617 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004618 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004619 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4620 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004621 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004622 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004623 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4624 operands.push_back(imageOperands);
4625 }
4626 if (mask & spv::ImageOperandsSampleMask) {
4627 spv::IdImmediate imageOperand = { true, *opIt++ };
4628 operands.push_back(imageOperand);
4629 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004630 if (mask & spv::ImageOperandsLodMask) {
4631 spv::IdImmediate imageOperand = { true, *opIt++ };
4632 operands.push_back(imageOperand);
4633 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004634 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004635 spv::IdImmediate imageOperand = { true,
4636 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004637 operands.push_back(imageOperand);
4638 }
4639
John Kessenich149afc32018-08-14 13:31:43 -06004640 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004641 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004642
John Kessenich149afc32018-08-14 13:31:43 -06004643 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004644 builder.setPrecision(result[0], precision);
4645
4646 // If needed, add a conversion constructor to the proper size.
4647 if (components != node->getType().getVectorSize())
4648 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4649
4650 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004651 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004652
Jeff Bolz36831c92018-09-05 10:11:41 -05004653 // Push the texel value before the operands
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004654 if (sampler.isMultiSample() || cracked.lod) {
John Kessenich149afc32018-08-14 13:31:43 -06004655 spv::IdImmediate texel = { true, *(opIt + 1) };
4656 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004657 } else {
4658 spv::IdImmediate texel = { true, *opIt };
4659 operands.push_back(texel);
4660 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004661
4662 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004663 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004664 mask = mask | spv::ImageOperandsSampleMask;
4665 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004666 if (cracked.lod) {
4667 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4668 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4669 mask = mask | spv::ImageOperandsLodMask;
4670 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004671 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4672 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004673 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004674 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004675 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4676 operands.push_back(imageOperands);
4677 }
4678 if (mask & spv::ImageOperandsSampleMask) {
4679 spv::IdImmediate imageOperand = { true, *opIt++ };
4680 operands.push_back(imageOperand);
4681 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004682 if (mask & spv::ImageOperandsLodMask) {
4683 spv::IdImmediate imageOperand = { true, *opIt++ };
4684 operands.push_back(imageOperand);
4685 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004686 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004687 spv::IdImmediate imageOperand = { true,
4688 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004689 operands.push_back(imageOperand);
4690 }
4691
John Kessenich56bab042015-09-16 10:54:31 -06004692 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004693 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004694 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004695 return spv::NoResult;
John Kessenichf43c7392019-03-31 10:51:57 -06004696 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4697 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu5eafa472016-02-19 22:24:03 +08004698 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004699 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004700 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4701
Jeff Bolz36831c92018-09-05 10:11:41 -05004702 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004703 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004704 mask = mask | spv::ImageOperandsSampleMask;
4705 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004706 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004707 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4708 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4709
Jeff Bolz36831c92018-09-05 10:11:41 -05004710 mask = mask | spv::ImageOperandsLodMask;
4711 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004712 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4713 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004714 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004715 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004716 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004717 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004718 }
4719 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004720 spv::IdImmediate imageOperand = { true, *opIt++ };
4721 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004722 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004723 if (mask & spv::ImageOperandsLodMask) {
4724 spv::IdImmediate imageOperand = { true, *opIt++ };
4725 operands.push_back(imageOperand);
4726 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004727 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4728 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4729 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004730 }
4731
4732 // Create the return type that was a special structure
4733 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004734 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004735 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4736 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4737
4738 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4739
4740 // Decode the return type
4741 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4742 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004743 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004744 // Process image atomic operations
4745
4746 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4747 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004748 // For non-MS, the sample value should be 0
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004749 spv::IdImmediate sample = { true, sampler.isMultiSample() ? *(opIt++) : builder.makeUintConstant(0) };
John Kessenich149afc32018-08-14 13:31:43 -06004750 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004751
Jeff Bolz36831c92018-09-05 10:11:41 -05004752 spv::Id resultTypeId;
4753 // imageAtomicStore has a void return type so base the pointer type on
4754 // the type of the value operand.
4755 if (node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufb18b6d2020-02-22 22:04:31 +08004756 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(*opIt));
Jeff Bolz36831c92018-09-05 10:11:41 -05004757 } else {
4758 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4759 }
John Kessenich56bab042015-09-16 10:54:31 -06004760 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08004761
4762 std::vector<spv::Id> operands;
4763 operands.push_back(pointer);
4764 for (; opIt != arguments.end(); ++opIt)
4765 operands.push_back(*opIt);
4766
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004767 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(), lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08004768 }
4769 }
4770
John Kessenicha28f7a72019-08-06 07:00:58 -06004771#ifndef GLSLANG_WEB
amhagan05506bb2017-06-13 16:53:02 -04004772 // Check for fragment mask functions other than queries
4773 if (cracked.fragMask) {
4774 assert(sampler.ms);
4775
4776 auto opIt = arguments.begin();
4777 std::vector<spv::Id> operands;
4778
4779 // Extract the image if necessary
4780 if (builder.isSampledImage(params.sampler))
4781 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4782
4783 operands.push_back(params.sampler);
4784 ++opIt;
4785
4786 if (sampler.isSubpass()) {
4787 // add on the (0,0) coordinate
4788 spv::Id zero = builder.makeIntConstant(0);
4789 std::vector<spv::Id> comps;
4790 comps.push_back(zero);
4791 comps.push_back(zero);
4792 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
4793 }
4794
4795 for (; opIt != arguments.end(); ++opIt)
4796 operands.push_back(*opIt);
4797
4798 spv::Op fragMaskOp = spv::OpNop;
4799 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4800 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4801 else if (node->getOp() == glslang::EOpFragmentFetch)
4802 fragMaskOp = spv::OpFragmentFetchAMD;
4803
4804 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4805 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4806 return builder.createOp(fragMaskOp, resultType(), operands);
4807 }
4808#endif
4809
Rex Xufc618912015-09-09 16:42:49 +08004810 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004811 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004812 bool imageFootprint = node->isImageFootprint();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004813 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.isArrayed() && sampler.isShadow();
Rex Xu71519fe2015-11-11 15:35:47 +08004814
John Kessenichfc51d282015-08-19 13:34:18 -06004815 // check for bias argument
4816 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004817 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06004818 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004819 if (cracked.gather)
4820 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004821
4822 if (f16ShadowCompare)
4823 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06004824 if (cracked.offset)
4825 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004826 else if (cracked.offsets)
4827 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06004828 if (cracked.grad)
4829 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004830 if (cracked.lodClamp)
4831 ++nonBiasArgCount;
4832 if (sparse)
4833 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004834 if (imageFootprint)
4835 //Following three extra arguments
4836 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4837 nonBiasArgCount += 3;
John Kessenichfc51d282015-08-19 13:34:18 -06004838 if ((int)arguments.size() > nonBiasArgCount)
4839 bias = true;
4840 }
4841
John Kessenicha5c33d62016-06-02 23:45:21 -06004842 // See if the sampler param should really be just the SPV image part
4843 if (cracked.fetch) {
4844 // a fetch needs to have the image extracted first
4845 if (builder.isSampledImage(params.sampler))
4846 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4847 }
4848
John Kessenicha28f7a72019-08-06 07:00:58 -06004849#ifndef GLSLANG_WEB
Rex Xu225e0fc2016-11-17 17:47:59 +08004850 if (cracked.gather) {
4851 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4852 if (bias || cracked.lod ||
4853 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4854 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004855 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004856 }
4857 }
4858#endif
4859
John Kessenichfc51d282015-08-19 13:34:18 -06004860 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004861
John Kessenichfc51d282015-08-19 13:34:18 -06004862 params.coords = arguments[1];
4863 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004864 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004865
4866 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004867 if (cubeCompare || f16ShadowCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06004868 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004869 ++extraArgs;
4870 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004871 params.Dref = arguments[2];
4872 ++extraArgs;
4873 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004874 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004875 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004876 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004877 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004878 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004879 dRefComp = builder.getNumComponents(params.coords) - 1;
4880 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004881 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4882 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004883
4884 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004885 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004886 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004887 ++extraArgs;
John Kessenichb9197c82019-08-11 07:41:45 -06004888 } else if (glslangIntermediate->getStage() != EShLangFragment &&
4889 !(glslangIntermediate->getStage() == EShLangCompute &&
4890 glslangIntermediate->hasLayoutDerivativeModeNone())) {
John Kessenich019f08f2016-02-15 15:40:42 -07004891 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4892 noImplicitLod = true;
4893 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004894
4895 // multisample
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004896 if (sampler.isMultiSample()) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004897 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004898 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004899 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004900
4901 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004902 if (cracked.grad) {
4903 params.gradX = arguments[2 + extraArgs];
4904 params.gradY = arguments[3 + extraArgs];
4905 extraArgs += 2;
4906 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004907
4908 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004909 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004910 params.offset = arguments[2 + extraArgs];
4911 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004912 } else if (cracked.offsets) {
4913 params.offsets = arguments[2 + extraArgs];
4914 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004915 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004916
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004917#ifndef GLSLANG_WEB
John Kessenich76d4dfc2016-06-16 12:43:23 -06004918 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004919 if (cracked.lodClamp) {
4920 params.lodClamp = arguments[2 + extraArgs];
4921 ++extraArgs;
4922 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004923 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004924 if (sparse) {
4925 params.texelOut = arguments[2 + extraArgs];
4926 ++extraArgs;
4927 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004928 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004929 if (cracked.gather && ! sampler.shadow) {
4930 // default component is 0, if missing, otherwise an argument
4931 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004932 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004933 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004934 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004935 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004936 }
Chao Chen3a137962018-09-19 11:41:27 -07004937 spv::Id resultStruct = spv::NoResult;
4938 if (imageFootprint) {
4939 //Following three extra arguments
4940 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4941 params.granularity = arguments[2 + extraArgs];
4942 params.coarse = arguments[3 + extraArgs];
4943 resultStruct = arguments[4 + extraArgs];
4944 extraArgs += 3;
4945 }
4946#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004947 // bias
4948 if (bias) {
4949 params.bias = arguments[2 + extraArgs];
4950 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004951 }
John Kessenichfc51d282015-08-19 13:34:18 -06004952
John Kessenicha28f7a72019-08-06 07:00:58 -06004953#ifndef GLSLANG_WEB
Chao Chen3a137962018-09-19 11:41:27 -07004954 if (imageFootprint) {
4955 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
4956 builder.addCapability(spv::CapabilityImageFootprintNV);
4957
4958
4959 //resultStructType(OpenGL type) contains 5 elements:
4960 //struct gl_TextureFootprint2DNV {
4961 // uvec2 anchor;
4962 // uvec2 offset;
4963 // uvec2 mask;
4964 // uint lod;
4965 // uint granularity;
4966 //};
4967 //or
4968 //struct gl_TextureFootprint3DNV {
4969 // uvec3 anchor;
4970 // uvec3 offset;
4971 // uvec2 mask;
4972 // uint lod;
4973 // uint granularity;
4974 //};
4975 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
4976 assert(builder.isStructType(resultStructType));
4977
4978 //resType (SPIR-V type) contains 6 elements:
4979 //Member 0 must be a Boolean type scalar(LOD),
4980 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
4981 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
4982 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
4983 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
4984 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
4985 std::vector<spv::Id> members;
4986 members.push_back(resultType());
4987 for (int i = 0; i < 5; i++) {
4988 members.push_back(builder.getContainedTypeId(resultStructType, i));
4989 }
4990 spv::Id resType = builder.makeStructType(members, "ResType");
4991
4992 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06004993 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
4994 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07004995
4996 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
4997 for (int i = 0; i < 5; i++) {
4998 builder.clearAccessChain();
4999 builder.setAccessChainLValue(resultStruct);
5000
5001 //Accessing to a struct we created, no coherent flag is set
5002 spv::Builder::AccessChain::CoherentFlags flags;
5003 flags.clear();
5004
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005005 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
Chao Chen3a137962018-09-19 11:41:27 -07005006 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1), i+1));
5007 }
5008 return builder.createCompositeExtract(res, resultType(), 0);
5009 }
5010#endif
5011
John Kessenich65336482016-06-16 14:06:26 -06005012 // projective component (might not to move)
5013 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
5014 // are divided by the last component of P."
5015 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
5016 // unused components will appear after all used components."
5017 if (cracked.proj) {
5018 int projSourceComp = builder.getNumComponents(params.coords) - 1;
5019 int projTargetComp;
5020 switch (sampler.dim) {
5021 case glslang::Esd1D: projTargetComp = 1; break;
5022 case glslang::Esd2D: projTargetComp = 2; break;
5023 case glslang::EsdRect: projTargetComp = 2; break;
5024 default: projTargetComp = projSourceComp; break;
5025 }
5026 // copy the projective coordinate if we have to
5027 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07005028 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06005029 builder.getScalarTypeId(builder.getTypeId(params.coords)),
5030 projSourceComp);
5031 params.coords = builder.createCompositeInsert(projComp, params.coords,
5032 builder.getTypeId(params.coords), projTargetComp);
5033 }
5034 }
5035
John Kessenichf8d1d742019-10-21 06:55:11 -06005036#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -05005037 // nonprivate
5038 if (imageType.getQualifier().nonprivate) {
5039 params.nonprivate = true;
5040 }
5041
5042 // volatile
5043 if (imageType.getQualifier().volatil) {
5044 params.volatil = true;
5045 }
John Kessenichf8d1d742019-10-21 06:55:11 -06005046#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05005047
St0fFa1184dd2018-04-09 21:08:14 +02005048 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06005049 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
5050 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02005051 );
LoopDawg4425f242018-02-18 11:40:01 -07005052
5053 if (components != node->getType().getVectorSize())
5054 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
5055
5056 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06005057}
5058
5059spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
5060{
5061 // Grab the function's pointer from the previously created function
5062 spv::Function* function = functionMap[node->getName().c_str()];
5063 if (! function)
5064 return 0;
5065
5066 const glslang::TIntermSequence& glslangArgs = node->getSequence();
5067 const glslang::TQualifierList& qualifiers = node->getQualifierList();
5068
5069 // See comments in makeFunctions() for details about the semantics for parameter passing.
5070 //
5071 // These imply we need a four step process:
5072 // 1. Evaluate the arguments
5073 // 2. Allocate and make copies of in, out, and inout arguments
5074 // 3. Make the call
5075 // 4. Copy back the results
5076
John Kessenichd3ed90b2018-05-04 11:43:03 -06005077 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06005078 std::vector<spv::Builder::AccessChain> lValues;
5079 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07005080 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06005081 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005082 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06005083 // build l-value
5084 builder.clearAccessChain();
5085 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06005086 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06005087 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07005088 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005089 // save l-value
5090 lValues.push_back(builder.getAccessChain());
5091 } else {
5092 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07005093 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06005094 }
5095 }
5096
5097 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
5098 // copy the original into that space.
5099 //
5100 // Also, build up the list of actual arguments to pass in for the call
5101 int lValueCount = 0;
5102 int rValueCount = 0;
5103 std::vector<spv::Id> spvArgs;
5104 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
5105 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06005106 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07005107 builder.setAccessChain(lValues[lValueCount]);
5108 arg = builder.accessChainGetLValue();
5109 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06005110 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005111 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06005112 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06005113 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
5114 // need to copy the input into output space
5115 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07005116 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06005117 builder.clearAccessChain();
5118 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005119 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005120 }
5121 ++lValueCount;
5122 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005123 // process r-value, which involves a copy for a type mismatch
5124 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
5125 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
5126 builder.clearAccessChain();
5127 builder.setAccessChainLValue(argCopy);
5128 multiTypeStore(*argTypes[a], rValues[rValueCount]);
5129 arg = builder.createLoad(argCopy);
5130 } else
5131 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005132 ++rValueCount;
5133 }
5134 spvArgs.push_back(arg);
5135 }
5136
5137 // 3. Make the call.
5138 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005139 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06005140
5141 // 4. Copy back out an "out" arguments.
5142 lValueCount = 0;
5143 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005144 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005145 ++lValueCount;
5146 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005147 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
5148 spv::Id copy = builder.createLoad(spvArgs[a]);
5149 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005150 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005151 }
5152 ++lValueCount;
5153 }
5154 }
5155
5156 return result;
5157}
5158
5159// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005160spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005161 spv::Id typeId, spv::Id left, spv::Id right,
5162 glslang::TBasicType typeProxy, bool reduceComparison)
5163{
John Kessenich66011cb2018-03-06 16:12:04 -07005164 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5165 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005166 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005167
5168 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005169 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005170 bool comparison = false;
5171
5172 switch (op) {
5173 case glslang::EOpAdd:
5174 case glslang::EOpAddAssign:
5175 if (isFloat)
5176 binOp = spv::OpFAdd;
5177 else
5178 binOp = spv::OpIAdd;
5179 break;
5180 case glslang::EOpSub:
5181 case glslang::EOpSubAssign:
5182 if (isFloat)
5183 binOp = spv::OpFSub;
5184 else
5185 binOp = spv::OpISub;
5186 break;
5187 case glslang::EOpMul:
5188 case glslang::EOpMulAssign:
5189 if (isFloat)
5190 binOp = spv::OpFMul;
5191 else
5192 binOp = spv::OpIMul;
5193 break;
5194 case glslang::EOpVectorTimesScalar:
5195 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005196 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005197 if (builder.isVector(right))
5198 std::swap(left, right);
5199 assert(builder.isScalar(right));
5200 needMatchingVectors = false;
5201 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005202 } else if (isFloat)
5203 binOp = spv::OpFMul;
5204 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005205 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005206 break;
5207 case glslang::EOpVectorTimesMatrix:
5208 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005209 binOp = spv::OpVectorTimesMatrix;
5210 break;
5211 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005212 binOp = spv::OpMatrixTimesVector;
5213 break;
5214 case glslang::EOpMatrixTimesScalar:
5215 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005216 binOp = spv::OpMatrixTimesScalar;
5217 break;
5218 case glslang::EOpMatrixTimesMatrix:
5219 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005220 binOp = spv::OpMatrixTimesMatrix;
5221 break;
5222 case glslang::EOpOuterProduct:
5223 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005224 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005225 break;
5226
5227 case glslang::EOpDiv:
5228 case glslang::EOpDivAssign:
5229 if (isFloat)
5230 binOp = spv::OpFDiv;
5231 else if (isUnsigned)
5232 binOp = spv::OpUDiv;
5233 else
5234 binOp = spv::OpSDiv;
5235 break;
5236 case glslang::EOpMod:
5237 case glslang::EOpModAssign:
5238 if (isFloat)
5239 binOp = spv::OpFMod;
5240 else if (isUnsigned)
5241 binOp = spv::OpUMod;
5242 else
5243 binOp = spv::OpSMod;
5244 break;
5245 case glslang::EOpRightShift:
5246 case glslang::EOpRightShiftAssign:
5247 if (isUnsigned)
5248 binOp = spv::OpShiftRightLogical;
5249 else
5250 binOp = spv::OpShiftRightArithmetic;
5251 break;
5252 case glslang::EOpLeftShift:
5253 case glslang::EOpLeftShiftAssign:
5254 binOp = spv::OpShiftLeftLogical;
5255 break;
5256 case glslang::EOpAnd:
5257 case glslang::EOpAndAssign:
5258 binOp = spv::OpBitwiseAnd;
5259 break;
5260 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005261 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005262 binOp = spv::OpLogicalAnd;
5263 break;
5264 case glslang::EOpInclusiveOr:
5265 case glslang::EOpInclusiveOrAssign:
5266 binOp = spv::OpBitwiseOr;
5267 break;
5268 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005269 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005270 binOp = spv::OpLogicalOr;
5271 break;
5272 case glslang::EOpExclusiveOr:
5273 case glslang::EOpExclusiveOrAssign:
5274 binOp = spv::OpBitwiseXor;
5275 break;
5276 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005277 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005278 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005279 break;
5280
Ian Romanickb3bd4022019-01-21 08:57:25 -08005281 case glslang::EOpAbsDifference:
5282 binOp = isUnsigned ? spv::OpAbsUSubINTEL : spv::OpAbsISubINTEL;
5283 break;
5284
5285 case glslang::EOpAddSaturate:
5286 binOp = isUnsigned ? spv::OpUAddSatINTEL : spv::OpIAddSatINTEL;
5287 break;
5288
5289 case glslang::EOpSubSaturate:
5290 binOp = isUnsigned ? spv::OpUSubSatINTEL : spv::OpISubSatINTEL;
5291 break;
5292
5293 case glslang::EOpAverage:
5294 binOp = isUnsigned ? spv::OpUAverageINTEL : spv::OpIAverageINTEL;
5295 break;
5296
5297 case glslang::EOpAverageRounded:
5298 binOp = isUnsigned ? spv::OpUAverageRoundedINTEL : spv::OpIAverageRoundedINTEL;
5299 break;
5300
5301 case glslang::EOpMul32x16:
5302 binOp = isUnsigned ? spv::OpUMul32x16INTEL : spv::OpIMul32x16INTEL;
5303 break;
5304
John Kessenich140f3df2015-06-26 16:58:36 -06005305 case glslang::EOpLessThan:
5306 case glslang::EOpGreaterThan:
5307 case glslang::EOpLessThanEqual:
5308 case glslang::EOpGreaterThanEqual:
5309 case glslang::EOpEqual:
5310 case glslang::EOpNotEqual:
5311 case glslang::EOpVectorEqual:
5312 case glslang::EOpVectorNotEqual:
5313 comparison = true;
5314 break;
5315 default:
5316 break;
5317 }
5318
John Kessenich7c1aa102015-10-15 13:29:11 -06005319 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005320 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005321 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005322 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5323 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005324 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005325
5326 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005327 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005328 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005329
qining25262b32016-05-06 17:25:16 -04005330 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005331 decorations.addNoContraction(builder, result);
5332 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005333 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005334 }
5335
5336 if (! comparison)
5337 return 0;
5338
John Kessenich7c1aa102015-10-15 13:29:11 -06005339 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005340
John Kessenich4583b612016-08-07 19:14:22 -06005341 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005342 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5343 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenichb9197c82019-08-11 07:41:45 -06005344 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005345 return result;
5346 }
John Kessenich140f3df2015-06-26 16:58:36 -06005347
5348 switch (op) {
5349 case glslang::EOpLessThan:
5350 if (isFloat)
5351 binOp = spv::OpFOrdLessThan;
5352 else if (isUnsigned)
5353 binOp = spv::OpULessThan;
5354 else
5355 binOp = spv::OpSLessThan;
5356 break;
5357 case glslang::EOpGreaterThan:
5358 if (isFloat)
5359 binOp = spv::OpFOrdGreaterThan;
5360 else if (isUnsigned)
5361 binOp = spv::OpUGreaterThan;
5362 else
5363 binOp = spv::OpSGreaterThan;
5364 break;
5365 case glslang::EOpLessThanEqual:
5366 if (isFloat)
5367 binOp = spv::OpFOrdLessThanEqual;
5368 else if (isUnsigned)
5369 binOp = spv::OpULessThanEqual;
5370 else
5371 binOp = spv::OpSLessThanEqual;
5372 break;
5373 case glslang::EOpGreaterThanEqual:
5374 if (isFloat)
5375 binOp = spv::OpFOrdGreaterThanEqual;
5376 else if (isUnsigned)
5377 binOp = spv::OpUGreaterThanEqual;
5378 else
5379 binOp = spv::OpSGreaterThanEqual;
5380 break;
5381 case glslang::EOpEqual:
5382 case glslang::EOpVectorEqual:
5383 if (isFloat)
5384 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005385 else if (isBool)
5386 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005387 else
5388 binOp = spv::OpIEqual;
5389 break;
5390 case glslang::EOpNotEqual:
5391 case glslang::EOpVectorNotEqual:
5392 if (isFloat)
5393 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005394 else if (isBool)
5395 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005396 else
5397 binOp = spv::OpINotEqual;
5398 break;
5399 default:
5400 break;
5401 }
5402
qining25262b32016-05-06 17:25:16 -04005403 if (binOp != spv::OpNop) {
5404 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005405 decorations.addNoContraction(builder, result);
5406 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005407 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005408 }
John Kessenich140f3df2015-06-26 16:58:36 -06005409
5410 return 0;
5411}
5412
John Kessenich04bb8a02015-12-12 12:28:14 -07005413//
5414// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5415// These can be any of:
5416//
5417// matrix * scalar
5418// scalar * matrix
5419// matrix * matrix linear algebraic
5420// matrix * vector
5421// vector * matrix
5422// matrix * matrix componentwise
5423// matrix op matrix op in {+, -, /}
5424// matrix op scalar op in {+, -, /}
5425// scalar op matrix op in {+, -, /}
5426//
John Kessenichead86222018-03-28 18:01:20 -06005427spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5428 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005429{
5430 bool firstClass = true;
5431
5432 // First, handle first-class matrix operations (* and matrix/scalar)
5433 switch (op) {
5434 case spv::OpFDiv:
5435 if (builder.isMatrix(left) && builder.isScalar(right)) {
5436 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005437 spv::Id resultType = builder.getTypeId(right);
5438 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005439 op = spv::OpMatrixTimesScalar;
5440 } else
5441 firstClass = false;
5442 break;
5443 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005444 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005445 std::swap(left, right);
5446 assert(builder.isScalar(right));
5447 break;
5448 case spv::OpVectorTimesMatrix:
5449 assert(builder.isVector(left));
5450 assert(builder.isMatrix(right));
5451 break;
5452 case spv::OpMatrixTimesVector:
5453 assert(builder.isMatrix(left));
5454 assert(builder.isVector(right));
5455 break;
5456 case spv::OpMatrixTimesMatrix:
5457 assert(builder.isMatrix(left));
5458 assert(builder.isMatrix(right));
5459 break;
5460 default:
5461 firstClass = false;
5462 break;
5463 }
5464
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005465 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5466 firstClass = true;
5467
qining25262b32016-05-06 17:25:16 -04005468 if (firstClass) {
5469 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005470 decorations.addNoContraction(builder, result);
5471 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005472 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005473 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005474
LoopDawg592860c2016-06-09 08:57:35 -06005475 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005476 // The result type of all of them is the same type as the (a) matrix operand.
5477 // The algorithm is to:
5478 // - break the matrix(es) into vectors
5479 // - smear any scalar to a vector
5480 // - do vector operations
5481 // - make a matrix out the vector results
5482 switch (op) {
5483 case spv::OpFAdd:
5484 case spv::OpFSub:
5485 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005486 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005487 case spv::OpFMul:
5488 {
5489 // one time set up...
5490 bool leftMat = builder.isMatrix(left);
5491 bool rightMat = builder.isMatrix(right);
5492 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5493 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5494 spv::Id scalarType = builder.getScalarTypeId(typeId);
5495 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5496 std::vector<spv::Id> results;
5497 spv::Id smearVec = spv::NoResult;
5498 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005499 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005500 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005501 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005502
5503 // do each vector op
5504 for (unsigned int c = 0; c < numCols; ++c) {
5505 std::vector<unsigned int> indexes;
5506 indexes.push_back(c);
5507 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5508 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005509 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005510 decorations.addNoContraction(builder, result);
5511 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005512 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005513 }
5514
5515 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005516 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005517 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005518 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005519 }
5520 default:
5521 assert(0);
5522 return spv::NoResult;
5523 }
5524}
5525
John Kessenichead86222018-03-28 18:01:20 -06005526spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005527 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005528{
5529 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005530 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005531 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005532 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5533 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005534
5535 switch (op) {
5536 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005537 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005538 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005539 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005540 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005541 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005542 unaryOp = spv::OpSNegate;
5543 break;
5544
5545 case glslang::EOpLogicalNot:
5546 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005547 unaryOp = spv::OpLogicalNot;
5548 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005549 case glslang::EOpBitwiseNot:
5550 unaryOp = spv::OpNot;
5551 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005552
John Kessenich140f3df2015-06-26 16:58:36 -06005553 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005554 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005555 break;
5556 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005557 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005558 break;
5559 case glslang::EOpTranspose:
5560 unaryOp = spv::OpTranspose;
5561 break;
5562
5563 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005564 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005565 break;
5566 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005567 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005568 break;
5569 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005570 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005571 break;
5572 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005573 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005574 break;
5575 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005576 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005577 break;
5578 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005579 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005580 break;
5581 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005582 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005583 break;
5584 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005585 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005586 break;
5587
5588 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005589 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005590 break;
5591 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005592 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005593 break;
5594 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005595 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005596 break;
5597 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005598 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005599 break;
5600 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005601 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005602 break;
5603 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005604 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005605 break;
5606
5607 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005608 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005609 break;
5610 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005611 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005612 break;
5613
5614 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005615 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005616 break;
5617 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005618 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005619 break;
5620 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005621 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005622 break;
5623 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005624 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005625 break;
5626 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005627 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005628 break;
5629 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005630 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005631 break;
5632
5633 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005634 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005635 break;
5636 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005637 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005638 break;
5639 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005640 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005641 break;
5642 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005643 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005644 break;
5645 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005646 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005647 break;
5648 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005649 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005650 break;
5651
5652 case glslang::EOpIsNan:
5653 unaryOp = spv::OpIsNan;
5654 break;
5655 case glslang::EOpIsInf:
5656 unaryOp = spv::OpIsInf;
5657 break;
LoopDawg592860c2016-06-09 08:57:35 -06005658 case glslang::EOpIsFinite:
5659 unaryOp = spv::OpIsFinite;
5660 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005661
Rex Xucbc426e2015-12-15 16:03:10 +08005662 case glslang::EOpFloatBitsToInt:
5663 case glslang::EOpFloatBitsToUint:
5664 case glslang::EOpIntBitsToFloat:
5665 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005666 case glslang::EOpDoubleBitsToInt64:
5667 case glslang::EOpDoubleBitsToUint64:
5668 case glslang::EOpInt64BitsToDouble:
5669 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005670 case glslang::EOpFloat16BitsToInt16:
5671 case glslang::EOpFloat16BitsToUint16:
5672 case glslang::EOpInt16BitsToFloat16:
5673 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005674 unaryOp = spv::OpBitcast;
5675 break;
5676
John Kessenich140f3df2015-06-26 16:58:36 -06005677 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005678 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005679 break;
5680 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005681 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005682 break;
5683 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005684 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005685 break;
5686 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005687 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005688 break;
5689 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005690 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005691 break;
5692 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005693 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005694 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005695#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06005696 case glslang::EOpPackSnorm4x8:
5697 libCall = spv::GLSLstd450PackSnorm4x8;
5698 break;
5699 case glslang::EOpUnpackSnorm4x8:
5700 libCall = spv::GLSLstd450UnpackSnorm4x8;
5701 break;
5702 case glslang::EOpPackUnorm4x8:
5703 libCall = spv::GLSLstd450PackUnorm4x8;
5704 break;
5705 case glslang::EOpUnpackUnorm4x8:
5706 libCall = spv::GLSLstd450UnpackUnorm4x8;
5707 break;
5708 case glslang::EOpPackDouble2x32:
5709 libCall = spv::GLSLstd450PackDouble2x32;
5710 break;
5711 case glslang::EOpUnpackDouble2x32:
5712 libCall = spv::GLSLstd450UnpackDouble2x32;
5713 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005714#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005715
Rex Xu8ff43de2016-04-22 16:51:45 +08005716 case glslang::EOpPackInt2x32:
5717 case glslang::EOpUnpackInt2x32:
5718 case glslang::EOpPackUint2x32:
5719 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005720 case glslang::EOpPack16:
5721 case glslang::EOpPack32:
5722 case glslang::EOpPack64:
5723 case glslang::EOpUnpack32:
5724 case glslang::EOpUnpack16:
5725 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005726 case glslang::EOpPackInt2x16:
5727 case glslang::EOpUnpackInt2x16:
5728 case glslang::EOpPackUint2x16:
5729 case glslang::EOpUnpackUint2x16:
5730 case glslang::EOpPackInt4x16:
5731 case glslang::EOpUnpackInt4x16:
5732 case glslang::EOpPackUint4x16:
5733 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005734 case glslang::EOpPackFloat2x16:
5735 case glslang::EOpUnpackFloat2x16:
5736 unaryOp = spv::OpBitcast;
5737 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005738
John Kessenich140f3df2015-06-26 16:58:36 -06005739 case glslang::EOpDPdx:
5740 unaryOp = spv::OpDPdx;
5741 break;
5742 case glslang::EOpDPdy:
5743 unaryOp = spv::OpDPdy;
5744 break;
5745 case glslang::EOpFwidth:
5746 unaryOp = spv::OpFwidth;
5747 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005748
John Kessenich140f3df2015-06-26 16:58:36 -06005749 case glslang::EOpAny:
5750 unaryOp = spv::OpAny;
5751 break;
5752 case glslang::EOpAll:
5753 unaryOp = spv::OpAll;
5754 break;
5755
5756 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005757 if (isFloat)
5758 libCall = spv::GLSLstd450FAbs;
5759 else
5760 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005761 break;
5762 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005763 if (isFloat)
5764 libCall = spv::GLSLstd450FSign;
5765 else
5766 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005767 break;
5768
John Kessenicha28f7a72019-08-06 07:00:58 -06005769#ifndef GLSLANG_WEB
5770 case glslang::EOpDPdxFine:
5771 unaryOp = spv::OpDPdxFine;
5772 break;
5773 case glslang::EOpDPdyFine:
5774 unaryOp = spv::OpDPdyFine;
5775 break;
5776 case glslang::EOpFwidthFine:
5777 unaryOp = spv::OpFwidthFine;
5778 break;
5779 case glslang::EOpDPdxCoarse:
5780 unaryOp = spv::OpDPdxCoarse;
5781 break;
5782 case glslang::EOpDPdyCoarse:
5783 unaryOp = spv::OpDPdyCoarse;
5784 break;
5785 case glslang::EOpFwidthCoarse:
5786 unaryOp = spv::OpFwidthCoarse;
5787 break;
5788 case glslang::EOpInterpolateAtCentroid:
5789 if (typeProxy == glslang::EbtFloat16)
5790 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5791 libCall = spv::GLSLstd450InterpolateAtCentroid;
5792 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005793 case glslang::EOpAtomicCounterIncrement:
5794 case glslang::EOpAtomicCounterDecrement:
5795 case glslang::EOpAtomicCounter:
5796 {
5797 // Handle all of the atomics in one place, in createAtomicOperation()
5798 std::vector<spv::Id> operands;
5799 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005800 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06005801 }
5802
John Kessenichfc51d282015-08-19 13:34:18 -06005803 case glslang::EOpBitFieldReverse:
5804 unaryOp = spv::OpBitReverse;
5805 break;
5806 case glslang::EOpBitCount:
5807 unaryOp = spv::OpBitCount;
5808 break;
5809 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005810 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005811 break;
5812 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005813 if (isUnsigned)
5814 libCall = spv::GLSLstd450FindUMsb;
5815 else
5816 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005817 break;
5818
Ian Romanickb3bd4022019-01-21 08:57:25 -08005819 case glslang::EOpCountLeadingZeros:
5820 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
5821 builder.addExtension("SPV_INTEL_shader_integer_functions2");
5822 unaryOp = spv::OpUCountLeadingZerosINTEL;
5823 break;
5824
5825 case glslang::EOpCountTrailingZeros:
5826 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
5827 builder.addExtension("SPV_INTEL_shader_integer_functions2");
5828 unaryOp = spv::OpUCountTrailingZerosINTEL;
5829 break;
5830
Rex Xu574ab042016-04-14 16:53:07 +08005831 case glslang::EOpBallot:
5832 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005833 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005834 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005835 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005836 case glslang::EOpMinInvocations:
5837 case glslang::EOpMaxInvocations:
5838 case glslang::EOpAddInvocations:
5839 case glslang::EOpMinInvocationsNonUniform:
5840 case glslang::EOpMaxInvocationsNonUniform:
5841 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005842 case glslang::EOpMinInvocationsInclusiveScan:
5843 case glslang::EOpMaxInvocationsInclusiveScan:
5844 case glslang::EOpAddInvocationsInclusiveScan:
5845 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5846 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5847 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5848 case glslang::EOpMinInvocationsExclusiveScan:
5849 case glslang::EOpMaxInvocationsExclusiveScan:
5850 case glslang::EOpAddInvocationsExclusiveScan:
5851 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5852 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5853 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu51596642016-09-21 18:56:12 +08005854 {
5855 std::vector<spv::Id> operands;
5856 operands.push_back(operand);
5857 return createInvocationsOperation(op, typeId, operands, typeProxy);
5858 }
John Kessenich66011cb2018-03-06 16:12:04 -07005859 case glslang::EOpSubgroupAll:
5860 case glslang::EOpSubgroupAny:
5861 case glslang::EOpSubgroupAllEqual:
5862 case glslang::EOpSubgroupBroadcastFirst:
5863 case glslang::EOpSubgroupBallot:
5864 case glslang::EOpSubgroupInverseBallot:
5865 case glslang::EOpSubgroupBallotBitCount:
5866 case glslang::EOpSubgroupBallotInclusiveBitCount:
5867 case glslang::EOpSubgroupBallotExclusiveBitCount:
5868 case glslang::EOpSubgroupBallotFindLSB:
5869 case glslang::EOpSubgroupBallotFindMSB:
5870 case glslang::EOpSubgroupAdd:
5871 case glslang::EOpSubgroupMul:
5872 case glslang::EOpSubgroupMin:
5873 case glslang::EOpSubgroupMax:
5874 case glslang::EOpSubgroupAnd:
5875 case glslang::EOpSubgroupOr:
5876 case glslang::EOpSubgroupXor:
5877 case glslang::EOpSubgroupInclusiveAdd:
5878 case glslang::EOpSubgroupInclusiveMul:
5879 case glslang::EOpSubgroupInclusiveMin:
5880 case glslang::EOpSubgroupInclusiveMax:
5881 case glslang::EOpSubgroupInclusiveAnd:
5882 case glslang::EOpSubgroupInclusiveOr:
5883 case glslang::EOpSubgroupInclusiveXor:
5884 case glslang::EOpSubgroupExclusiveAdd:
5885 case glslang::EOpSubgroupExclusiveMul:
5886 case glslang::EOpSubgroupExclusiveMin:
5887 case glslang::EOpSubgroupExclusiveMax:
5888 case glslang::EOpSubgroupExclusiveAnd:
5889 case glslang::EOpSubgroupExclusiveOr:
5890 case glslang::EOpSubgroupExclusiveXor:
5891 case glslang::EOpSubgroupQuadSwapHorizontal:
5892 case glslang::EOpSubgroupQuadSwapVertical:
5893 case glslang::EOpSubgroupQuadSwapDiagonal: {
5894 std::vector<spv::Id> operands;
5895 operands.push_back(operand);
5896 return createSubgroupOperation(op, typeId, operands, typeProxy);
5897 }
Rex Xu9d93a232016-05-05 12:30:44 +08005898 case glslang::EOpMbcnt:
5899 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5900 libCall = spv::MbcntAMD;
5901 break;
5902
5903 case glslang::EOpCubeFaceIndex:
5904 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5905 libCall = spv::CubeFaceIndexAMD;
5906 break;
5907
5908 case glslang::EOpCubeFaceCoord:
5909 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5910 libCall = spv::CubeFaceCoordAMD;
5911 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005912 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005913 unaryOp = spv::OpGroupNonUniformPartitionNV;
5914 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005915 case glslang::EOpConstructReference:
5916 unaryOp = spv::OpBitcast;
5917 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005918#endif
Jeff Bolz88220d52019-05-08 10:24:46 -05005919
5920 case glslang::EOpCopyObject:
5921 unaryOp = spv::OpCopyObject;
5922 break;
5923
John Kessenich140f3df2015-06-26 16:58:36 -06005924 default:
5925 return 0;
5926 }
5927
5928 spv::Id id;
5929 if (libCall >= 0) {
5930 std::vector<spv::Id> args;
5931 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005932 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005933 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005934 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005935 }
John Kessenich140f3df2015-06-26 16:58:36 -06005936
John Kessenichb9197c82019-08-11 07:41:45 -06005937 decorations.addNoContraction(builder, id);
5938 decorations.addNonUniform(builder, id);
John Kessenichead86222018-03-28 18:01:20 -06005939 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005940}
5941
John Kessenich7a53f762016-01-20 11:19:27 -07005942// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005943spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5944 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005945{
5946 // Handle unary operations vector by vector.
5947 // The result type is the same type as the original type.
5948 // The algorithm is to:
5949 // - break the matrix into vectors
5950 // - apply the operation to each vector
5951 // - make a matrix out the vector results
5952
5953 // get the types sorted out
5954 int numCols = builder.getNumColumns(operand);
5955 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005956 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5957 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005958 std::vector<spv::Id> results;
5959
5960 // do each vector op
5961 for (int c = 0; c < numCols; ++c) {
5962 std::vector<unsigned int> indexes;
5963 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005964 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5965 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005966 decorations.addNoContraction(builder, destVec);
5967 decorations.addNonUniform(builder, destVec);
John Kessenichead86222018-03-28 18:01:20 -06005968 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005969 }
5970
5971 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005972 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005973 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005974 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005975}
5976
John Kessenichad7645f2018-06-04 19:11:25 -06005977// For converting integers where both the bitwidth and the signedness could
5978// change, but only do the width change here. The caller is still responsible
5979// for the signedness conversion.
5980spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005981{
John Kessenichad7645f2018-06-04 19:11:25 -06005982 // Get the result type width, based on the type to convert to.
5983 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005984 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005985 case glslang::EOpConvInt16ToUint8:
5986 case glslang::EOpConvIntToUint8:
5987 case glslang::EOpConvInt64ToUint8:
5988 case glslang::EOpConvUint16ToInt8:
5989 case glslang::EOpConvUintToInt8:
5990 case glslang::EOpConvUint64ToInt8:
5991 width = 8;
5992 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005993 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005994 case glslang::EOpConvIntToUint16:
5995 case glslang::EOpConvInt64ToUint16:
5996 case glslang::EOpConvUint8ToInt16:
5997 case glslang::EOpConvUintToInt16:
5998 case glslang::EOpConvUint64ToInt16:
5999 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07006000 break;
6001 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06006002 case glslang::EOpConvInt16ToUint:
6003 case glslang::EOpConvInt64ToUint:
6004 case glslang::EOpConvUint8ToInt:
6005 case glslang::EOpConvUint16ToInt:
6006 case glslang::EOpConvUint64ToInt:
6007 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006008 break;
6009 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006010 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006011 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006012 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006013 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006014 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06006015 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07006016 break;
6017
6018 default:
6019 assert(false && "Default missing");
6020 break;
6021 }
6022
John Kessenichad7645f2018-06-04 19:11:25 -06006023 // Get the conversion operation and result type,
6024 // based on the target width, but the source type.
6025 spv::Id type = spv::NoType;
6026 spv::Op convOp = spv::OpNop;
6027 switch(op) {
6028 case glslang::EOpConvInt8ToUint16:
6029 case glslang::EOpConvInt8ToUint:
6030 case glslang::EOpConvInt8ToUint64:
6031 case glslang::EOpConvInt16ToUint8:
6032 case glslang::EOpConvInt16ToUint:
6033 case glslang::EOpConvInt16ToUint64:
6034 case glslang::EOpConvIntToUint8:
6035 case glslang::EOpConvIntToUint16:
6036 case glslang::EOpConvIntToUint64:
6037 case glslang::EOpConvInt64ToUint8:
6038 case glslang::EOpConvInt64ToUint16:
6039 case glslang::EOpConvInt64ToUint:
6040 convOp = spv::OpSConvert;
6041 type = builder.makeIntType(width);
6042 break;
6043 default:
6044 convOp = spv::OpUConvert;
6045 type = builder.makeUintType(width);
6046 break;
6047 }
6048
John Kessenich66011cb2018-03-06 16:12:04 -07006049 if (vectorSize > 0)
6050 type = builder.makeVectorType(type, vectorSize);
6051
John Kessenichad7645f2018-06-04 19:11:25 -06006052 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006053}
6054
John Kessenichead86222018-03-28 18:01:20 -06006055spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
6056 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06006057{
6058 spv::Op convOp = spv::OpNop;
6059 spv::Id zero = 0;
6060 spv::Id one = 0;
6061
6062 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
6063
6064 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07006065 case glslang::EOpConvIntToBool:
6066 case glslang::EOpConvUintToBool:
6067 zero = builder.makeUintConstant(0);
6068 zero = makeSmearedConstant(zero, vectorSize);
6069 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006070 case glslang::EOpConvFloatToBool:
6071 zero = builder.makeFloatConstant(0.0F);
6072 zero = makeSmearedConstant(zero, vectorSize);
6073 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006074 case glslang::EOpConvBoolToFloat:
6075 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006076 zero = builder.makeFloatConstant(0.0F);
6077 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06006078 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006079
John Kessenich140f3df2015-06-26 16:58:36 -06006080 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006081 case glslang::EOpConvBoolToInt64:
John Kessenichb9197c82019-08-11 07:41:45 -06006082#ifndef GLSLANG_WEB
6083 if (op == glslang::EOpConvBoolToInt64) {
Rex Xucabbb782017-03-24 13:41:14 +08006084 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006085 one = builder.makeInt64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006086 } else
6087#endif
6088 {
6089 zero = builder.makeIntConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006090 one = builder.makeIntConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006091 }
Rex Xucabbb782017-03-24 13:41:14 +08006092
John Kessenich140f3df2015-06-26 16:58:36 -06006093 convOp = spv::OpSelect;
6094 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006095
John Kessenich140f3df2015-06-26 16:58:36 -06006096 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006097 case glslang::EOpConvBoolToUint64:
John Kessenichb9197c82019-08-11 07:41:45 -06006098#ifndef GLSLANG_WEB
6099 if (op == glslang::EOpConvBoolToUint64) {
Rex Xucabbb782017-03-24 13:41:14 +08006100 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006101 one = builder.makeUint64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006102 } else
6103#endif
6104 {
6105 zero = builder.makeUintConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006106 one = builder.makeUintConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006107 }
Rex Xucabbb782017-03-24 13:41:14 +08006108
John Kessenich140f3df2015-06-26 16:58:36 -06006109 convOp = spv::OpSelect;
6110 break;
6111
John Kessenich66011cb2018-03-06 16:12:04 -07006112 case glslang::EOpConvInt8ToFloat16:
6113 case glslang::EOpConvInt8ToFloat:
6114 case glslang::EOpConvInt8ToDouble:
6115 case glslang::EOpConvInt16ToFloat16:
6116 case glslang::EOpConvInt16ToFloat:
6117 case glslang::EOpConvInt16ToDouble:
6118 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006119 case glslang::EOpConvIntToFloat:
6120 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006121 case glslang::EOpConvInt64ToFloat:
6122 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006123 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006124 convOp = spv::OpConvertSToF;
6125 break;
6126
John Kessenich66011cb2018-03-06 16:12:04 -07006127 case glslang::EOpConvUint8ToFloat16:
6128 case glslang::EOpConvUint8ToFloat:
6129 case glslang::EOpConvUint8ToDouble:
6130 case glslang::EOpConvUint16ToFloat16:
6131 case glslang::EOpConvUint16ToFloat:
6132 case glslang::EOpConvUint16ToDouble:
6133 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006134 case glslang::EOpConvUintToFloat:
6135 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006136 case glslang::EOpConvUint64ToFloat:
6137 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006138 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006139 convOp = spv::OpConvertUToF;
6140 break;
6141
John Kessenich66011cb2018-03-06 16:12:04 -07006142 case glslang::EOpConvFloat16ToInt8:
6143 case glslang::EOpConvFloatToInt8:
6144 case glslang::EOpConvDoubleToInt8:
6145 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006146 case glslang::EOpConvFloatToInt16:
6147 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006148 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006149 case glslang::EOpConvFloatToInt:
6150 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006151 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006152 case glslang::EOpConvFloatToInt64:
6153 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006154 convOp = spv::OpConvertFToS;
6155 break;
6156
John Kessenich66011cb2018-03-06 16:12:04 -07006157 case glslang::EOpConvUint8ToInt8:
6158 case glslang::EOpConvInt8ToUint8:
6159 case glslang::EOpConvUint16ToInt16:
6160 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006161 case glslang::EOpConvUintToInt:
6162 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006163 case glslang::EOpConvUint64ToInt64:
6164 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006165 if (builder.isInSpecConstCodeGenMode()) {
6166 // Build zero scalar or vector for OpIAdd.
John Kessenich39697cd2019-08-08 10:35:51 -06006167#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07006168 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6169 zero = builder.makeUint8Constant(0);
6170 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006171 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006172 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6173 zero = builder.makeUint64Constant(0);
John Kessenich39697cd2019-08-08 10:35:51 -06006174 } else
6175#endif
6176 {
Rex Xucabbb782017-03-24 13:41:14 +08006177 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006178 }
qining189b2032016-04-12 23:16:20 -04006179 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006180 // Use OpIAdd, instead of OpBitcast to do the conversion when
6181 // generating for OpSpecConstantOp instruction.
6182 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6183 }
6184 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006185 convOp = spv::OpBitcast;
6186 break;
6187
John Kessenich66011cb2018-03-06 16:12:04 -07006188 case glslang::EOpConvFloat16ToUint8:
6189 case glslang::EOpConvFloatToUint8:
6190 case glslang::EOpConvDoubleToUint8:
6191 case glslang::EOpConvFloat16ToUint16:
6192 case glslang::EOpConvFloatToUint16:
6193 case glslang::EOpConvDoubleToUint16:
6194 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006195 case glslang::EOpConvFloatToUint:
6196 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006197 case glslang::EOpConvFloatToUint64:
6198 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006199 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006200 convOp = spv::OpConvertFToU;
6201 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006202
John Kessenich39697cd2019-08-08 10:35:51 -06006203#ifndef GLSLANG_WEB
6204 case glslang::EOpConvInt8ToBool:
6205 case glslang::EOpConvUint8ToBool:
6206 zero = builder.makeUint8Constant(0);
6207 zero = makeSmearedConstant(zero, vectorSize);
6208 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6209 case glslang::EOpConvInt16ToBool:
6210 case glslang::EOpConvUint16ToBool:
6211 zero = builder.makeUint16Constant(0);
6212 zero = makeSmearedConstant(zero, vectorSize);
6213 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6214 case glslang::EOpConvInt64ToBool:
6215 case glslang::EOpConvUint64ToBool:
6216 zero = builder.makeUint64Constant(0);
6217 zero = makeSmearedConstant(zero, vectorSize);
6218 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6219 case glslang::EOpConvDoubleToBool:
6220 zero = builder.makeDoubleConstant(0.0);
6221 zero = makeSmearedConstant(zero, vectorSize);
6222 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6223 case glslang::EOpConvFloat16ToBool:
6224 zero = builder.makeFloat16Constant(0.0F);
6225 zero = makeSmearedConstant(zero, vectorSize);
6226 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6227 case glslang::EOpConvBoolToDouble:
6228 convOp = spv::OpSelect;
6229 zero = builder.makeDoubleConstant(0.0);
6230 one = builder.makeDoubleConstant(1.0);
6231 break;
6232 case glslang::EOpConvBoolToFloat16:
6233 convOp = spv::OpSelect;
6234 zero = builder.makeFloat16Constant(0.0F);
6235 one = builder.makeFloat16Constant(1.0F);
6236 break;
6237 case glslang::EOpConvBoolToInt8:
6238 zero = builder.makeInt8Constant(0);
6239 one = builder.makeInt8Constant(1);
6240 convOp = spv::OpSelect;
6241 break;
6242 case glslang::EOpConvBoolToUint8:
6243 zero = builder.makeUint8Constant(0);
6244 one = builder.makeUint8Constant(1);
6245 convOp = spv::OpSelect;
6246 break;
6247 case glslang::EOpConvBoolToInt16:
6248 zero = builder.makeInt16Constant(0);
6249 one = builder.makeInt16Constant(1);
6250 convOp = spv::OpSelect;
6251 break;
6252 case glslang::EOpConvBoolToUint16:
6253 zero = builder.makeUint16Constant(0);
6254 one = builder.makeUint16Constant(1);
6255 convOp = spv::OpSelect;
6256 break;
6257 case glslang::EOpConvDoubleToFloat:
6258 case glslang::EOpConvFloatToDouble:
6259 case glslang::EOpConvDoubleToFloat16:
6260 case glslang::EOpConvFloat16ToDouble:
6261 case glslang::EOpConvFloatToFloat16:
6262 case glslang::EOpConvFloat16ToFloat:
6263 convOp = spv::OpFConvert;
6264 if (builder.isMatrixType(destType))
6265 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
6266 break;
6267
John Kessenich66011cb2018-03-06 16:12:04 -07006268 case glslang::EOpConvInt8ToInt16:
6269 case glslang::EOpConvInt8ToInt:
6270 case glslang::EOpConvInt8ToInt64:
6271 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006272 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006273 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006274 case glslang::EOpConvIntToInt8:
6275 case glslang::EOpConvIntToInt16:
6276 case glslang::EOpConvIntToInt64:
6277 case glslang::EOpConvInt64ToInt8:
6278 case glslang::EOpConvInt64ToInt16:
6279 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006280 convOp = spv::OpSConvert;
6281 break;
6282
John Kessenich66011cb2018-03-06 16:12:04 -07006283 case glslang::EOpConvUint8ToUint16:
6284 case glslang::EOpConvUint8ToUint:
6285 case glslang::EOpConvUint8ToUint64:
6286 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006287 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006288 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006289 case glslang::EOpConvUintToUint8:
6290 case glslang::EOpConvUintToUint16:
6291 case glslang::EOpConvUintToUint64:
6292 case glslang::EOpConvUint64ToUint8:
6293 case glslang::EOpConvUint64ToUint16:
6294 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006295 convOp = spv::OpUConvert;
6296 break;
6297
John Kessenich66011cb2018-03-06 16:12:04 -07006298 case glslang::EOpConvInt8ToUint16:
6299 case glslang::EOpConvInt8ToUint:
6300 case glslang::EOpConvInt8ToUint64:
6301 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006302 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006303 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006304 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006305 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006306 case glslang::EOpConvIntToUint64:
6307 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006308 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006309 case glslang::EOpConvInt64ToUint:
6310 case glslang::EOpConvUint8ToInt16:
6311 case glslang::EOpConvUint8ToInt:
6312 case glslang::EOpConvUint8ToInt64:
6313 case glslang::EOpConvUint16ToInt8:
6314 case glslang::EOpConvUint16ToInt:
6315 case glslang::EOpConvUint16ToInt64:
6316 case glslang::EOpConvUintToInt8:
6317 case glslang::EOpConvUintToInt16:
6318 case glslang::EOpConvUintToInt64:
6319 case glslang::EOpConvUint64ToInt8:
6320 case glslang::EOpConvUint64ToInt16:
6321 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006322 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006323 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006324
6325 if (builder.isInSpecConstCodeGenMode()) {
6326 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006327 switch(op) {
6328 case glslang::EOpConvInt16ToUint8:
6329 case glslang::EOpConvIntToUint8:
6330 case glslang::EOpConvInt64ToUint8:
6331 case glslang::EOpConvUint16ToInt8:
6332 case glslang::EOpConvUintToInt8:
6333 case glslang::EOpConvUint64ToInt8:
6334 zero = builder.makeUint8Constant(0);
6335 break;
6336 case glslang::EOpConvInt8ToUint16:
6337 case glslang::EOpConvIntToUint16:
6338 case glslang::EOpConvInt64ToUint16:
6339 case glslang::EOpConvUint8ToInt16:
6340 case glslang::EOpConvUintToInt16:
6341 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006342 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006343 break;
6344 case glslang::EOpConvInt8ToUint:
6345 case glslang::EOpConvInt16ToUint:
6346 case glslang::EOpConvInt64ToUint:
6347 case glslang::EOpConvUint8ToInt:
6348 case glslang::EOpConvUint16ToInt:
6349 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006350 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006351 break;
6352 case glslang::EOpConvInt8ToUint64:
6353 case glslang::EOpConvInt16ToUint64:
6354 case glslang::EOpConvIntToUint64:
6355 case glslang::EOpConvUint8ToInt64:
6356 case glslang::EOpConvUint16ToInt64:
6357 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006358 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006359 break;
6360 default:
6361 assert(false && "Default missing");
6362 break;
6363 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006364 zero = makeSmearedConstant(zero, vectorSize);
6365 // Use OpIAdd, instead of OpBitcast to do the conversion when
6366 // generating for OpSpecConstantOp instruction.
6367 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6368 }
6369 // For normal run-time conversion instruction, use OpBitcast.
6370 convOp = spv::OpBitcast;
6371 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006372 case glslang::EOpConvUint64ToPtr:
6373 convOp = spv::OpConvertUToPtr;
6374 break;
6375 case glslang::EOpConvPtrToUint64:
6376 convOp = spv::OpConvertPtrToU;
6377 break;
John Kessenich90e402f2019-09-17 23:19:38 -06006378 case glslang::EOpConvPtrToUvec2:
6379 case glslang::EOpConvUvec2ToPtr:
John Kessenichee8e9c12019-10-10 20:54:21 -06006380 if (builder.isVector(operand))
6381 builder.promoteIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer,
6382 spv::E_SPV_KHR_physical_storage_buffer, spv::Spv_1_5);
John Kessenich90e402f2019-09-17 23:19:38 -06006383 convOp = spv::OpBitcast;
6384 break;
John Kessenich39697cd2019-08-08 10:35:51 -06006385#endif
6386
John Kessenich140f3df2015-06-26 16:58:36 -06006387 default:
6388 break;
6389 }
6390
6391 spv::Id result = 0;
6392 if (convOp == spv::OpNop)
6393 return result;
6394
6395 if (convOp == spv::OpSelect) {
6396 zero = makeSmearedConstant(zero, vectorSize);
6397 one = makeSmearedConstant(one, vectorSize);
6398 result = builder.createTriOp(convOp, destType, operand, one, zero);
6399 } else
6400 result = builder.createUnaryOp(convOp, destType, operand);
6401
John Kessenichead86222018-03-28 18:01:20 -06006402 result = builder.setPrecision(result, decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006403 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006404 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006405}
6406
6407spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6408{
6409 if (vectorSize == 0)
6410 return constant;
6411
6412 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6413 std::vector<spv::Id> components;
6414 for (int c = 0; c < vectorSize; ++c)
6415 components.push_back(constant);
6416 return builder.makeCompositeConstant(vectorTypeId, components);
6417}
6418
John Kessenich426394d2015-07-23 10:22:48 -06006419// For glslang ops that map to SPV atomic opCodes
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006420spv::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 -06006421{
6422 spv::Op opCode = spv::OpNop;
6423
6424 switch (op) {
6425 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006426 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006427 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006428 opCode = spv::OpAtomicIAdd;
6429 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006430 case glslang::EOpAtomicCounterSubtract:
6431 opCode = spv::OpAtomicISub;
6432 break;
John Kessenich426394d2015-07-23 10:22:48 -06006433 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006434 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006435 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08006436 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006437 break;
6438 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006439 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006440 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08006441 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006442 break;
6443 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006444 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006445 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006446 opCode = spv::OpAtomicAnd;
6447 break;
6448 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006449 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006450 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006451 opCode = spv::OpAtomicOr;
6452 break;
6453 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006454 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006455 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006456 opCode = spv::OpAtomicXor;
6457 break;
6458 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006459 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006460 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006461 opCode = spv::OpAtomicExchange;
6462 break;
6463 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006464 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006465 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006466 opCode = spv::OpAtomicCompareExchange;
6467 break;
6468 case glslang::EOpAtomicCounterIncrement:
6469 opCode = spv::OpAtomicIIncrement;
6470 break;
6471 case glslang::EOpAtomicCounterDecrement:
6472 opCode = spv::OpAtomicIDecrement;
6473 break;
6474 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006475 case glslang::EOpImageAtomicLoad:
6476 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006477 opCode = spv::OpAtomicLoad;
6478 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006479 case glslang::EOpAtomicStore:
6480 case glslang::EOpImageAtomicStore:
6481 opCode = spv::OpAtomicStore;
6482 break;
John Kessenich426394d2015-07-23 10:22:48 -06006483 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006484 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006485 break;
6486 }
6487
Rex Xue8fe8b02017-09-26 15:42:56 +08006488 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6489 builder.addCapability(spv::CapabilityInt64Atomics);
6490
John Kessenich426394d2015-07-23 10:22:48 -06006491 // Sort out the operands
6492 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006493 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006494 // - compare-exchange swaps the value and comparator
6495 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006496 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006497 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6498 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6499 spv::Id scopeId;
6500 if (glslangIntermediate->usingVulkanMemoryModel()) {
6501 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6502 } else {
6503 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6504 }
6505 // semantics default to relaxed
Jeff Bolz016ddee2019-10-17 11:22:57 -05006506 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.isVolatile() && glslangIntermediate->usingVulkanMemoryModel() ?
John Kessenichb9197c82019-08-11 07:41:45 -06006507 spv::MemorySemanticsVolatileMask :
6508 spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006509 spv::Id semanticsId2 = semanticsId;
6510
6511 pointerId = operands[0];
6512 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6513 // no additional operands
6514 } else if (opCode == spv::OpAtomicCompareExchange) {
6515 compareId = operands[1];
6516 valueId = operands[2];
6517 if (operands.size() > 3) {
6518 scopeId = operands[3];
6519 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6520 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
6521 }
6522 } else if (opCode == spv::OpAtomicLoad) {
6523 if (operands.size() > 1) {
6524 scopeId = operands[1];
6525 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
6526 }
6527 } else {
6528 // atomic store or RMW
6529 valueId = operands[1];
6530 if (operands.size() > 2) {
6531 scopeId = operands[2];
6532 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
6533 }
Rex Xu04db3f52015-09-16 11:44:02 +08006534 }
John Kessenich426394d2015-07-23 10:22:48 -06006535
Jeff Bolz36831c92018-09-05 10:11:41 -05006536 // Check for capabilities
6537 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006538 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6539 spv::MemorySemanticsMakeVisibleKHRMask |
6540 spv::MemorySemanticsOutputMemoryKHRMask |
6541 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006542 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6543 }
John Kessenich426394d2015-07-23 10:22:48 -06006544
Jeff Bolz36831c92018-09-05 10:11:41 -05006545 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6546 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6547 }
John Kessenich48d6e792017-10-06 21:21:48 -06006548
Jeff Bolz36831c92018-09-05 10:11:41 -05006549 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6550 spvAtomicOperands.push_back(pointerId);
6551 spvAtomicOperands.push_back(scopeId);
6552 spvAtomicOperands.push_back(semanticsId);
6553 if (opCode == spv::OpAtomicCompareExchange) {
6554 spvAtomicOperands.push_back(semanticsId2);
6555 spvAtomicOperands.push_back(valueId);
6556 spvAtomicOperands.push_back(compareId);
6557 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6558 spvAtomicOperands.push_back(valueId);
6559 }
John Kessenich48d6e792017-10-06 21:21:48 -06006560
Jeff Bolz36831c92018-09-05 10:11:41 -05006561 if (opCode == spv::OpAtomicStore) {
6562 builder.createNoResultOp(opCode, spvAtomicOperands);
6563 return 0;
6564 } else {
6565 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6566
6567 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6568 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6569 if (op == glslang::EOpAtomicCounterDecrement)
6570 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6571
6572 return resultId;
6573 }
John Kessenich426394d2015-07-23 10:22:48 -06006574}
6575
John Kessenich91cef522016-05-05 16:45:40 -06006576// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08006577spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006578{
John Kessenich66011cb2018-03-06 16:12:04 -07006579 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6580 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08006581
Rex Xu51596642016-09-21 18:56:12 +08006582 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006583 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006584 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6585
chaocf200da82016-12-20 12:44:35 -08006586 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6587 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006588 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6589 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006590 } else if (op == glslang::EOpAnyInvocation ||
6591 op == glslang::EOpAllInvocations ||
6592 op == glslang::EOpAllInvocationsEqual) {
6593 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6594 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006595 } else {
6596 builder.addCapability(spv::CapabilityGroups);
Rex Xu17ff3432016-10-14 17:41:45 +08006597 if (op == glslang::EOpMinInvocationsNonUniform ||
6598 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006599 op == glslang::EOpAddInvocationsNonUniform ||
6600 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6601 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6602 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6603 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6604 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6605 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006606 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +08006607
Rex Xu430ef402016-10-14 17:22:23 +08006608 switch (op) {
6609 case glslang::EOpMinInvocations:
6610 case glslang::EOpMaxInvocations:
6611 case glslang::EOpAddInvocations:
6612 case glslang::EOpMinInvocationsNonUniform:
6613 case glslang::EOpMaxInvocationsNonUniform:
6614 case glslang::EOpAddInvocationsNonUniform:
6615 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006616 break;
6617 case glslang::EOpMinInvocationsInclusiveScan:
6618 case glslang::EOpMaxInvocationsInclusiveScan:
6619 case glslang::EOpAddInvocationsInclusiveScan:
6620 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6621 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6622 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6623 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006624 break;
6625 case glslang::EOpMinInvocationsExclusiveScan:
6626 case glslang::EOpMaxInvocationsExclusiveScan:
6627 case glslang::EOpAddInvocationsExclusiveScan:
6628 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6629 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6630 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6631 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006632 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006633 default:
6634 break;
Rex Xu430ef402016-10-14 17:22:23 +08006635 }
John Kessenich149afc32018-08-14 13:31:43 -06006636 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6637 spvGroupOperands.push_back(scope);
6638 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006639 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006640 spvGroupOperands.push_back(groupOp);
6641 }
Rex Xu51596642016-09-21 18:56:12 +08006642 }
6643
John Kessenich149afc32018-08-14 13:31:43 -06006644 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6645 spv::IdImmediate op = { true, *opIt };
6646 spvGroupOperands.push_back(op);
6647 }
John Kessenich91cef522016-05-05 16:45:40 -06006648
6649 switch (op) {
6650 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006651 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006652 break;
John Kessenich91cef522016-05-05 16:45:40 -06006653 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006654 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006655 break;
John Kessenich91cef522016-05-05 16:45:40 -06006656 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006657 opCode = spv::OpSubgroupAllEqualKHR;
6658 break;
Rex Xu51596642016-09-21 18:56:12 +08006659 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006660 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006661 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006662 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006663 break;
6664 case glslang::EOpReadFirstInvocation:
6665 opCode = spv::OpSubgroupFirstInvocationKHR;
6666 break;
6667 case glslang::EOpBallot:
6668 {
6669 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6670 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6671 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6672 //
6673 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6674 //
6675 spv::Id uintType = builder.makeUintType(32);
6676 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6677 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6678
6679 std::vector<spv::Id> components;
6680 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6681 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6682
6683 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6684 return builder.createUnaryOp(spv::OpBitcast, typeId,
6685 builder.createCompositeConstruct(uvec2Type, components));
6686 }
6687
Rex Xu9d93a232016-05-05 12:30:44 +08006688 case glslang::EOpMinInvocations:
6689 case glslang::EOpMaxInvocations:
6690 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006691 case glslang::EOpMinInvocationsInclusiveScan:
6692 case glslang::EOpMaxInvocationsInclusiveScan:
6693 case glslang::EOpAddInvocationsInclusiveScan:
6694 case glslang::EOpMinInvocationsExclusiveScan:
6695 case glslang::EOpMaxInvocationsExclusiveScan:
6696 case glslang::EOpAddInvocationsExclusiveScan:
6697 if (op == glslang::EOpMinInvocations ||
6698 op == glslang::EOpMinInvocationsInclusiveScan ||
6699 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006700 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006701 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006702 else {
6703 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006704 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006705 else
Rex Xu51596642016-09-21 18:56:12 +08006706 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006707 }
Rex Xu430ef402016-10-14 17:22:23 +08006708 } else if (op == glslang::EOpMaxInvocations ||
6709 op == glslang::EOpMaxInvocationsInclusiveScan ||
6710 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006711 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006712 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006713 else {
6714 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006715 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006716 else
Rex Xu51596642016-09-21 18:56:12 +08006717 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006718 }
6719 } else {
6720 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006721 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006722 else
Rex Xu51596642016-09-21 18:56:12 +08006723 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006724 }
6725
Rex Xu2bbbe062016-08-23 15:41:05 +08006726 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006727 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006728
6729 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006730 case glslang::EOpMinInvocationsNonUniform:
6731 case glslang::EOpMaxInvocationsNonUniform:
6732 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006733 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6734 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6735 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6736 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6737 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6738 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6739 if (op == glslang::EOpMinInvocationsNonUniform ||
6740 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6741 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006742 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006743 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006744 else {
6745 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006746 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006747 else
Rex Xu51596642016-09-21 18:56:12 +08006748 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006749 }
6750 }
Rex Xu430ef402016-10-14 17:22:23 +08006751 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6752 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6753 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006754 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006755 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006756 else {
6757 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006758 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006759 else
Rex Xu51596642016-09-21 18:56:12 +08006760 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006761 }
6762 }
6763 else {
6764 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006765 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006766 else
Rex Xu51596642016-09-21 18:56:12 +08006767 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006768 }
6769
Rex Xu2bbbe062016-08-23 15:41:05 +08006770 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006771 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006772
6773 break;
John Kessenich91cef522016-05-05 16:45:40 -06006774 default:
6775 logger->missingFunctionality("invocation operation");
6776 return spv::NoResult;
6777 }
Rex Xu51596642016-09-21 18:56:12 +08006778
6779 assert(opCode != spv::OpNop);
6780 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006781}
6782
Rex Xu2bbbe062016-08-23 15:41:05 +08006783// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006784spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6785 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006786{
6787 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6788 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006789 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006790 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006791 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
6792 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
6793 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
6794
6795 // Handle group invocation operations scalar by scalar.
6796 // The result type is the same type as the original type.
6797 // The algorithm is to:
6798 // - break the vector into scalars
6799 // - apply the operation to each scalar
6800 // - make a vector out the scalar results
6801
6802 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006803 int numComponents = builder.getNumComponents(operands[0]);
6804 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006805 std::vector<spv::Id> results;
6806
6807 // do each scalar op
6808 for (int comp = 0; comp < numComponents; ++comp) {
6809 std::vector<unsigned int> indexes;
6810 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006811 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6812 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006813 if (op == spv::OpSubgroupReadInvocationKHR) {
6814 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006815 spv::IdImmediate operand = { true, operands[1] };
6816 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006817 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006818 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6819 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006820 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006821 spv::IdImmediate operand = { true, operands[1] };
6822 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006823 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006824 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6825 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006826 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006827 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006828 spvGroupOperands.push_back(scalar);
6829 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006830
Rex Xub7072052016-09-26 15:53:40 +08006831 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006832 }
6833
6834 // put the pieces together
6835 return builder.createCompositeConstruct(typeId, results);
6836}
Rex Xu2bbbe062016-08-23 15:41:05 +08006837
John Kessenich66011cb2018-03-06 16:12:04 -07006838// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006839spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6840 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006841{
6842 // Add the required capabilities.
6843 switch (op) {
6844 case glslang::EOpSubgroupElect:
6845 builder.addCapability(spv::CapabilityGroupNonUniform);
6846 break;
6847 case glslang::EOpSubgroupAll:
6848 case glslang::EOpSubgroupAny:
6849 case glslang::EOpSubgroupAllEqual:
6850 builder.addCapability(spv::CapabilityGroupNonUniform);
6851 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6852 break;
6853 case glslang::EOpSubgroupBroadcast:
6854 case glslang::EOpSubgroupBroadcastFirst:
6855 case glslang::EOpSubgroupBallot:
6856 case glslang::EOpSubgroupInverseBallot:
6857 case glslang::EOpSubgroupBallotBitExtract:
6858 case glslang::EOpSubgroupBallotBitCount:
6859 case glslang::EOpSubgroupBallotInclusiveBitCount:
6860 case glslang::EOpSubgroupBallotExclusiveBitCount:
6861 case glslang::EOpSubgroupBallotFindLSB:
6862 case glslang::EOpSubgroupBallotFindMSB:
6863 builder.addCapability(spv::CapabilityGroupNonUniform);
6864 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6865 break;
6866 case glslang::EOpSubgroupShuffle:
6867 case glslang::EOpSubgroupShuffleXor:
6868 builder.addCapability(spv::CapabilityGroupNonUniform);
6869 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6870 break;
6871 case glslang::EOpSubgroupShuffleUp:
6872 case glslang::EOpSubgroupShuffleDown:
6873 builder.addCapability(spv::CapabilityGroupNonUniform);
6874 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6875 break;
6876 case glslang::EOpSubgroupAdd:
6877 case glslang::EOpSubgroupMul:
6878 case glslang::EOpSubgroupMin:
6879 case glslang::EOpSubgroupMax:
6880 case glslang::EOpSubgroupAnd:
6881 case glslang::EOpSubgroupOr:
6882 case glslang::EOpSubgroupXor:
6883 case glslang::EOpSubgroupInclusiveAdd:
6884 case glslang::EOpSubgroupInclusiveMul:
6885 case glslang::EOpSubgroupInclusiveMin:
6886 case glslang::EOpSubgroupInclusiveMax:
6887 case glslang::EOpSubgroupInclusiveAnd:
6888 case glslang::EOpSubgroupInclusiveOr:
6889 case glslang::EOpSubgroupInclusiveXor:
6890 case glslang::EOpSubgroupExclusiveAdd:
6891 case glslang::EOpSubgroupExclusiveMul:
6892 case glslang::EOpSubgroupExclusiveMin:
6893 case glslang::EOpSubgroupExclusiveMax:
6894 case glslang::EOpSubgroupExclusiveAnd:
6895 case glslang::EOpSubgroupExclusiveOr:
6896 case glslang::EOpSubgroupExclusiveXor:
6897 builder.addCapability(spv::CapabilityGroupNonUniform);
6898 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6899 break;
6900 case glslang::EOpSubgroupClusteredAdd:
6901 case glslang::EOpSubgroupClusteredMul:
6902 case glslang::EOpSubgroupClusteredMin:
6903 case glslang::EOpSubgroupClusteredMax:
6904 case glslang::EOpSubgroupClusteredAnd:
6905 case glslang::EOpSubgroupClusteredOr:
6906 case glslang::EOpSubgroupClusteredXor:
6907 builder.addCapability(spv::CapabilityGroupNonUniform);
6908 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6909 break;
6910 case glslang::EOpSubgroupQuadBroadcast:
6911 case glslang::EOpSubgroupQuadSwapHorizontal:
6912 case glslang::EOpSubgroupQuadSwapVertical:
6913 case glslang::EOpSubgroupQuadSwapDiagonal:
6914 builder.addCapability(spv::CapabilityGroupNonUniform);
6915 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6916 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006917 case glslang::EOpSubgroupPartitionedAdd:
6918 case glslang::EOpSubgroupPartitionedMul:
6919 case glslang::EOpSubgroupPartitionedMin:
6920 case glslang::EOpSubgroupPartitionedMax:
6921 case glslang::EOpSubgroupPartitionedAnd:
6922 case glslang::EOpSubgroupPartitionedOr:
6923 case glslang::EOpSubgroupPartitionedXor:
6924 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6925 case glslang::EOpSubgroupPartitionedInclusiveMul:
6926 case glslang::EOpSubgroupPartitionedInclusiveMin:
6927 case glslang::EOpSubgroupPartitionedInclusiveMax:
6928 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6929 case glslang::EOpSubgroupPartitionedInclusiveOr:
6930 case glslang::EOpSubgroupPartitionedInclusiveXor:
6931 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6932 case glslang::EOpSubgroupPartitionedExclusiveMul:
6933 case glslang::EOpSubgroupPartitionedExclusiveMin:
6934 case glslang::EOpSubgroupPartitionedExclusiveMax:
6935 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6936 case glslang::EOpSubgroupPartitionedExclusiveOr:
6937 case glslang::EOpSubgroupPartitionedExclusiveXor:
6938 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6939 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6940 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006941 default: assert(0 && "Unhandled subgroup operation!");
6942 }
6943
Jeff Bolzc5b669e2019-09-08 08:49:18 -05006944
6945 const bool isUnsigned = isTypeUnsignedInt(typeProxy);
6946 const bool isFloat = isTypeFloat(typeProxy);
John Kessenich66011cb2018-03-06 16:12:04 -07006947 const bool isBool = typeProxy == glslang::EbtBool;
6948
6949 spv::Op opCode = spv::OpNop;
6950
6951 // Figure out which opcode to use.
6952 switch (op) {
6953 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6954 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6955 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6956 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6957 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6958 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6959 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6960 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6961 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6962 case glslang::EOpSubgroupBallotBitCount:
6963 case glslang::EOpSubgroupBallotInclusiveBitCount:
6964 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6965 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6966 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6967 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6968 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6969 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6970 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6971 case glslang::EOpSubgroupAdd:
6972 case glslang::EOpSubgroupInclusiveAdd:
6973 case glslang::EOpSubgroupExclusiveAdd:
6974 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006975 case glslang::EOpSubgroupPartitionedAdd:
6976 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6977 case glslang::EOpSubgroupPartitionedExclusiveAdd:
John Kessenich66011cb2018-03-06 16:12:04 -07006978 if (isFloat) {
6979 opCode = spv::OpGroupNonUniformFAdd;
6980 } else {
6981 opCode = spv::OpGroupNonUniformIAdd;
6982 }
6983 break;
6984 case glslang::EOpSubgroupMul:
6985 case glslang::EOpSubgroupInclusiveMul:
6986 case glslang::EOpSubgroupExclusiveMul:
6987 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006988 case glslang::EOpSubgroupPartitionedMul:
6989 case glslang::EOpSubgroupPartitionedInclusiveMul:
6990 case glslang::EOpSubgroupPartitionedExclusiveMul:
John Kessenich66011cb2018-03-06 16:12:04 -07006991 if (isFloat) {
6992 opCode = spv::OpGroupNonUniformFMul;
6993 } else {
6994 opCode = spv::OpGroupNonUniformIMul;
6995 }
6996 break;
6997 case glslang::EOpSubgroupMin:
6998 case glslang::EOpSubgroupInclusiveMin:
6999 case glslang::EOpSubgroupExclusiveMin:
7000 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007001 case glslang::EOpSubgroupPartitionedMin:
7002 case glslang::EOpSubgroupPartitionedInclusiveMin:
7003 case glslang::EOpSubgroupPartitionedExclusiveMin:
John Kessenich66011cb2018-03-06 16:12:04 -07007004 if (isFloat) {
7005 opCode = spv::OpGroupNonUniformFMin;
7006 } else if (isUnsigned) {
7007 opCode = spv::OpGroupNonUniformUMin;
7008 } else {
7009 opCode = spv::OpGroupNonUniformSMin;
7010 }
7011 break;
7012 case glslang::EOpSubgroupMax:
7013 case glslang::EOpSubgroupInclusiveMax:
7014 case glslang::EOpSubgroupExclusiveMax:
7015 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007016 case glslang::EOpSubgroupPartitionedMax:
7017 case glslang::EOpSubgroupPartitionedInclusiveMax:
7018 case glslang::EOpSubgroupPartitionedExclusiveMax:
John Kessenich66011cb2018-03-06 16:12:04 -07007019 if (isFloat) {
7020 opCode = spv::OpGroupNonUniformFMax;
7021 } else if (isUnsigned) {
7022 opCode = spv::OpGroupNonUniformUMax;
7023 } else {
7024 opCode = spv::OpGroupNonUniformSMax;
7025 }
7026 break;
7027 case glslang::EOpSubgroupAnd:
7028 case glslang::EOpSubgroupInclusiveAnd:
7029 case glslang::EOpSubgroupExclusiveAnd:
7030 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007031 case glslang::EOpSubgroupPartitionedAnd:
7032 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7033 case glslang::EOpSubgroupPartitionedExclusiveAnd:
John Kessenich66011cb2018-03-06 16:12:04 -07007034 if (isBool) {
7035 opCode = spv::OpGroupNonUniformLogicalAnd;
7036 } else {
7037 opCode = spv::OpGroupNonUniformBitwiseAnd;
7038 }
7039 break;
7040 case glslang::EOpSubgroupOr:
7041 case glslang::EOpSubgroupInclusiveOr:
7042 case glslang::EOpSubgroupExclusiveOr:
7043 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007044 case glslang::EOpSubgroupPartitionedOr:
7045 case glslang::EOpSubgroupPartitionedInclusiveOr:
7046 case glslang::EOpSubgroupPartitionedExclusiveOr:
John Kessenich66011cb2018-03-06 16:12:04 -07007047 if (isBool) {
7048 opCode = spv::OpGroupNonUniformLogicalOr;
7049 } else {
7050 opCode = spv::OpGroupNonUniformBitwiseOr;
7051 }
7052 break;
7053 case glslang::EOpSubgroupXor:
7054 case glslang::EOpSubgroupInclusiveXor:
7055 case glslang::EOpSubgroupExclusiveXor:
7056 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007057 case glslang::EOpSubgroupPartitionedXor:
7058 case glslang::EOpSubgroupPartitionedInclusiveXor:
7059 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007060 if (isBool) {
7061 opCode = spv::OpGroupNonUniformLogicalXor;
7062 } else {
7063 opCode = spv::OpGroupNonUniformBitwiseXor;
7064 }
7065 break;
7066 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
7067 case glslang::EOpSubgroupQuadSwapHorizontal:
7068 case glslang::EOpSubgroupQuadSwapVertical:
7069 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
7070 default: assert(0 && "Unhandled subgroup operation!");
7071 }
7072
John Kessenich149afc32018-08-14 13:31:43 -06007073 // get the right Group Operation
7074 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07007075 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06007076 default:
7077 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007078 case glslang::EOpSubgroupBallotBitCount:
7079 case glslang::EOpSubgroupAdd:
7080 case glslang::EOpSubgroupMul:
7081 case glslang::EOpSubgroupMin:
7082 case glslang::EOpSubgroupMax:
7083 case glslang::EOpSubgroupAnd:
7084 case glslang::EOpSubgroupOr:
7085 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06007086 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007087 break;
7088 case glslang::EOpSubgroupBallotInclusiveBitCount:
7089 case glslang::EOpSubgroupInclusiveAdd:
7090 case glslang::EOpSubgroupInclusiveMul:
7091 case glslang::EOpSubgroupInclusiveMin:
7092 case glslang::EOpSubgroupInclusiveMax:
7093 case glslang::EOpSubgroupInclusiveAnd:
7094 case glslang::EOpSubgroupInclusiveOr:
7095 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007096 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007097 break;
7098 case glslang::EOpSubgroupBallotExclusiveBitCount:
7099 case glslang::EOpSubgroupExclusiveAdd:
7100 case glslang::EOpSubgroupExclusiveMul:
7101 case glslang::EOpSubgroupExclusiveMin:
7102 case glslang::EOpSubgroupExclusiveMax:
7103 case glslang::EOpSubgroupExclusiveAnd:
7104 case glslang::EOpSubgroupExclusiveOr:
7105 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007106 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007107 break;
7108 case glslang::EOpSubgroupClusteredAdd:
7109 case glslang::EOpSubgroupClusteredMul:
7110 case glslang::EOpSubgroupClusteredMin:
7111 case glslang::EOpSubgroupClusteredMax:
7112 case glslang::EOpSubgroupClusteredAnd:
7113 case glslang::EOpSubgroupClusteredOr:
7114 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06007115 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007116 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007117 case glslang::EOpSubgroupPartitionedAdd:
7118 case glslang::EOpSubgroupPartitionedMul:
7119 case glslang::EOpSubgroupPartitionedMin:
7120 case glslang::EOpSubgroupPartitionedMax:
7121 case glslang::EOpSubgroupPartitionedAnd:
7122 case glslang::EOpSubgroupPartitionedOr:
7123 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06007124 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007125 break;
7126 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7127 case glslang::EOpSubgroupPartitionedInclusiveMul:
7128 case glslang::EOpSubgroupPartitionedInclusiveMin:
7129 case glslang::EOpSubgroupPartitionedInclusiveMax:
7130 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7131 case glslang::EOpSubgroupPartitionedInclusiveOr:
7132 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007133 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007134 break;
7135 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7136 case glslang::EOpSubgroupPartitionedExclusiveMul:
7137 case glslang::EOpSubgroupPartitionedExclusiveMin:
7138 case glslang::EOpSubgroupPartitionedExclusiveMax:
7139 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7140 case glslang::EOpSubgroupPartitionedExclusiveOr:
7141 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007142 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007143 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007144 }
7145
John Kessenich149afc32018-08-14 13:31:43 -06007146 // build the instruction
7147 std::vector<spv::IdImmediate> spvGroupOperands;
7148
7149 // Every operation begins with the Execution Scope operand.
7150 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7151 spvGroupOperands.push_back(executionScope);
7152
7153 // Next, for all operations that use a Group Operation, push that as an operand.
7154 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007155 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007156 spvGroupOperands.push_back(groupOperand);
7157 }
7158
John Kessenich66011cb2018-03-06 16:12:04 -07007159 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06007160 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
7161 spv::IdImmediate operand = { true, *opIt };
7162 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07007163 }
7164
7165 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06007166 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07007167 switch (op) {
7168 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06007169 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
7170 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
7171 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
7172 }
7173 if (directionId != spv::NoResult) {
7174 spv::IdImmediate direction = { true, directionId };
7175 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007176 }
7177
7178 return builder.createOp(opCode, typeId, spvGroupOperands);
7179}
7180
John Kessenich5e4b1242015-08-06 22:53:06 -06007181spv::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 -06007182{
John Kessenich66011cb2018-03-06 16:12:04 -07007183 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7184 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007185
John Kessenich140f3df2015-06-26 16:58:36 -06007186 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007187 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007188 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007189 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007190 spv::Id typeId0 = 0;
7191 if (consumedOperands > 0)
7192 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007193 spv::Id typeId1 = 0;
7194 if (consumedOperands > 1)
7195 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007196 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007197
7198 switch (op) {
7199 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007200 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007201 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007202 else if (isUnsigned)
7203 libCall = spv::GLSLstd450UMin;
7204 else
7205 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007206 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007207 break;
7208 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007209 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007210 break;
7211 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007212 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007213 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007214 else if (isUnsigned)
7215 libCall = spv::GLSLstd450UMax;
7216 else
7217 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007218 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007219 break;
7220 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007221 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007222 break;
7223 case glslang::EOpDot:
7224 opCode = spv::OpDot;
7225 break;
7226 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007227 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007228 break;
7229
7230 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007231 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007232 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007233 else if (isUnsigned)
7234 libCall = spv::GLSLstd450UClamp;
7235 else
7236 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007237 builder.promoteScalar(precision, operands.front(), operands[1]);
7238 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007239 break;
7240 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007241 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7242 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007243 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007244 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007245 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007246 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007247 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007248 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007249 break;
7250 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007251 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007252 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007253 break;
7254 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007255 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007256 builder.promoteScalar(precision, operands[0], operands[2]);
7257 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007258 break;
7259
7260 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007261 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007262 break;
7263 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007264 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007265 break;
7266 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007267 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007268 break;
7269 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007270 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007271 break;
7272 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007273 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007274 break;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007275 case glslang::EOpBarrier:
7276 {
7277 // This is for the extended controlBarrier function, with four operands.
7278 // The unextended barrier() goes through createNoArgOperation.
7279 assert(operands.size() == 4);
7280 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7281 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7282 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
7283 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7284 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7285 spv::MemorySemanticsMakeVisibleKHRMask |
7286 spv::MemorySemanticsOutputMemoryKHRMask |
7287 spv::MemorySemanticsVolatileMask)) {
7288 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7289 }
7290 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
7291 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7292 }
7293 return 0;
7294 }
7295 break;
7296 case glslang::EOpMemoryBarrier:
7297 {
7298 // This is for the extended memoryBarrier function, with three operands.
7299 // The unextended memoryBarrier() goes through createNoArgOperation.
7300 assert(operands.size() == 3);
7301 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7302 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7303 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7304 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7305 spv::MemorySemanticsMakeVisibleKHRMask |
7306 spv::MemorySemanticsOutputMemoryKHRMask |
7307 spv::MemorySemanticsVolatileMask)) {
7308 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7309 }
7310 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7311 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7312 }
7313 return 0;
7314 }
7315 break;
7316
John Kessenicha28f7a72019-08-06 07:00:58 -06007317#ifndef GLSLANG_WEB
Rex Xu7a26c172015-12-08 17:12:09 +08007318 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007319 if (typeProxy == glslang::EbtFloat16)
7320 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007321 libCall = spv::GLSLstd450InterpolateAtSample;
7322 break;
7323 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007324 if (typeProxy == glslang::EbtFloat16)
7325 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007326 libCall = spv::GLSLstd450InterpolateAtOffset;
7327 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007328 case glslang::EOpAddCarry:
7329 opCode = spv::OpIAddCarry;
7330 typeId = builder.makeStructResultType(typeId0, typeId0);
7331 consumedOperands = 2;
7332 break;
7333 case glslang::EOpSubBorrow:
7334 opCode = spv::OpISubBorrow;
7335 typeId = builder.makeStructResultType(typeId0, typeId0);
7336 consumedOperands = 2;
7337 break;
7338 case glslang::EOpUMulExtended:
7339 opCode = spv::OpUMulExtended;
7340 typeId = builder.makeStructResultType(typeId0, typeId0);
7341 consumedOperands = 2;
7342 break;
7343 case glslang::EOpIMulExtended:
7344 opCode = spv::OpSMulExtended;
7345 typeId = builder.makeStructResultType(typeId0, typeId0);
7346 consumedOperands = 2;
7347 break;
7348 case glslang::EOpBitfieldExtract:
7349 if (isUnsigned)
7350 opCode = spv::OpBitFieldUExtract;
7351 else
7352 opCode = spv::OpBitFieldSExtract;
7353 break;
7354 case glslang::EOpBitfieldInsert:
7355 opCode = spv::OpBitFieldInsert;
7356 break;
7357
7358 case glslang::EOpFma:
7359 libCall = spv::GLSLstd450Fma;
7360 break;
7361 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007362 {
7363 libCall = spv::GLSLstd450FrexpStruct;
7364 assert(builder.isPointerType(typeId1));
7365 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007366 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007367 if (width == 16)
7368 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7369 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
Rex Xu470026f2017-03-29 17:12:40 +08007370 if (builder.getNumComponents(operands[0]) == 1)
7371 frexpIntType = builder.makeIntegerType(width, true);
7372 else
7373 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
7374 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7375 consumedOperands = 1;
7376 }
John Kessenich55e7d112015-11-15 21:33:39 -07007377 break;
7378 case glslang::EOpLdexp:
7379 libCall = spv::GLSLstd450Ldexp;
7380 break;
7381
Rex Xu574ab042016-04-14 16:53:07 +08007382 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007383 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007384
John Kessenich66011cb2018-03-06 16:12:04 -07007385 case glslang::EOpSubgroupBroadcast:
7386 case glslang::EOpSubgroupBallotBitExtract:
7387 case glslang::EOpSubgroupShuffle:
7388 case glslang::EOpSubgroupShuffleXor:
7389 case glslang::EOpSubgroupShuffleUp:
7390 case glslang::EOpSubgroupShuffleDown:
7391 case glslang::EOpSubgroupClusteredAdd:
7392 case glslang::EOpSubgroupClusteredMul:
7393 case glslang::EOpSubgroupClusteredMin:
7394 case glslang::EOpSubgroupClusteredMax:
7395 case glslang::EOpSubgroupClusteredAnd:
7396 case glslang::EOpSubgroupClusteredOr:
7397 case glslang::EOpSubgroupClusteredXor:
7398 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007399 case glslang::EOpSubgroupPartitionedAdd:
7400 case glslang::EOpSubgroupPartitionedMul:
7401 case glslang::EOpSubgroupPartitionedMin:
7402 case glslang::EOpSubgroupPartitionedMax:
7403 case glslang::EOpSubgroupPartitionedAnd:
7404 case glslang::EOpSubgroupPartitionedOr:
7405 case glslang::EOpSubgroupPartitionedXor:
7406 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7407 case glslang::EOpSubgroupPartitionedInclusiveMul:
7408 case glslang::EOpSubgroupPartitionedInclusiveMin:
7409 case glslang::EOpSubgroupPartitionedInclusiveMax:
7410 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7411 case glslang::EOpSubgroupPartitionedInclusiveOr:
7412 case glslang::EOpSubgroupPartitionedInclusiveXor:
7413 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7414 case glslang::EOpSubgroupPartitionedExclusiveMul:
7415 case glslang::EOpSubgroupPartitionedExclusiveMin:
7416 case glslang::EOpSubgroupPartitionedExclusiveMax:
7417 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7418 case glslang::EOpSubgroupPartitionedExclusiveOr:
7419 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007420 return createSubgroupOperation(op, typeId, operands, typeProxy);
7421
Rex Xu9d93a232016-05-05 12:30:44 +08007422 case glslang::EOpSwizzleInvocations:
7423 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7424 libCall = spv::SwizzleInvocationsAMD;
7425 break;
7426 case glslang::EOpSwizzleInvocationsMasked:
7427 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7428 libCall = spv::SwizzleInvocationsMaskedAMD;
7429 break;
7430 case glslang::EOpWriteInvocation:
7431 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7432 libCall = spv::WriteInvocationAMD;
7433 break;
7434
7435 case glslang::EOpMin3:
7436 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7437 if (isFloat)
7438 libCall = spv::FMin3AMD;
7439 else {
7440 if (isUnsigned)
7441 libCall = spv::UMin3AMD;
7442 else
7443 libCall = spv::SMin3AMD;
7444 }
7445 break;
7446 case glslang::EOpMax3:
7447 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7448 if (isFloat)
7449 libCall = spv::FMax3AMD;
7450 else {
7451 if (isUnsigned)
7452 libCall = spv::UMax3AMD;
7453 else
7454 libCall = spv::SMax3AMD;
7455 }
7456 break;
7457 case glslang::EOpMid3:
7458 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7459 if (isFloat)
7460 libCall = spv::FMid3AMD;
7461 else {
7462 if (isUnsigned)
7463 libCall = spv::UMid3AMD;
7464 else
7465 libCall = spv::SMid3AMD;
7466 }
7467 break;
7468
7469 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007470 if (typeProxy == glslang::EbtFloat16)
7471 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007472 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7473 libCall = spv::InterpolateAtVertexAMD;
7474 break;
Chao Chen3c366992018-09-19 11:41:59 -07007475
Chao Chenb50c02e2018-09-19 11:42:24 -07007476 case glslang::EOpReportIntersectionNV:
7477 {
7478 typeId = builder.makeBoolType();
Ashwin Leleff1783d2018-10-22 16:41:44 -07007479 opCode = spv::OpReportIntersectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07007480 }
7481 break;
7482 case glslang::EOpTraceNV:
7483 {
Ashwin Leleff1783d2018-10-22 16:41:44 -07007484 builder.createNoResultOp(spv::OpTraceNV, operands);
7485 return 0;
7486 }
7487 break;
7488 case glslang::EOpExecuteCallableNV:
7489 {
7490 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007491 return 0;
7492 }
7493 break;
Chao Chen3c366992018-09-19 11:41:59 -07007494 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7495 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7496 return 0;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007497 case glslang::EOpCooperativeMatrixMulAdd:
7498 opCode = spv::OpCooperativeMatrixMulAddNV;
7499 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007500#endif // GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007501 default:
7502 return 0;
7503 }
7504
7505 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007506 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007507 // Use an extended instruction from the standard library.
7508 // Construct the call arguments, without modifying the original operands vector.
7509 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7510 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007511 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007512 } else if (opCode == spv::OpDot && !isFloat) {
7513 // int dot(int, int)
7514 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7515 const int componentCount = builder.getNumComponents(operands[0]);
7516 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7517 builder.setPrecision(mulOp, precision);
7518 id = builder.createCompositeExtract(mulOp, typeId, 0);
7519 for (int i = 1; i < componentCount; ++i) {
7520 builder.setPrecision(id, precision);
John Kessenich5de15a22019-12-26 10:56:54 -07007521 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(mulOp, typeId, i));
t.jungb16bea82018-11-15 10:21:36 +01007522 }
John Kessenich2359bd02015-12-06 19:29:11 -07007523 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007524 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007525 case 0:
7526 // should all be handled by visitAggregate and createNoArgOperation
7527 assert(0);
7528 return 0;
7529 case 1:
7530 // should all be handled by createUnaryOperation
7531 assert(0);
7532 return 0;
7533 case 2:
7534 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7535 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007536 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007537 // anything 3 or over doesn't have l-value operands, so all should be consumed
7538 assert(consumedOperands == operands.size());
7539 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007540 break;
7541 }
7542 }
7543
John Kessenichb9197c82019-08-11 07:41:45 -06007544#ifndef GLSLANG_WEB
John Kessenich55e7d112015-11-15 21:33:39 -07007545 // Decode the return types that were structures
7546 switch (op) {
7547 case glslang::EOpAddCarry:
7548 case glslang::EOpSubBorrow:
7549 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7550 id = builder.createCompositeExtract(id, typeId0, 0);
7551 break;
7552 case glslang::EOpUMulExtended:
7553 case glslang::EOpIMulExtended:
7554 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7555 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7556 break;
7557 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007558 {
7559 assert(operands.size() == 2);
7560 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7561 // "exp" is floating-point type (from HLSL intrinsic)
7562 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7563 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7564 builder.createStore(member1, operands[1]);
7565 } else
7566 // "exp" is integer type (from GLSL built-in function)
7567 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7568 id = builder.createCompositeExtract(id, typeId0, 0);
7569 }
John Kessenich55e7d112015-11-15 21:33:39 -07007570 break;
7571 default:
7572 break;
7573 }
John Kessenichb9197c82019-08-11 07:41:45 -06007574#endif
John Kessenich55e7d112015-11-15 21:33:39 -07007575
John Kessenich32cfd492016-02-02 12:37:46 -07007576 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007577}
7578
Rex Xu9d93a232016-05-05 12:30:44 +08007579// Intrinsics with no arguments (or no return value, and no precision).
7580spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007581{
Jeff Bolz36831c92018-09-05 10:11:41 -05007582 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
7583 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007584
7585 switch (op) {
John Kessenich140f3df2015-06-26 16:58:36 -06007586 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007587 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007588 if (glslangIntermediate->usingVulkanMemoryModel()) {
7589 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7590 spv::MemorySemanticsOutputMemoryKHRMask |
7591 spv::MemorySemanticsAcquireReleaseMask);
7592 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7593 } else {
7594 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7595 }
John Kessenich82979362017-12-11 04:02:24 -07007596 } else {
7597 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7598 spv::MemorySemanticsWorkgroupMemoryMask |
7599 spv::MemorySemanticsAcquireReleaseMask);
7600 }
John Kessenich140f3df2015-06-26 16:58:36 -06007601 return 0;
7602 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007603 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7604 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007605 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007606 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007607 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7608 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007609 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007610 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007611 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7612 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007613 return 0;
7614 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007615 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7616 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007617 return 0;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007618#ifndef GLSLANG_WEB
7619 case glslang::EOpMemoryBarrierAtomicCounter:
7620 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7621 spv::MemorySemanticsAcquireReleaseMask);
7622 return 0;
7623 case glslang::EOpMemoryBarrierImage:
7624 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7625 spv::MemorySemanticsAcquireReleaseMask);
7626 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007627 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007628 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007629 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007630 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007631 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007632 case glslang::EOpDeviceMemoryBarrier:
7633 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7634 spv::MemorySemanticsImageMemoryMask |
7635 spv::MemorySemanticsAcquireReleaseMask);
7636 return 0;
7637 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7638 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7639 spv::MemorySemanticsImageMemoryMask |
7640 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007641 return 0;
7642 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007643 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7644 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007645 return 0;
7646 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007647 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7648 spv::MemorySemanticsWorkgroupMemoryMask |
7649 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007650 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007651 case glslang::EOpSubgroupBarrier:
7652 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7653 spv::MemorySemanticsAcquireReleaseMask);
7654 return spv::NoResult;
7655 case glslang::EOpSubgroupMemoryBarrier:
7656 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7657 spv::MemorySemanticsAcquireReleaseMask);
7658 return spv::NoResult;
7659 case glslang::EOpSubgroupMemoryBarrierBuffer:
7660 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7661 spv::MemorySemanticsAcquireReleaseMask);
7662 return spv::NoResult;
7663 case glslang::EOpSubgroupMemoryBarrierImage:
7664 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7665 spv::MemorySemanticsAcquireReleaseMask);
7666 return spv::NoResult;
7667 case glslang::EOpSubgroupMemoryBarrierShared:
7668 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7669 spv::MemorySemanticsAcquireReleaseMask);
7670 return spv::NoResult;
John Kessenichf8d1d742019-10-21 06:55:11 -06007671
7672 case glslang::EOpEmitVertex:
7673 builder.createNoResultOp(spv::OpEmitVertex);
7674 return 0;
7675 case glslang::EOpEndPrimitive:
7676 builder.createNoResultOp(spv::OpEndPrimitive);
7677 return 0;
7678
John Kessenich66011cb2018-03-06 16:12:04 -07007679 case glslang::EOpSubgroupElect: {
7680 std::vector<spv::Id> operands;
7681 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7682 }
Rex Xu9d93a232016-05-05 12:30:44 +08007683 case glslang::EOpTime:
7684 {
7685 std::vector<spv::Id> args; // Dummy arguments
7686 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7687 return builder.setPrecision(id, precision);
7688 }
Chao Chenb50c02e2018-09-19 11:42:24 -07007689 case glslang::EOpIgnoreIntersectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007690 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007691 return 0;
7692 case glslang::EOpTerminateRayNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007693 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007694 return 0;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05007695
7696 case glslang::EOpBeginInvocationInterlock:
7697 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
7698 return 0;
7699 case glslang::EOpEndInvocationInterlock:
7700 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
7701 return 0;
7702
Jeff Bolzba6170b2019-07-01 09:23:23 -05007703 case glslang::EOpIsHelperInvocation:
7704 {
7705 std::vector<spv::Id> args; // Dummy arguments
Rex Xubb7307b2019-07-15 14:57:20 +08007706 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
7707 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
7708 return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
Jeff Bolzba6170b2019-07-01 09:23:23 -05007709 }
7710
amhagan91fb0092019-07-10 21:14:38 -04007711 case glslang::EOpReadClockSubgroupKHR: {
7712 std::vector<spv::Id> args;
7713 args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
7714 builder.addExtension(spv::E_SPV_KHR_shader_clock);
7715 builder.addCapability(spv::CapabilityShaderClockKHR);
7716 return builder.createOp(spv::OpReadClockKHR, typeId, args);
7717 }
7718
7719 case glslang::EOpReadClockDeviceKHR: {
7720 std::vector<spv::Id> args;
7721 args.push_back(builder.makeUintConstant(spv::ScopeDevice));
7722 builder.addExtension(spv::E_SPV_KHR_shader_clock);
7723 builder.addCapability(spv::CapabilityShaderClockKHR);
7724 return builder.createOp(spv::OpReadClockKHR, typeId, args);
7725 }
John Kessenich3dd1ce52019-10-17 07:08:40 -06007726#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007727 default:
John Kessenich155d3512019-08-08 23:29:20 -06007728 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007729 }
John Kessenich155d3512019-08-08 23:29:20 -06007730
7731 logger->missingFunctionality("unknown operation with no arguments");
7732
7733 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007734}
7735
7736spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7737{
John Kessenich2f273362015-07-18 22:34:27 -06007738 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007739 spv::Id id;
7740 if (symbolValues.end() != iter) {
7741 id = iter->second;
7742 return id;
7743 }
7744
7745 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06007746 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
7747 auto forcedType = getForcedType(builtIn, symbol->getType());
7748 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06007749 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06007750 if (forcedType.second != spv::NoType)
7751 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06007752
Rex Xuc884b4a2016-06-29 15:03:44 +08007753 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007754 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7755 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7756 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenicha28f7a72019-08-06 07:00:58 -06007757#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07007758 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
John Kessenichb9197c82019-08-11 07:41:45 -06007759 if (symbol->getQualifier().hasComponent())
7760 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
7761 if (symbol->getQualifier().hasIndex())
7762 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
Chao Chen3c366992018-09-19 11:41:59 -07007763#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007764 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007765 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich91e4aa52016-07-07 17:46:42 -06007766 // atomic counters use this:
7767 if (symbol->getQualifier().hasOffset())
7768 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007769 }
7770
scygan2c864272016-05-18 18:09:17 +02007771 if (symbol->getQualifier().hasLocation())
7772 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007773 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007774 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007775 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007776 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007777 }
John Kessenich140f3df2015-06-26 16:58:36 -06007778 if (symbol->getQualifier().hasSet())
7779 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007780 else if (IsDescriptorResource(symbol->getType())) {
7781 // default to 0
7782 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7783 }
John Kessenich140f3df2015-06-26 16:58:36 -06007784 if (symbol->getQualifier().hasBinding())
7785 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06007786 else if (IsDescriptorResource(symbol->getType())) {
7787 // default to 0
7788 builder.addDecoration(id, spv::DecorationBinding, 0);
7789 }
John Kessenich6c292d32016-02-15 20:58:50 -07007790 if (symbol->getQualifier().hasAttachment())
7791 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06007792 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007793 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07007794 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007795 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007796 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7797 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7798 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7799 }
7800 if (symbol->getQualifier().hasXfbOffset())
7801 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007802 }
7803
John Kessenichb9197c82019-08-11 07:41:45 -06007804 // add built-in variable decoration
7805 if (builtIn != spv::BuiltInMax) {
7806 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
7807 }
7808
7809#ifndef GLSLANG_WEB
Rex Xu1da878f2016-02-21 20:59:01 +08007810 if (symbol->getType().isImage()) {
7811 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05007812 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007813 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007814 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007815 }
7816
John Kessenich5611c6d2018-04-05 11:25:02 -06007817 // nonuniform
7818 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7819
chaoc0ad6a4e2016-12-19 16:29:34 -08007820 if (builtIn == spv::BuiltInSampleMask) {
7821 spv::Decoration decoration;
7822 // GL_NV_sample_mask_override_coverage extension
7823 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007824 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007825 else
7826 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007827 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007828 if (decoration != spv::DecorationMax) {
Jason Macnakdbd4c3c2019-07-12 14:33:02 -07007829 builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
chaoc0ad6a4e2016-12-19 16:29:34 -08007830 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7831 }
7832 }
chaoc771d89f2017-01-13 01:10:53 -08007833 else if (builtIn == spv::BuiltInLayer) {
7834 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007835 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007836 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007837 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7838 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7839 }
John Kessenichb41bff62017-08-11 13:07:17 -06007840 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007841 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7842 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007843 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7844 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7845 }
7846 }
7847
chaoc6e5acae2016-12-20 13:28:52 -08007848 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007849 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007850 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007851 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7852 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007853 if (symbol->getQualifier().pervertexNV) {
7854 builder.addDecoration(id, spv::DecorationPerVertexNV);
7855 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7856 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7857 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007858
John Kessenich5d610ee2018-03-07 18:05:55 -07007859 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7860 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7861 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7862 symbol->getType().getQualifier().semanticName);
7863 }
7864
John Kessenich7015bd62019-08-01 03:28:08 -06007865 if (symbol->isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007866 builder.addDecoration(id, symbol->getType().getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
7867 }
John Kessenichb9197c82019-08-11 07:41:45 -06007868#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007869
John Kessenich140f3df2015-06-26 16:58:36 -06007870 return id;
7871}
7872
John Kessenicha28f7a72019-08-06 07:00:58 -06007873#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07007874// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7875void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7876{
7877 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07007878 if (qualifier.perPrimitiveNV) {
7879 // Need to add capability/extension for fragment shader.
7880 // Mesh shader already adds this by default.
7881 if (glslangIntermediate->getStage() == EShLangFragment) {
7882 builder.addCapability(spv::CapabilityMeshShadingNV);
7883 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7884 }
Chao Chen3c366992018-09-19 11:41:59 -07007885 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007886 }
Chao Chen3c366992018-09-19 11:41:59 -07007887 if (qualifier.perViewNV)
7888 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7889 if (qualifier.perTaskNV)
7890 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7891 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07007892 if (qualifier.perPrimitiveNV) {
7893 // Need to add capability/extension for fragment shader.
7894 // Mesh shader already adds this by default.
7895 if (glslangIntermediate->getStage() == EShLangFragment) {
7896 builder.addCapability(spv::CapabilityMeshShadingNV);
7897 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7898 }
Chao Chen3c366992018-09-19 11:41:59 -07007899 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007900 }
Chao Chen3c366992018-09-19 11:41:59 -07007901 if (qualifier.perViewNV)
7902 builder.addDecoration(id, spv::DecorationPerViewNV);
7903 if (qualifier.perTaskNV)
7904 builder.addDecoration(id, spv::DecorationPerTaskNV);
7905 }
7906}
7907#endif
7908
John Kessenich55e7d112015-11-15 21:33:39 -07007909// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07007910// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07007911//
7912// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7913//
7914// Recursively walk the nodes. The nodes form a tree whose leaves are
7915// regular constants, which themselves are trees that createSpvConstant()
7916// recursively walks. So, this function walks the "top" of the tree:
7917// - emit specialization constant-building instructions for specConstant
7918// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04007919spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07007920{
John Kessenich7cc0e282016-03-20 00:46:02 -06007921 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07007922
qining4f4bb812016-04-03 23:55:17 -04007923 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07007924 if (! node.getQualifier().specConstant) {
7925 // hand off to the non-spec-constant path
7926 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
7927 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04007928 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07007929 nextConst, false);
7930 }
7931
7932 // We now know we have a specialization constant to build
7933
John Kessenichd94c0032016-05-30 19:29:40 -06007934 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04007935 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
7936 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
7937 std::vector<spv::Id> dimConstId;
7938 for (int dim = 0; dim < 3; ++dim) {
7939 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
7940 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07007941 if (specConst) {
7942 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
7943 glslangIntermediate->getLocalSizeSpecId(dim));
7944 }
qining4f4bb812016-04-03 23:55:17 -04007945 }
7946 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
7947 }
7948
7949 // An AST node labelled as specialization constant should be a symbol node.
7950 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
7951 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007952 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04007953 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04007954 // Traverse the constant constructor sub tree like generating normal run-time instructions.
7955 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
7956 // will set the builder into spec constant op instruction generating mode.
7957 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007958 result = accessChainLoad(sub_tree->getType());
7959 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04007960 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007961 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05007962 } else {
7963 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05007964 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07007965 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007966 builder.addName(result, sn->getName().c_str());
7967 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07007968 }
qining4f4bb812016-04-03 23:55:17 -04007969
7970 // Neither a front-end constant node, nor a specialization constant node with constant union array or
7971 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04007972 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04007973 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07007974}
7975
John Kessenich140f3df2015-06-26 16:58:36 -06007976// Use 'consts' as the flattened glslang source of scalar constants to recursively
7977// build the aggregate SPIR-V constant.
7978//
7979// If there are not enough elements present in 'consts', 0 will be substituted;
7980// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
7981//
qining08408382016-03-21 09:51:37 -04007982spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06007983{
7984 // vector of constants for SPIR-V
7985 std::vector<spv::Id> spvConsts;
7986
7987 // Type is used for struct and array constants
7988 spv::Id typeId = convertGlslangToSpvType(glslangType);
7989
7990 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007991 glslang::TType elementType(glslangType, 0);
7992 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04007993 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007994 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007995 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06007996 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04007997 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007998 } else if (glslangType.isCoopMat()) {
7999 glslang::TType componentType(glslangType.getBasicType());
8000 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008001 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008002 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
8003 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04008004 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06008005 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06008006 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
8007 bool zero = nextConst >= consts.size();
8008 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008009 case glslang::EbtInt:
8010 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
8011 break;
8012 case glslang::EbtUint:
8013 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
8014 break;
8015 case glslang::EbtFloat:
8016 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8017 break;
8018 case glslang::EbtBool:
8019 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
8020 break;
8021#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008022 case glslang::EbtInt8:
8023 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
8024 break;
8025 case glslang::EbtUint8:
8026 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
8027 break;
8028 case glslang::EbtInt16:
8029 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
8030 break;
8031 case glslang::EbtUint16:
8032 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
8033 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008034 case glslang::EbtInt64:
8035 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
8036 break;
8037 case glslang::EbtUint64:
8038 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
8039 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008040 case glslang::EbtDouble:
8041 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
8042 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008043 case glslang::EbtFloat16:
8044 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8045 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008046#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008047 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008048 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008049 break;
8050 }
8051 ++nextConst;
8052 }
8053 } else {
8054 // we have a non-aggregate (scalar) constant
8055 bool zero = nextConst >= consts.size();
8056 spv::Id scalar = 0;
8057 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008058 case glslang::EbtInt:
8059 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
8060 break;
8061 case glslang::EbtUint:
8062 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
8063 break;
8064 case glslang::EbtFloat:
8065 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8066 break;
8067 case glslang::EbtBool:
8068 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
8069 break;
8070#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008071 case glslang::EbtInt8:
8072 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
8073 break;
8074 case glslang::EbtUint8:
8075 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
8076 break;
8077 case glslang::EbtInt16:
8078 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
8079 break;
8080 case glslang::EbtUint16:
8081 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
8082 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008083 case glslang::EbtInt64:
8084 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
8085 break;
8086 case glslang::EbtUint64:
8087 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8088 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008089 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07008090 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06008091 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008092 case glslang::EbtFloat16:
8093 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8094 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06008095 case glslang::EbtReference:
8096 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8097 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
8098 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008099#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008100 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008101 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008102 break;
8103 }
8104 ++nextConst;
8105 return scalar;
8106 }
8107
8108 return builder.makeCompositeConstant(typeId, spvConsts);
8109}
8110
John Kessenich7c1aa102015-10-15 13:29:11 -06008111// Return true if the node is a constant or symbol whose reading has no
8112// non-trivial observable cost or effect.
8113bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
8114{
8115 // don't know what this is
8116 if (node == nullptr)
8117 return false;
8118
8119 // a constant is safe
8120 if (node->getAsConstantUnion() != nullptr)
8121 return true;
8122
8123 // not a symbol means non-trivial
8124 if (node->getAsSymbolNode() == nullptr)
8125 return false;
8126
8127 // a symbol, depends on what's being read
8128 switch (node->getType().getQualifier().storage) {
8129 case glslang::EvqTemporary:
8130 case glslang::EvqGlobal:
8131 case glslang::EvqIn:
8132 case glslang::EvqInOut:
8133 case glslang::EvqConst:
8134 case glslang::EvqConstReadOnly:
8135 case glslang::EvqUniform:
8136 return true;
8137 default:
8138 return false;
8139 }
qining25262b32016-05-06 17:25:16 -04008140}
John Kessenich7c1aa102015-10-15 13:29:11 -06008141
8142// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06008143// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06008144// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06008145// Return true if trivial.
8146bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
8147{
8148 if (node == nullptr)
8149 return false;
8150
John Kessenich84cc15f2017-05-24 16:44:47 -06008151 // count non scalars as trivial, as well as anything coming from HLSL
8152 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06008153 return true;
8154
John Kessenich7c1aa102015-10-15 13:29:11 -06008155 // symbols and constants are trivial
8156 if (isTrivialLeaf(node))
8157 return true;
8158
8159 // otherwise, it needs to be a simple operation or one or two leaf nodes
8160
8161 // not a simple operation
8162 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
8163 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
8164 if (binaryNode == nullptr && unaryNode == nullptr)
8165 return false;
8166
8167 // not on leaf nodes
8168 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
8169 return false;
8170
8171 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
8172 return false;
8173 }
8174
8175 switch (node->getAsOperator()->getOp()) {
8176 case glslang::EOpLogicalNot:
8177 case glslang::EOpConvIntToBool:
8178 case glslang::EOpConvUintToBool:
8179 case glslang::EOpConvFloatToBool:
8180 case glslang::EOpConvDoubleToBool:
8181 case glslang::EOpEqual:
8182 case glslang::EOpNotEqual:
8183 case glslang::EOpLessThan:
8184 case glslang::EOpGreaterThan:
8185 case glslang::EOpLessThanEqual:
8186 case glslang::EOpGreaterThanEqual:
8187 case glslang::EOpIndexDirect:
8188 case glslang::EOpIndexDirectStruct:
8189 case glslang::EOpLogicalXor:
8190 case glslang::EOpAny:
8191 case glslang::EOpAll:
8192 return true;
8193 default:
8194 return false;
8195 }
8196}
8197
8198// Emit short-circuiting code, where 'right' is never evaluated unless
8199// the left side is true (for &&) or false (for ||).
8200spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
8201{
8202 spv::Id boolTypeId = builder.makeBoolType();
8203
8204 // emit left operand
8205 builder.clearAccessChain();
8206 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008207 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008208
8209 // Operands to accumulate OpPhi operands
8210 std::vector<spv::Id> phiOperands;
8211 // accumulate left operand's phi information
8212 phiOperands.push_back(leftId);
8213 phiOperands.push_back(builder.getBuildPoint()->getId());
8214
8215 // Make the two kinds of operation symmetric with a "!"
8216 // || => emit "if (! left) result = right"
8217 // && => emit "if ( left) result = right"
8218 //
8219 // TODO: this runtime "not" for || could be avoided by adding functionality
8220 // to 'builder' to have an "else" without an "then"
8221 if (op == glslang::EOpLogicalOr)
8222 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8223
8224 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008225 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008226
8227 // emit right operand as the "then" part of the "if"
8228 builder.clearAccessChain();
8229 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008230 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008231
8232 // accumulate left operand's phi information
8233 phiOperands.push_back(rightId);
8234 phiOperands.push_back(builder.getBuildPoint()->getId());
8235
8236 // finish the "if"
8237 ifBuilder.makeEndIf();
8238
8239 // phi together the two results
8240 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8241}
8242
John Kessenicha28f7a72019-08-06 07:00:58 -06008243#ifndef GLSLANG_WEB
Rex Xu9d93a232016-05-05 12:30:44 +08008244// Return type Id of the imported set of extended instructions corresponds to the name.
8245// Import this set if it has not been imported yet.
8246spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8247{
8248 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8249 return extBuiltinMap[name];
8250 else {
Rex Xu51596642016-09-21 18:56:12 +08008251 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008252 spv::Id extBuiltins = builder.import(name);
8253 extBuiltinMap[name] = extBuiltins;
8254 return extBuiltins;
8255 }
8256}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008257#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008258
John Kessenich140f3df2015-06-26 16:58:36 -06008259}; // end anonymous namespace
8260
8261namespace glslang {
8262
John Kessenich68d78fd2015-07-12 19:28:10 -06008263void GetSpirvVersion(std::string& version)
8264{
John Kessenich9e55f632015-07-15 10:03:39 -06008265 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008266 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008267 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008268 version = buf;
8269}
8270
John Kessenicha372a3e2017-11-02 22:32:14 -06008271// For low-order part of the generator's magic number. Bump up
8272// when there is a change in the style (e.g., if SSA form changes,
8273// or a different instruction sequence to do something gets used).
8274int GetSpirvGeneratorVersion()
8275{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008276 // return 1; // start
8277 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008278 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008279 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008280 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008281 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8282 // versions 4 and 6 each generate OpArrayLength as it has long been done
John Kessenich31c33702019-11-02 21:26:40 -06008283 // return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
8284 return 8; // switch to new dead block eliminator; use OpUnreachable
John Kessenicha372a3e2017-11-02 22:32:14 -06008285}
8286
John Kessenich140f3df2015-06-26 16:58:36 -06008287// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008288void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008289{
8290 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008291 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008292 if (out.fail())
8293 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008294 for (int i = 0; i < (int)spirv.size(); ++i) {
8295 unsigned int word = spirv[i];
8296 out.write((const char*)&word, 4);
8297 }
8298 out.close();
8299}
8300
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008301// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008302void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008303{
John Kessenich155d3512019-08-08 23:29:20 -06008304#ifndef GLSLANG_WEB
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008305 std::ofstream out;
8306 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008307 if (out.fail())
8308 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07008309 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06008310 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07008311 std::endl;
Flavio15017db2017-02-15 14:29:33 -08008312 if (varName != nullptr) {
8313 out << "\t #pragma once" << std::endl;
8314 out << "const uint32_t " << varName << "[] = {" << std::endl;
8315 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008316 const int WORDS_PER_LINE = 8;
8317 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8318 out << "\t";
8319 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8320 const unsigned int word = spirv[i + j];
8321 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8322 if (i + j + 1 < (int)spirv.size()) {
8323 out << ",";
8324 }
8325 }
8326 out << std::endl;
8327 }
Flavio15017db2017-02-15 14:29:33 -08008328 if (varName != nullptr) {
8329 out << "};";
8330 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008331 out.close();
John Kessenich155d3512019-08-08 23:29:20 -06008332#endif
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008333}
8334
John Kessenich140f3df2015-06-26 16:58:36 -06008335//
8336// Set up the glslang traversal
8337//
John Kessenich4e11b612018-08-30 16:56:59 -06008338void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008339{
Lei Zhang17535f72016-05-04 15:55:59 -04008340 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008341 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008342}
8343
John Kessenich4e11b612018-08-30 16:56:59 -06008344void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008345 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008346{
John Kessenich140f3df2015-06-26 16:58:36 -06008347 TIntermNode* root = intermediate.getTreeRoot();
8348
8349 if (root == 0)
8350 return;
8351
John Kessenich4e11b612018-08-30 16:56:59 -06008352 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008353 if (options == nullptr)
8354 options = &defaultOptions;
8355
John Kessenich4e11b612018-08-30 16:56:59 -06008356 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008357
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008358 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008359 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008360 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008361 it.dumpSpv(spirv);
8362
GregFfb03a552018-03-29 11:49:14 -06008363#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008364 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8365 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008366 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
8367 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer) {
John Kesseniche7df8e02018-08-22 17:12:46 -06008368 SpirvToolsLegalize(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008369 prelegalization = false;
8370 }
John Kessenich717c80a2018-08-23 15:17:10 -06008371
John Kessenich4e11b612018-08-30 16:56:59 -06008372 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008373 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008374
John Kessenich717c80a2018-08-23 15:17:10 -06008375 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008376 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008377
GregFcd1f1692017-09-21 18:40:22 -06008378#endif
8379
John Kessenich4e11b612018-08-30 16:56:59 -06008380 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008381}
8382
8383}; // end namespace glslang