blob: 64bce356feb16712644e44dacf4834bc9f16d263 [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.
3// Copyright (C) 2015-2016 Google, Inc.
John Kessenich140f3df2015-06-26 16:58:36 -06004//
John Kessenich927608b2017-01-06 12:34:14 -07005// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06006//
John Kessenich927608b2017-01-06 12:34:14 -07007// Redistribution and use in source and binary forms, with or without
8// modification, are permitted provided that the following conditions
9// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060010//
11// Redistributions of source code must retain the above copyright
12// notice, this list of conditions and the following disclaimer.
13//
14// Redistributions in binary form must reproduce the above
15// copyright notice, this list of conditions and the following
16// disclaimer in the documentation and/or other materials provided
17// with the distribution.
18//
19// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
20// contributors may be used to endorse or promote products derived
21// from this software without specific prior written permission.
22//
John Kessenich927608b2017-01-06 12:34:14 -070023// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34// POSSIBILITY OF SUCH DAMAGE.
John Kessenich140f3df2015-06-26 16:58:36 -060035
36//
John Kessenich140f3df2015-06-26 16:58:36 -060037// Visit the nodes in the glslang intermediate tree representation to
38// translate them to SPIR-V.
39//
40
John Kessenich5e4b1242015-08-06 22:53:06 -060041#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060042#include "GlslangToSpv.h"
43#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060044namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080045 #include "GLSL.std.450.h"
46 #include "GLSL.ext.KHR.h"
Piers Daniell1c5443c2017-12-13 13:07:22 -070047 #include "GLSL.ext.EXT.h"
Rex Xu9d93a232016-05-05 12:30:44 +080048#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080049 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080050#endif
chaoc0ad6a4e2016-12-19 16:29:34 -080051#ifdef NV_EXTENSIONS
52 #include "GLSL.ext.NV.h"
53#endif
John Kessenich5e4b1242015-08-06 22:53:06 -060054}
John Kessenich140f3df2015-06-26 16:58:36 -060055
GregFcd1f1692017-09-21 18:40:22 -060056#ifdef ENABLE_OPT
57 #include "spirv-tools/optimizer.hpp"
58 #include "message.h"
59 #include "SPVRemapper.h"
60#endif
61
62#ifdef ENABLE_OPT
63using namespace spvtools;
64#endif
65
John Kessenich140f3df2015-06-26 16:58:36 -060066// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020067#include "../glslang/MachineIndependent/localintermediate.h"
68#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060069#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050070#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060071
John Kessenich140f3df2015-06-26 16:58:36 -060072#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050073#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040074#include <list>
75#include <map>
76#include <stack>
77#include <string>
78#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060079
80namespace {
81
qining4c912612016-04-01 10:35:16 -040082namespace {
83class SpecConstantOpModeGuard {
84public:
85 SpecConstantOpModeGuard(spv::Builder* builder)
86 : builder_(builder) {
87 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040088 }
89 ~SpecConstantOpModeGuard() {
90 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
91 : builder_->setToNormalCodeGenMode();
92 }
qining40887662016-04-03 22:20:42 -040093 void turnOnSpecConstantOpMode() {
94 builder_->setToSpecConstCodeGenMode();
95 }
qining4c912612016-04-01 10:35:16 -040096
97private:
98 spv::Builder* builder_;
99 bool previous_flag_;
100};
101}
102
John Kessenich140f3df2015-06-26 16:58:36 -0600103//
104// The main holder of information for translating glslang to SPIR-V.
105//
106// Derives from the AST walking base class.
107//
108class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
109public:
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700110 TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger,
111 glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700112 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600113
114 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
115 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
116 void visitConstantUnion(glslang::TIntermConstantUnion*);
117 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
118 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
119 void visitSymbol(glslang::TIntermSymbol* symbol);
120 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
121 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
122 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
123
John Kessenichfca82622016-11-26 13:23:20 -0700124 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700125 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600126
127protected:
Rex Xu17ff3432016-10-14 17:41:45 +0800128 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800129 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100130 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700131 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
Rex Xu57e65922017-07-04 23:23:40 +0800132 spv::SelectionControlMask TranslateSelectionControl(glslang::TSelectionControl) const;
steve-lunargf1709e72017-05-02 20:14:50 -0600133 spv::LoopControlMask TranslateLoopControl(glslang::TLoopControl) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600134 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich140f3df2015-06-26 16:58:36 -0600135 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
136 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600137 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
138 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
139 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600140 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700141 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich0e737842017-03-24 18:38:16 -0600142 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600143 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
144 glslang::TLayoutPacking, const glslang::TQualifier&);
145 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
146 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700147 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700148 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800149 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600150 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700151 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700152 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
153 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
154 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100155 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600156
John Kessenich6fccb3c2016-09-19 16:01:41 -0600157 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd41993d2017-09-10 15:21:05 -0600158 bool writableParam(glslang::TStorageQualifier);
159 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600160 void makeFunctions(const glslang::TIntermSequence&);
161 void makeGlobalInitializers(const glslang::TIntermSequence&);
162 void visitFunctions(const glslang::TIntermSequence&);
163 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800164 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600165 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
166 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600167 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
168
qining25262b32016-05-06 17:25:16 -0400169 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
170 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
171 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu2bbbe062016-08-23 15:41:05 +0800172 spv::Id createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu73e3ce72016-04-27 18:48:17 +0800173 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id destTypeId, spv::Id operand, glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600174 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800175 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu51596642016-09-21 18:56:12 +0800176 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800177 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich5e4b1242015-08-06 22:53:06 -0600178 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 +0800179 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600180 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
181 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700182 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600183 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700184 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400185 spv::Id createSpvConstant(const glslang::TIntermTyped&);
186 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600187 bool isTrivialLeaf(const glslang::TIntermTyped* node);
188 bool isTrivial(const glslang::TIntermTyped* node);
189 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500190#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +0800191 spv::Id getExtBuiltins(const char* name);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500192#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600193
John Kessenich121853f2017-05-31 17:11:16 -0600194 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600195 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600196 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700197 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600198 int sequenceDepth;
199
Lei Zhang17535f72016-05-04 15:55:59 -0400200 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400201
John Kessenich140f3df2015-06-26 16:58:36 -0600202 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
203 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700204 bool inEntryPoint;
205 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700206 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 -0700207 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600208 const glslang::TIntermediate* glslangIntermediate;
209 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800210 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600211
John Kessenich2f273362015-07-18 22:34:27 -0600212 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600213 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600214 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700215 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600216 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper; // for mapping glslang block indices to spv indices (e.g., due to hidden members)
John Kessenich140f3df2015-06-26 16:58:36 -0600217 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600218};
219
220//
221// Helper functions for translating glslang representations to SPIR-V enumerants.
222//
223
224// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700225spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600226{
John Kessenich66e2faf2016-03-12 18:34:36 -0700227 switch (source) {
228 case glslang::EShSourceGlsl:
229 switch (profile) {
230 case ENoProfile:
231 case ECoreProfile:
232 case ECompatibilityProfile:
233 return spv::SourceLanguageGLSL;
234 case EEsProfile:
235 return spv::SourceLanguageESSL;
236 default:
237 return spv::SourceLanguageUnknown;
238 }
239 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600240 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600241 default:
242 return spv::SourceLanguageUnknown;
243 }
244}
245
246// Translate glslang language (stage) to SPIR-V execution model.
247spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
248{
249 switch (stage) {
250 case EShLangVertex: return spv::ExecutionModelVertex;
251 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
252 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
253 case EShLangGeometry: return spv::ExecutionModelGeometry;
254 case EShLangFragment: return spv::ExecutionModelFragment;
255 case EShLangCompute: return spv::ExecutionModelGLCompute;
256 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700257 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600258 return spv::ExecutionModelFragment;
259 }
260}
261
John Kessenich140f3df2015-06-26 16:58:36 -0600262// Translate glslang sampler type to SPIR-V dimensionality.
263spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
264{
265 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700266 case glslang::Esd1D: return spv::Dim1D;
267 case glslang::Esd2D: return spv::Dim2D;
268 case glslang::Esd3D: return spv::Dim3D;
269 case glslang::EsdCube: return spv::DimCube;
270 case glslang::EsdRect: return spv::DimRect;
271 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700272 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600273 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700274 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600275 return spv::Dim2D;
276 }
277}
278
John Kessenichf6640762016-08-01 19:44:00 -0600279// Translate glslang precision to SPIR-V precision decorations.
280spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600281{
John Kessenichf6640762016-08-01 19:44:00 -0600282 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700283 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600284 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600285 default:
286 return spv::NoPrecision;
287 }
288}
289
John Kessenichf6640762016-08-01 19:44:00 -0600290// Translate glslang type to SPIR-V precision decorations.
291spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
292{
293 return TranslatePrecisionDecoration(type.getQualifier().precision);
294}
295
John Kessenich140f3df2015-06-26 16:58:36 -0600296// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600297spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600298{
299 if (type.getBasicType() == glslang::EbtBlock) {
300 switch (type.getQualifier().storage) {
301 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600302 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600303 case glslang::EvqVaryingIn: return spv::DecorationBlock;
304 case glslang::EvqVaryingOut: return spv::DecorationBlock;
305 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700306 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600307 break;
308 }
309 }
310
John Kessenich4016e382016-07-15 11:53:56 -0600311 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600312}
313
Rex Xu1da878f2016-02-21 20:59:01 +0800314// Translate glslang type to SPIR-V memory decorations.
315void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
316{
317 if (qualifier.coherent)
318 memory.push_back(spv::DecorationCoherent);
319 if (qualifier.volatil)
320 memory.push_back(spv::DecorationVolatile);
321 if (qualifier.restrict)
322 memory.push_back(spv::DecorationRestrict);
323 if (qualifier.readonly)
324 memory.push_back(spv::DecorationNonWritable);
325 if (qualifier.writeonly)
326 memory.push_back(spv::DecorationNonReadable);
327}
328
John Kessenich140f3df2015-06-26 16:58:36 -0600329// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700330spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600331{
332 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700333 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600334 case glslang::ElmRowMajor:
335 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700336 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600337 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700338 default:
339 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600340 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600341 }
342 } else {
343 switch (type.getBasicType()) {
344 default:
John Kessenich4016e382016-07-15 11:53:56 -0600345 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600346 break;
347 case glslang::EbtBlock:
348 switch (type.getQualifier().storage) {
349 case glslang::EvqUniform:
350 case glslang::EvqBuffer:
351 switch (type.getQualifier().layoutPacking) {
352 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600353 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
354 default:
John Kessenich4016e382016-07-15 11:53:56 -0600355 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600356 }
357 case glslang::EvqVaryingIn:
358 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700359 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600360 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600361 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700362 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600363 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600364 }
365 }
366 }
367}
368
369// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600370// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700371// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800372spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600373{
Rex Xubbceed72016-05-21 09:40:44 +0800374 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700375 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600376 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800377 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700378 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700379 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600380 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800381#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800382 else if (qualifier.explicitInterp) {
383 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800384 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800385 }
Rex Xu9d93a232016-05-05 12:30:44 +0800386#endif
Rex Xubbceed72016-05-21 09:40:44 +0800387 else
John Kessenich4016e382016-07-15 11:53:56 -0600388 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800389}
390
391// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600392// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800393// should be applied.
394spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
395{
396 if (qualifier.patch)
397 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700398 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600399 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700400 else if (qualifier.sample) {
401 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600402 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700403 } else
John Kessenich4016e382016-07-15 11:53:56 -0600404 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600405}
406
John Kessenich92187592016-02-01 13:45:25 -0700407// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700408spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600409{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700410 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600411 return spv::DecorationInvariant;
412 else
John Kessenich4016e382016-07-15 11:53:56 -0600413 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600414}
415
qining9220dbb2016-05-04 17:34:38 -0400416// If glslang type is noContraction, return SPIR-V NoContraction decoration.
417spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
418{
419 if (qualifier.noContraction)
420 return spv::DecorationNoContraction;
421 else
John Kessenich4016e382016-07-15 11:53:56 -0600422 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400423}
424
David Netoa901ffe2016-06-08 14:11:40 +0100425// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
426// associated capabilities when required. For some built-in variables, a capability
427// is generated only when using the variable in an executable instruction, but not when
428// just declaring a struct member variable with it. This is true for PointSize,
429// ClipDistance, and CullDistance.
430spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600431{
432 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700433 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600434 // Defer adding the capability until the built-in is actually used.
435 if (! memberDeclaration) {
436 switch (glslangIntermediate->getStage()) {
437 case EShLangGeometry:
438 builder.addCapability(spv::CapabilityGeometryPointSize);
439 break;
440 case EShLangTessControl:
441 case EShLangTessEvaluation:
442 builder.addCapability(spv::CapabilityTessellationPointSize);
443 break;
444 default:
445 break;
446 }
John Kessenich92187592016-02-01 13:45:25 -0700447 }
448 return spv::BuiltInPointSize;
449
John Kessenichebb50532016-05-16 19:22:05 -0600450 // These *Distance capabilities logically belong here, but if the member is declared and
451 // then never used, consumers of SPIR-V prefer the capability not be declared.
452 // They are now generated when used, rather than here when declared.
453 // Potentially, the specification should be more clear what the minimum
454 // use needed is to trigger the capability.
455 //
John Kessenich92187592016-02-01 13:45:25 -0700456 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100457 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800458 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700459 return spv::BuiltInClipDistance;
460
461 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100462 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800463 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700464 return spv::BuiltInCullDistance;
465
466 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600467 builder.addCapability(spv::CapabilityMultiViewport);
468 if (glslangIntermediate->getStage() == EShLangVertex ||
469 glslangIntermediate->getStage() == EShLangTessControl ||
470 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800471
John Kessenichba6a3c22017-09-13 13:22:50 -0600472 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
473 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800474 }
John Kessenich92187592016-02-01 13:45:25 -0700475 return spv::BuiltInViewportIndex;
476
John Kessenich5e801132016-02-15 11:09:46 -0700477 case glslang::EbvSampleId:
478 builder.addCapability(spv::CapabilitySampleRateShading);
479 return spv::BuiltInSampleId;
480
481 case glslang::EbvSamplePosition:
482 builder.addCapability(spv::CapabilitySampleRateShading);
483 return spv::BuiltInSamplePosition;
484
485 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700486 return spv::BuiltInSampleMask;
487
John Kessenich78a45572016-07-08 14:05:15 -0600488 case glslang::EbvLayer:
John Kessenichba6a3c22017-09-13 13:22:50 -0600489 builder.addCapability(spv::CapabilityGeometry);
490 if (glslangIntermediate->getStage() == EShLangVertex ||
491 glslangIntermediate->getStage() == EShLangTessControl ||
492 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800493
John Kessenichba6a3c22017-09-13 13:22:50 -0600494 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
495 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800496 }
John Kessenich78a45572016-07-08 14:05:15 -0600497 return spv::BuiltInLayer;
498
John Kessenich140f3df2015-06-26 16:58:36 -0600499 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600500 case glslang::EbvVertexId: return spv::BuiltInVertexId;
501 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700502 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
503 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800504
John Kessenichda581a22015-10-14 14:10:30 -0600505 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800506 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
507 builder.addCapability(spv::CapabilityDrawParameters);
508 return spv::BuiltInBaseVertex;
509
John Kessenichda581a22015-10-14 14:10:30 -0600510 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800511 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
512 builder.addCapability(spv::CapabilityDrawParameters);
513 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200514
John Kessenichda581a22015-10-14 14:10:30 -0600515 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800516 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
517 builder.addCapability(spv::CapabilityDrawParameters);
518 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200519
520 case glslang::EbvPrimitiveId:
521 if (glslangIntermediate->getStage() == EShLangFragment)
522 builder.addCapability(spv::CapabilityGeometry);
523 return spv::BuiltInPrimitiveId;
524
Rex Xu37cdcee2017-06-29 17:46:34 +0800525 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800526 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
527 builder.addCapability(spv::CapabilityStencilExportEXT);
528 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800529
John Kessenich140f3df2015-06-26 16:58:36 -0600530 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600531 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
532 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
533 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
534 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
535 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
536 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
537 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600538 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
539 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
540 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
541 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
542 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
543 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
544 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
545 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800546
Rex Xu574ab042016-04-14 16:53:07 +0800547 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800548 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800549 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
550 return spv::BuiltInSubgroupSize;
551
Rex Xu574ab042016-04-14 16:53:07 +0800552 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800553 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800554 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
555 return spv::BuiltInSubgroupLocalInvocationId;
556
Rex Xu574ab042016-04-14 16:53:07 +0800557 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800558 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
559 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
560 return spv::BuiltInSubgroupEqMaskKHR;
561
Rex Xu574ab042016-04-14 16:53:07 +0800562 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800563 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
564 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
565 return spv::BuiltInSubgroupGeMaskKHR;
566
Rex Xu574ab042016-04-14 16:53:07 +0800567 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800568 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
569 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
570 return spv::BuiltInSubgroupGtMaskKHR;
571
Rex Xu574ab042016-04-14 16:53:07 +0800572 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800573 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
574 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
575 return spv::BuiltInSubgroupLeMaskKHR;
576
Rex Xu574ab042016-04-14 16:53:07 +0800577 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800578 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
579 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
580 return spv::BuiltInSubgroupLtMaskKHR;
581
Rex Xu9d93a232016-05-05 12:30:44 +0800582#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800583 case glslang::EbvBaryCoordNoPersp:
584 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
585 return spv::BuiltInBaryCoordNoPerspAMD;
586
587 case glslang::EbvBaryCoordNoPerspCentroid:
588 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
589 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
590
591 case glslang::EbvBaryCoordNoPerspSample:
592 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
593 return spv::BuiltInBaryCoordNoPerspSampleAMD;
594
595 case glslang::EbvBaryCoordSmooth:
596 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
597 return spv::BuiltInBaryCoordSmoothAMD;
598
599 case glslang::EbvBaryCoordSmoothCentroid:
600 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
601 return spv::BuiltInBaryCoordSmoothCentroidAMD;
602
603 case glslang::EbvBaryCoordSmoothSample:
604 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
605 return spv::BuiltInBaryCoordSmoothSampleAMD;
606
607 case glslang::EbvBaryCoordPullModel:
608 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
609 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800610#endif
chaoc771d89f2017-01-13 01:10:53 -0800611
John Kessenich6c8aaac2017-02-27 01:20:51 -0700612 case glslang::EbvDeviceIndex:
613 builder.addExtension(spv::E_SPV_KHR_device_group);
614 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700615 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700616
617 case glslang::EbvViewIndex:
618 builder.addExtension(spv::E_SPV_KHR_multiview);
619 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700620 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700621
chaoc771d89f2017-01-13 01:10:53 -0800622#ifdef NV_EXTENSIONS
623 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800624 if (!memberDeclaration) {
625 builder.addExtension(spv::E_SPV_NV_viewport_array2);
626 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
627 }
chaoc771d89f2017-01-13 01:10:53 -0800628 return spv::BuiltInViewportMaskNV;
629 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800630 if (!memberDeclaration) {
631 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
632 builder.addCapability(spv::CapabilityShaderStereoViewNV);
633 }
chaoc771d89f2017-01-13 01:10:53 -0800634 return spv::BuiltInSecondaryPositionNV;
635 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800636 if (!memberDeclaration) {
637 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
638 builder.addCapability(spv::CapabilityShaderStereoViewNV);
639 }
chaoc771d89f2017-01-13 01:10:53 -0800640 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800641 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800642 if (!memberDeclaration) {
643 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
644 builder.addCapability(spv::CapabilityPerViewAttributesNV);
645 }
chaocdf3956c2017-02-14 14:52:34 -0800646 return spv::BuiltInPositionPerViewNV;
647 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800648 if (!memberDeclaration) {
649 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
650 builder.addCapability(spv::CapabilityPerViewAttributesNV);
651 }
chaocdf3956c2017-02-14 14:52:34 -0800652 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700653 case glslang::EbvFragFullyCoveredNV:
654 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
655 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
656 return spv::BuiltInFullyCoveredEXT;
chaoc771d89f2017-01-13 01:10:53 -0800657#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800658 default:
659 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600660 }
661}
662
Rex Xufc618912015-09-09 16:42:49 +0800663// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700664spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800665{
666 assert(type.getBasicType() == glslang::EbtSampler);
667
John Kessenich5d0fa972016-02-15 11:57:00 -0700668 // Check for capabilities
669 switch (type.getQualifier().layoutFormat) {
670 case glslang::ElfRg32f:
671 case glslang::ElfRg16f:
672 case glslang::ElfR11fG11fB10f:
673 case glslang::ElfR16f:
674 case glslang::ElfRgba16:
675 case glslang::ElfRgb10A2:
676 case glslang::ElfRg16:
677 case glslang::ElfRg8:
678 case glslang::ElfR16:
679 case glslang::ElfR8:
680 case glslang::ElfRgba16Snorm:
681 case glslang::ElfRg16Snorm:
682 case glslang::ElfRg8Snorm:
683 case glslang::ElfR16Snorm:
684 case glslang::ElfR8Snorm:
685
686 case glslang::ElfRg32i:
687 case glslang::ElfRg16i:
688 case glslang::ElfRg8i:
689 case glslang::ElfR16i:
690 case glslang::ElfR8i:
691
692 case glslang::ElfRgb10a2ui:
693 case glslang::ElfRg32ui:
694 case glslang::ElfRg16ui:
695 case glslang::ElfRg8ui:
696 case glslang::ElfR16ui:
697 case glslang::ElfR8ui:
698 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
699 break;
700
701 default:
702 break;
703 }
704
705 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800706 switch (type.getQualifier().layoutFormat) {
707 case glslang::ElfNone: return spv::ImageFormatUnknown;
708 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
709 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
710 case glslang::ElfR32f: return spv::ImageFormatR32f;
711 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
712 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
713 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
714 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
715 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
716 case glslang::ElfR16f: return spv::ImageFormatR16f;
717 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
718 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
719 case glslang::ElfRg16: return spv::ImageFormatRg16;
720 case glslang::ElfRg8: return spv::ImageFormatRg8;
721 case glslang::ElfR16: return spv::ImageFormatR16;
722 case glslang::ElfR8: return spv::ImageFormatR8;
723 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
724 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
725 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
726 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
727 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
728 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
729 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
730 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
731 case glslang::ElfR32i: return spv::ImageFormatR32i;
732 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
733 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
734 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
735 case glslang::ElfR16i: return spv::ImageFormatR16i;
736 case glslang::ElfR8i: return spv::ImageFormatR8i;
737 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
738 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
739 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
740 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
741 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
742 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
743 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
744 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
745 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
746 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600747 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800748 }
749}
750
Rex Xu57e65922017-07-04 23:23:40 +0800751spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(glslang::TSelectionControl selectionControl) const
752{
753 switch (selectionControl) {
754 case glslang::ESelectionControlNone: return spv::SelectionControlMaskNone;
755 case glslang::ESelectionControlFlatten: return spv::SelectionControlFlattenMask;
756 case glslang::ESelectionControlDontFlatten: return spv::SelectionControlDontFlattenMask;
757 default: return spv::SelectionControlMaskNone;
758 }
759}
760
steve-lunargf1709e72017-05-02 20:14:50 -0600761spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(glslang::TLoopControl loopControl) const
762{
763 switch (loopControl) {
764 case glslang::ELoopControlNone: return spv::LoopControlMaskNone;
765 case glslang::ELoopControlUnroll: return spv::LoopControlUnrollMask;
766 case glslang::ELoopControlDontUnroll: return spv::LoopControlDontUnrollMask;
767 // TODO: DependencyInfinite
768 // TODO: DependencyLength
769 default: return spv::LoopControlMaskNone;
770 }
771}
772
John Kessenicha5c5fb62017-05-05 05:09:58 -0600773// Translate glslang type to SPIR-V storage class.
774spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
775{
776 if (type.getQualifier().isPipeInput())
777 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600778 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -0600779 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600780
781 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
782 type.getQualifier().storage == glslang::EvqUniform) {
783 if (type.getBasicType() == glslang::EbtAtomicUint)
784 return spv::StorageClassAtomicCounter;
785 if (type.containsOpaque())
786 return spv::StorageClassUniformConstant;
787 }
788
789 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenicha5c5fb62017-05-05 05:09:58 -0600790 builder.addExtension(spv::E_SPV_KHR_storage_buffer_storage_class);
791 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600792 }
793
794 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -0600795 if (type.getQualifier().layoutPushConstant)
796 return spv::StorageClassPushConstant;
797 if (type.getBasicType() == glslang::EbtBlock)
798 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600799 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600800 }
John Kessenichbed4e4f2017-09-08 02:38:07 -0600801
802 switch (type.getQualifier().storage) {
803 case glslang::EvqShared: return spv::StorageClassWorkgroup;
804 case glslang::EvqGlobal: return spv::StorageClassPrivate;
805 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
806 case glslang::EvqTemporary: return spv::StorageClassFunction;
807 default:
808 assert(0);
809 break;
810 }
811
812 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600813}
814
qining25262b32016-05-06 17:25:16 -0400815// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700816// descriptor set.
817bool IsDescriptorResource(const glslang::TType& type)
818{
John Kessenichf7497e22016-03-08 21:36:22 -0700819 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700820 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700821 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700822
823 // non block...
824 // basically samplerXXX/subpass/sampler/texture are all included
825 // if they are the global-scope-class, not the function parameter
826 // (or local, if they ever exist) class.
827 if (type.getBasicType() == glslang::EbtSampler)
828 return type.getQualifier().isUniformOrBuffer();
829
830 // None of the above.
831 return false;
832}
833
John Kesseniche0b6cad2015-12-24 10:30:13 -0700834void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
835{
836 if (child.layoutMatrix == glslang::ElmNone)
837 child.layoutMatrix = parent.layoutMatrix;
838
839 if (parent.invariant)
840 child.invariant = true;
841 if (parent.nopersp)
842 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800843#ifdef AMD_EXTENSIONS
844 if (parent.explicitInterp)
845 child.explicitInterp = true;
846#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700847 if (parent.flat)
848 child.flat = true;
849 if (parent.centroid)
850 child.centroid = true;
851 if (parent.patch)
852 child.patch = true;
853 if (parent.sample)
854 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800855 if (parent.coherent)
856 child.coherent = true;
857 if (parent.volatil)
858 child.volatil = true;
859 if (parent.restrict)
860 child.restrict = true;
861 if (parent.readonly)
862 child.readonly = true;
863 if (parent.writeonly)
864 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700865}
866
John Kessenichf2b7f332016-09-01 17:05:23 -0600867bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700868{
John Kessenich7b9fa252016-01-21 18:56:57 -0700869 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600870 // - struct members might inherit from a struct declaration
871 // (note that non-block structs don't explicitly inherit,
872 // only implicitly, meaning no decoration involved)
873 // - affect decorations on the struct members
874 // (note smooth does not, and expecting something like volatile
875 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700876 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600877 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700878}
879
John Kessenich140f3df2015-06-26 16:58:36 -0600880//
881// Implement the TGlslangToSpvTraverser class.
882//
883
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700884TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -0600885 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
886 : TIntermTraverser(true, false, true),
887 options(options),
888 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -0600889 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700890 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700891 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600892 glslangIntermediate(glslangIntermediate)
893{
894 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
895
896 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -0600897 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
898 glslangIntermediate->getVersion());
899
John Kessenich121853f2017-05-31 17:11:16 -0600900 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -0600901 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -0600902 builder.setSourceFile(glslangIntermediate->getSourceFile());
903
904 // Set the source shader's text. If for SPV version 1.0, include
905 // a preamble in comments stating the OpModuleProcessed instructions.
906 // Otherwise, emit those as actual instructions.
907 std::string text;
908 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
909 for (int p = 0; p < (int)processes.size(); ++p) {
910 if (glslangIntermediate->getSpv().spv < 0x00010100) {
911 text.append("// OpModuleProcessed ");
912 text.append(processes[p]);
913 text.append("\n");
914 } else
915 builder.addModuleProcessed(processes[p]);
916 }
917 if (glslangIntermediate->getSpv().spv < 0x00010100 && (int)processes.size() > 0)
918 text.append("#line 1\n");
919 text.append(glslangIntermediate->getSourceText());
920 builder.setSourceText(text);
John Kessenich121853f2017-05-31 17:11:16 -0600921 }
John Kessenich140f3df2015-06-26 16:58:36 -0600922 stdBuiltins = builder.import("GLSL.std.450");
923 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600924 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
925 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600926
927 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600928 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
929 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600930 builder.addSourceExtension(it->c_str());
931
932 // Add the top-level modes for this shader.
933
John Kessenich92187592016-02-01 13:45:25 -0700934 if (glslangIntermediate->getXfbMode()) {
935 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600936 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700937 }
John Kessenich140f3df2015-06-26 16:58:36 -0600938
939 unsigned int mode;
940 switch (glslangIntermediate->getStage()) {
941 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600942 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600943 break;
944
steve-lunarge7412492017-03-23 11:56:07 -0600945 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -0600946 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600947 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600948
steve-lunarge7412492017-03-23 11:56:07 -0600949 glslang::TLayoutGeometry primitive;
950
951 if (glslangIntermediate->getStage() == EShLangTessControl) {
952 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
953 primitive = glslangIntermediate->getOutputPrimitive();
954 } else {
955 primitive = glslangIntermediate->getInputPrimitive();
956 }
957
958 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -0700959 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
960 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
961 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600962 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600963 }
John Kessenich4016e382016-07-15 11:53:56 -0600964 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600965 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
966
John Kesseniche6903322015-10-13 16:29:02 -0600967 switch (glslangIntermediate->getVertexSpacing()) {
968 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
969 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
970 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600971 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600972 }
John Kessenich4016e382016-07-15 11:53:56 -0600973 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600974 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
975
976 switch (glslangIntermediate->getVertexOrder()) {
977 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
978 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600979 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600980 }
John Kessenich4016e382016-07-15 11:53:56 -0600981 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600982 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
983
984 if (glslangIntermediate->getPointMode())
985 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600986 break;
987
988 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600989 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600990 switch (glslangIntermediate->getInputPrimitive()) {
991 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
992 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
993 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700994 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600995 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600996 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600997 }
John Kessenich4016e382016-07-15 11:53:56 -0600998 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600999 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001000
John Kessenich140f3df2015-06-26 16:58:36 -06001001 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1002
1003 switch (glslangIntermediate->getOutputPrimitive()) {
1004 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1005 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1006 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001007 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001008 }
John Kessenich4016e382016-07-15 11:53:56 -06001009 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001010 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1011 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1012 break;
1013
1014 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001015 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001016 if (glslangIntermediate->getPixelCenterInteger())
1017 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001018
John Kessenich140f3df2015-06-26 16:58:36 -06001019 if (glslangIntermediate->getOriginUpperLeft())
1020 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001021 else
1022 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001023
1024 if (glslangIntermediate->getEarlyFragmentTests())
1025 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1026
chaocc1204522017-06-30 17:14:30 -07001027 if (glslangIntermediate->getPostDepthCoverage()) {
1028 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1029 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1030 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1031 }
1032
John Kesseniche6903322015-10-13 16:29:02 -06001033 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001034 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1035 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001036 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001037 }
John Kessenich4016e382016-07-15 11:53:56 -06001038 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001039 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1040
1041 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1042 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001043 break;
1044
1045 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001046 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001047 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1048 glslangIntermediate->getLocalSize(1),
1049 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -06001050 break;
1051
1052 default:
1053 break;
1054 }
John Kessenich140f3df2015-06-26 16:58:36 -06001055}
1056
John Kessenichfca82622016-11-26 13:23:20 -07001057// Finish creating SPV, after the traversal is complete.
1058void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001059{
John Kessenich517fe7a2016-11-26 13:31:47 -07001060 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001061 builder.setBuildPoint(shaderEntry->getLastBlock());
1062 builder.leaveFunction();
1063 }
1064
John Kessenich7ba63412015-12-20 17:37:07 -07001065 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001066 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1067 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001068
qiningda397332016-03-09 19:54:03 -05001069 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -07001070}
1071
John Kessenichfca82622016-11-26 13:23:20 -07001072// Write the SPV into 'out'.
1073void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001074{
John Kessenichfca82622016-11-26 13:23:20 -07001075 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001076}
1077
1078//
1079// Implement the traversal functions.
1080//
1081// Return true from interior nodes to have the external traversal
1082// continue on to children. Return false if children were
1083// already processed.
1084//
1085
1086//
qining25262b32016-05-06 17:25:16 -04001087// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001088// - uniform/input reads
1089// - output writes
1090// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1091// - something simple that degenerates into the last bullet
1092//
1093void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1094{
qining75d1d802016-04-06 14:42:01 -04001095 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1096 if (symbol->getType().getQualifier().isSpecConstant())
1097 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1098
John Kessenich140f3df2015-06-26 16:58:36 -06001099 // getSymbolId() will set up all the IO decorations on the first call.
1100 // Formal function parameters were mapped during makeFunctions().
1101 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001102
1103 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1104 if (builder.isPointer(id)) {
1105 spv::StorageClass sc = builder.getStorageClass(id);
John Kessenich5f77d862017-09-19 11:09:59 -06001106 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput) {
1107 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0)
1108 iOSet.insert(id);
1109 }
John Kessenich7ba63412015-12-20 17:37:07 -07001110 }
1111
1112 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001113 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001114 // Prepare to generate code for the access
1115
1116 // L-value chains will be computed left to right. We're on the symbol now,
1117 // which is the left-most part of the access chain, so now is "clear" time,
1118 // followed by setting the base.
1119 builder.clearAccessChain();
1120
1121 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001122 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001123 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001124 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001125 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001126 // These are also pure R-values.
1127 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001128 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001129 builder.setAccessChainRValue(id);
1130 else
1131 builder.setAccessChainLValue(id);
1132 }
1133}
1134
1135bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1136{
John Kesseniche485c7a2017-05-31 18:50:53 -06001137 builder.setLine(node->getLoc().line);
1138
qining40887662016-04-03 22:20:42 -04001139 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1140 if (node->getType().getQualifier().isSpecConstant())
1141 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1142
John Kessenich140f3df2015-06-26 16:58:36 -06001143 // First, handle special cases
1144 switch (node->getOp()) {
1145 case glslang::EOpAssign:
1146 case glslang::EOpAddAssign:
1147 case glslang::EOpSubAssign:
1148 case glslang::EOpMulAssign:
1149 case glslang::EOpVectorTimesMatrixAssign:
1150 case glslang::EOpVectorTimesScalarAssign:
1151 case glslang::EOpMatrixTimesScalarAssign:
1152 case glslang::EOpMatrixTimesMatrixAssign:
1153 case glslang::EOpDivAssign:
1154 case glslang::EOpModAssign:
1155 case glslang::EOpAndAssign:
1156 case glslang::EOpInclusiveOrAssign:
1157 case glslang::EOpExclusiveOrAssign:
1158 case glslang::EOpLeftShiftAssign:
1159 case glslang::EOpRightShiftAssign:
1160 // A bin-op assign "a += b" means the same thing as "a = a + b"
1161 // where a is evaluated before b. For a simple assignment, GLSL
1162 // says to evaluate the left before the right. So, always, left
1163 // node then right node.
1164 {
1165 // get the left l-value, save it away
1166 builder.clearAccessChain();
1167 node->getLeft()->traverse(this);
1168 spv::Builder::AccessChain lValue = builder.getAccessChain();
1169
1170 // evaluate the right
1171 builder.clearAccessChain();
1172 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001173 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001174
1175 if (node->getOp() != glslang::EOpAssign) {
1176 // the left is also an r-value
1177 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001178 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001179
1180 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001181 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001182 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001183 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1184 node->getType().getBasicType());
1185
1186 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001187 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001188 }
1189
1190 // store the result
1191 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001192 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001193
1194 // assignments are expressions having an rValue after they are evaluated...
1195 builder.clearAccessChain();
1196 builder.setAccessChainRValue(rValue);
1197 }
1198 return false;
1199 case glslang::EOpIndexDirect:
1200 case glslang::EOpIndexDirectStruct:
1201 {
1202 // Get the left part of the access chain.
1203 node->getLeft()->traverse(this);
1204
1205 // Add the next element in the chain
1206
David Netoa901ffe2016-06-08 14:11:40 +01001207 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001208 if (! node->getLeft()->getType().isArray() &&
1209 node->getLeft()->getType().isVector() &&
1210 node->getOp() == glslang::EOpIndexDirect) {
1211 // This is essentially a hard-coded vector swizzle of size 1,
1212 // so short circuit the access-chain stuff with a swizzle.
1213 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001214 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001215 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001216 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001217 int spvIndex = glslangIndex;
1218 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1219 node->getOp() == glslang::EOpIndexDirectStruct)
1220 {
1221 // This may be, e.g., an anonymous block-member selection, which generally need
1222 // index remapping due to hidden members in anonymous blocks.
1223 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1224 assert(remapper.size() > 0);
1225 spvIndex = remapper[glslangIndex];
1226 }
John Kessenichebb50532016-05-16 19:22:05 -06001227
David Netoa901ffe2016-06-08 14:11:40 +01001228 // normal case for indexing array or structure or block
1229 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1230
1231 // Add capabilities here for accessing PointSize and clip/cull distance.
1232 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001233 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001234 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001235 }
1236 }
1237 return false;
1238 case glslang::EOpIndexIndirect:
1239 {
1240 // Structure or array or vector indirection.
1241 // Will use native SPIR-V access-chain for struct and array indirection;
1242 // matrices are arrays of vectors, so will also work for a matrix.
1243 // Will use the access chain's 'component' for variable index into a vector.
1244
1245 // This adapter is building access chains left to right.
1246 // Set up the access chain to the left.
1247 node->getLeft()->traverse(this);
1248
1249 // save it so that computing the right side doesn't trash it
1250 spv::Builder::AccessChain partial = builder.getAccessChain();
1251
1252 // compute the next index in the chain
1253 builder.clearAccessChain();
1254 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001255 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001256
1257 // restore the saved access chain
1258 builder.setAccessChain(partial);
1259
1260 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001261 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001262 else
John Kessenichfa668da2015-09-13 14:46:30 -06001263 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001264 }
1265 return false;
1266 case glslang::EOpVectorSwizzle:
1267 {
1268 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001269 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001270 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001271 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001272 }
1273 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001274 case glslang::EOpMatrixSwizzle:
1275 logger->missingFunctionality("matrix swizzle");
1276 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001277 case glslang::EOpLogicalOr:
1278 case glslang::EOpLogicalAnd:
1279 {
1280
1281 // These may require short circuiting, but can sometimes be done as straight
1282 // binary operations. The right operand must be short circuited if it has
1283 // side effects, and should probably be if it is complex.
1284 if (isTrivial(node->getRight()->getAsTyped()))
1285 break; // handle below as a normal binary operation
1286 // otherwise, we need to do dynamic short circuiting on the right operand
1287 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1288 builder.clearAccessChain();
1289 builder.setAccessChainRValue(result);
1290 }
1291 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001292 default:
1293 break;
1294 }
1295
1296 // Assume generic binary op...
1297
John Kessenich32cfd492016-02-02 12:37:46 -07001298 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001299 builder.clearAccessChain();
1300 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001301 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001302
John Kessenich32cfd492016-02-02 12:37:46 -07001303 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001304 builder.clearAccessChain();
1305 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001306 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001307
John Kessenich32cfd492016-02-02 12:37:46 -07001308 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001309 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001310 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001311 convertGlslangToSpvType(node->getType()), left, right,
1312 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001313
John Kessenich50e57562015-12-21 21:21:11 -07001314 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001315 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001316 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001317 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001318 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001319 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001320 return false;
1321 }
John Kessenich140f3df2015-06-26 16:58:36 -06001322}
1323
1324bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1325{
John Kesseniche485c7a2017-05-31 18:50:53 -06001326 builder.setLine(node->getLoc().line);
1327
qining40887662016-04-03 22:20:42 -04001328 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1329 if (node->getType().getQualifier().isSpecConstant())
1330 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1331
John Kessenichfc51d282015-08-19 13:34:18 -06001332 spv::Id result = spv::NoResult;
1333
1334 // try texturing first
1335 result = createImageTextureFunctionCall(node);
1336 if (result != spv::NoResult) {
1337 builder.clearAccessChain();
1338 builder.setAccessChainRValue(result);
1339
1340 return false; // done with this node
1341 }
1342
1343 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001344
1345 if (node->getOp() == glslang::EOpArrayLength) {
1346 // Quite special; won't want to evaluate the operand.
1347
1348 // Normal .length() would have been constant folded by the front-end.
1349 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001350 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001351 assert(node->getOperand()->getType().isRuntimeSizedArray());
1352 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1353 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001354 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1355 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001356
1357 builder.clearAccessChain();
1358 builder.setAccessChainRValue(length);
1359
1360 return false;
1361 }
1362
John Kessenichfc51d282015-08-19 13:34:18 -06001363 // Start by evaluating the operand
1364
John Kessenich8c8505c2016-07-26 12:50:38 -06001365 // Does it need a swizzle inversion? If so, evaluation is inverted;
1366 // operate first on the swizzle base, then apply the swizzle.
1367 spv::Id invertedType = spv::NoType;
1368 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1369 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1370 invertedType = getInvertedSwizzleType(*node->getOperand());
1371
John Kessenich140f3df2015-06-26 16:58:36 -06001372 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001373 if (invertedType != spv::NoType)
1374 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1375 else
1376 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001377
Rex Xufc618912015-09-09 16:42:49 +08001378 spv::Id operand = spv::NoResult;
1379
1380 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1381 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001382 node->getOp() == glslang::EOpAtomicCounter ||
1383 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001384 operand = builder.accessChainGetLValue(); // Special case l-value operands
1385 else
John Kessenich32cfd492016-02-02 12:37:46 -07001386 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001387
John Kessenichf6640762016-08-01 19:44:00 -06001388 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001389 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001390
1391 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001392 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001393 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001394
1395 // if not, then possibly an operation
1396 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001397 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001398
1399 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001400 if (invertedType)
1401 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1402
John Kessenich140f3df2015-06-26 16:58:36 -06001403 builder.clearAccessChain();
1404 builder.setAccessChainRValue(result);
1405
1406 return false; // done with this node
1407 }
1408
1409 // it must be a special case, check...
1410 switch (node->getOp()) {
1411 case glslang::EOpPostIncrement:
1412 case glslang::EOpPostDecrement:
1413 case glslang::EOpPreIncrement:
1414 case glslang::EOpPreDecrement:
1415 {
1416 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001417 spv::Id one = 0;
1418 if (node->getBasicType() == glslang::EbtFloat)
1419 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001420 else if (node->getBasicType() == glslang::EbtDouble)
1421 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001422#ifdef AMD_EXTENSIONS
1423 else if (node->getBasicType() == glslang::EbtFloat16)
1424 one = builder.makeFloat16Constant(1.0F);
1425#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001426 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1427 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001428#ifdef AMD_EXTENSIONS
1429 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1430 one = builder.makeInt16Constant(1);
1431#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001432 else
1433 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001434 glslang::TOperator op;
1435 if (node->getOp() == glslang::EOpPreIncrement ||
1436 node->getOp() == glslang::EOpPostIncrement)
1437 op = glslang::EOpAdd;
1438 else
1439 op = glslang::EOpSub;
1440
John Kessenichf6640762016-08-01 19:44:00 -06001441 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001442 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001443 convertGlslangToSpvType(node->getType()), operand, one,
1444 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001445 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001446
1447 // The result of operation is always stored, but conditionally the
1448 // consumed result. The consumed result is always an r-value.
1449 builder.accessChainStore(result);
1450 builder.clearAccessChain();
1451 if (node->getOp() == glslang::EOpPreIncrement ||
1452 node->getOp() == glslang::EOpPreDecrement)
1453 builder.setAccessChainRValue(result);
1454 else
1455 builder.setAccessChainRValue(operand);
1456 }
1457
1458 return false;
1459
1460 case glslang::EOpEmitStreamVertex:
1461 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1462 return false;
1463 case glslang::EOpEndStreamPrimitive:
1464 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1465 return false;
1466
1467 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001468 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001469 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001470 }
John Kessenich140f3df2015-06-26 16:58:36 -06001471}
1472
1473bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1474{
qining27e04a02016-04-14 16:40:20 -04001475 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1476 if (node->getType().getQualifier().isSpecConstant())
1477 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1478
John Kessenichfc51d282015-08-19 13:34:18 -06001479 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001480 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1481 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001482
1483 // try texturing
1484 result = createImageTextureFunctionCall(node);
1485 if (result != spv::NoResult) {
1486 builder.clearAccessChain();
1487 builder.setAccessChainRValue(result);
1488
1489 return false;
Rex Xu129799a2017-07-05 17:23:28 +08001490#ifdef AMD_EXTENSIONS
1491 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
1492#else
John Kessenich56bab042015-09-16 10:54:31 -06001493 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08001494#endif
Rex Xufc618912015-09-09 16:42:49 +08001495 // "imageStore" is a special case, which has no result
1496 return false;
1497 }
John Kessenichfc51d282015-08-19 13:34:18 -06001498
John Kessenich140f3df2015-06-26 16:58:36 -06001499 glslang::TOperator binOp = glslang::EOpNull;
1500 bool reduceComparison = true;
1501 bool isMatrix = false;
1502 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001503 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001504
1505 assert(node->getOp());
1506
John Kessenichf6640762016-08-01 19:44:00 -06001507 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001508
1509 switch (node->getOp()) {
1510 case glslang::EOpSequence:
1511 {
1512 if (preVisit)
1513 ++sequenceDepth;
1514 else
1515 --sequenceDepth;
1516
1517 if (sequenceDepth == 1) {
1518 // If this is the parent node of all the functions, we want to see them
1519 // early, so all call points have actual SPIR-V functions to reference.
1520 // In all cases, still let the traverser visit the children for us.
1521 makeFunctions(node->getAsAggregate()->getSequence());
1522
John Kessenich6fccb3c2016-09-19 16:01:41 -06001523 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001524 // anything else gets there, so visit out of order, doing them all now.
1525 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1526
John Kessenich6a60c2f2016-12-08 21:01:59 -07001527 // 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 -06001528 // so do them manually.
1529 visitFunctions(node->getAsAggregate()->getSequence());
1530
1531 return false;
1532 }
1533
1534 return true;
1535 }
1536 case glslang::EOpLinkerObjects:
1537 {
1538 if (visit == glslang::EvPreVisit)
1539 linkageOnly = true;
1540 else
1541 linkageOnly = false;
1542
1543 return true;
1544 }
1545 case glslang::EOpComma:
1546 {
1547 // processing from left to right naturally leaves the right-most
1548 // lying around in the access chain
1549 glslang::TIntermSequence& glslangOperands = node->getSequence();
1550 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1551 glslangOperands[i]->traverse(this);
1552
1553 return false;
1554 }
1555 case glslang::EOpFunction:
1556 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001557 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001558 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001559 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001560 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001561 } else {
1562 handleFunctionEntry(node);
1563 }
1564 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001565 if (inEntryPoint)
1566 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001567 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001568 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001569 }
1570
1571 return true;
1572 case glslang::EOpParameters:
1573 // Parameters will have been consumed by EOpFunction processing, but not
1574 // the body, so we still visited the function node's children, making this
1575 // child redundant.
1576 return false;
1577 case glslang::EOpFunctionCall:
1578 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001579 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001580 if (node->isUserDefined())
1581 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001582 // 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 -07001583 if (result) {
1584 builder.clearAccessChain();
1585 builder.setAccessChainRValue(result);
1586 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001587 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001588
1589 return false;
1590 }
1591 case glslang::EOpConstructMat2x2:
1592 case glslang::EOpConstructMat2x3:
1593 case glslang::EOpConstructMat2x4:
1594 case glslang::EOpConstructMat3x2:
1595 case glslang::EOpConstructMat3x3:
1596 case glslang::EOpConstructMat3x4:
1597 case glslang::EOpConstructMat4x2:
1598 case glslang::EOpConstructMat4x3:
1599 case glslang::EOpConstructMat4x4:
1600 case glslang::EOpConstructDMat2x2:
1601 case glslang::EOpConstructDMat2x3:
1602 case glslang::EOpConstructDMat2x4:
1603 case glslang::EOpConstructDMat3x2:
1604 case glslang::EOpConstructDMat3x3:
1605 case glslang::EOpConstructDMat3x4:
1606 case glslang::EOpConstructDMat4x2:
1607 case glslang::EOpConstructDMat4x3:
1608 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06001609 case glslang::EOpConstructIMat2x2:
1610 case glslang::EOpConstructIMat2x3:
1611 case glslang::EOpConstructIMat2x4:
1612 case glslang::EOpConstructIMat3x2:
1613 case glslang::EOpConstructIMat3x3:
1614 case glslang::EOpConstructIMat3x4:
1615 case glslang::EOpConstructIMat4x2:
1616 case glslang::EOpConstructIMat4x3:
1617 case glslang::EOpConstructIMat4x4:
1618 case glslang::EOpConstructUMat2x2:
1619 case glslang::EOpConstructUMat2x3:
1620 case glslang::EOpConstructUMat2x4:
1621 case glslang::EOpConstructUMat3x2:
1622 case glslang::EOpConstructUMat3x3:
1623 case glslang::EOpConstructUMat3x4:
1624 case glslang::EOpConstructUMat4x2:
1625 case glslang::EOpConstructUMat4x3:
1626 case glslang::EOpConstructUMat4x4:
1627 case glslang::EOpConstructBMat2x2:
1628 case glslang::EOpConstructBMat2x3:
1629 case glslang::EOpConstructBMat2x4:
1630 case glslang::EOpConstructBMat3x2:
1631 case glslang::EOpConstructBMat3x3:
1632 case glslang::EOpConstructBMat3x4:
1633 case glslang::EOpConstructBMat4x2:
1634 case glslang::EOpConstructBMat4x3:
1635 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001636#ifdef AMD_EXTENSIONS
1637 case glslang::EOpConstructF16Mat2x2:
1638 case glslang::EOpConstructF16Mat2x3:
1639 case glslang::EOpConstructF16Mat2x4:
1640 case glslang::EOpConstructF16Mat3x2:
1641 case glslang::EOpConstructF16Mat3x3:
1642 case glslang::EOpConstructF16Mat3x4:
1643 case glslang::EOpConstructF16Mat4x2:
1644 case glslang::EOpConstructF16Mat4x3:
1645 case glslang::EOpConstructF16Mat4x4:
1646#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001647 isMatrix = true;
1648 // fall through
1649 case glslang::EOpConstructFloat:
1650 case glslang::EOpConstructVec2:
1651 case glslang::EOpConstructVec3:
1652 case glslang::EOpConstructVec4:
1653 case glslang::EOpConstructDouble:
1654 case glslang::EOpConstructDVec2:
1655 case glslang::EOpConstructDVec3:
1656 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001657#ifdef AMD_EXTENSIONS
1658 case glslang::EOpConstructFloat16:
1659 case glslang::EOpConstructF16Vec2:
1660 case glslang::EOpConstructF16Vec3:
1661 case glslang::EOpConstructF16Vec4:
1662#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001663 case glslang::EOpConstructBool:
1664 case glslang::EOpConstructBVec2:
1665 case glslang::EOpConstructBVec3:
1666 case glslang::EOpConstructBVec4:
1667 case glslang::EOpConstructInt:
1668 case glslang::EOpConstructIVec2:
1669 case glslang::EOpConstructIVec3:
1670 case glslang::EOpConstructIVec4:
1671 case glslang::EOpConstructUint:
1672 case glslang::EOpConstructUVec2:
1673 case glslang::EOpConstructUVec3:
1674 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001675 case glslang::EOpConstructInt64:
1676 case glslang::EOpConstructI64Vec2:
1677 case glslang::EOpConstructI64Vec3:
1678 case glslang::EOpConstructI64Vec4:
1679 case glslang::EOpConstructUint64:
1680 case glslang::EOpConstructU64Vec2:
1681 case glslang::EOpConstructU64Vec3:
1682 case glslang::EOpConstructU64Vec4:
Rex Xucabbb782017-03-24 13:41:14 +08001683#ifdef AMD_EXTENSIONS
1684 case glslang::EOpConstructInt16:
1685 case glslang::EOpConstructI16Vec2:
1686 case glslang::EOpConstructI16Vec3:
1687 case glslang::EOpConstructI16Vec4:
1688 case glslang::EOpConstructUint16:
1689 case glslang::EOpConstructU16Vec2:
1690 case glslang::EOpConstructU16Vec3:
1691 case glslang::EOpConstructU16Vec4:
1692#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001693 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001694 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001695 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001696 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001697 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001698 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001699 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001700 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001701 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001702 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001703 std::vector<spv::Id> constituents;
1704 for (int c = 0; c < (int)arguments.size(); ++c)
1705 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001706 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001707 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001708 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001709 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001710 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001711
1712 builder.clearAccessChain();
1713 builder.setAccessChainRValue(constructed);
1714
1715 return false;
1716 }
1717
1718 // These six are component-wise compares with component-wise results.
1719 // Forward on to createBinaryOperation(), requesting a vector result.
1720 case glslang::EOpLessThan:
1721 case glslang::EOpGreaterThan:
1722 case glslang::EOpLessThanEqual:
1723 case glslang::EOpGreaterThanEqual:
1724 case glslang::EOpVectorEqual:
1725 case glslang::EOpVectorNotEqual:
1726 {
1727 // Map the operation to a binary
1728 binOp = node->getOp();
1729 reduceComparison = false;
1730 switch (node->getOp()) {
1731 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1732 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1733 default: binOp = node->getOp(); break;
1734 }
1735
1736 break;
1737 }
1738 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001739 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001740 binOp = glslang::EOpMul;
1741 break;
1742 case glslang::EOpOuterProduct:
1743 // two vectors multiplied to make a matrix
1744 binOp = glslang::EOpOuterProduct;
1745 break;
1746 case glslang::EOpDot:
1747 {
qining25262b32016-05-06 17:25:16 -04001748 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001749 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001750 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001751 binOp = glslang::EOpMul;
1752 break;
1753 }
1754 case glslang::EOpMod:
1755 // when an aggregate, this is the floating-point mod built-in function,
1756 // which can be emitted by the one in createBinaryOperation()
1757 binOp = glslang::EOpMod;
1758 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001759 case glslang::EOpEmitVertex:
1760 case glslang::EOpEndPrimitive:
1761 case glslang::EOpBarrier:
1762 case glslang::EOpMemoryBarrier:
1763 case glslang::EOpMemoryBarrierAtomicCounter:
1764 case glslang::EOpMemoryBarrierBuffer:
1765 case glslang::EOpMemoryBarrierImage:
1766 case glslang::EOpMemoryBarrierShared:
1767 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07001768 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001769 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07001770 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001771 case glslang::EOpWorkgroupMemoryBarrier:
1772 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001773 noReturnValue = true;
1774 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1775 break;
1776
John Kessenich426394d2015-07-23 10:22:48 -06001777 case glslang::EOpAtomicAdd:
1778 case glslang::EOpAtomicMin:
1779 case glslang::EOpAtomicMax:
1780 case glslang::EOpAtomicAnd:
1781 case glslang::EOpAtomicOr:
1782 case glslang::EOpAtomicXor:
1783 case glslang::EOpAtomicExchange:
1784 case glslang::EOpAtomicCompSwap:
1785 atomic = true;
1786 break;
1787
John Kessenich0d0c6d32017-07-23 16:08:26 -06001788 case glslang::EOpAtomicCounterAdd:
1789 case glslang::EOpAtomicCounterSubtract:
1790 case glslang::EOpAtomicCounterMin:
1791 case glslang::EOpAtomicCounterMax:
1792 case glslang::EOpAtomicCounterAnd:
1793 case glslang::EOpAtomicCounterOr:
1794 case glslang::EOpAtomicCounterXor:
1795 case glslang::EOpAtomicCounterExchange:
1796 case glslang::EOpAtomicCounterCompSwap:
1797 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
1798 builder.addCapability(spv::CapabilityAtomicStorageOps);
1799 atomic = true;
1800 break;
1801
John Kessenich140f3df2015-06-26 16:58:36 -06001802 default:
1803 break;
1804 }
1805
1806 //
1807 // See if it maps to a regular operation.
1808 //
John Kessenich140f3df2015-06-26 16:58:36 -06001809 if (binOp != glslang::EOpNull) {
1810 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1811 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1812 assert(left && right);
1813
1814 builder.clearAccessChain();
1815 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001816 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001817
1818 builder.clearAccessChain();
1819 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001820 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001821
John Kesseniche485c7a2017-05-31 18:50:53 -06001822 builder.setLine(node->getLoc().line);
qining25262b32016-05-06 17:25:16 -04001823 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001824 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001825 left->getType().getBasicType(), reduceComparison);
1826
1827 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001828 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001829 builder.clearAccessChain();
1830 builder.setAccessChainRValue(result);
1831
1832 return false;
1833 }
1834
John Kessenich426394d2015-07-23 10:22:48 -06001835 //
1836 // Create the list of operands.
1837 //
John Kessenich140f3df2015-06-26 16:58:36 -06001838 glslang::TIntermSequence& glslangOperands = node->getSequence();
1839 std::vector<spv::Id> operands;
1840 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001841 // special case l-value operands; there are just a few
1842 bool lvalue = false;
1843 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001844 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001845 case glslang::EOpModf:
1846 if (arg == 1)
1847 lvalue = true;
1848 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001849 case glslang::EOpInterpolateAtSample:
1850 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001851#ifdef AMD_EXTENSIONS
1852 case glslang::EOpInterpolateAtVertex:
1853#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001854 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001855 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001856
1857 // Does it need a swizzle inversion? If so, evaluation is inverted;
1858 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001859 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001860 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1861 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1862 }
Rex Xu7a26c172015-12-08 17:12:09 +08001863 break;
Rex Xud4782c12015-09-06 16:30:11 +08001864 case glslang::EOpAtomicAdd:
1865 case glslang::EOpAtomicMin:
1866 case glslang::EOpAtomicMax:
1867 case glslang::EOpAtomicAnd:
1868 case glslang::EOpAtomicOr:
1869 case glslang::EOpAtomicXor:
1870 case glslang::EOpAtomicExchange:
1871 case glslang::EOpAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06001872 case glslang::EOpAtomicCounterAdd:
1873 case glslang::EOpAtomicCounterSubtract:
1874 case glslang::EOpAtomicCounterMin:
1875 case glslang::EOpAtomicCounterMax:
1876 case glslang::EOpAtomicCounterAnd:
1877 case glslang::EOpAtomicCounterOr:
1878 case glslang::EOpAtomicCounterXor:
1879 case glslang::EOpAtomicCounterExchange:
1880 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08001881 if (arg == 0)
1882 lvalue = true;
1883 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001884 case glslang::EOpAddCarry:
1885 case glslang::EOpSubBorrow:
1886 if (arg == 2)
1887 lvalue = true;
1888 break;
1889 case glslang::EOpUMulExtended:
1890 case glslang::EOpIMulExtended:
1891 if (arg >= 2)
1892 lvalue = true;
1893 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001894 default:
1895 break;
1896 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001897 builder.clearAccessChain();
1898 if (invertedType != spv::NoType && arg == 0)
1899 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1900 else
1901 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001902 if (lvalue)
1903 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06001904 else {
1905 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07001906 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06001907 }
John Kessenich140f3df2015-06-26 16:58:36 -06001908 }
John Kessenich426394d2015-07-23 10:22:48 -06001909
John Kesseniche485c7a2017-05-31 18:50:53 -06001910 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06001911 if (atomic) {
1912 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001913 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001914 } else {
1915 // Pass through to generic operations.
1916 switch (glslangOperands.size()) {
1917 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001918 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001919 break;
1920 case 1:
qining25262b32016-05-06 17:25:16 -04001921 result = createUnaryOperation(
1922 node->getOp(), precision,
1923 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001924 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001925 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001926 break;
1927 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001928 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001929 break;
1930 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001931 if (invertedType)
1932 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001933 }
1934
1935 if (noReturnValue)
1936 return false;
1937
1938 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001939 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001940 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001941 } else {
1942 builder.clearAccessChain();
1943 builder.setAccessChainRValue(result);
1944 return false;
1945 }
1946}
1947
John Kessenich433e9ff2017-01-26 20:31:11 -07001948// This path handles both if-then-else and ?:
1949// The if-then-else has a node type of void, while
1950// ?: has either a void or a non-void node type
1951//
1952// Leaving the result, when not void:
1953// GLSL only has r-values as the result of a :?, but
1954// if we have an l-value, that can be more efficient if it will
1955// become the base of a complex r-value expression, because the
1956// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001957bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1958{
John Kessenich433e9ff2017-01-26 20:31:11 -07001959 // See if it simple and safe to generate OpSelect instead of using control flow.
1960 // Crucially, side effects must be avoided, and there are performance trade-offs.
1961 // Return true if good idea (and safe) for OpSelect, false otherwise.
1962 const auto selectPolicy = [&]() -> bool {
John Kessenich04794372017-03-01 13:49:11 -07001963 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
1964 node->getBasicType() == glslang::EbtVoid)
John Kessenich433e9ff2017-01-26 20:31:11 -07001965 return false;
1966
1967 if (node->getTrueBlock() == nullptr ||
1968 node->getFalseBlock() == nullptr)
1969 return false;
1970
1971 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
1972 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
1973
1974 // return true if a single operand to ? : is okay for OpSelect
1975 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001976 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07001977 };
1978
1979 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
1980 operandOkay(node->getFalseBlock()->getAsTyped());
1981 };
1982
1983 // Emit OpSelect for this selection.
1984 const auto handleAsOpSelect = [&]() {
1985 node->getCondition()->traverse(this);
1986 spv::Id condition = accessChainLoad(node->getCondition()->getType());
1987 node->getTrueBlock()->traverse(this);
1988 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1989 node->getFalseBlock()->traverse(this);
1990 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1991
John Kesseniche485c7a2017-05-31 18:50:53 -06001992 builder.setLine(node->getLoc().line);
1993
John Kesseniche434ad92017-03-30 10:09:28 -06001994 // smear condition to vector, if necessary (AST is always scalar)
1995 if (builder.isVector(trueValue))
1996 condition = builder.smearScalar(spv::NoPrecision, condition,
1997 builder.makeVectorType(builder.makeBoolType(),
1998 builder.getNumComponents(trueValue)));
1999
2000 spv::Id select = builder.createTriOp(spv::OpSelect,
2001 convertGlslangToSpvType(node->getType()), condition,
2002 trueValue, falseValue);
John Kessenich433e9ff2017-01-26 20:31:11 -07002003 builder.clearAccessChain();
2004 builder.setAccessChainRValue(select);
2005 };
2006
2007 // Try for OpSelect
2008
2009 if (selectPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002010 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2011 if (node->getType().getQualifier().isSpecConstant())
2012 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2013
John Kessenich433e9ff2017-01-26 20:31:11 -07002014 handleAsOpSelect();
2015 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06002016 }
2017
Rex Xu57e65922017-07-04 23:23:40 +08002018 // Instead, emit control flow...
John Kessenich433e9ff2017-01-26 20:31:11 -07002019 // Don't handle results as temporaries, because there will be two names
2020 // and better to leave SSA to later passes.
2021 spv::Id result = (node->getBasicType() == glslang::EbtVoid)
2022 ? spv::NoResult
2023 : builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2024
John Kessenich140f3df2015-06-26 16:58:36 -06002025 // emit the condition before doing anything with selection
2026 node->getCondition()->traverse(this);
2027
Rex Xu57e65922017-07-04 23:23:40 +08002028 // Selection control:
2029 const spv::SelectionControlMask control = TranslateSelectionControl(node->getSelectionControl());
2030
John Kessenich140f3df2015-06-26 16:58:36 -06002031 // make an "if" based on the value created by the condition
Rex Xu57e65922017-07-04 23:23:40 +08002032 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), control, builder);
John Kessenich140f3df2015-06-26 16:58:36 -06002033
John Kessenich433e9ff2017-01-26 20:31:11 -07002034 // emit the "then" statement
2035 if (node->getTrueBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06002036 node->getTrueBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07002037 if (result != spv::NoResult)
2038 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002039 }
2040
John Kessenich433e9ff2017-01-26 20:31:11 -07002041 if (node->getFalseBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06002042 ifBuilder.makeBeginElse();
2043 // emit the "else" statement
2044 node->getFalseBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07002045 if (result != spv::NoResult)
John Kessenich32cfd492016-02-02 12:37:46 -07002046 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002047 }
2048
John Kessenich433e9ff2017-01-26 20:31:11 -07002049 // finish off the control flow
John Kessenich140f3df2015-06-26 16:58:36 -06002050 ifBuilder.makeEndIf();
2051
John Kessenich433e9ff2017-01-26 20:31:11 -07002052 if (result != spv::NoResult) {
John Kessenich140f3df2015-06-26 16:58:36 -06002053 // GLSL only has r-values as the result of a :?, but
2054 // if we have an l-value, that can be more efficient if it will
2055 // become the base of a complex r-value expression, because the
2056 // next layer copies r-values into memory to use the access-chain mechanism
2057 builder.clearAccessChain();
2058 builder.setAccessChainLValue(result);
2059 }
2060
2061 return false;
2062}
2063
2064bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2065{
2066 // emit and get the condition before doing anything with switch
2067 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002068 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002069
Rex Xu57e65922017-07-04 23:23:40 +08002070 // Selection control:
2071 const spv::SelectionControlMask control = TranslateSelectionControl(node->getSelectionControl());
2072
John Kessenich140f3df2015-06-26 16:58:36 -06002073 // browse the children to sort out code segments
2074 int defaultSegment = -1;
2075 std::vector<TIntermNode*> codeSegments;
2076 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2077 std::vector<int> caseValues;
2078 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2079 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2080 TIntermNode* child = *c;
2081 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002082 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002083 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002084 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002085 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2086 } else
2087 codeSegments.push_back(child);
2088 }
2089
qining25262b32016-05-06 17:25:16 -04002090 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002091 // statements between the last case and the end of the switch statement
2092 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2093 (int)codeSegments.size() == defaultSegment)
2094 codeSegments.push_back(nullptr);
2095
2096 // make the switch statement
2097 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002098 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002099
2100 // emit all the code in the segments
2101 breakForLoop.push(false);
2102 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2103 builder.nextSwitchSegment(segmentBlocks, s);
2104 if (codeSegments[s])
2105 codeSegments[s]->traverse(this);
2106 else
2107 builder.addSwitchBreak();
2108 }
2109 breakForLoop.pop();
2110
2111 builder.endSwitch(segmentBlocks);
2112
2113 return false;
2114}
2115
2116void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2117{
2118 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002119 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002120
2121 builder.clearAccessChain();
2122 builder.setAccessChainRValue(constant);
2123}
2124
2125bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2126{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002127 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002128 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002129
2130 // Loop control:
2131 const spv::LoopControlMask control = TranslateLoopControl(node->getLoopControl());
2132
2133 // TODO: dependency length
2134
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002135 // Spec requires back edges to target header blocks, and every header block
2136 // must dominate its merge block. Make a header block first to ensure these
2137 // conditions are met. By definition, it will contain OpLoopMerge, followed
2138 // by a block-ending branch. But we don't want to put any other body/test
2139 // instructions in it, since the body/test may have arbitrary instructions,
2140 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002141 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002142 builder.setBuildPoint(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002143 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002144 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002145 spv::Block& test = builder.makeNewBlock();
2146 builder.createBranch(&test);
2147
2148 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002149 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002150 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002151 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2152
2153 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002154 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002155 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002156 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002157 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002158 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002159
2160 builder.setBuildPoint(&blocks.continue_target);
2161 if (node->getTerminal())
2162 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002163 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002164 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002165 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002166 builder.createBranch(&blocks.body);
2167
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002168 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002169 builder.setBuildPoint(&blocks.body);
2170 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002171 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002172 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002173 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002174
2175 builder.setBuildPoint(&blocks.continue_target);
2176 if (node->getTerminal())
2177 node->getTerminal()->traverse(this);
2178 if (node->getTest()) {
2179 node->getTest()->traverse(this);
2180 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002181 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002182 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002183 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002184 // TODO: unless there was a break/return/discard instruction
2185 // somewhere in the body, this is an infinite loop, so we should
2186 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002187 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002188 }
John Kessenich140f3df2015-06-26 16:58:36 -06002189 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002190 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002191 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002192 return false;
2193}
2194
2195bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2196{
2197 if (node->getExpression())
2198 node->getExpression()->traverse(this);
2199
John Kesseniche485c7a2017-05-31 18:50:53 -06002200 builder.setLine(node->getLoc().line);
2201
John Kessenich140f3df2015-06-26 16:58:36 -06002202 switch (node->getFlowOp()) {
2203 case glslang::EOpKill:
2204 builder.makeDiscard();
2205 break;
2206 case glslang::EOpBreak:
2207 if (breakForLoop.top())
2208 builder.createLoopExit();
2209 else
2210 builder.addSwitchBreak();
2211 break;
2212 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002213 builder.createLoopContinue();
2214 break;
2215 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002216 if (node->getExpression()) {
2217 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2218 spv::Id returnId = accessChainLoad(glslangReturnType);
2219 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2220 builder.clearAccessChain();
2221 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2222 builder.setAccessChainLValue(copyId);
2223 multiTypeStore(glslangReturnType, returnId);
2224 returnId = builder.createLoad(copyId);
2225 }
2226 builder.makeReturn(false, returnId);
2227 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002228 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002229
2230 builder.clearAccessChain();
2231 break;
2232
2233 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002234 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002235 break;
2236 }
2237
2238 return false;
2239}
2240
2241spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2242{
qining25262b32016-05-06 17:25:16 -04002243 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002244 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002245 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002246 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002247 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002248 }
2249
2250 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002251 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002252 spv::Id spvType = convertGlslangToSpvType(node->getType());
2253
Rex Xuf89ad982017-04-07 23:22:33 +08002254#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08002255 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2256 node->getType().containsBasicType(glslang::EbtInt16) ||
2257 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002258 if (contains16BitType) {
2259 if (storageClass == spv::StorageClassInput || storageClass == spv::StorageClassOutput) {
2260 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2261 builder.addCapability(spv::CapabilityStorageInputOutput16);
2262 } else if (storageClass == spv::StorageClassPushConstant) {
2263 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2264 builder.addCapability(spv::CapabilityStoragePushConstant16);
2265 } else if (storageClass == spv::StorageClassUniform) {
2266 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2267 builder.addCapability(spv::CapabilityStorageUniform16);
2268 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2269 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2270 }
2271 }
2272#endif
2273
John Kessenich140f3df2015-06-26 16:58:36 -06002274 const char* name = node->getName().c_str();
2275 if (glslang::IsAnonymous(name))
2276 name = "";
2277
2278 return builder.createVariable(storageClass, spvType, name);
2279}
2280
2281// Return type Id of the sampled type.
2282spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2283{
2284 switch (sampler.type) {
2285 case glslang::EbtFloat: return builder.makeFloatType(32);
2286 case glslang::EbtInt: return builder.makeIntType(32);
2287 case glslang::EbtUint: return builder.makeUintType(32);
2288 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002289 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002290 return builder.makeFloatType(32);
2291 }
2292}
2293
John Kessenich8c8505c2016-07-26 12:50:38 -06002294// If node is a swizzle operation, return the type that should be used if
2295// the swizzle base is first consumed by another operation, before the swizzle
2296// is applied.
2297spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2298{
John Kessenichecba76f2017-01-06 00:34:48 -07002299 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002300 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2301 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2302 else
2303 return spv::NoType;
2304}
2305
2306// When inverting a swizzle with a parent op, this function
2307// will apply the swizzle operation to a completed parent operation.
2308spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2309{
2310 std::vector<unsigned> swizzle;
2311 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2312 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2313}
2314
John Kessenich8c8505c2016-07-26 12:50:38 -06002315// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2316void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2317{
2318 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2319 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2320 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2321}
2322
John Kessenich3ac051e2015-12-20 11:29:16 -07002323// Convert from a glslang type to an SPV type, by calling into a
2324// recursive version of this function. This establishes the inherited
2325// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002326spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2327{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002328 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002329}
2330
2331// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002332// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002333// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002334spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002335{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002336 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002337
2338 switch (type.getBasicType()) {
2339 case glslang::EbtVoid:
2340 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002341 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002342 break;
2343 case glslang::EbtFloat:
2344 spvType = builder.makeFloatType(32);
2345 break;
2346 case glslang::EbtDouble:
2347 spvType = builder.makeFloatType(64);
2348 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002349#ifdef AMD_EXTENSIONS
2350 case glslang::EbtFloat16:
2351 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002352 spvType = builder.makeFloatType(16);
2353 break;
2354#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002355 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002356 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2357 // a 32-bit int where non-0 means true.
2358 if (explicitLayout != glslang::ElpNone)
2359 spvType = builder.makeUintType(32);
2360 else
2361 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002362 break;
2363 case glslang::EbtInt:
2364 spvType = builder.makeIntType(32);
2365 break;
2366 case glslang::EbtUint:
2367 spvType = builder.makeUintType(32);
2368 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002369 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002370 spvType = builder.makeIntType(64);
2371 break;
2372 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002373 spvType = builder.makeUintType(64);
2374 break;
Rex Xucabbb782017-03-24 13:41:14 +08002375#ifdef AMD_EXTENSIONS
2376 case glslang::EbtInt16:
2377 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2378 spvType = builder.makeIntType(16);
2379 break;
2380 case glslang::EbtUint16:
2381 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2382 spvType = builder.makeUintType(16);
2383 break;
2384#endif
John Kessenich426394d2015-07-23 10:22:48 -06002385 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002386 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002387 spvType = builder.makeUintType(32);
2388 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002389 case glslang::EbtSampler:
2390 {
2391 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002392 if (sampler.sampler) {
2393 // pure sampler
2394 spvType = builder.makeSamplerType();
2395 } else {
2396 // an image is present, make its type
2397 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2398 sampler.image ? 2 : 1, TranslateImageFormat(type));
2399 if (sampler.combined) {
2400 // already has both image and sampler, make the combined type
2401 spvType = builder.makeSampledImageType(spvType);
2402 }
John Kessenich55e7d112015-11-15 21:33:39 -07002403 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002404 }
John Kessenich140f3df2015-06-26 16:58:36 -06002405 break;
2406 case glslang::EbtStruct:
2407 case glslang::EbtBlock:
2408 {
2409 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002410 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002411
2412 // Try to share structs for different layouts, but not yet for other
2413 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002414 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002415 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002416 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002417 break;
2418
2419 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002420 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002421 memberRemapper[glslangMembers].resize(glslangMembers->size());
2422 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002423 }
2424 break;
2425 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002426 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002427 break;
2428 }
2429
2430 if (type.isMatrix())
2431 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2432 else {
2433 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2434 if (type.getVectorSize() > 1)
2435 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2436 }
2437
2438 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002439 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2440
John Kessenichc9a80832015-09-12 12:17:44 -06002441 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002442 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002443 // We need to decorate array strides for types needing explicit layout, except blocks.
2444 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002445 // Use a dummy glslang type for querying internal strides of
2446 // arrays of arrays, but using just a one-dimensional array.
2447 glslang::TType simpleArrayType(type, 0); // deference type of the array
2448 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2449 simpleArrayType.getArraySizes().dereference();
2450
2451 // Will compute the higher-order strides here, rather than making a whole
2452 // pile of types and doing repetitive recursion on their contents.
2453 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2454 }
John Kessenichf8842e52016-01-04 19:22:56 -07002455
2456 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002457 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002458 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002459 if (stride > 0)
2460 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002461 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002462 }
2463 } else {
2464 // single-dimensional array, and don't yet have stride
2465
John Kessenichf8842e52016-01-04 19:22:56 -07002466 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002467 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2468 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002469 }
John Kessenich31ed4832015-09-09 17:51:38 -06002470
John Kessenichc9a80832015-09-12 12:17:44 -06002471 // Do the outer dimension, which might not be known for a runtime-sized array
2472 if (type.isRuntimeSizedArray()) {
2473 spvType = builder.makeRuntimeArray(spvType);
2474 } else {
2475 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002476 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002477 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002478 if (stride > 0)
2479 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002480 }
2481
2482 return spvType;
2483}
2484
John Kessenich0e737842017-03-24 18:38:16 -06002485// TODO: this functionality should exist at a higher level, in creating the AST
2486//
2487// Identify interface members that don't have their required extension turned on.
2488//
2489bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2490{
2491 auto& extensions = glslangIntermediate->getRequestedExtensions();
2492
Rex Xubcf291a2017-03-29 23:01:36 +08002493 if (member.getFieldName() == "gl_ViewportMask" &&
2494 extensions.find("GL_NV_viewport_array2") == extensions.end())
2495 return true;
2496 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2497 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2498 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002499 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2500 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2501 return true;
2502 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2503 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2504 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002505 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2506 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2507 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002508
2509 return false;
2510};
2511
John Kessenich6090df02016-06-30 21:18:02 -06002512// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2513// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2514// Mutually recursive with convertGlslangToSpvType().
2515spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2516 const glslang::TTypeList* glslangMembers,
2517 glslang::TLayoutPacking explicitLayout,
2518 const glslang::TQualifier& qualifier)
2519{
2520 // Create a vector of struct types for SPIR-V to consume
2521 std::vector<spv::Id> spvMembers;
2522 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
John Kessenich6090df02016-06-30 21:18:02 -06002523 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2524 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2525 if (glslangMember.hiddenMember()) {
2526 ++memberDelta;
2527 if (type.getBasicType() == glslang::EbtBlock)
2528 memberRemapper[glslangMembers][i] = -1;
2529 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002530 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002531 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002532 if (filterMember(glslangMember))
2533 continue;
2534 }
John Kessenich6090df02016-06-30 21:18:02 -06002535 // modify just this child's view of the qualifier
2536 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2537 InheritQualifiers(memberQualifier, qualifier);
2538
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002539 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06002540 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002541 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06002542
2543 // recurse
2544 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2545 }
2546 }
2547
2548 // Make the SPIR-V type
2549 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002550 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002551 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2552
2553 // Decorate it
2554 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2555
2556 return spvType;
2557}
2558
2559void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2560 const glslang::TTypeList* glslangMembers,
2561 glslang::TLayoutPacking explicitLayout,
2562 const glslang::TQualifier& qualifier,
2563 spv::Id spvType)
2564{
2565 // Name and decorate the non-hidden members
2566 int offset = -1;
2567 int locationOffset = 0; // for use within the members of this struct
2568 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2569 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2570 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002571 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002572 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002573 if (filterMember(glslangMember))
2574 continue;
2575 }
John Kessenich6090df02016-06-30 21:18:02 -06002576
2577 // modify just this child's view of the qualifier
2578 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2579 InheritQualifiers(memberQualifier, qualifier);
2580
2581 // using -1 above to indicate a hidden member
2582 if (member >= 0) {
2583 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2584 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2585 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2586 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002587 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2588 type.getQualifier().storage == glslang::EvqVaryingOut) {
2589 if (type.getBasicType() == glslang::EbtBlock ||
2590 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002591 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2592 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2593 }
2594 }
2595 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2596
Rex Xu286ca432017-07-27 14:33:16 +08002597 if (type.getBasicType() == glslang::EbtBlock &&
2598 qualifier.storage == glslang::EvqBuffer) {
2599 // Add memory decorations only to top-level members of shader storage block
John Kessenich6090df02016-06-30 21:18:02 -06002600 std::vector<spv::Decoration> memory;
2601 TranslateMemoryDecoration(memberQualifier, memory);
2602 for (unsigned int i = 0; i < memory.size(); ++i)
2603 addMemberDecoration(spvType, member, memory[i]);
2604 }
2605
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002606 // Location assignment was already completed correctly by the front end,
2607 // just track whether a member needs to be decorated.
John Kessenich2f47bc92016-06-30 21:47:35 -06002608 // Ignore member locations if the container is an array, as that's
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002609 // ill-specified and decisions have been made to not allow this.
2610 if (! type.isArray() && memberQualifier.hasLocation())
2611 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06002612
John Kessenich2f47bc92016-06-30 21:47:35 -06002613 if (qualifier.hasLocation()) // track for upcoming inheritance
2614 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2615
John Kessenich6090df02016-06-30 21:18:02 -06002616 // component, XFB, others
2617 if (glslangMember.getQualifier().hasComponent())
2618 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2619 if (glslangMember.getQualifier().hasXfbOffset())
2620 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2621 else if (explicitLayout != glslang::ElpNone) {
2622 // figure out what to do with offset, which is accumulating
2623 int nextOffset;
2624 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2625 if (offset >= 0)
2626 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2627 offset = nextOffset;
2628 }
2629
2630 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2631 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2632
2633 // built-in variable decorations
2634 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002635 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002636 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002637
2638#ifdef NV_EXTENSIONS
2639 if (builtIn == spv::BuiltInLayer) {
2640 // SPV_NV_viewport_array2 extension
2641 if (glslangMember.getQualifier().layoutViewportRelative){
2642 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2643 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2644 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2645 }
2646 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2647 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2648 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2649 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2650 }
2651 }
chaocdf3956c2017-02-14 14:52:34 -08002652 if (glslangMember.getQualifier().layoutPassthrough) {
2653 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2654 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2655 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2656 }
chaoc771d89f2017-01-13 01:10:53 -08002657#endif
John Kessenich6090df02016-06-30 21:18:02 -06002658 }
2659 }
2660
2661 // Decorate the structure
2662 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich67027182017-04-19 18:34:49 -06002663 addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002664 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2665 builder.addCapability(spv::CapabilityGeometryStreams);
2666 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2667 }
John Kessenich6090df02016-06-30 21:18:02 -06002668}
2669
John Kessenich6c292d32016-02-15 20:58:50 -07002670// Turn the expression forming the array size into an id.
2671// This is not quite trivial, because of specialization constants.
2672// Sometimes, a raw constant is turned into an Id, and sometimes
2673// a specialization constant expression is.
2674spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2675{
2676 // First, see if this is sized with a node, meaning a specialization constant:
2677 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2678 if (specNode != nullptr) {
2679 builder.clearAccessChain();
2680 specNode->traverse(this);
2681 return accessChainLoad(specNode->getAsTyped()->getType());
2682 }
qining25262b32016-05-06 17:25:16 -04002683
John Kessenich6c292d32016-02-15 20:58:50 -07002684 // Otherwise, need a compile-time (front end) size, get it:
2685 int size = arraySizes.getDimSize(dim);
2686 assert(size > 0);
2687 return builder.makeUintConstant(size);
2688}
2689
John Kessenich103bef92016-02-08 21:38:15 -07002690// Wrap the builder's accessChainLoad to:
2691// - localize handling of RelaxedPrecision
2692// - use the SPIR-V inferred type instead of another conversion of the glslang type
2693// (avoids unnecessary work and possible type punning for structures)
2694// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002695spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2696{
John Kessenich103bef92016-02-08 21:38:15 -07002697 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2698 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2699
2700 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002701 if (type.getBasicType() == glslang::EbtBool) {
2702 if (builder.isScalarType(nominalTypeId)) {
2703 // Conversion for bool
2704 spv::Id boolType = builder.makeBoolType();
2705 if (nominalTypeId != boolType)
2706 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2707 } else if (builder.isVectorType(nominalTypeId)) {
2708 // Conversion for bvec
2709 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2710 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2711 if (nominalTypeId != bvecType)
2712 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2713 }
2714 }
John Kessenich103bef92016-02-08 21:38:15 -07002715
2716 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002717}
2718
Rex Xu27253232016-02-23 17:51:09 +08002719// Wrap the builder's accessChainStore to:
2720// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002721//
2722// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002723void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2724{
2725 // Need to convert to abstract types when necessary
2726 if (type.getBasicType() == glslang::EbtBool) {
2727 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2728
2729 if (builder.isScalarType(nominalTypeId)) {
2730 // Conversion for bool
2731 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06002732 if (nominalTypeId != boolType) {
2733 // keep these outside arguments, for determinant order-of-evaluation
2734 spv::Id one = builder.makeUintConstant(1);
2735 spv::Id zero = builder.makeUintConstant(0);
2736 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2737 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06002738 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08002739 } else if (builder.isVectorType(nominalTypeId)) {
2740 // Conversion for bvec
2741 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2742 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06002743 if (nominalTypeId != bvecType) {
2744 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06002745 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2746 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2747 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06002748 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06002749 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
2750 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08002751 }
2752 }
2753
2754 builder.accessChainStore(rvalue);
2755}
2756
John Kessenich4bf71552016-09-02 11:20:21 -06002757// For storing when types match at the glslang level, but not might match at the
2758// SPIR-V level.
2759//
2760// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002761// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002762// as in a member-decorated way.
2763//
2764// NOTE: This function can handle any store request; if it's not special it
2765// simplifies to a simple OpStore.
2766//
2767// Implicitly uses the existing builder.accessChain as the storage target.
2768void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2769{
John Kessenichb3e24e42016-09-11 12:33:43 -06002770 // we only do the complex path here if it's an aggregate
2771 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002772 accessChainStore(type, rValue);
2773 return;
2774 }
2775
John Kessenichb3e24e42016-09-11 12:33:43 -06002776 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002777 spv::Id rType = builder.getTypeId(rValue);
2778 spv::Id lValue = builder.accessChainGetLValue();
2779 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2780 if (lType == rType) {
2781 accessChainStore(type, rValue);
2782 return;
2783 }
2784
John Kessenichb3e24e42016-09-11 12:33:43 -06002785 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002786 // where the two types were the same type in GLSL. This requires member
2787 // by member copy, recursively.
2788
John Kessenichb3e24e42016-09-11 12:33:43 -06002789 // If an array, copy element by element.
2790 if (type.isArray()) {
2791 glslang::TType glslangElementType(type, 0);
2792 spv::Id elementRType = builder.getContainedTypeId(rType);
2793 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2794 // get the source member
2795 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002796
John Kessenichb3e24e42016-09-11 12:33:43 -06002797 // set up the target storage
2798 builder.clearAccessChain();
2799 builder.setAccessChainLValue(lValue);
2800 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002801
John Kessenichb3e24e42016-09-11 12:33:43 -06002802 // store the member
2803 multiTypeStore(glslangElementType, elementRValue);
2804 }
2805 } else {
2806 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002807
John Kessenichb3e24e42016-09-11 12:33:43 -06002808 // loop over structure members
2809 const glslang::TTypeList& members = *type.getStruct();
2810 for (int m = 0; m < (int)members.size(); ++m) {
2811 const glslang::TType& glslangMemberType = *members[m].type;
2812
2813 // get the source member
2814 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2815 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2816
2817 // set up the target storage
2818 builder.clearAccessChain();
2819 builder.setAccessChainLValue(lValue);
2820 builder.accessChainPush(builder.makeIntConstant(m));
2821
2822 // store the member
2823 multiTypeStore(glslangMemberType, memberRValue);
2824 }
John Kessenich4bf71552016-09-02 11:20:21 -06002825 }
2826}
2827
John Kessenichf85e8062015-12-19 13:57:10 -07002828// Decide whether or not this type should be
2829// decorated with offsets and strides, and if so
2830// whether std140 or std430 rules should be applied.
2831glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002832{
John Kessenichf85e8062015-12-19 13:57:10 -07002833 // has to be a block
2834 if (type.getBasicType() != glslang::EbtBlock)
2835 return glslang::ElpNone;
2836
2837 // has to be a uniform or buffer block
2838 if (type.getQualifier().storage != glslang::EvqUniform &&
2839 type.getQualifier().storage != glslang::EvqBuffer)
2840 return glslang::ElpNone;
2841
2842 // return the layout to use
2843 switch (type.getQualifier().layoutPacking) {
2844 case glslang::ElpStd140:
2845 case glslang::ElpStd430:
2846 return type.getQualifier().layoutPacking;
2847 default:
2848 return glslang::ElpNone;
2849 }
John Kessenich31ed4832015-09-09 17:51:38 -06002850}
2851
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002852// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002853int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002854{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002855 int size;
John Kessenich49987892015-12-29 17:11:44 -07002856 int stride;
2857 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002858
2859 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002860}
2861
John Kessenich49987892015-12-29 17:11:44 -07002862// 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 -07002863// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002864int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002865{
John Kessenich49987892015-12-29 17:11:44 -07002866 glslang::TType elementType;
2867 elementType.shallowCopy(matrixType);
2868 elementType.clearArraySizes();
2869
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002870 int size;
John Kessenich49987892015-12-29 17:11:44 -07002871 int stride;
2872 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2873
2874 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002875}
2876
John Kessenich5e4b1242015-08-06 22:53:06 -06002877// Given a member type of a struct, realign the current offset for it, and compute
2878// the next (not yet aligned) offset for the next member, which will get aligned
2879// on the next call.
2880// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2881// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2882// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06002883void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002884 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002885{
2886 // this will get a positive value when deemed necessary
2887 nextOffset = -1;
2888
John Kessenich5e4b1242015-08-06 22:53:06 -06002889 // override anything in currentOffset with user-set offset
2890 if (memberType.getQualifier().hasOffset())
2891 currentOffset = memberType.getQualifier().layoutOffset;
2892
2893 // It could be that current linker usage in glslang updated all the layoutOffset,
2894 // in which case the following code does not matter. But, that's not quite right
2895 // once cross-compilation unit GLSL validation is done, as the original user
2896 // settings are needed in layoutOffset, and then the following will come into play.
2897
John Kessenichf85e8062015-12-19 13:57:10 -07002898 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002899 if (! memberType.getQualifier().hasOffset())
2900 currentOffset = -1;
2901
2902 return;
2903 }
2904
John Kessenichf85e8062015-12-19 13:57:10 -07002905 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002906 if (currentOffset < 0)
2907 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002908
John Kessenich5e4b1242015-08-06 22:53:06 -06002909 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2910 // but possibly not yet correctly aligned.
2911
2912 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002913 int dummyStride;
2914 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06002915
2916 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06002917 // TODO: make this consistent in early phases of code:
2918 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
2919 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
2920 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kessenich4f1403e2017-04-05 17:38:20 -06002921 if (glslangIntermediate->usingHlslOFfsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06002922 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06002923 int dummySize;
2924 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
2925 if (componentAlignment <= 4)
2926 memberAlignment = componentAlignment;
2927 }
2928
2929 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06002930 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06002931
2932 // Bump up to vec4 if there is a bad straddle
2933 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
2934 glslang::RoundToPow2(currentOffset, 16);
2935
John Kessenich5e4b1242015-08-06 22:53:06 -06002936 nextOffset = currentOffset + memberSize;
2937}
2938
David Netoa901ffe2016-06-08 14:11:40 +01002939void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002940{
David Netoa901ffe2016-06-08 14:11:40 +01002941 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2942 switch (glslangBuiltIn)
2943 {
2944 case glslang::EbvClipDistance:
2945 case glslang::EbvCullDistance:
2946 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08002947#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08002948 case glslang::EbvViewportMaskNV:
2949 case glslang::EbvSecondaryPositionNV:
2950 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08002951 case glslang::EbvPositionPerViewNV:
2952 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08002953#endif
David Netoa901ffe2016-06-08 14:11:40 +01002954 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2955 // Alternately, we could just call this for any glslang built-in, since the
2956 // capability already guards against duplicates.
2957 TranslateBuiltInDecoration(glslangBuiltIn, false);
2958 break;
2959 default:
2960 // Capabilities were already generated when the struct was declared.
2961 break;
2962 }
John Kessenichebb50532016-05-16 19:22:05 -06002963}
2964
John Kessenich6fccb3c2016-09-19 16:01:41 -06002965bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002966{
John Kessenicheee9d532016-09-19 18:09:30 -06002967 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002968}
2969
John Kessenichd41993d2017-09-10 15:21:05 -06002970// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07002971// Assumes called after originalParam(), which filters out block/buffer/opaque-based
2972// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd41993d2017-09-10 15:21:05 -06002973bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier)
2974{
John Kessenich6a14f782017-12-04 02:48:10 -07002975 assert(qualifier == glslang::EvqIn ||
2976 qualifier == glslang::EvqOut ||
2977 qualifier == glslang::EvqInOut ||
2978 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06002979 return qualifier != glslang::EvqConstReadOnly;
2980}
2981
2982// Is parameter pass-by-original?
2983bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
2984 bool implicitThisParam)
2985{
2986 if (implicitThisParam) // implicit this
2987 return true;
2988 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07002989 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06002990 return paramType.containsOpaque() || // sampler, etc.
2991 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
2992}
2993
John Kessenich140f3df2015-06-26 16:58:36 -06002994// Make all the functions, skeletally, without actually visiting their bodies.
2995void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2996{
John Kessenichfad62972017-07-18 02:35:46 -06002997 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type) {
2998 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
2999 if (paramPrecision != spv::NoPrecision)
3000 decorations.push_back(paramPrecision);
John Kessenich961cd352017-07-18 02:58:06 -06003001 TranslateMemoryDecoration(type.getQualifier(), decorations);
John Kessenichfad62972017-07-18 02:35:46 -06003002 };
3003
John Kessenich140f3df2015-06-26 16:58:36 -06003004 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3005 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003006 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003007 continue;
3008
3009 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003010 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003011 //
qining25262b32016-05-06 17:25:16 -04003012 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003013 // function. What it is an address of varies:
3014 //
John Kessenich4bf71552016-09-02 11:20:21 -06003015 // - "in" parameters not marked as "const" can be written to without modifying the calling
3016 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003017 //
3018 // - "const in" parameters can just be the r-value, as no writes need occur.
3019 //
John Kessenich4bf71552016-09-02 11:20:21 -06003020 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3021 // 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 -06003022
3023 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003024 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003025 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3026
John Kessenichfad62972017-07-18 02:35:46 -06003027 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3028 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003029
John Kessenichfad62972017-07-18 02:35:46 -06003030 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003031 for (int p = 0; p < (int)parameters.size(); ++p) {
3032 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3033 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003034 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003035 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003036 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003037 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3038 else
John Kessenich4bf71552016-09-02 11:20:21 -06003039 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenichfad62972017-07-18 02:35:46 -06003040 getParamDecorations(paramDecorations[p], paramType);
John Kessenich140f3df2015-06-26 16:58:36 -06003041 paramTypes.push_back(typeId);
3042 }
3043
3044 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003045 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3046 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003047 glslFunction->getName().c_str(), paramTypes,
3048 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003049 if (implicitThis)
3050 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003051
3052 // Track function to emit/call later
3053 functionMap[glslFunction->getName().c_str()] = function;
3054
3055 // Set the parameter id's
3056 for (int p = 0; p < (int)parameters.size(); ++p) {
3057 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3058 // give a name too
3059 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3060 }
3061 }
3062}
3063
3064// Process all the initializers, while skipping the functions and link objects
3065void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3066{
3067 builder.setBuildPoint(shaderEntry->getLastBlock());
3068 for (int i = 0; i < (int)initializers.size(); ++i) {
3069 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3070 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3071
3072 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003073 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003074 initializer->traverse(this);
3075 }
3076 }
3077}
3078
3079// Process all the functions, while skipping initializers.
3080void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3081{
3082 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3083 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003084 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003085 node->traverse(this);
3086 }
3087}
3088
3089void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3090{
qining25262b32016-05-06 17:25:16 -04003091 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003092 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003093 currentFunction = functionMap[node->getName().c_str()];
3094 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003095 builder.setBuildPoint(functionBlock);
3096}
3097
Rex Xu04db3f52015-09-16 11:44:02 +08003098void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003099{
Rex Xufc618912015-09-09 16:42:49 +08003100 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003101
3102 glslang::TSampler sampler = {};
3103 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08003104 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003105 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3106 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3107 }
3108
John Kessenich140f3df2015-06-26 16:58:36 -06003109 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3110 builder.clearAccessChain();
3111 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003112
3113 // Special case l-value operands
3114 bool lvalue = false;
3115 switch (node.getOp()) {
3116 case glslang::EOpImageAtomicAdd:
3117 case glslang::EOpImageAtomicMin:
3118 case glslang::EOpImageAtomicMax:
3119 case glslang::EOpImageAtomicAnd:
3120 case glslang::EOpImageAtomicOr:
3121 case glslang::EOpImageAtomicXor:
3122 case glslang::EOpImageAtomicExchange:
3123 case glslang::EOpImageAtomicCompSwap:
3124 if (i == 0)
3125 lvalue = true;
3126 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003127 case glslang::EOpSparseImageLoad:
3128 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3129 lvalue = true;
3130 break;
Rex Xu48edadf2015-12-31 16:11:41 +08003131 case glslang::EOpSparseTexture:
3132 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3133 lvalue = true;
3134 break;
3135 case glslang::EOpSparseTextureClamp:
3136 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3137 lvalue = true;
3138 break;
3139 case glslang::EOpSparseTextureLod:
3140 case glslang::EOpSparseTextureOffset:
3141 if (i == 3)
3142 lvalue = true;
3143 break;
3144 case glslang::EOpSparseTextureFetch:
3145 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3146 lvalue = true;
3147 break;
3148 case glslang::EOpSparseTextureFetchOffset:
3149 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3150 lvalue = true;
3151 break;
3152 case glslang::EOpSparseTextureLodOffset:
3153 case glslang::EOpSparseTextureGrad:
3154 case glslang::EOpSparseTextureOffsetClamp:
3155 if (i == 4)
3156 lvalue = true;
3157 break;
3158 case glslang::EOpSparseTextureGradOffset:
3159 case glslang::EOpSparseTextureGradClamp:
3160 if (i == 5)
3161 lvalue = true;
3162 break;
3163 case glslang::EOpSparseTextureGradOffsetClamp:
3164 if (i == 6)
3165 lvalue = true;
3166 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003167 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003168 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3169 lvalue = true;
3170 break;
3171 case glslang::EOpSparseTextureGatherOffset:
3172 case glslang::EOpSparseTextureGatherOffsets:
3173 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3174 lvalue = true;
3175 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003176#ifdef AMD_EXTENSIONS
3177 case glslang::EOpSparseTextureGatherLod:
3178 if (i == 3)
3179 lvalue = true;
3180 break;
3181 case glslang::EOpSparseTextureGatherLodOffset:
3182 case glslang::EOpSparseTextureGatherLodOffsets:
3183 if (i == 4)
3184 lvalue = true;
3185 break;
Rex Xu129799a2017-07-05 17:23:28 +08003186 case glslang::EOpSparseImageLoadLod:
3187 if (i == 3)
3188 lvalue = true;
3189 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003190#endif
Rex Xufc618912015-09-09 16:42:49 +08003191 default:
3192 break;
3193 }
3194
Rex Xu6b86d492015-09-16 17:48:22 +08003195 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003196 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003197 else
John Kessenich32cfd492016-02-02 12:37:46 -07003198 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003199 }
3200}
3201
John Kessenichfc51d282015-08-19 13:34:18 -06003202void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003203{
John Kessenichfc51d282015-08-19 13:34:18 -06003204 builder.clearAccessChain();
3205 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003206 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003207}
John Kessenich140f3df2015-06-26 16:58:36 -06003208
John Kessenichfc51d282015-08-19 13:34:18 -06003209spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3210{
John Kesseniche485c7a2017-05-31 18:50:53 -06003211 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003212 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003213
3214 builder.setLine(node->getLoc().line);
3215
John Kessenich8c8505c2016-07-26 12:50:38 -06003216 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06003217
John Kessenichfc51d282015-08-19 13:34:18 -06003218 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003219 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3220 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
3221 std::vector<spv::Id> arguments;
3222 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003223 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003224 else
3225 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003226 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003227
3228 spv::Builder::TextureParameters params = { };
3229 params.sampler = arguments[0];
3230
Rex Xu04db3f52015-09-16 11:44:02 +08003231 glslang::TCrackedTextureOp cracked;
3232 node->crackTexture(sampler, cracked);
3233
amhagan05506bb2017-06-13 16:53:02 -04003234 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003235
John Kessenichfc51d282015-08-19 13:34:18 -06003236 // Check for queries
3237 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003238 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3239 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003240 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003241
John Kessenichfc51d282015-08-19 13:34:18 -06003242 switch (node->getOp()) {
3243 case glslang::EOpImageQuerySize:
3244 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003245 if (arguments.size() > 1) {
3246 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003247 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003248 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003249 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003250 case glslang::EOpImageQuerySamples:
3251 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003252 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003253 case glslang::EOpTextureQueryLod:
3254 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003255 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003256 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003257 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003258 case glslang::EOpSparseTexelsResident:
3259 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003260 default:
3261 assert(0);
3262 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003263 }
John Kessenich140f3df2015-06-26 16:58:36 -06003264 }
3265
Rex Xufc618912015-09-09 16:42:49 +08003266 // Check for image functions other than queries
3267 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003268 std::vector<spv::Id> operands;
3269 auto opIt = arguments.begin();
3270 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003271
3272 // Handle subpass operations
3273 // TODO: GLSL should change to have the "MS" only on the type rather than the
3274 // built-in function.
3275 if (cracked.subpass) {
3276 // add on the (0,0) coordinate
3277 spv::Id zero = builder.makeIntConstant(0);
3278 std::vector<spv::Id> comps;
3279 comps.push_back(zero);
3280 comps.push_back(zero);
3281 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3282 if (sampler.ms) {
3283 operands.push_back(spv::ImageOperandsSampleMask);
3284 operands.push_back(*(opIt++));
3285 }
John Kessenichfe4e5722017-10-19 02:07:30 -06003286 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
3287 builder.setPrecision(result, precision);
3288 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07003289 }
3290
John Kessenich56bab042015-09-16 10:54:31 -06003291 operands.push_back(*(opIt++));
Rex Xu129799a2017-07-05 17:23:28 +08003292#ifdef AMD_EXTENSIONS
3293 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
3294#else
John Kessenich56bab042015-09-16 10:54:31 -06003295 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003296#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003297 if (sampler.ms) {
3298 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003299 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003300#ifdef AMD_EXTENSIONS
3301 } else if (cracked.lod) {
3302 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3303 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3304
3305 operands.push_back(spv::ImageOperandsLodMask);
3306 operands.push_back(*opIt);
3307#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003308 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003309 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3310 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06003311
3312 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
3313 builder.setPrecision(result, precision);
3314 return result;
Rex Xu129799a2017-07-05 17:23:28 +08003315#ifdef AMD_EXTENSIONS
3316 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
3317#else
John Kessenich56bab042015-09-16 10:54:31 -06003318 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08003319#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003320 if (sampler.ms) {
3321 operands.push_back(*(opIt + 1));
3322 operands.push_back(spv::ImageOperandsSampleMask);
3323 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003324#ifdef AMD_EXTENSIONS
3325 } else if (cracked.lod) {
3326 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3327 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3328
3329 operands.push_back(*(opIt + 1));
3330 operands.push_back(spv::ImageOperandsLodMask);
3331 operands.push_back(*opIt);
3332#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003333 } else
3334 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003335 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003336 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3337 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003338 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08003339#ifdef AMD_EXTENSIONS
3340 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
3341#else
Rex Xu5eafa472016-02-19 22:24:03 +08003342 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003343#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003344 builder.addCapability(spv::CapabilitySparseResidency);
3345 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3346 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3347
3348 if (sampler.ms) {
3349 operands.push_back(spv::ImageOperandsSampleMask);
3350 operands.push_back(*opIt++);
Rex Xu129799a2017-07-05 17:23:28 +08003351#ifdef AMD_EXTENSIONS
3352 } else if (cracked.lod) {
3353 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3354 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3355
3356 operands.push_back(spv::ImageOperandsLodMask);
3357 operands.push_back(*opIt++);
3358#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003359 }
3360
3361 // Create the return type that was a special structure
3362 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003363 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003364 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3365 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3366
3367 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3368
3369 // Decode the return type
3370 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3371 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003372 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003373 // Process image atomic operations
3374
3375 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3376 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003377 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003378
John Kessenich8c8505c2016-07-26 12:50:38 -06003379 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003380 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003381
3382 std::vector<spv::Id> operands;
3383 operands.push_back(pointer);
3384 for (; opIt != arguments.end(); ++opIt)
3385 operands.push_back(*opIt);
3386
John Kessenich8c8505c2016-07-26 12:50:38 -06003387 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003388 }
3389 }
3390
amhagan05506bb2017-06-13 16:53:02 -04003391#ifdef AMD_EXTENSIONS
3392 // Check for fragment mask functions other than queries
3393 if (cracked.fragMask) {
3394 assert(sampler.ms);
3395
3396 auto opIt = arguments.begin();
3397 std::vector<spv::Id> operands;
3398
3399 // Extract the image if necessary
3400 if (builder.isSampledImage(params.sampler))
3401 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3402
3403 operands.push_back(params.sampler);
3404 ++opIt;
3405
3406 if (sampler.isSubpass()) {
3407 // add on the (0,0) coordinate
3408 spv::Id zero = builder.makeIntConstant(0);
3409 std::vector<spv::Id> comps;
3410 comps.push_back(zero);
3411 comps.push_back(zero);
3412 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3413 }
3414
3415 for (; opIt != arguments.end(); ++opIt)
3416 operands.push_back(*opIt);
3417
3418 spv::Op fragMaskOp = spv::OpNop;
3419 if (node->getOp() == glslang::EOpFragmentMaskFetch)
3420 fragMaskOp = spv::OpFragmentMaskFetchAMD;
3421 else if (node->getOp() == glslang::EOpFragmentFetch)
3422 fragMaskOp = spv::OpFragmentFetchAMD;
3423
3424 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
3425 builder.addCapability(spv::CapabilityFragmentMaskAMD);
3426 return builder.createOp(fragMaskOp, resultType(), operands);
3427 }
3428#endif
3429
Rex Xufc618912015-09-09 16:42:49 +08003430 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003431 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003432 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3433
John Kessenichfc51d282015-08-19 13:34:18 -06003434 // check for bias argument
3435 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08003436#ifdef AMD_EXTENSIONS
3437 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
3438#else
Rex Xu71519fe2015-11-11 15:35:47 +08003439 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08003440#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003441 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08003442#ifdef AMD_EXTENSIONS
3443 if (cracked.gather)
3444 ++nonBiasArgCount; // comp argument should be present when bias argument is present
3445#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003446 if (cracked.offset)
3447 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003448#ifdef AMD_EXTENSIONS
3449 else if (cracked.offsets)
3450 ++nonBiasArgCount;
3451#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003452 if (cracked.grad)
3453 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003454 if (cracked.lodClamp)
3455 ++nonBiasArgCount;
3456 if (sparse)
3457 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003458
3459 if ((int)arguments.size() > nonBiasArgCount)
3460 bias = true;
3461 }
3462
John Kessenicha5c33d62016-06-02 23:45:21 -06003463 // See if the sampler param should really be just the SPV image part
3464 if (cracked.fetch) {
3465 // a fetch needs to have the image extracted first
3466 if (builder.isSampledImage(params.sampler))
3467 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3468 }
3469
Rex Xu225e0fc2016-11-17 17:47:59 +08003470#ifdef AMD_EXTENSIONS
3471 if (cracked.gather) {
3472 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
3473 if (bias || cracked.lod ||
3474 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
3475 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08003476 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08003477 }
3478 }
3479#endif
3480
John Kessenichfc51d282015-08-19 13:34:18 -06003481 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003482
John Kessenichfc51d282015-08-19 13:34:18 -06003483 params.coords = arguments[1];
3484 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003485 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003486
3487 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003488 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003489 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003490 ++extraArgs;
3491 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003492 params.Dref = arguments[2];
3493 ++extraArgs;
3494 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003495 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003496 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003497 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003498 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003499 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003500 dRefComp = builder.getNumComponents(params.coords) - 1;
3501 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003502 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3503 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003504
3505 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003506 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003507 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06003508 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003509 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3510 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3511 noImplicitLod = true;
3512 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003513
3514 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003515 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003516 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003517 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003518 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003519
3520 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003521 if (cracked.grad) {
3522 params.gradX = arguments[2 + extraArgs];
3523 params.gradY = arguments[3 + extraArgs];
3524 extraArgs += 2;
3525 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003526
3527 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003528 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003529 params.offset = arguments[2 + extraArgs];
3530 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003531 } else if (cracked.offsets) {
3532 params.offsets = arguments[2 + extraArgs];
3533 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003534 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003535
3536 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003537 if (cracked.lodClamp) {
3538 params.lodClamp = arguments[2 + extraArgs];
3539 ++extraArgs;
3540 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003541
3542 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003543 if (sparse) {
3544 params.texelOut = arguments[2 + extraArgs];
3545 ++extraArgs;
3546 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003547
John Kessenich76d4dfc2016-06-16 12:43:23 -06003548 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003549 if (cracked.gather && ! sampler.shadow) {
3550 // default component is 0, if missing, otherwise an argument
3551 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003552 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003553 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08003554 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003555 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08003556 }
3557
3558 // bias
3559 if (bias) {
3560 params.bias = arguments[2 + extraArgs];
3561 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003562 }
John Kessenichfc51d282015-08-19 13:34:18 -06003563
John Kessenich65336482016-06-16 14:06:26 -06003564 // projective component (might not to move)
3565 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3566 // are divided by the last component of P."
3567 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3568 // unused components will appear after all used components."
3569 if (cracked.proj) {
3570 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3571 int projTargetComp;
3572 switch (sampler.dim) {
3573 case glslang::Esd1D: projTargetComp = 1; break;
3574 case glslang::Esd2D: projTargetComp = 2; break;
3575 case glslang::EsdRect: projTargetComp = 2; break;
3576 default: projTargetComp = projSourceComp; break;
3577 }
3578 // copy the projective coordinate if we have to
3579 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003580 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003581 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3582 projSourceComp);
3583 params.coords = builder.createCompositeInsert(projComp, params.coords,
3584 builder.getTypeId(params.coords), projTargetComp);
3585 }
3586 }
3587
John Kessenich8c8505c2016-07-26 12:50:38 -06003588 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003589}
3590
3591spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3592{
3593 // Grab the function's pointer from the previously created function
3594 spv::Function* function = functionMap[node->getName().c_str()];
3595 if (! function)
3596 return 0;
3597
3598 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3599 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3600
3601 // See comments in makeFunctions() for details about the semantics for parameter passing.
3602 //
3603 // These imply we need a four step process:
3604 // 1. Evaluate the arguments
3605 // 2. Allocate and make copies of in, out, and inout arguments
3606 // 3. Make the call
3607 // 4. Copy back the results
3608
3609 // 1. Evaluate the arguments
3610 std::vector<spv::Builder::AccessChain> lValues;
3611 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003612 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003613 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003614 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003615 // build l-value
3616 builder.clearAccessChain();
3617 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003618 argTypes.push_back(&paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003619 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenich6a14f782017-12-04 02:48:10 -07003620 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0) ||
3621 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003622 // save l-value
3623 lValues.push_back(builder.getAccessChain());
3624 } else {
3625 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003626 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003627 }
3628 }
3629
3630 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3631 // copy the original into that space.
3632 //
3633 // Also, build up the list of actual arguments to pass in for the call
3634 int lValueCount = 0;
3635 int rValueCount = 0;
3636 std::vector<spv::Id> spvArgs;
3637 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003638 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003639 spv::Id arg;
John Kessenichd41993d2017-09-10 15:21:05 -06003640 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003641 builder.setAccessChain(lValues[lValueCount]);
3642 arg = builder.accessChainGetLValue();
3643 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06003644 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003645 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003646 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3647 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3648 // need to copy the input into output space
3649 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003650 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003651 builder.clearAccessChain();
3652 builder.setAccessChainLValue(arg);
3653 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003654 }
3655 ++lValueCount;
3656 } else {
3657 arg = rValues[rValueCount];
3658 ++rValueCount;
3659 }
3660 spvArgs.push_back(arg);
3661 }
3662
3663 // 3. Make the call.
3664 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003665 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003666
3667 // 4. Copy back out an "out" arguments.
3668 lValueCount = 0;
3669 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003670 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenichd41993d2017-09-10 15:21:05 -06003671 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0))
3672 ++lValueCount;
3673 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003674 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3675 spv::Id copy = builder.createLoad(spvArgs[a]);
3676 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003677 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003678 }
3679 ++lValueCount;
3680 }
3681 }
3682
3683 return result;
3684}
3685
3686// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003687spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3688 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003689 spv::Id typeId, spv::Id left, spv::Id right,
3690 glslang::TBasicType typeProxy, bool reduceComparison)
3691{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003692#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08003693 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003694 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3695#else
Rex Xucabbb782017-03-24 13:41:14 +08003696 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06003697 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003698#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003699 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003700
3701 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003702 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003703 bool comparison = false;
3704
3705 switch (op) {
3706 case glslang::EOpAdd:
3707 case glslang::EOpAddAssign:
3708 if (isFloat)
3709 binOp = spv::OpFAdd;
3710 else
3711 binOp = spv::OpIAdd;
3712 break;
3713 case glslang::EOpSub:
3714 case glslang::EOpSubAssign:
3715 if (isFloat)
3716 binOp = spv::OpFSub;
3717 else
3718 binOp = spv::OpISub;
3719 break;
3720 case glslang::EOpMul:
3721 case glslang::EOpMulAssign:
3722 if (isFloat)
3723 binOp = spv::OpFMul;
3724 else
3725 binOp = spv::OpIMul;
3726 break;
3727 case glslang::EOpVectorTimesScalar:
3728 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003729 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003730 if (builder.isVector(right))
3731 std::swap(left, right);
3732 assert(builder.isScalar(right));
3733 needMatchingVectors = false;
3734 binOp = spv::OpVectorTimesScalar;
3735 } else
3736 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003737 break;
3738 case glslang::EOpVectorTimesMatrix:
3739 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003740 binOp = spv::OpVectorTimesMatrix;
3741 break;
3742 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003743 binOp = spv::OpMatrixTimesVector;
3744 break;
3745 case glslang::EOpMatrixTimesScalar:
3746 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003747 binOp = spv::OpMatrixTimesScalar;
3748 break;
3749 case glslang::EOpMatrixTimesMatrix:
3750 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003751 binOp = spv::OpMatrixTimesMatrix;
3752 break;
3753 case glslang::EOpOuterProduct:
3754 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003755 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003756 break;
3757
3758 case glslang::EOpDiv:
3759 case glslang::EOpDivAssign:
3760 if (isFloat)
3761 binOp = spv::OpFDiv;
3762 else if (isUnsigned)
3763 binOp = spv::OpUDiv;
3764 else
3765 binOp = spv::OpSDiv;
3766 break;
3767 case glslang::EOpMod:
3768 case glslang::EOpModAssign:
3769 if (isFloat)
3770 binOp = spv::OpFMod;
3771 else if (isUnsigned)
3772 binOp = spv::OpUMod;
3773 else
3774 binOp = spv::OpSMod;
3775 break;
3776 case glslang::EOpRightShift:
3777 case glslang::EOpRightShiftAssign:
3778 if (isUnsigned)
3779 binOp = spv::OpShiftRightLogical;
3780 else
3781 binOp = spv::OpShiftRightArithmetic;
3782 break;
3783 case glslang::EOpLeftShift:
3784 case glslang::EOpLeftShiftAssign:
3785 binOp = spv::OpShiftLeftLogical;
3786 break;
3787 case glslang::EOpAnd:
3788 case glslang::EOpAndAssign:
3789 binOp = spv::OpBitwiseAnd;
3790 break;
3791 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003792 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003793 binOp = spv::OpLogicalAnd;
3794 break;
3795 case glslang::EOpInclusiveOr:
3796 case glslang::EOpInclusiveOrAssign:
3797 binOp = spv::OpBitwiseOr;
3798 break;
3799 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003800 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003801 binOp = spv::OpLogicalOr;
3802 break;
3803 case glslang::EOpExclusiveOr:
3804 case glslang::EOpExclusiveOrAssign:
3805 binOp = spv::OpBitwiseXor;
3806 break;
3807 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003808 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003809 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003810 break;
3811
3812 case glslang::EOpLessThan:
3813 case glslang::EOpGreaterThan:
3814 case glslang::EOpLessThanEqual:
3815 case glslang::EOpGreaterThanEqual:
3816 case glslang::EOpEqual:
3817 case glslang::EOpNotEqual:
3818 case glslang::EOpVectorEqual:
3819 case glslang::EOpVectorNotEqual:
3820 comparison = true;
3821 break;
3822 default:
3823 break;
3824 }
3825
John Kessenich7c1aa102015-10-15 13:29:11 -06003826 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003827 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003828 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003829 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003830 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003831
3832 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003833 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003834 builder.promoteScalar(precision, left, right);
3835
qining25262b32016-05-06 17:25:16 -04003836 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3837 addDecoration(result, noContraction);
3838 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003839 }
3840
3841 if (! comparison)
3842 return 0;
3843
John Kessenich7c1aa102015-10-15 13:29:11 -06003844 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003845
John Kessenich4583b612016-08-07 19:14:22 -06003846 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3847 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003848 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003849
3850 switch (op) {
3851 case glslang::EOpLessThan:
3852 if (isFloat)
3853 binOp = spv::OpFOrdLessThan;
3854 else if (isUnsigned)
3855 binOp = spv::OpULessThan;
3856 else
3857 binOp = spv::OpSLessThan;
3858 break;
3859 case glslang::EOpGreaterThan:
3860 if (isFloat)
3861 binOp = spv::OpFOrdGreaterThan;
3862 else if (isUnsigned)
3863 binOp = spv::OpUGreaterThan;
3864 else
3865 binOp = spv::OpSGreaterThan;
3866 break;
3867 case glslang::EOpLessThanEqual:
3868 if (isFloat)
3869 binOp = spv::OpFOrdLessThanEqual;
3870 else if (isUnsigned)
3871 binOp = spv::OpULessThanEqual;
3872 else
3873 binOp = spv::OpSLessThanEqual;
3874 break;
3875 case glslang::EOpGreaterThanEqual:
3876 if (isFloat)
3877 binOp = spv::OpFOrdGreaterThanEqual;
3878 else if (isUnsigned)
3879 binOp = spv::OpUGreaterThanEqual;
3880 else
3881 binOp = spv::OpSGreaterThanEqual;
3882 break;
3883 case glslang::EOpEqual:
3884 case glslang::EOpVectorEqual:
3885 if (isFloat)
3886 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003887 else if (isBool)
3888 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003889 else
3890 binOp = spv::OpIEqual;
3891 break;
3892 case glslang::EOpNotEqual:
3893 case glslang::EOpVectorNotEqual:
3894 if (isFloat)
3895 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003896 else if (isBool)
3897 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003898 else
3899 binOp = spv::OpINotEqual;
3900 break;
3901 default:
3902 break;
3903 }
3904
qining25262b32016-05-06 17:25:16 -04003905 if (binOp != spv::OpNop) {
3906 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3907 addDecoration(result, noContraction);
3908 return builder.setPrecision(result, precision);
3909 }
John Kessenich140f3df2015-06-26 16:58:36 -06003910
3911 return 0;
3912}
3913
John Kessenich04bb8a02015-12-12 12:28:14 -07003914//
3915// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3916// These can be any of:
3917//
3918// matrix * scalar
3919// scalar * matrix
3920// matrix * matrix linear algebraic
3921// matrix * vector
3922// vector * matrix
3923// matrix * matrix componentwise
3924// matrix op matrix op in {+, -, /}
3925// matrix op scalar op in {+, -, /}
3926// scalar op matrix op in {+, -, /}
3927//
qining25262b32016-05-06 17:25:16 -04003928spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07003929{
3930 bool firstClass = true;
3931
3932 // First, handle first-class matrix operations (* and matrix/scalar)
3933 switch (op) {
3934 case spv::OpFDiv:
3935 if (builder.isMatrix(left) && builder.isScalar(right)) {
3936 // turn matrix / scalar into a multiply...
3937 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3938 op = spv::OpMatrixTimesScalar;
3939 } else
3940 firstClass = false;
3941 break;
3942 case spv::OpMatrixTimesScalar:
3943 if (builder.isMatrix(right))
3944 std::swap(left, right);
3945 assert(builder.isScalar(right));
3946 break;
3947 case spv::OpVectorTimesMatrix:
3948 assert(builder.isVector(left));
3949 assert(builder.isMatrix(right));
3950 break;
3951 case spv::OpMatrixTimesVector:
3952 assert(builder.isMatrix(left));
3953 assert(builder.isVector(right));
3954 break;
3955 case spv::OpMatrixTimesMatrix:
3956 assert(builder.isMatrix(left));
3957 assert(builder.isMatrix(right));
3958 break;
3959 default:
3960 firstClass = false;
3961 break;
3962 }
3963
qining25262b32016-05-06 17:25:16 -04003964 if (firstClass) {
3965 spv::Id result = builder.createBinOp(op, typeId, left, right);
3966 addDecoration(result, noContraction);
3967 return builder.setPrecision(result, precision);
3968 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003969
LoopDawg592860c2016-06-09 08:57:35 -06003970 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003971 // The result type of all of them is the same type as the (a) matrix operand.
3972 // The algorithm is to:
3973 // - break the matrix(es) into vectors
3974 // - smear any scalar to a vector
3975 // - do vector operations
3976 // - make a matrix out the vector results
3977 switch (op) {
3978 case spv::OpFAdd:
3979 case spv::OpFSub:
3980 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003981 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003982 case spv::OpFMul:
3983 {
3984 // one time set up...
3985 bool leftMat = builder.isMatrix(left);
3986 bool rightMat = builder.isMatrix(right);
3987 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3988 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3989 spv::Id scalarType = builder.getScalarTypeId(typeId);
3990 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3991 std::vector<spv::Id> results;
3992 spv::Id smearVec = spv::NoResult;
3993 if (builder.isScalar(left))
3994 smearVec = builder.smearScalar(precision, left, vecType);
3995 else if (builder.isScalar(right))
3996 smearVec = builder.smearScalar(precision, right, vecType);
3997
3998 // do each vector op
3999 for (unsigned int c = 0; c < numCols; ++c) {
4000 std::vector<unsigned int> indexes;
4001 indexes.push_back(c);
4002 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
4003 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04004004 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
4005 addDecoration(result, noContraction);
4006 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07004007 }
4008
4009 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004010 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07004011 }
4012 default:
4013 assert(0);
4014 return spv::NoResult;
4015 }
4016}
4017
qining25262b32016-05-06 17:25:16 -04004018spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004019{
4020 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004021 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004022 int libCall = -1;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004023#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004024 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004025 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4026#else
Rex Xucabbb782017-03-24 13:41:14 +08004027 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08004028 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004029#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004030
4031 switch (op) {
4032 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07004033 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06004034 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07004035 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04004036 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07004037 } else
John Kessenich140f3df2015-06-26 16:58:36 -06004038 unaryOp = spv::OpSNegate;
4039 break;
4040
4041 case glslang::EOpLogicalNot:
4042 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06004043 unaryOp = spv::OpLogicalNot;
4044 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004045 case glslang::EOpBitwiseNot:
4046 unaryOp = spv::OpNot;
4047 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06004048
John Kessenich140f3df2015-06-26 16:58:36 -06004049 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06004050 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06004051 break;
4052 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06004053 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06004054 break;
4055 case glslang::EOpTranspose:
4056 unaryOp = spv::OpTranspose;
4057 break;
4058
4059 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06004060 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06004061 break;
4062 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06004063 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06004064 break;
4065 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004066 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06004067 break;
4068 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004069 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06004070 break;
4071 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004072 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06004073 break;
4074 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004075 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06004076 break;
4077 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004078 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06004079 break;
4080 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004081 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06004082 break;
4083
4084 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004085 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004086 break;
4087 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004088 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004089 break;
4090 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004091 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004092 break;
4093 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004094 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004095 break;
4096 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004097 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004098 break;
4099 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004100 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004101 break;
4102
4103 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06004104 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06004105 break;
4106 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06004107 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06004108 break;
4109
4110 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004111 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06004112 break;
4113 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06004114 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06004115 break;
4116 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004117 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06004118 break;
4119 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004120 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06004121 break;
4122 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004123 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004124 break;
4125 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004126 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004127 break;
4128
4129 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06004130 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06004131 break;
4132 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06004133 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06004134 break;
4135 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06004136 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06004137 break;
4138 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06004139 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06004140 break;
4141 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06004142 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06004143 break;
4144 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004145 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06004146 break;
4147
4148 case glslang::EOpIsNan:
4149 unaryOp = spv::OpIsNan;
4150 break;
4151 case glslang::EOpIsInf:
4152 unaryOp = spv::OpIsInf;
4153 break;
LoopDawg592860c2016-06-09 08:57:35 -06004154 case glslang::EOpIsFinite:
4155 unaryOp = spv::OpIsFinite;
4156 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004157
Rex Xucbc426e2015-12-15 16:03:10 +08004158 case glslang::EOpFloatBitsToInt:
4159 case glslang::EOpFloatBitsToUint:
4160 case glslang::EOpIntBitsToFloat:
4161 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08004162 case glslang::EOpDoubleBitsToInt64:
4163 case glslang::EOpDoubleBitsToUint64:
4164 case glslang::EOpInt64BitsToDouble:
4165 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08004166#ifdef AMD_EXTENSIONS
4167 case glslang::EOpFloat16BitsToInt16:
4168 case glslang::EOpFloat16BitsToUint16:
4169 case glslang::EOpInt16BitsToFloat16:
4170 case glslang::EOpUint16BitsToFloat16:
4171#endif
Rex Xucbc426e2015-12-15 16:03:10 +08004172 unaryOp = spv::OpBitcast;
4173 break;
4174
John Kessenich140f3df2015-06-26 16:58:36 -06004175 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004176 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004177 break;
4178 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004179 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004180 break;
4181 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004182 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004183 break;
4184 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004185 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004186 break;
4187 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004188 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004189 break;
4190 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004191 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004192 break;
John Kessenichfc51d282015-08-19 13:34:18 -06004193 case glslang::EOpPackSnorm4x8:
4194 libCall = spv::GLSLstd450PackSnorm4x8;
4195 break;
4196 case glslang::EOpUnpackSnorm4x8:
4197 libCall = spv::GLSLstd450UnpackSnorm4x8;
4198 break;
4199 case glslang::EOpPackUnorm4x8:
4200 libCall = spv::GLSLstd450PackUnorm4x8;
4201 break;
4202 case glslang::EOpUnpackUnorm4x8:
4203 libCall = spv::GLSLstd450UnpackUnorm4x8;
4204 break;
4205 case glslang::EOpPackDouble2x32:
4206 libCall = spv::GLSLstd450PackDouble2x32;
4207 break;
4208 case glslang::EOpUnpackDouble2x32:
4209 libCall = spv::GLSLstd450UnpackDouble2x32;
4210 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004211
Rex Xu8ff43de2016-04-22 16:51:45 +08004212 case glslang::EOpPackInt2x32:
4213 case glslang::EOpUnpackInt2x32:
4214 case glslang::EOpPackUint2x32:
4215 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08004216 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08004217 break;
4218
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004219#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004220 case glslang::EOpPackInt2x16:
4221 case glslang::EOpUnpackInt2x16:
4222 case glslang::EOpPackUint2x16:
4223 case glslang::EOpUnpackUint2x16:
4224 case glslang::EOpPackInt4x16:
4225 case glslang::EOpUnpackInt4x16:
4226 case glslang::EOpPackUint4x16:
4227 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004228 case glslang::EOpPackFloat2x16:
4229 case glslang::EOpUnpackFloat2x16:
4230 unaryOp = spv::OpBitcast;
4231 break;
4232#endif
4233
John Kessenich140f3df2015-06-26 16:58:36 -06004234 case glslang::EOpDPdx:
4235 unaryOp = spv::OpDPdx;
4236 break;
4237 case glslang::EOpDPdy:
4238 unaryOp = spv::OpDPdy;
4239 break;
4240 case glslang::EOpFwidth:
4241 unaryOp = spv::OpFwidth;
4242 break;
4243 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07004244 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004245 unaryOp = spv::OpDPdxFine;
4246 break;
4247 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07004248 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004249 unaryOp = spv::OpDPdyFine;
4250 break;
4251 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07004252 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004253 unaryOp = spv::OpFwidthFine;
4254 break;
4255 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004256 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004257 unaryOp = spv::OpDPdxCoarse;
4258 break;
4259 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004260 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004261 unaryOp = spv::OpDPdyCoarse;
4262 break;
4263 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004264 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004265 unaryOp = spv::OpFwidthCoarse;
4266 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004267 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07004268 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004269 libCall = spv::GLSLstd450InterpolateAtCentroid;
4270 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004271 case glslang::EOpAny:
4272 unaryOp = spv::OpAny;
4273 break;
4274 case glslang::EOpAll:
4275 unaryOp = spv::OpAll;
4276 break;
4277
4278 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004279 if (isFloat)
4280 libCall = spv::GLSLstd450FAbs;
4281 else
4282 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004283 break;
4284 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004285 if (isFloat)
4286 libCall = spv::GLSLstd450FSign;
4287 else
4288 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004289 break;
4290
John Kessenichfc51d282015-08-19 13:34:18 -06004291 case glslang::EOpAtomicCounterIncrement:
4292 case glslang::EOpAtomicCounterDecrement:
4293 case glslang::EOpAtomicCounter:
4294 {
4295 // Handle all of the atomics in one place, in createAtomicOperation()
4296 std::vector<spv::Id> operands;
4297 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08004298 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004299 }
4300
John Kessenichfc51d282015-08-19 13:34:18 -06004301 case glslang::EOpBitFieldReverse:
4302 unaryOp = spv::OpBitReverse;
4303 break;
4304 case glslang::EOpBitCount:
4305 unaryOp = spv::OpBitCount;
4306 break;
4307 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004308 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004309 break;
4310 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004311 if (isUnsigned)
4312 libCall = spv::GLSLstd450FindUMsb;
4313 else
4314 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004315 break;
4316
Rex Xu574ab042016-04-14 16:53:07 +08004317 case glslang::EOpBallot:
4318 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004319 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004320 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004321 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004322#ifdef AMD_EXTENSIONS
4323 case glslang::EOpMinInvocations:
4324 case glslang::EOpMaxInvocations:
4325 case glslang::EOpAddInvocations:
4326 case glslang::EOpMinInvocationsNonUniform:
4327 case glslang::EOpMaxInvocationsNonUniform:
4328 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004329 case glslang::EOpMinInvocationsInclusiveScan:
4330 case glslang::EOpMaxInvocationsInclusiveScan:
4331 case glslang::EOpAddInvocationsInclusiveScan:
4332 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4333 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4334 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4335 case glslang::EOpMinInvocationsExclusiveScan:
4336 case glslang::EOpMaxInvocationsExclusiveScan:
4337 case glslang::EOpAddInvocationsExclusiveScan:
4338 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4339 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4340 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004341#endif
Rex Xu51596642016-09-21 18:56:12 +08004342 {
4343 std::vector<spv::Id> operands;
4344 operands.push_back(operand);
4345 return createInvocationsOperation(op, typeId, operands, typeProxy);
4346 }
Rex Xu9d93a232016-05-05 12:30:44 +08004347
4348#ifdef AMD_EXTENSIONS
4349 case glslang::EOpMbcnt:
4350 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4351 libCall = spv::MbcntAMD;
4352 break;
4353
4354 case glslang::EOpCubeFaceIndex:
4355 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4356 libCall = spv::CubeFaceIndexAMD;
4357 break;
4358
4359 case glslang::EOpCubeFaceCoord:
4360 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4361 libCall = spv::CubeFaceCoordAMD;
4362 break;
4363#endif
Rex Xu338b1852016-05-05 20:38:33 +08004364
John Kessenich140f3df2015-06-26 16:58:36 -06004365 default:
4366 return 0;
4367 }
4368
4369 spv::Id id;
4370 if (libCall >= 0) {
4371 std::vector<spv::Id> args;
4372 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004373 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004374 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004375 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004376 }
John Kessenich140f3df2015-06-26 16:58:36 -06004377
qining25262b32016-05-06 17:25:16 -04004378 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07004379 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004380}
4381
John Kessenich7a53f762016-01-20 11:19:27 -07004382// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04004383spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07004384{
4385 // Handle unary operations vector by vector.
4386 // The result type is the same type as the original type.
4387 // The algorithm is to:
4388 // - break the matrix into vectors
4389 // - apply the operation to each vector
4390 // - make a matrix out the vector results
4391
4392 // get the types sorted out
4393 int numCols = builder.getNumColumns(operand);
4394 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004395 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4396 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004397 std::vector<spv::Id> results;
4398
4399 // do each vector op
4400 for (int c = 0; c < numCols; ++c) {
4401 std::vector<unsigned int> indexes;
4402 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004403 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4404 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
4405 addDecoration(destVec, noContraction);
4406 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004407 }
4408
4409 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004410 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07004411}
4412
Rex Xu73e3ce72016-04-27 18:48:17 +08004413spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id destType, spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004414{
4415 spv::Op convOp = spv::OpNop;
4416 spv::Id zero = 0;
4417 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08004418 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004419
4420 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4421
4422 switch (op) {
4423 case glslang::EOpConvIntToBool:
4424 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08004425 case glslang::EOpConvInt64ToBool:
4426 case glslang::EOpConvUint64ToBool:
Rex Xucabbb782017-03-24 13:41:14 +08004427#ifdef AMD_EXTENSIONS
4428 case glslang::EOpConvInt16ToBool:
4429 case glslang::EOpConvUint16ToBool:
4430#endif
4431 if (op == glslang::EOpConvInt64ToBool || op == glslang::EOpConvUint64ToBool)
4432 zero = builder.makeUint64Constant(0);
4433#ifdef AMD_EXTENSIONS
4434 else if (op == glslang::EOpConvInt16ToBool || op == glslang::EOpConvUint16ToBool)
4435 zero = builder.makeUint16Constant(0);
4436#endif
4437 else
4438 zero = builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004439 zero = makeSmearedConstant(zero, vectorSize);
4440 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4441
4442 case glslang::EOpConvFloatToBool:
4443 zero = builder.makeFloatConstant(0.0F);
4444 zero = makeSmearedConstant(zero, vectorSize);
4445 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4446
4447 case glslang::EOpConvDoubleToBool:
4448 zero = builder.makeDoubleConstant(0.0);
4449 zero = makeSmearedConstant(zero, vectorSize);
4450 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4451
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004452#ifdef AMD_EXTENSIONS
4453 case glslang::EOpConvFloat16ToBool:
4454 zero = builder.makeFloat16Constant(0.0F);
4455 zero = makeSmearedConstant(zero, vectorSize);
4456 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4457#endif
4458
John Kessenich140f3df2015-06-26 16:58:36 -06004459 case glslang::EOpConvBoolToFloat:
4460 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004461 zero = builder.makeFloatConstant(0.0F);
4462 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004463 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004464
John Kessenich140f3df2015-06-26 16:58:36 -06004465 case glslang::EOpConvBoolToDouble:
4466 convOp = spv::OpSelect;
4467 zero = builder.makeDoubleConstant(0.0);
4468 one = builder.makeDoubleConstant(1.0);
4469 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004470
4471#ifdef AMD_EXTENSIONS
4472 case glslang::EOpConvBoolToFloat16:
4473 convOp = spv::OpSelect;
4474 zero = builder.makeFloat16Constant(0.0F);
4475 one = builder.makeFloat16Constant(1.0F);
4476 break;
4477#endif
4478
John Kessenich140f3df2015-06-26 16:58:36 -06004479 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004480 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004481#ifdef AMD_EXTENSIONS
4482 case glslang::EOpConvBoolToInt16:
4483#endif
4484 if (op == glslang::EOpConvBoolToInt64)
4485 zero = builder.makeInt64Constant(0);
4486#ifdef AMD_EXTENSIONS
4487 else if (op == glslang::EOpConvBoolToInt16)
4488 zero = builder.makeInt16Constant(0);
4489#endif
4490 else
4491 zero = builder.makeIntConstant(0);
4492
4493 if (op == glslang::EOpConvBoolToInt64)
4494 one = builder.makeInt64Constant(1);
4495#ifdef AMD_EXTENSIONS
4496 else if (op == glslang::EOpConvBoolToInt16)
4497 one = builder.makeInt16Constant(1);
4498#endif
4499 else
4500 one = builder.makeIntConstant(1);
4501
John Kessenich140f3df2015-06-26 16:58:36 -06004502 convOp = spv::OpSelect;
4503 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004504
John Kessenich140f3df2015-06-26 16:58:36 -06004505 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004506 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004507#ifdef AMD_EXTENSIONS
4508 case glslang::EOpConvBoolToUint16:
4509#endif
4510 if (op == glslang::EOpConvBoolToUint64)
4511 zero = builder.makeUint64Constant(0);
4512#ifdef AMD_EXTENSIONS
4513 else if (op == glslang::EOpConvBoolToUint16)
4514 zero = builder.makeUint16Constant(0);
4515#endif
4516 else
4517 zero = builder.makeUintConstant(0);
4518
4519 if (op == glslang::EOpConvBoolToUint64)
4520 one = builder.makeUint64Constant(1);
4521#ifdef AMD_EXTENSIONS
4522 else if (op == glslang::EOpConvBoolToUint16)
4523 one = builder.makeUint16Constant(1);
4524#endif
4525 else
4526 one = builder.makeUintConstant(1);
4527
John Kessenich140f3df2015-06-26 16:58:36 -06004528 convOp = spv::OpSelect;
4529 break;
4530
4531 case glslang::EOpConvIntToFloat:
4532 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004533 case glslang::EOpConvInt64ToFloat:
4534 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004535#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004536 case glslang::EOpConvInt16ToFloat:
4537 case glslang::EOpConvInt16ToDouble:
4538 case glslang::EOpConvInt16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004539 case glslang::EOpConvIntToFloat16:
4540 case glslang::EOpConvInt64ToFloat16:
4541#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004542 convOp = spv::OpConvertSToF;
4543 break;
4544
4545 case glslang::EOpConvUintToFloat:
4546 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004547 case glslang::EOpConvUint64ToFloat:
4548 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004549#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004550 case glslang::EOpConvUint16ToFloat:
4551 case glslang::EOpConvUint16ToDouble:
4552 case glslang::EOpConvUint16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004553 case glslang::EOpConvUintToFloat16:
4554 case glslang::EOpConvUint64ToFloat16:
4555#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004556 convOp = spv::OpConvertUToF;
4557 break;
4558
4559 case glslang::EOpConvDoubleToFloat:
4560 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004561#ifdef AMD_EXTENSIONS
4562 case glslang::EOpConvDoubleToFloat16:
4563 case glslang::EOpConvFloat16ToDouble:
4564 case glslang::EOpConvFloatToFloat16:
4565 case glslang::EOpConvFloat16ToFloat:
4566#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004567 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004568 if (builder.isMatrixType(destType))
4569 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004570 break;
4571
4572 case glslang::EOpConvFloatToInt:
4573 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004574 case glslang::EOpConvFloatToInt64:
4575 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004576#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004577 case glslang::EOpConvFloatToInt16:
4578 case glslang::EOpConvDoubleToInt16:
4579 case glslang::EOpConvFloat16ToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004580 case glslang::EOpConvFloat16ToInt:
4581 case glslang::EOpConvFloat16ToInt64:
4582#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004583 convOp = spv::OpConvertFToS;
4584 break;
4585
4586 case glslang::EOpConvUintToInt:
4587 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004588 case glslang::EOpConvUint64ToInt64:
4589 case glslang::EOpConvInt64ToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004590#ifdef AMD_EXTENSIONS
4591 case glslang::EOpConvUint16ToInt16:
4592 case glslang::EOpConvInt16ToUint16:
4593#endif
qininge24aa5e2016-04-07 15:40:27 -04004594 if (builder.isInSpecConstCodeGenMode()) {
4595 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004596 if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64)
4597 zero = builder.makeUint64Constant(0);
4598#ifdef AMD_EXTENSIONS
4599 else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16)
4600 zero = builder.makeUint16Constant(0);
4601#endif
4602 else
4603 zero = builder.makeUintConstant(0);
4604
qining189b2032016-04-12 23:16:20 -04004605 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004606 // Use OpIAdd, instead of OpBitcast to do the conversion when
4607 // generating for OpSpecConstantOp instruction.
4608 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4609 }
4610 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004611 convOp = spv::OpBitcast;
4612 break;
4613
4614 case glslang::EOpConvFloatToUint:
4615 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004616 case glslang::EOpConvFloatToUint64:
4617 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004618#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004619 case glslang::EOpConvFloatToUint16:
4620 case glslang::EOpConvDoubleToUint16:
4621 case glslang::EOpConvFloat16ToUint16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004622 case glslang::EOpConvFloat16ToUint:
4623 case glslang::EOpConvFloat16ToUint64:
4624#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004625 convOp = spv::OpConvertFToU;
4626 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004627
4628 case glslang::EOpConvIntToInt64:
4629 case glslang::EOpConvInt64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004630#ifdef AMD_EXTENSIONS
4631 case glslang::EOpConvIntToInt16:
4632 case glslang::EOpConvInt16ToInt:
4633 case glslang::EOpConvInt64ToInt16:
4634 case glslang::EOpConvInt16ToInt64:
4635#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004636 convOp = spv::OpSConvert;
4637 break;
4638
4639 case glslang::EOpConvUintToUint64:
4640 case glslang::EOpConvUint64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004641#ifdef AMD_EXTENSIONS
4642 case glslang::EOpConvUintToUint16:
4643 case glslang::EOpConvUint16ToUint:
4644 case glslang::EOpConvUint64ToUint16:
4645 case glslang::EOpConvUint16ToUint64:
4646#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004647 convOp = spv::OpUConvert;
4648 break;
4649
4650 case glslang::EOpConvIntToUint64:
4651 case glslang::EOpConvInt64ToUint:
4652 case glslang::EOpConvUint64ToInt:
4653 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004654#ifdef AMD_EXTENSIONS
4655 case glslang::EOpConvInt16ToUint:
4656 case glslang::EOpConvUintToInt16:
4657 case glslang::EOpConvInt16ToUint64:
4658 case glslang::EOpConvUint64ToInt16:
4659 case glslang::EOpConvUint16ToInt:
4660 case glslang::EOpConvIntToUint16:
4661 case glslang::EOpConvUint16ToInt64:
4662 case glslang::EOpConvInt64ToUint16:
4663#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004664 // OpSConvert/OpUConvert + OpBitCast
4665 switch (op) {
4666 case glslang::EOpConvIntToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004667#ifdef AMD_EXTENSIONS
4668 case glslang::EOpConvInt16ToUint64:
4669#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004670 convOp = spv::OpSConvert;
4671 type = builder.makeIntType(64);
4672 break;
4673 case glslang::EOpConvInt64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004674#ifdef AMD_EXTENSIONS
4675 case glslang::EOpConvInt16ToUint:
4676#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004677 convOp = spv::OpSConvert;
4678 type = builder.makeIntType(32);
4679 break;
4680 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004681#ifdef AMD_EXTENSIONS
4682 case glslang::EOpConvUint16ToInt:
4683#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004684 convOp = spv::OpUConvert;
4685 type = builder.makeUintType(32);
4686 break;
4687 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004688#ifdef AMD_EXTENSIONS
4689 case glslang::EOpConvUint16ToInt64:
4690#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004691 convOp = spv::OpUConvert;
4692 type = builder.makeUintType(64);
4693 break;
Rex Xucabbb782017-03-24 13:41:14 +08004694#ifdef AMD_EXTENSIONS
4695 case glslang::EOpConvUintToInt16:
4696 case glslang::EOpConvUint64ToInt16:
4697 convOp = spv::OpUConvert;
4698 type = builder.makeUintType(16);
4699 break;
4700 case glslang::EOpConvIntToUint16:
4701 case glslang::EOpConvInt64ToUint16:
4702 convOp = spv::OpSConvert;
4703 type = builder.makeIntType(16);
4704 break;
4705#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004706 default:
4707 assert(0);
4708 break;
4709 }
4710
4711 if (vectorSize > 0)
4712 type = builder.makeVectorType(type, vectorSize);
4713
4714 operand = builder.createUnaryOp(convOp, type, operand);
4715
4716 if (builder.isInSpecConstCodeGenMode()) {
4717 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004718#ifdef AMD_EXTENSIONS
4719 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64 ||
4720 op == glslang::EOpConvInt16ToUint64 || op == glslang::EOpConvUint16ToInt64)
4721 zero = builder.makeUint64Constant(0);
4722 else if (op == glslang::EOpConvIntToUint16 || op == glslang::EOpConvUintToInt16 ||
4723 op == glslang::EOpConvInt64ToUint16 || op == glslang::EOpConvUint64ToInt16)
4724 zero = builder.makeUint16Constant(0);
4725 else
4726 zero = builder.makeUintConstant(0);
4727#else
4728 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64)
4729 zero = builder.makeUint64Constant(0);
4730 else
4731 zero = builder.makeUintConstant(0);
4732#endif
4733
Rex Xu8ff43de2016-04-22 16:51:45 +08004734 zero = makeSmearedConstant(zero, vectorSize);
4735 // Use OpIAdd, instead of OpBitcast to do the conversion when
4736 // generating for OpSpecConstantOp instruction.
4737 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4738 }
4739 // For normal run-time conversion instruction, use OpBitcast.
4740 convOp = spv::OpBitcast;
4741 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004742 default:
4743 break;
4744 }
4745
4746 spv::Id result = 0;
4747 if (convOp == spv::OpNop)
4748 return result;
4749
4750 if (convOp == spv::OpSelect) {
4751 zero = makeSmearedConstant(zero, vectorSize);
4752 one = makeSmearedConstant(one, vectorSize);
4753 result = builder.createTriOp(convOp, destType, operand, one, zero);
4754 } else
4755 result = builder.createUnaryOp(convOp, destType, operand);
4756
John Kessenich32cfd492016-02-02 12:37:46 -07004757 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004758}
4759
4760spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4761{
4762 if (vectorSize == 0)
4763 return constant;
4764
4765 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4766 std::vector<spv::Id> components;
4767 for (int c = 0; c < vectorSize; ++c)
4768 components.push_back(constant);
4769 return builder.makeCompositeConstant(vectorTypeId, components);
4770}
4771
John Kessenich426394d2015-07-23 10:22:48 -06004772// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004773spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich426394d2015-07-23 10:22:48 -06004774{
4775 spv::Op opCode = spv::OpNop;
4776
4777 switch (op) {
4778 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004779 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004780 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004781 opCode = spv::OpAtomicIAdd;
4782 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06004783 case glslang::EOpAtomicCounterSubtract:
4784 opCode = spv::OpAtomicISub;
4785 break;
John Kessenich426394d2015-07-23 10:22:48 -06004786 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004787 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004788 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08004789 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004790 break;
4791 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004792 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004793 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08004794 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004795 break;
4796 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004797 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004798 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004799 opCode = spv::OpAtomicAnd;
4800 break;
4801 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004802 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004803 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06004804 opCode = spv::OpAtomicOr;
4805 break;
4806 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004807 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004808 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06004809 opCode = spv::OpAtomicXor;
4810 break;
4811 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004812 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004813 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004814 opCode = spv::OpAtomicExchange;
4815 break;
4816 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004817 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004818 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004819 opCode = spv::OpAtomicCompareExchange;
4820 break;
4821 case glslang::EOpAtomicCounterIncrement:
4822 opCode = spv::OpAtomicIIncrement;
4823 break;
4824 case glslang::EOpAtomicCounterDecrement:
4825 opCode = spv::OpAtomicIDecrement;
4826 break;
4827 case glslang::EOpAtomicCounter:
4828 opCode = spv::OpAtomicLoad;
4829 break;
4830 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004831 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004832 break;
4833 }
4834
Rex Xue8fe8b02017-09-26 15:42:56 +08004835 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
4836 builder.addCapability(spv::CapabilityInt64Atomics);
4837
John Kessenich426394d2015-07-23 10:22:48 -06004838 // Sort out the operands
4839 // - mapping from glslang -> SPV
4840 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004841 // - compare-exchange swaps the value and comparator
4842 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06004843 // - EOpAtomicCounterDecrement needs a post decrement
John Kessenich426394d2015-07-23 10:22:48 -06004844 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4845 auto opIt = operands.begin(); // walk the glslang operands
4846 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004847 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4848 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4849 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004850 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4851 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004852 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004853 spvAtomicOperands.push_back(*(opIt + 1));
4854 spvAtomicOperands.push_back(*opIt);
4855 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004856 }
John Kessenich426394d2015-07-23 10:22:48 -06004857
John Kessenich3e60a6f2015-09-14 22:45:16 -06004858 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004859 for (; opIt != operands.end(); ++opIt)
4860 spvAtomicOperands.push_back(*opIt);
4861
John Kessenich48d6e792017-10-06 21:21:48 -06004862 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
4863
4864 // GLSL and HLSL atomic-counter decrement return post-decrement value,
4865 // while SPIR-V returns pre-decrement value. Translate between these semantics.
4866 if (op == glslang::EOpAtomicCounterDecrement)
4867 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
4868
4869 return resultId;
John Kessenich426394d2015-07-23 10:22:48 -06004870}
4871
John Kessenich91cef522016-05-05 16:45:40 -06004872// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004873spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004874{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004875#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004876 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004877 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004878#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004879
Rex Xu51596642016-09-21 18:56:12 +08004880 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004881 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004882 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4883
chaocf200da82016-12-20 12:44:35 -08004884 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4885 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004886 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4887 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004888 } else if (op == glslang::EOpAnyInvocation ||
4889 op == glslang::EOpAllInvocations ||
4890 op == glslang::EOpAllInvocationsEqual) {
4891 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4892 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004893 } else {
4894 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004895#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004896 if (op == glslang::EOpMinInvocationsNonUniform ||
4897 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004898 op == glslang::EOpAddInvocationsNonUniform ||
4899 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4900 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4901 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4902 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4903 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4904 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004905 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004906#endif
Rex Xu51596642016-09-21 18:56:12 +08004907
4908 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004909#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004910 switch (op) {
4911 case glslang::EOpMinInvocations:
4912 case glslang::EOpMaxInvocations:
4913 case glslang::EOpAddInvocations:
4914 case glslang::EOpMinInvocationsNonUniform:
4915 case glslang::EOpMaxInvocationsNonUniform:
4916 case glslang::EOpAddInvocationsNonUniform:
4917 groupOperation = spv::GroupOperationReduce;
4918 spvGroupOperands.push_back(groupOperation);
4919 break;
4920 case glslang::EOpMinInvocationsInclusiveScan:
4921 case glslang::EOpMaxInvocationsInclusiveScan:
4922 case glslang::EOpAddInvocationsInclusiveScan:
4923 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4924 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4925 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4926 groupOperation = spv::GroupOperationInclusiveScan;
4927 spvGroupOperands.push_back(groupOperation);
4928 break;
4929 case glslang::EOpMinInvocationsExclusiveScan:
4930 case glslang::EOpMaxInvocationsExclusiveScan:
4931 case glslang::EOpAddInvocationsExclusiveScan:
4932 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4933 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4934 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4935 groupOperation = spv::GroupOperationExclusiveScan;
4936 spvGroupOperands.push_back(groupOperation);
4937 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004938 default:
4939 break;
Rex Xu430ef402016-10-14 17:22:23 +08004940 }
Rex Xu9d93a232016-05-05 12:30:44 +08004941#endif
Rex Xu51596642016-09-21 18:56:12 +08004942 }
4943
4944 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4945 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004946
4947 switch (op) {
4948 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004949 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004950 break;
John Kessenich91cef522016-05-05 16:45:40 -06004951 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004952 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004953 break;
John Kessenich91cef522016-05-05 16:45:40 -06004954 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004955 opCode = spv::OpSubgroupAllEqualKHR;
4956 break;
Rex Xu51596642016-09-21 18:56:12 +08004957 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004958 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004959 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004960 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004961 break;
4962 case glslang::EOpReadFirstInvocation:
4963 opCode = spv::OpSubgroupFirstInvocationKHR;
4964 break;
4965 case glslang::EOpBallot:
4966 {
4967 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4968 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4969 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4970 //
4971 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4972 //
4973 spv::Id uintType = builder.makeUintType(32);
4974 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4975 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4976
4977 std::vector<spv::Id> components;
4978 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4979 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4980
4981 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4982 return builder.createUnaryOp(spv::OpBitcast, typeId,
4983 builder.createCompositeConstruct(uvec2Type, components));
4984 }
4985
Rex Xu9d93a232016-05-05 12:30:44 +08004986#ifdef AMD_EXTENSIONS
4987 case glslang::EOpMinInvocations:
4988 case glslang::EOpMaxInvocations:
4989 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08004990 case glslang::EOpMinInvocationsInclusiveScan:
4991 case glslang::EOpMaxInvocationsInclusiveScan:
4992 case glslang::EOpAddInvocationsInclusiveScan:
4993 case glslang::EOpMinInvocationsExclusiveScan:
4994 case glslang::EOpMaxInvocationsExclusiveScan:
4995 case glslang::EOpAddInvocationsExclusiveScan:
4996 if (op == glslang::EOpMinInvocations ||
4997 op == glslang::EOpMinInvocationsInclusiveScan ||
4998 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004999 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005000 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005001 else {
5002 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005003 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005004 else
Rex Xu51596642016-09-21 18:56:12 +08005005 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005006 }
Rex Xu430ef402016-10-14 17:22:23 +08005007 } else if (op == glslang::EOpMaxInvocations ||
5008 op == glslang::EOpMaxInvocationsInclusiveScan ||
5009 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005010 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005011 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005012 else {
5013 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005014 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005015 else
Rex Xu51596642016-09-21 18:56:12 +08005016 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005017 }
5018 } else {
5019 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005020 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005021 else
Rex Xu51596642016-09-21 18:56:12 +08005022 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005023 }
5024
Rex Xu2bbbe062016-08-23 15:41:05 +08005025 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005026 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005027
5028 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005029 case glslang::EOpMinInvocationsNonUniform:
5030 case glslang::EOpMaxInvocationsNonUniform:
5031 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005032 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5033 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5034 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5035 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5036 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5037 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5038 if (op == glslang::EOpMinInvocationsNonUniform ||
5039 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5040 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005041 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005042 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005043 else {
5044 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005045 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005046 else
Rex Xu51596642016-09-21 18:56:12 +08005047 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005048 }
5049 }
Rex Xu430ef402016-10-14 17:22:23 +08005050 else if (op == glslang::EOpMaxInvocationsNonUniform ||
5051 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5052 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005053 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005054 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005055 else {
5056 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005057 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005058 else
Rex Xu51596642016-09-21 18:56:12 +08005059 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005060 }
5061 }
5062 else {
5063 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005064 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005065 else
Rex Xu51596642016-09-21 18:56:12 +08005066 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005067 }
5068
Rex Xu2bbbe062016-08-23 15:41:05 +08005069 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005070 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005071
5072 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005073#endif
John Kessenich91cef522016-05-05 16:45:40 -06005074 default:
5075 logger->missingFunctionality("invocation operation");
5076 return spv::NoResult;
5077 }
Rex Xu51596642016-09-21 18:56:12 +08005078
5079 assert(opCode != spv::OpNop);
5080 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06005081}
5082
Rex Xu2bbbe062016-08-23 15:41:05 +08005083// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08005084spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08005085{
Rex Xub7072052016-09-26 15:53:40 +08005086#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08005087 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5088 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08005089 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08005090 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08005091 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
5092 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
5093 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08005094#else
5095 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5096 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08005097 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
5098 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08005099#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08005100
5101 // Handle group invocation operations scalar by scalar.
5102 // The result type is the same type as the original type.
5103 // The algorithm is to:
5104 // - break the vector into scalars
5105 // - apply the operation to each scalar
5106 // - make a vector out the scalar results
5107
5108 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08005109 int numComponents = builder.getNumComponents(operands[0]);
5110 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08005111 std::vector<spv::Id> results;
5112
5113 // do each scalar op
5114 for (int comp = 0; comp < numComponents; ++comp) {
5115 std::vector<unsigned int> indexes;
5116 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08005117 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08005118 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08005119 if (op == spv::OpSubgroupReadInvocationKHR) {
5120 spvGroupOperands.push_back(scalar);
5121 spvGroupOperands.push_back(operands[1]);
5122 } else if (op == spv::OpGroupBroadcast) {
5123 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08005124 spvGroupOperands.push_back(scalar);
5125 spvGroupOperands.push_back(operands[1]);
5126 } else {
chaocf200da82016-12-20 12:44:35 -08005127 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08005128 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08005129 spvGroupOperands.push_back(scalar);
5130 }
Rex Xu2bbbe062016-08-23 15:41:05 +08005131
Rex Xub7072052016-09-26 15:53:40 +08005132 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08005133 }
5134
5135 // put the pieces together
5136 return builder.createCompositeConstruct(typeId, results);
5137}
Rex Xu2bbbe062016-08-23 15:41:05 +08005138
John Kessenich5e4b1242015-08-06 22:53:06 -06005139spv::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 -06005140{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005141#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08005142 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005143 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
5144#else
Rex Xucabbb782017-03-24 13:41:14 +08005145 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06005146 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005147#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06005148
John Kessenich140f3df2015-06-26 16:58:36 -06005149 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005150 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005151 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05005152 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07005153 spv::Id typeId0 = 0;
5154 if (consumedOperands > 0)
5155 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08005156 spv::Id typeId1 = 0;
5157 if (consumedOperands > 1)
5158 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07005159 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06005160
5161 switch (op) {
5162 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005163 if (isFloat)
5164 libCall = spv::GLSLstd450FMin;
5165 else if (isUnsigned)
5166 libCall = spv::GLSLstd450UMin;
5167 else
5168 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005169 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005170 break;
5171 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06005172 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06005173 break;
5174 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06005175 if (isFloat)
5176 libCall = spv::GLSLstd450FMax;
5177 else if (isUnsigned)
5178 libCall = spv::GLSLstd450UMax;
5179 else
5180 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005181 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005182 break;
5183 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06005184 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06005185 break;
5186 case glslang::EOpDot:
5187 opCode = spv::OpDot;
5188 break;
5189 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005190 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06005191 break;
5192
5193 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005194 if (isFloat)
5195 libCall = spv::GLSLstd450FClamp;
5196 else if (isUnsigned)
5197 libCall = spv::GLSLstd450UClamp;
5198 else
5199 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005200 builder.promoteScalar(precision, operands.front(), operands[1]);
5201 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005202 break;
5203 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08005204 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
5205 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07005206 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08005207 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07005208 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08005209 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07005210 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07005211 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005212 break;
5213 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005214 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005215 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005216 break;
5217 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005218 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005219 builder.promoteScalar(precision, operands[0], operands[2]);
5220 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005221 break;
5222
5223 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06005224 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06005225 break;
5226 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06005227 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06005228 break;
5229 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06005230 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06005231 break;
5232 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06005233 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06005234 break;
5235 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005236 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06005237 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005238 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07005239 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005240 libCall = spv::GLSLstd450InterpolateAtSample;
5241 break;
5242 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07005243 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005244 libCall = spv::GLSLstd450InterpolateAtOffset;
5245 break;
John Kessenich55e7d112015-11-15 21:33:39 -07005246 case glslang::EOpAddCarry:
5247 opCode = spv::OpIAddCarry;
5248 typeId = builder.makeStructResultType(typeId0, typeId0);
5249 consumedOperands = 2;
5250 break;
5251 case glslang::EOpSubBorrow:
5252 opCode = spv::OpISubBorrow;
5253 typeId = builder.makeStructResultType(typeId0, typeId0);
5254 consumedOperands = 2;
5255 break;
5256 case glslang::EOpUMulExtended:
5257 opCode = spv::OpUMulExtended;
5258 typeId = builder.makeStructResultType(typeId0, typeId0);
5259 consumedOperands = 2;
5260 break;
5261 case glslang::EOpIMulExtended:
5262 opCode = spv::OpSMulExtended;
5263 typeId = builder.makeStructResultType(typeId0, typeId0);
5264 consumedOperands = 2;
5265 break;
5266 case glslang::EOpBitfieldExtract:
5267 if (isUnsigned)
5268 opCode = spv::OpBitFieldUExtract;
5269 else
5270 opCode = spv::OpBitFieldSExtract;
5271 break;
5272 case glslang::EOpBitfieldInsert:
5273 opCode = spv::OpBitFieldInsert;
5274 break;
5275
5276 case glslang::EOpFma:
5277 libCall = spv::GLSLstd450Fma;
5278 break;
5279 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005280 {
5281 libCall = spv::GLSLstd450FrexpStruct;
5282 assert(builder.isPointerType(typeId1));
5283 typeId1 = builder.getContainedTypeId(typeId1);
5284#ifdef AMD_EXTENSIONS
5285 int width = builder.getScalarTypeWidth(typeId1);
5286#else
5287 int width = 32;
5288#endif
5289 if (builder.getNumComponents(operands[0]) == 1)
5290 frexpIntType = builder.makeIntegerType(width, true);
5291 else
5292 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
5293 typeId = builder.makeStructResultType(typeId0, frexpIntType);
5294 consumedOperands = 1;
5295 }
John Kessenich55e7d112015-11-15 21:33:39 -07005296 break;
5297 case glslang::EOpLdexp:
5298 libCall = spv::GLSLstd450Ldexp;
5299 break;
5300
Rex Xu574ab042016-04-14 16:53:07 +08005301 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08005302 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08005303
Rex Xu9d93a232016-05-05 12:30:44 +08005304#ifdef AMD_EXTENSIONS
5305 case glslang::EOpSwizzleInvocations:
5306 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5307 libCall = spv::SwizzleInvocationsAMD;
5308 break;
5309 case glslang::EOpSwizzleInvocationsMasked:
5310 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5311 libCall = spv::SwizzleInvocationsMaskedAMD;
5312 break;
5313 case glslang::EOpWriteInvocation:
5314 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5315 libCall = spv::WriteInvocationAMD;
5316 break;
5317
5318 case glslang::EOpMin3:
5319 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5320 if (isFloat)
5321 libCall = spv::FMin3AMD;
5322 else {
5323 if (isUnsigned)
5324 libCall = spv::UMin3AMD;
5325 else
5326 libCall = spv::SMin3AMD;
5327 }
5328 break;
5329 case glslang::EOpMax3:
5330 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5331 if (isFloat)
5332 libCall = spv::FMax3AMD;
5333 else {
5334 if (isUnsigned)
5335 libCall = spv::UMax3AMD;
5336 else
5337 libCall = spv::SMax3AMD;
5338 }
5339 break;
5340 case glslang::EOpMid3:
5341 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5342 if (isFloat)
5343 libCall = spv::FMid3AMD;
5344 else {
5345 if (isUnsigned)
5346 libCall = spv::UMid3AMD;
5347 else
5348 libCall = spv::SMid3AMD;
5349 }
5350 break;
5351
5352 case glslang::EOpInterpolateAtVertex:
5353 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
5354 libCall = spv::InterpolateAtVertexAMD;
5355 break;
5356#endif
5357
John Kessenich140f3df2015-06-26 16:58:36 -06005358 default:
5359 return 0;
5360 }
5361
5362 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07005363 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05005364 // Use an extended instruction from the standard library.
5365 // Construct the call arguments, without modifying the original operands vector.
5366 // We might need the remaining arguments, e.g. in the EOpFrexp case.
5367 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08005368 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07005369 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07005370 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06005371 case 0:
5372 // should all be handled by visitAggregate and createNoArgOperation
5373 assert(0);
5374 return 0;
5375 case 1:
5376 // should all be handled by createUnaryOperation
5377 assert(0);
5378 return 0;
5379 case 2:
5380 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
5381 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005382 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005383 // anything 3 or over doesn't have l-value operands, so all should be consumed
5384 assert(consumedOperands == operands.size());
5385 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06005386 break;
5387 }
5388 }
5389
John Kessenich55e7d112015-11-15 21:33:39 -07005390 // Decode the return types that were structures
5391 switch (op) {
5392 case glslang::EOpAddCarry:
5393 case glslang::EOpSubBorrow:
5394 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5395 id = builder.createCompositeExtract(id, typeId0, 0);
5396 break;
5397 case glslang::EOpUMulExtended:
5398 case glslang::EOpIMulExtended:
5399 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
5400 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5401 break;
5402 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005403 {
5404 assert(operands.size() == 2);
5405 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
5406 // "exp" is floating-point type (from HLSL intrinsic)
5407 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
5408 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
5409 builder.createStore(member1, operands[1]);
5410 } else
5411 // "exp" is integer type (from GLSL built-in function)
5412 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
5413 id = builder.createCompositeExtract(id, typeId0, 0);
5414 }
John Kessenich55e7d112015-11-15 21:33:39 -07005415 break;
5416 default:
5417 break;
5418 }
5419
John Kessenich32cfd492016-02-02 12:37:46 -07005420 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005421}
5422
Rex Xu9d93a232016-05-05 12:30:44 +08005423// Intrinsics with no arguments (or no return value, and no precision).
5424spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06005425{
5426 // TODO: get the barrier operands correct
5427
5428 switch (op) {
5429 case glslang::EOpEmitVertex:
5430 builder.createNoResultOp(spv::OpEmitVertex);
5431 return 0;
5432 case glslang::EOpEndPrimitive:
5433 builder.createNoResultOp(spv::OpEndPrimitive);
5434 return 0;
5435 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07005436 if (glslangIntermediate->getStage() == EShLangTessControl) {
5437 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
5438 // TODO: prefer the following, when available:
5439 // builder.createControlBarrier(spv::ScopePatch, spv::ScopePatch,
5440 // spv::MemorySemanticsPatchMask |
5441 // spv::MemorySemanticsAcquireReleaseMask);
5442 } else {
5443 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
5444 spv::MemorySemanticsWorkgroupMemoryMask |
5445 spv::MemorySemanticsAcquireReleaseMask);
5446 }
John Kessenich140f3df2015-06-26 16:58:36 -06005447 return 0;
5448 case glslang::EOpMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07005449 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory |
5450 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005451 return 0;
5452 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich82979362017-12-11 04:02:24 -07005453 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask |
5454 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005455 return 0;
5456 case glslang::EOpMemoryBarrierBuffer:
John Kessenich82979362017-12-11 04:02:24 -07005457 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
5458 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005459 return 0;
5460 case glslang::EOpMemoryBarrierImage:
John Kessenich82979362017-12-11 04:02:24 -07005461 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask |
5462 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005463 return 0;
5464 case glslang::EOpMemoryBarrierShared:
John Kessenich82979362017-12-11 04:02:24 -07005465 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask |
5466 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005467 return 0;
5468 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07005469 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
5470 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005471 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06005472 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07005473 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07005474 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07005475 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06005476 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07005477 case glslang::EOpDeviceMemoryBarrier:
5478 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
5479 spv::MemorySemanticsImageMemoryMask |
5480 spv::MemorySemanticsAcquireReleaseMask);
5481 return 0;
5482 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
5483 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
5484 spv::MemorySemanticsImageMemoryMask |
5485 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06005486 return 0;
5487 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07005488 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
5489 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06005490 return 0;
5491 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07005492 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
5493 spv::MemorySemanticsWorkgroupMemoryMask |
5494 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06005495 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08005496#ifdef AMD_EXTENSIONS
5497 case glslang::EOpTime:
5498 {
5499 std::vector<spv::Id> args; // Dummy arguments
5500 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
5501 return builder.setPrecision(id, precision);
5502 }
5503#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005504 default:
Lei Zhang17535f72016-05-04 15:55:59 -04005505 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06005506 return 0;
5507 }
5508}
5509
5510spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
5511{
John Kessenich2f273362015-07-18 22:34:27 -06005512 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06005513 spv::Id id;
5514 if (symbolValues.end() != iter) {
5515 id = iter->second;
5516 return id;
5517 }
5518
5519 // it was not found, create it
5520 id = createSpvVariable(symbol);
5521 symbolValues[symbol->getId()] = id;
5522
Rex Xuc884b4a2016-06-29 15:03:44 +08005523 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06005524 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07005525 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08005526 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07005527 if (symbol->getType().getQualifier().hasSpecConstantId())
5528 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06005529 if (symbol->getQualifier().hasIndex())
5530 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
5531 if (symbol->getQualifier().hasComponent())
5532 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06005533 // atomic counters use this:
5534 if (symbol->getQualifier().hasOffset())
5535 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005536 }
5537
scygan2c864272016-05-18 18:09:17 +02005538 if (symbol->getQualifier().hasLocation())
5539 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07005540 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07005541 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07005542 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06005543 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07005544 }
John Kessenich140f3df2015-06-26 16:58:36 -06005545 if (symbol->getQualifier().hasSet())
5546 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07005547 else if (IsDescriptorResource(symbol->getType())) {
5548 // default to 0
5549 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
5550 }
John Kessenich140f3df2015-06-26 16:58:36 -06005551 if (symbol->getQualifier().hasBinding())
5552 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07005553 if (symbol->getQualifier().hasAttachment())
5554 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06005555 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005556 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005557 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005558 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenichedaf5562017-12-15 06:21:46 -07005559 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06005560 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07005561 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
5562 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
5563 builder.addDecoration(id, spv::DecorationXfbStride, stride);
5564 }
5565 if (symbol->getQualifier().hasXfbOffset())
5566 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005567 }
5568
Rex Xu1da878f2016-02-21 20:59:01 +08005569 if (symbol->getType().isImage()) {
5570 std::vector<spv::Decoration> memory;
5571 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
5572 for (unsigned int i = 0; i < memory.size(); ++i)
5573 addDecoration(id, memory[i]);
5574 }
5575
John Kessenich140f3df2015-06-26 16:58:36 -06005576 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06005577 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06005578 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07005579 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06005580
John Kessenichecba76f2017-01-06 00:34:48 -07005581#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08005582 if (builtIn == spv::BuiltInSampleMask) {
5583 spv::Decoration decoration;
5584 // GL_NV_sample_mask_override_coverage extension
5585 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08005586 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08005587 else
5588 decoration = (spv::Decoration)spv::DecorationMax;
5589 addDecoration(id, decoration);
5590 if (decoration != spv::DecorationMax) {
5591 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
5592 }
5593 }
chaoc771d89f2017-01-13 01:10:53 -08005594 else if (builtIn == spv::BuiltInLayer) {
5595 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06005596 if (symbol->getQualifier().layoutViewportRelative) {
chaoc771d89f2017-01-13 01:10:53 -08005597 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
5598 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
5599 builder.addExtension(spv::E_SPV_NV_viewport_array2);
5600 }
John Kessenichb41bff62017-08-11 13:07:17 -06005601 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
chaoc771d89f2017-01-13 01:10:53 -08005602 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
5603 builder.addCapability(spv::CapabilityShaderStereoViewNV);
5604 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
5605 }
5606 }
5607
chaoc6e5acae2016-12-20 13:28:52 -08005608 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08005609 addDecoration(id, spv::DecorationPassthroughNV);
5610 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08005611 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
5612 }
chaoc0ad6a4e2016-12-19 16:29:34 -08005613#endif
5614
John Kessenich140f3df2015-06-26 16:58:36 -06005615 return id;
5616}
5617
John Kessenich55e7d112015-11-15 21:33:39 -07005618// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06005619void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
5620{
John Kessenich4016e382016-07-15 11:53:56 -06005621 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005622 builder.addDecoration(id, dec);
5623}
5624
John Kessenich55e7d112015-11-15 21:33:39 -07005625// If 'dec' is valid, add a one-operand decoration to an object
5626void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
5627{
John Kessenich4016e382016-07-15 11:53:56 -06005628 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07005629 builder.addDecoration(id, dec, value);
5630}
5631
5632// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005633void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5634{
John Kessenich4016e382016-07-15 11:53:56 -06005635 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005636 builder.addMemberDecoration(id, (unsigned)member, dec);
5637}
5638
John Kessenich92187592016-02-01 13:45:25 -07005639// If 'dec' is valid, add a one-operand decoration to a struct member
5640void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5641{
John Kessenich4016e382016-07-15 11:53:56 -06005642 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005643 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5644}
5645
John Kessenich55e7d112015-11-15 21:33:39 -07005646// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005647// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005648//
5649// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5650//
5651// Recursively walk the nodes. The nodes form a tree whose leaves are
5652// regular constants, which themselves are trees that createSpvConstant()
5653// recursively walks. So, this function walks the "top" of the tree:
5654// - emit specialization constant-building instructions for specConstant
5655// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005656spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005657{
John Kessenich7cc0e282016-03-20 00:46:02 -06005658 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005659
qining4f4bb812016-04-03 23:55:17 -04005660 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005661 if (! node.getQualifier().specConstant) {
5662 // hand off to the non-spec-constant path
5663 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5664 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005665 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005666 nextConst, false);
5667 }
5668
5669 // We now know we have a specialization constant to build
5670
John Kessenichd94c0032016-05-30 19:29:40 -06005671 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005672 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5673 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5674 std::vector<spv::Id> dimConstId;
5675 for (int dim = 0; dim < 3; ++dim) {
5676 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5677 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5678 if (specConst)
5679 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5680 }
5681 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5682 }
5683
5684 // An AST node labelled as specialization constant should be a symbol node.
5685 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5686 if (auto* sn = node.getAsSymbolNode()) {
5687 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005688 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5689 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5690 // will set the builder into spec constant op instruction generating mode.
5691 sub_tree->traverse(this);
5692 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005693 } else if (auto* const_union_array = &sn->getConstArray()){
5694 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005695 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5696 builder.addName(id, sn->getName().c_str());
5697 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005698 }
5699 }
qining4f4bb812016-04-03 23:55:17 -04005700
5701 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5702 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005703 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005704 exit(1);
5705 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005706}
5707
John Kessenich140f3df2015-06-26 16:58:36 -06005708// Use 'consts' as the flattened glslang source of scalar constants to recursively
5709// build the aggregate SPIR-V constant.
5710//
5711// If there are not enough elements present in 'consts', 0 will be substituted;
5712// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5713//
qining08408382016-03-21 09:51:37 -04005714spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005715{
5716 // vector of constants for SPIR-V
5717 std::vector<spv::Id> spvConsts;
5718
5719 // Type is used for struct and array constants
5720 spv::Id typeId = convertGlslangToSpvType(glslangType);
5721
5722 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005723 glslang::TType elementType(glslangType, 0);
5724 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005725 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005726 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005727 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005728 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005729 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005730 } else if (glslangType.getStruct()) {
5731 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5732 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005733 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005734 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005735 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5736 bool zero = nextConst >= consts.size();
5737 switch (glslangType.getBasicType()) {
5738 case glslang::EbtInt:
5739 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5740 break;
5741 case glslang::EbtUint:
5742 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5743 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005744 case glslang::EbtInt64:
5745 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5746 break;
5747 case glslang::EbtUint64:
5748 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5749 break;
Rex Xucabbb782017-03-24 13:41:14 +08005750#ifdef AMD_EXTENSIONS
5751 case glslang::EbtInt16:
5752 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst()));
5753 break;
5754 case glslang::EbtUint16:
5755 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst()));
5756 break;
5757#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005758 case glslang::EbtFloat:
5759 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5760 break;
5761 case glslang::EbtDouble:
5762 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5763 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005764#ifdef AMD_EXTENSIONS
5765 case glslang::EbtFloat16:
5766 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5767 break;
5768#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005769 case glslang::EbtBool:
5770 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5771 break;
5772 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005773 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005774 break;
5775 }
5776 ++nextConst;
5777 }
5778 } else {
5779 // we have a non-aggregate (scalar) constant
5780 bool zero = nextConst >= consts.size();
5781 spv::Id scalar = 0;
5782 switch (glslangType.getBasicType()) {
5783 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005784 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005785 break;
5786 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005787 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005788 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005789 case glslang::EbtInt64:
5790 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5791 break;
5792 case glslang::EbtUint64:
5793 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5794 break;
Rex Xucabbb782017-03-24 13:41:14 +08005795#ifdef AMD_EXTENSIONS
5796 case glslang::EbtInt16:
5797 scalar = builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst(), specConstant);
5798 break;
5799 case glslang::EbtUint16:
5800 scalar = builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst(), specConstant);
5801 break;
5802#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005803 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005804 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005805 break;
5806 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005807 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005808 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005809#ifdef AMD_EXTENSIONS
5810 case glslang::EbtFloat16:
5811 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5812 break;
5813#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005814 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005815 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005816 break;
5817 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005818 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005819 break;
5820 }
5821 ++nextConst;
5822 return scalar;
5823 }
5824
5825 return builder.makeCompositeConstant(typeId, spvConsts);
5826}
5827
John Kessenich7c1aa102015-10-15 13:29:11 -06005828// Return true if the node is a constant or symbol whose reading has no
5829// non-trivial observable cost or effect.
5830bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5831{
5832 // don't know what this is
5833 if (node == nullptr)
5834 return false;
5835
5836 // a constant is safe
5837 if (node->getAsConstantUnion() != nullptr)
5838 return true;
5839
5840 // not a symbol means non-trivial
5841 if (node->getAsSymbolNode() == nullptr)
5842 return false;
5843
5844 // a symbol, depends on what's being read
5845 switch (node->getType().getQualifier().storage) {
5846 case glslang::EvqTemporary:
5847 case glslang::EvqGlobal:
5848 case glslang::EvqIn:
5849 case glslang::EvqInOut:
5850 case glslang::EvqConst:
5851 case glslang::EvqConstReadOnly:
5852 case glslang::EvqUniform:
5853 return true;
5854 default:
5855 return false;
5856 }
qining25262b32016-05-06 17:25:16 -04005857}
John Kessenich7c1aa102015-10-15 13:29:11 -06005858
5859// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06005860// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06005861// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06005862// Return true if trivial.
5863bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5864{
5865 if (node == nullptr)
5866 return false;
5867
John Kessenich84cc15f2017-05-24 16:44:47 -06005868 // count non scalars as trivial, as well as anything coming from HLSL
5869 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06005870 return true;
5871
John Kessenich7c1aa102015-10-15 13:29:11 -06005872 // symbols and constants are trivial
5873 if (isTrivialLeaf(node))
5874 return true;
5875
5876 // otherwise, it needs to be a simple operation or one or two leaf nodes
5877
5878 // not a simple operation
5879 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5880 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5881 if (binaryNode == nullptr && unaryNode == nullptr)
5882 return false;
5883
5884 // not on leaf nodes
5885 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5886 return false;
5887
5888 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5889 return false;
5890 }
5891
5892 switch (node->getAsOperator()->getOp()) {
5893 case glslang::EOpLogicalNot:
5894 case glslang::EOpConvIntToBool:
5895 case glslang::EOpConvUintToBool:
5896 case glslang::EOpConvFloatToBool:
5897 case glslang::EOpConvDoubleToBool:
5898 case glslang::EOpEqual:
5899 case glslang::EOpNotEqual:
5900 case glslang::EOpLessThan:
5901 case glslang::EOpGreaterThan:
5902 case glslang::EOpLessThanEqual:
5903 case glslang::EOpGreaterThanEqual:
5904 case glslang::EOpIndexDirect:
5905 case glslang::EOpIndexDirectStruct:
5906 case glslang::EOpLogicalXor:
5907 case glslang::EOpAny:
5908 case glslang::EOpAll:
5909 return true;
5910 default:
5911 return false;
5912 }
5913}
5914
5915// Emit short-circuiting code, where 'right' is never evaluated unless
5916// the left side is true (for &&) or false (for ||).
5917spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5918{
5919 spv::Id boolTypeId = builder.makeBoolType();
5920
5921 // emit left operand
5922 builder.clearAccessChain();
5923 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005924 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005925
5926 // Operands to accumulate OpPhi operands
5927 std::vector<spv::Id> phiOperands;
5928 // accumulate left operand's phi information
5929 phiOperands.push_back(leftId);
5930 phiOperands.push_back(builder.getBuildPoint()->getId());
5931
5932 // Make the two kinds of operation symmetric with a "!"
5933 // || => emit "if (! left) result = right"
5934 // && => emit "if ( left) result = right"
5935 //
5936 // TODO: this runtime "not" for || could be avoided by adding functionality
5937 // to 'builder' to have an "else" without an "then"
5938 if (op == glslang::EOpLogicalOr)
5939 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5940
5941 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08005942 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06005943
5944 // emit right operand as the "then" part of the "if"
5945 builder.clearAccessChain();
5946 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005947 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005948
5949 // accumulate left operand's phi information
5950 phiOperands.push_back(rightId);
5951 phiOperands.push_back(builder.getBuildPoint()->getId());
5952
5953 // finish the "if"
5954 ifBuilder.makeEndIf();
5955
5956 // phi together the two results
5957 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5958}
5959
Frank Henigman541f7bb2018-01-16 00:18:26 -05005960#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08005961// Return type Id of the imported set of extended instructions corresponds to the name.
5962// Import this set if it has not been imported yet.
5963spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5964{
5965 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5966 return extBuiltinMap[name];
5967 else {
Rex Xu51596642016-09-21 18:56:12 +08005968 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005969 spv::Id extBuiltins = builder.import(name);
5970 extBuiltinMap[name] = extBuiltins;
5971 return extBuiltins;
5972 }
5973}
Frank Henigman541f7bb2018-01-16 00:18:26 -05005974#endif
Rex Xu9d93a232016-05-05 12:30:44 +08005975
John Kessenich140f3df2015-06-26 16:58:36 -06005976}; // end anonymous namespace
5977
5978namespace glslang {
5979
John Kessenich68d78fd2015-07-12 19:28:10 -06005980void GetSpirvVersion(std::string& version)
5981{
John Kessenich9e55f632015-07-15 10:03:39 -06005982 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005983 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005984 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005985 version = buf;
5986}
5987
John Kessenicha372a3e2017-11-02 22:32:14 -06005988// For low-order part of the generator's magic number. Bump up
5989// when there is a change in the style (e.g., if SSA form changes,
5990// or a different instruction sequence to do something gets used).
5991int GetSpirvGeneratorVersion()
5992{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07005993 // return 1; // start
5994 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
5995 return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenicha372a3e2017-11-02 22:32:14 -06005996}
5997
John Kessenich140f3df2015-06-26 16:58:36 -06005998// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005999void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06006000{
6001 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06006002 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07006003 if (out.fail())
6004 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06006005 for (int i = 0; i < (int)spirv.size(); ++i) {
6006 unsigned int word = spirv[i];
6007 out.write((const char*)&word, 4);
6008 }
6009 out.close();
6010}
6011
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006012// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08006013void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006014{
6015 std::ofstream out;
6016 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07006017 if (out.fail())
6018 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006019 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08006020 if (varName != nullptr) {
6021 out << "\t #pragma once" << std::endl;
6022 out << "const uint32_t " << varName << "[] = {" << std::endl;
6023 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006024 const int WORDS_PER_LINE = 8;
6025 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
6026 out << "\t";
6027 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
6028 const unsigned int word = spirv[i + j];
6029 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
6030 if (i + j + 1 < (int)spirv.size()) {
6031 out << ",";
6032 }
6033 }
6034 out << std::endl;
6035 }
Flavio15017db2017-02-15 14:29:33 -08006036 if (varName != nullptr) {
6037 out << "};";
6038 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006039 out.close();
6040}
6041
GregFcd1f1692017-09-21 18:40:22 -06006042#ifdef ENABLE_OPT
6043void errHandler(const std::string& str) {
6044 std::cerr << str << std::endl;
6045}
6046#endif
6047
John Kessenich140f3df2015-06-26 16:58:36 -06006048//
6049// Set up the glslang traversal
6050//
John Kessenich121853f2017-05-31 17:11:16 -06006051void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06006052{
Lei Zhang17535f72016-05-04 15:55:59 -04006053 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06006054 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04006055}
6056
John Kessenich121853f2017-05-31 17:11:16 -06006057void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv,
6058 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04006059{
John Kessenich140f3df2015-06-26 16:58:36 -06006060 TIntermNode* root = intermediate.getTreeRoot();
6061
6062 if (root == 0)
6063 return;
6064
John Kessenich121853f2017-05-31 17:11:16 -06006065 glslang::SpvOptions defaultOptions;
6066 if (options == nullptr)
6067 options = &defaultOptions;
6068
John Kessenich140f3df2015-06-26 16:58:36 -06006069 glslang::GetThreadPoolAllocator().push();
6070
John Kessenich2b5ea9f2018-01-31 18:35:56 -07006071 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06006072 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07006073 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06006074 it.dumpSpv(spirv);
6075
GregFcd1f1692017-09-21 18:40:22 -06006076#ifdef ENABLE_OPT
6077 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
6078 // eg. forward and remove memory writes of opaque types.
6079 if ((intermediate.getSource() == EShSourceHlsl ||
6080 options->optimizeSize) &&
6081 !options->disableOptimizer) {
6082 spv_target_env target_env = SPV_ENV_UNIVERSAL_1_2;
6083
6084 spvtools::Optimizer optimizer(target_env);
6085 optimizer.SetMessageConsumer([](spv_message_level_t level,
6086 const char* source,
6087 const spv_position_t& position,
6088 const char* message) {
6089 std::cerr << StringifyMessage(level, source, position, message)
6090 << std::endl;
6091 });
6092
6093 optimizer.RegisterPass(CreateInlineExhaustivePass());
GregFe0639282017-12-21 10:55:57 -07006094 optimizer.RegisterPass(CreateEliminateDeadFunctionsPass());
6095 optimizer.RegisterPass(CreateScalarReplacementPass());
GregFcd1f1692017-09-21 18:40:22 -06006096 optimizer.RegisterPass(CreateLocalAccessChainConvertPass());
6097 optimizer.RegisterPass(CreateLocalSingleBlockLoadStoreElimPass());
6098 optimizer.RegisterPass(CreateLocalSingleStoreElimPass());
6099 optimizer.RegisterPass(CreateInsertExtractElimPass());
6100 optimizer.RegisterPass(CreateAggressiveDCEPass());
6101 optimizer.RegisterPass(CreateDeadBranchElimPass());
GregFcc80d802017-10-23 16:48:42 -06006102 optimizer.RegisterPass(CreateCFGCleanupPass());
GregFcd1f1692017-09-21 18:40:22 -06006103 optimizer.RegisterPass(CreateBlockMergePass());
6104 optimizer.RegisterPass(CreateLocalMultiStoreElimPass());
6105 optimizer.RegisterPass(CreateInsertExtractElimPass());
6106 optimizer.RegisterPass(CreateAggressiveDCEPass());
6107 // TODO(greg-lunarg): Add this when AMD driver issues are resolved
6108 // if (options->optimizeSize)
6109 // optimizer.RegisterPass(CreateCommonUniformElimPass());
6110
6111 if (!optimizer.Run(spirv.data(), spirv.size(), &spirv))
6112 return;
6113
6114 // Remove dead module-level objects: functions, types, vars
6115 // TODO(greg-lunarg): Switch to spirv-opt versions when available
6116 spv::spirvbin_t Remapper(0);
6117 Remapper.registerErrorHandler(errHandler);
6118 Remapper.remap(spirv, spv::spirvbin_t::DCE_ALL);
6119 }
6120#endif
6121
John Kessenich140f3df2015-06-26 16:58:36 -06006122 glslang::GetThreadPoolAllocator().pop();
6123}
6124
6125}; // end namespace glslang