blob: eaa8cd3afd2499aec3ca174c27eb55e97a146b61 [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"
Rex Xu9d93a232016-05-05 12:30:44 +080047#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080048 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080049#endif
chaoc0ad6a4e2016-12-19 16:29:34 -080050#ifdef NV_EXTENSIONS
51 #include "GLSL.ext.NV.h"
52#endif
John Kessenich5e4b1242015-08-06 22:53:06 -060053}
John Kessenich140f3df2015-06-26 16:58:36 -060054
55// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020056#include "../glslang/MachineIndependent/localintermediate.h"
57#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060058#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050059#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060060
John Kessenich140f3df2015-06-26 16:58:36 -060061#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050062#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040063#include <list>
64#include <map>
65#include <stack>
66#include <string>
67#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060068
69namespace {
70
John Kessenich55e7d112015-11-15 21:33:39 -070071// For low-order part of the generator's magic number. Bump up
72// when there is a change in the style (e.g., if SSA form changes,
73// or a different instruction sequence to do something gets used).
74const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060075
qining4c912612016-04-01 10:35:16 -040076namespace {
77class SpecConstantOpModeGuard {
78public:
79 SpecConstantOpModeGuard(spv::Builder* builder)
80 : builder_(builder) {
81 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040082 }
83 ~SpecConstantOpModeGuard() {
84 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
85 : builder_->setToNormalCodeGenMode();
86 }
qining40887662016-04-03 22:20:42 -040087 void turnOnSpecConstantOpMode() {
88 builder_->setToSpecConstCodeGenMode();
89 }
qining4c912612016-04-01 10:35:16 -040090
91private:
92 spv::Builder* builder_;
93 bool previous_flag_;
94};
95}
96
John Kessenich140f3df2015-06-26 16:58:36 -060097//
98// The main holder of information for translating glslang to SPIR-V.
99//
100// Derives from the AST walking base class.
101//
102class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
103public:
John Kessenich121853f2017-05-31 17:11:16 -0600104 TGlslangToSpvTraverser(const glslang::TIntermediate*, spv::SpvBuildLogger* logger, glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700105 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600106
107 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
108 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
109 void visitConstantUnion(glslang::TIntermConstantUnion*);
110 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
111 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
112 void visitSymbol(glslang::TIntermSymbol* symbol);
113 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
114 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
115 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
116
John Kessenichfca82622016-11-26 13:23:20 -0700117 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700118 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600119
120protected:
Rex Xu17ff3432016-10-14 17:41:45 +0800121 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800122 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100123 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700124 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
steve-lunargf1709e72017-05-02 20:14:50 -0600125 spv::LoopControlMask TranslateLoopControl(glslang::TLoopControl) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600126 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich140f3df2015-06-26 16:58:36 -0600127 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
128 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600129 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
130 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
131 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600132 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700133 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich0e737842017-03-24 18:38:16 -0600134 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600135 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
136 glslang::TLayoutPacking, const glslang::TQualifier&);
137 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
138 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700139 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700140 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800141 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600142 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700143 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700144 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
145 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
146 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 +0100147 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600148
John Kessenich6fccb3c2016-09-19 16:01:41 -0600149 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600150 void makeFunctions(const glslang::TIntermSequence&);
151 void makeGlobalInitializers(const glslang::TIntermSequence&);
152 void visitFunctions(const glslang::TIntermSequence&);
153 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800154 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600155 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
156 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600157 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
158
qining25262b32016-05-06 17:25:16 -0400159 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);
160 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
161 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 +0800162 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 +0800163 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 -0600164 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800165 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 +0800166 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800167 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich5e4b1242015-08-06 22:53:06 -0600168 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 +0800169 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600170 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
171 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700172 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600173 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700174 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400175 spv::Id createSpvConstant(const glslang::TIntermTyped&);
176 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600177 bool isTrivialLeaf(const glslang::TIntermTyped* node);
178 bool isTrivial(const glslang::TIntermTyped* node);
179 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800180 spv::Id getExtBuiltins(const char* name);
John Kessenich140f3df2015-06-26 16:58:36 -0600181
John Kessenich121853f2017-05-31 17:11:16 -0600182 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600183 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600184 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700185 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600186 int sequenceDepth;
187
Lei Zhang17535f72016-05-04 15:55:59 -0400188 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400189
John Kessenich140f3df2015-06-26 16:58:36 -0600190 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
191 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700192 bool inEntryPoint;
193 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700194 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 -0700195 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600196 const glslang::TIntermediate* glslangIntermediate;
197 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800198 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600199
John Kessenich2f273362015-07-18 22:34:27 -0600200 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600201 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600202 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700203 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600204 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 -0600205 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600206};
207
208//
209// Helper functions for translating glslang representations to SPIR-V enumerants.
210//
211
212// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700213spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600214{
John Kessenich66e2faf2016-03-12 18:34:36 -0700215 switch (source) {
216 case glslang::EShSourceGlsl:
217 switch (profile) {
218 case ENoProfile:
219 case ECoreProfile:
220 case ECompatibilityProfile:
221 return spv::SourceLanguageGLSL;
222 case EEsProfile:
223 return spv::SourceLanguageESSL;
224 default:
225 return spv::SourceLanguageUnknown;
226 }
227 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600228 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600229 default:
230 return spv::SourceLanguageUnknown;
231 }
232}
233
234// Translate glslang language (stage) to SPIR-V execution model.
235spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
236{
237 switch (stage) {
238 case EShLangVertex: return spv::ExecutionModelVertex;
239 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
240 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
241 case EShLangGeometry: return spv::ExecutionModelGeometry;
242 case EShLangFragment: return spv::ExecutionModelFragment;
243 case EShLangCompute: return spv::ExecutionModelGLCompute;
244 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700245 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600246 return spv::ExecutionModelFragment;
247 }
248}
249
John Kessenich140f3df2015-06-26 16:58:36 -0600250// Translate glslang sampler type to SPIR-V dimensionality.
251spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
252{
253 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700254 case glslang::Esd1D: return spv::Dim1D;
255 case glslang::Esd2D: return spv::Dim2D;
256 case glslang::Esd3D: return spv::Dim3D;
257 case glslang::EsdCube: return spv::DimCube;
258 case glslang::EsdRect: return spv::DimRect;
259 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700260 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600261 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700262 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600263 return spv::Dim2D;
264 }
265}
266
John Kessenichf6640762016-08-01 19:44:00 -0600267// Translate glslang precision to SPIR-V precision decorations.
268spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600269{
John Kessenichf6640762016-08-01 19:44:00 -0600270 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700271 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600272 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600273 default:
274 return spv::NoPrecision;
275 }
276}
277
John Kessenichf6640762016-08-01 19:44:00 -0600278// Translate glslang type to SPIR-V precision decorations.
279spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
280{
281 return TranslatePrecisionDecoration(type.getQualifier().precision);
282}
283
John Kessenich140f3df2015-06-26 16:58:36 -0600284// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600285spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600286{
287 if (type.getBasicType() == glslang::EbtBlock) {
288 switch (type.getQualifier().storage) {
289 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600290 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600291 case glslang::EvqVaryingIn: return spv::DecorationBlock;
292 case glslang::EvqVaryingOut: return spv::DecorationBlock;
293 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700294 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600295 break;
296 }
297 }
298
John Kessenich4016e382016-07-15 11:53:56 -0600299 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600300}
301
Rex Xu1da878f2016-02-21 20:59:01 +0800302// Translate glslang type to SPIR-V memory decorations.
303void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
304{
305 if (qualifier.coherent)
306 memory.push_back(spv::DecorationCoherent);
307 if (qualifier.volatil)
308 memory.push_back(spv::DecorationVolatile);
309 if (qualifier.restrict)
310 memory.push_back(spv::DecorationRestrict);
311 if (qualifier.readonly)
312 memory.push_back(spv::DecorationNonWritable);
313 if (qualifier.writeonly)
314 memory.push_back(spv::DecorationNonReadable);
315}
316
John Kessenich140f3df2015-06-26 16:58:36 -0600317// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700318spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600319{
320 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700321 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600322 case glslang::ElmRowMajor:
323 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700324 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600325 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700326 default:
327 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600328 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600329 }
330 } else {
331 switch (type.getBasicType()) {
332 default:
John Kessenich4016e382016-07-15 11:53:56 -0600333 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600334 break;
335 case glslang::EbtBlock:
336 switch (type.getQualifier().storage) {
337 case glslang::EvqUniform:
338 case glslang::EvqBuffer:
339 switch (type.getQualifier().layoutPacking) {
340 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600341 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
342 default:
John Kessenich4016e382016-07-15 11:53:56 -0600343 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600344 }
345 case glslang::EvqVaryingIn:
346 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700347 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600348 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600349 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700350 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600351 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600352 }
353 }
354 }
355}
356
357// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600358// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700359// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800360spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600361{
Rex Xubbceed72016-05-21 09:40:44 +0800362 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700363 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600364 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800365 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700366 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700367 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600368 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800369#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800370 else if (qualifier.explicitInterp) {
371 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800372 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800373 }
Rex Xu9d93a232016-05-05 12:30:44 +0800374#endif
Rex Xubbceed72016-05-21 09:40:44 +0800375 else
John Kessenich4016e382016-07-15 11:53:56 -0600376 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800377}
378
379// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600380// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800381// should be applied.
382spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
383{
384 if (qualifier.patch)
385 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700386 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600387 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700388 else if (qualifier.sample) {
389 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600390 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700391 } else
John Kessenich4016e382016-07-15 11:53:56 -0600392 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600393}
394
John Kessenich92187592016-02-01 13:45:25 -0700395// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700396spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600397{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700398 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600399 return spv::DecorationInvariant;
400 else
John Kessenich4016e382016-07-15 11:53:56 -0600401 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600402}
403
qining9220dbb2016-05-04 17:34:38 -0400404// If glslang type is noContraction, return SPIR-V NoContraction decoration.
405spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
406{
407 if (qualifier.noContraction)
408 return spv::DecorationNoContraction;
409 else
John Kessenich4016e382016-07-15 11:53:56 -0600410 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400411}
412
David Netoa901ffe2016-06-08 14:11:40 +0100413// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
414// associated capabilities when required. For some built-in variables, a capability
415// is generated only when using the variable in an executable instruction, but not when
416// just declaring a struct member variable with it. This is true for PointSize,
417// ClipDistance, and CullDistance.
418spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600419{
420 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700421 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600422 // Defer adding the capability until the built-in is actually used.
423 if (! memberDeclaration) {
424 switch (glslangIntermediate->getStage()) {
425 case EShLangGeometry:
426 builder.addCapability(spv::CapabilityGeometryPointSize);
427 break;
428 case EShLangTessControl:
429 case EShLangTessEvaluation:
430 builder.addCapability(spv::CapabilityTessellationPointSize);
431 break;
432 default:
433 break;
434 }
John Kessenich92187592016-02-01 13:45:25 -0700435 }
436 return spv::BuiltInPointSize;
437
John Kessenichebb50532016-05-16 19:22:05 -0600438 // These *Distance capabilities logically belong here, but if the member is declared and
439 // then never used, consumers of SPIR-V prefer the capability not be declared.
440 // They are now generated when used, rather than here when declared.
441 // Potentially, the specification should be more clear what the minimum
442 // use needed is to trigger the capability.
443 //
John Kessenich92187592016-02-01 13:45:25 -0700444 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100445 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800446 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700447 return spv::BuiltInClipDistance;
448
449 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100450 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800451 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700452 return spv::BuiltInCullDistance;
453
454 case glslang::EbvViewportIndex:
Rex Xu5e317ff2017-03-16 23:02:39 +0800455 if (!memberDeclaration) {
456 builder.addCapability(spv::CapabilityMultiViewport);
chaoc771d89f2017-01-13 01:10:53 -0800457#ifdef NV_EXTENSIONS
Rex Xu5e317ff2017-03-16 23:02:39 +0800458 if (glslangIntermediate->getStage() == EShLangVertex ||
459 glslangIntermediate->getStage() == EShLangTessControl ||
460 glslangIntermediate->getStage() == EShLangTessEvaluation) {
461
462 builder.addExtension(spv::E_SPV_NV_viewport_array2);
463 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
464 }
chaoc771d89f2017-01-13 01:10:53 -0800465#endif
Rex Xu5e317ff2017-03-16 23:02:39 +0800466 }
John Kessenich92187592016-02-01 13:45:25 -0700467 return spv::BuiltInViewportIndex;
468
John Kessenich5e801132016-02-15 11:09:46 -0700469 case glslang::EbvSampleId:
470 builder.addCapability(spv::CapabilitySampleRateShading);
471 return spv::BuiltInSampleId;
472
473 case glslang::EbvSamplePosition:
474 builder.addCapability(spv::CapabilitySampleRateShading);
475 return spv::BuiltInSamplePosition;
476
477 case glslang::EbvSampleMask:
478 builder.addCapability(spv::CapabilitySampleRateShading);
479 return spv::BuiltInSampleMask;
480
John Kessenich78a45572016-07-08 14:05:15 -0600481 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +0800482 if (!memberDeclaration) {
483 builder.addCapability(spv::CapabilityGeometry);
chaoc771d89f2017-01-13 01:10:53 -0800484#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -0800485 if (glslangIntermediate->getStage() == EShLangVertex ||
486 glslangIntermediate->getStage() == EShLangTessControl ||
Rex Xu5e317ff2017-03-16 23:02:39 +0800487 glslangIntermediate->getStage() == EShLangTessEvaluation) {
488
chaoc771d89f2017-01-13 01:10:53 -0800489 builder.addExtension(spv::E_SPV_NV_viewport_array2);
490 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
491 }
chaoc771d89f2017-01-13 01:10:53 -0800492#endif
Rex Xu5e317ff2017-03-16 23:02:39 +0800493 }
494
John Kessenich78a45572016-07-08 14:05:15 -0600495 return spv::BuiltInLayer;
496
John Kessenich140f3df2015-06-26 16:58:36 -0600497 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600498 case glslang::EbvVertexId: return spv::BuiltInVertexId;
499 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700500 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
501 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800502
John Kessenichda581a22015-10-14 14:10:30 -0600503 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800504 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
505 builder.addCapability(spv::CapabilityDrawParameters);
506 return spv::BuiltInBaseVertex;
507
John Kessenichda581a22015-10-14 14:10:30 -0600508 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800509 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
510 builder.addCapability(spv::CapabilityDrawParameters);
511 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200512
John Kessenichda581a22015-10-14 14:10:30 -0600513 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800514 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
515 builder.addCapability(spv::CapabilityDrawParameters);
516 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200517
518 case glslang::EbvPrimitiveId:
519 if (glslangIntermediate->getStage() == EShLangFragment)
520 builder.addCapability(spv::CapabilityGeometry);
521 return spv::BuiltInPrimitiveId;
522
Rex Xu37cdcee2017-06-29 17:46:34 +0800523 case glslang::EbvFragStencilRef:
524 logger->missingFunctionality("shader stencil export");
525 return spv::BuiltInMax;
526
John Kessenich140f3df2015-06-26 16:58:36 -0600527 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600528 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
529 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
530 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
531 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
532 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
533 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
534 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600535 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
536 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
537 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
538 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
539 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
540 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
541 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
542 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800543
Rex Xu574ab042016-04-14 16:53:07 +0800544 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800545 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800546 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
547 return spv::BuiltInSubgroupSize;
548
Rex Xu574ab042016-04-14 16:53:07 +0800549 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800550 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800551 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
552 return spv::BuiltInSubgroupLocalInvocationId;
553
Rex Xu574ab042016-04-14 16:53:07 +0800554 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800555 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
556 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
557 return spv::BuiltInSubgroupEqMaskKHR;
558
Rex Xu574ab042016-04-14 16:53:07 +0800559 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800560 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
561 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
562 return spv::BuiltInSubgroupGeMaskKHR;
563
Rex Xu574ab042016-04-14 16:53:07 +0800564 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800565 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
566 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
567 return spv::BuiltInSubgroupGtMaskKHR;
568
Rex Xu574ab042016-04-14 16:53:07 +0800569 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800570 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
571 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
572 return spv::BuiltInSubgroupLeMaskKHR;
573
Rex Xu574ab042016-04-14 16:53:07 +0800574 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800575 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
576 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
577 return spv::BuiltInSubgroupLtMaskKHR;
578
Rex Xu9d93a232016-05-05 12:30:44 +0800579#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800580 case glslang::EbvBaryCoordNoPersp:
581 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
582 return spv::BuiltInBaryCoordNoPerspAMD;
583
584 case glslang::EbvBaryCoordNoPerspCentroid:
585 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
586 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
587
588 case glslang::EbvBaryCoordNoPerspSample:
589 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
590 return spv::BuiltInBaryCoordNoPerspSampleAMD;
591
592 case glslang::EbvBaryCoordSmooth:
593 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
594 return spv::BuiltInBaryCoordSmoothAMD;
595
596 case glslang::EbvBaryCoordSmoothCentroid:
597 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
598 return spv::BuiltInBaryCoordSmoothCentroidAMD;
599
600 case glslang::EbvBaryCoordSmoothSample:
601 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
602 return spv::BuiltInBaryCoordSmoothSampleAMD;
603
604 case glslang::EbvBaryCoordPullModel:
605 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
606 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800607#endif
chaoc771d89f2017-01-13 01:10:53 -0800608
John Kessenich6c8aaac2017-02-27 01:20:51 -0700609 case glslang::EbvDeviceIndex:
610 builder.addExtension(spv::E_SPV_KHR_device_group);
611 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700612 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700613
614 case glslang::EbvViewIndex:
615 builder.addExtension(spv::E_SPV_KHR_multiview);
616 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700617 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700618
chaoc771d89f2017-01-13 01:10:53 -0800619#ifdef NV_EXTENSIONS
620 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800621 if (!memberDeclaration) {
622 builder.addExtension(spv::E_SPV_NV_viewport_array2);
623 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
624 }
chaoc771d89f2017-01-13 01:10:53 -0800625 return spv::BuiltInViewportMaskNV;
626 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800627 if (!memberDeclaration) {
628 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
629 builder.addCapability(spv::CapabilityShaderStereoViewNV);
630 }
chaoc771d89f2017-01-13 01:10:53 -0800631 return spv::BuiltInSecondaryPositionNV;
632 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800633 if (!memberDeclaration) {
634 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
635 builder.addCapability(spv::CapabilityShaderStereoViewNV);
636 }
chaoc771d89f2017-01-13 01:10:53 -0800637 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800638 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800639 if (!memberDeclaration) {
640 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
641 builder.addCapability(spv::CapabilityPerViewAttributesNV);
642 }
chaocdf3956c2017-02-14 14:52:34 -0800643 return spv::BuiltInPositionPerViewNV;
644 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800645 if (!memberDeclaration) {
646 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
647 builder.addCapability(spv::CapabilityPerViewAttributesNV);
648 }
chaocdf3956c2017-02-14 14:52:34 -0800649 return spv::BuiltInViewportMaskPerViewNV;
chaoc771d89f2017-01-13 01:10:53 -0800650#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800651 default:
652 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600653 }
654}
655
Rex Xufc618912015-09-09 16:42:49 +0800656// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700657spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800658{
659 assert(type.getBasicType() == glslang::EbtSampler);
660
John Kessenich5d0fa972016-02-15 11:57:00 -0700661 // Check for capabilities
662 switch (type.getQualifier().layoutFormat) {
663 case glslang::ElfRg32f:
664 case glslang::ElfRg16f:
665 case glslang::ElfR11fG11fB10f:
666 case glslang::ElfR16f:
667 case glslang::ElfRgba16:
668 case glslang::ElfRgb10A2:
669 case glslang::ElfRg16:
670 case glslang::ElfRg8:
671 case glslang::ElfR16:
672 case glslang::ElfR8:
673 case glslang::ElfRgba16Snorm:
674 case glslang::ElfRg16Snorm:
675 case glslang::ElfRg8Snorm:
676 case glslang::ElfR16Snorm:
677 case glslang::ElfR8Snorm:
678
679 case glslang::ElfRg32i:
680 case glslang::ElfRg16i:
681 case glslang::ElfRg8i:
682 case glslang::ElfR16i:
683 case glslang::ElfR8i:
684
685 case glslang::ElfRgb10a2ui:
686 case glslang::ElfRg32ui:
687 case glslang::ElfRg16ui:
688 case glslang::ElfRg8ui:
689 case glslang::ElfR16ui:
690 case glslang::ElfR8ui:
691 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
692 break;
693
694 default:
695 break;
696 }
697
698 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800699 switch (type.getQualifier().layoutFormat) {
700 case glslang::ElfNone: return spv::ImageFormatUnknown;
701 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
702 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
703 case glslang::ElfR32f: return spv::ImageFormatR32f;
704 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
705 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
706 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
707 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
708 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
709 case glslang::ElfR16f: return spv::ImageFormatR16f;
710 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
711 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
712 case glslang::ElfRg16: return spv::ImageFormatRg16;
713 case glslang::ElfRg8: return spv::ImageFormatRg8;
714 case glslang::ElfR16: return spv::ImageFormatR16;
715 case glslang::ElfR8: return spv::ImageFormatR8;
716 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
717 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
718 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
719 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
720 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
721 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
722 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
723 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
724 case glslang::ElfR32i: return spv::ImageFormatR32i;
725 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
726 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
727 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
728 case glslang::ElfR16i: return spv::ImageFormatR16i;
729 case glslang::ElfR8i: return spv::ImageFormatR8i;
730 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
731 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
732 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
733 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
734 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
735 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
736 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
737 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
738 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
739 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600740 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800741 }
742}
743
steve-lunargf1709e72017-05-02 20:14:50 -0600744spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(glslang::TLoopControl loopControl) const
745{
746 switch (loopControl) {
747 case glslang::ELoopControlNone: return spv::LoopControlMaskNone;
748 case glslang::ELoopControlUnroll: return spv::LoopControlUnrollMask;
749 case glslang::ELoopControlDontUnroll: return spv::LoopControlDontUnrollMask;
750 // TODO: DependencyInfinite
751 // TODO: DependencyLength
752 default: return spv::LoopControlMaskNone;
753 }
754}
755
John Kessenicha5c5fb62017-05-05 05:09:58 -0600756// Translate glslang type to SPIR-V storage class.
757spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
758{
759 if (type.getQualifier().isPipeInput())
760 return spv::StorageClassInput;
761 else if (type.getQualifier().isPipeOutput())
762 return spv::StorageClassOutput;
763 else if (type.getBasicType() == glslang::EbtAtomicUint)
764 return spv::StorageClassAtomicCounter;
765 else if (type.containsOpaque())
766 return spv::StorageClassUniformConstant;
767 else if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
768 builder.addExtension(spv::E_SPV_KHR_storage_buffer_storage_class);
769 return spv::StorageClassStorageBuffer;
770 } else if (type.getQualifier().isUniformOrBuffer()) {
771 if (type.getQualifier().layoutPushConstant)
772 return spv::StorageClassPushConstant;
773 if (type.getBasicType() == glslang::EbtBlock)
774 return spv::StorageClassUniform;
775 else
776 return spv::StorageClassUniformConstant;
777 } else {
778 switch (type.getQualifier().storage) {
779 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
780 case glslang::EvqGlobal: return spv::StorageClassPrivate;
781 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
782 case glslang::EvqTemporary: return spv::StorageClassFunction;
783 default:
784 assert(0);
785 return spv::StorageClassFunction;
786 }
787 }
788}
789
qining25262b32016-05-06 17:25:16 -0400790// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700791// descriptor set.
792bool IsDescriptorResource(const glslang::TType& type)
793{
John Kessenichf7497e22016-03-08 21:36:22 -0700794 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700795 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700796 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700797
798 // non block...
799 // basically samplerXXX/subpass/sampler/texture are all included
800 // if they are the global-scope-class, not the function parameter
801 // (or local, if they ever exist) class.
802 if (type.getBasicType() == glslang::EbtSampler)
803 return type.getQualifier().isUniformOrBuffer();
804
805 // None of the above.
806 return false;
807}
808
John Kesseniche0b6cad2015-12-24 10:30:13 -0700809void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
810{
811 if (child.layoutMatrix == glslang::ElmNone)
812 child.layoutMatrix = parent.layoutMatrix;
813
814 if (parent.invariant)
815 child.invariant = true;
816 if (parent.nopersp)
817 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800818#ifdef AMD_EXTENSIONS
819 if (parent.explicitInterp)
820 child.explicitInterp = true;
821#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700822 if (parent.flat)
823 child.flat = true;
824 if (parent.centroid)
825 child.centroid = true;
826 if (parent.patch)
827 child.patch = true;
828 if (parent.sample)
829 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800830 if (parent.coherent)
831 child.coherent = true;
832 if (parent.volatil)
833 child.volatil = true;
834 if (parent.restrict)
835 child.restrict = true;
836 if (parent.readonly)
837 child.readonly = true;
838 if (parent.writeonly)
839 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700840}
841
John Kessenichf2b7f332016-09-01 17:05:23 -0600842bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700843{
John Kessenich7b9fa252016-01-21 18:56:57 -0700844 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600845 // - struct members might inherit from a struct declaration
846 // (note that non-block structs don't explicitly inherit,
847 // only implicitly, meaning no decoration involved)
848 // - affect decorations on the struct members
849 // (note smooth does not, and expecting something like volatile
850 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700851 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600852 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700853}
854
John Kessenich140f3df2015-06-26 16:58:36 -0600855//
856// Implement the TGlslangToSpvTraverser class.
857//
858
John Kessenich121853f2017-05-31 17:11:16 -0600859TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate,
860 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
861 : TIntermTraverser(true, false, true),
862 options(options),
863 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -0600864 sequenceDepth(0), logger(buildLogger),
Lei Zhang17535f72016-05-04 15:55:59 -0400865 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700866 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600867 glslangIntermediate(glslangIntermediate)
868{
869 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
870
871 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700872 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich121853f2017-05-31 17:11:16 -0600873 if (options.generateDebugInfo) {
874 builder.setSourceFile(glslangIntermediate->getSourceFile());
875 builder.setSourceText(glslangIntermediate->getSourceText());
John Kesseniche485c7a2017-05-31 18:50:53 -0600876 builder.setEmitOpLines();
John Kessenich121853f2017-05-31 17:11:16 -0600877 }
John Kessenich140f3df2015-06-26 16:58:36 -0600878 stdBuiltins = builder.import("GLSL.std.450");
879 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600880 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
881 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600882
883 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600884 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
885 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600886 builder.addSourceExtension(it->c_str());
887
888 // Add the top-level modes for this shader.
889
John Kessenich92187592016-02-01 13:45:25 -0700890 if (glslangIntermediate->getXfbMode()) {
891 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600892 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700893 }
John Kessenich140f3df2015-06-26 16:58:36 -0600894
895 unsigned int mode;
896 switch (glslangIntermediate->getStage()) {
897 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600898 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600899 break;
900
steve-lunarge7412492017-03-23 11:56:07 -0600901 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -0600902 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600903 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600904
steve-lunarge7412492017-03-23 11:56:07 -0600905 glslang::TLayoutGeometry primitive;
906
907 if (glslangIntermediate->getStage() == EShLangTessControl) {
908 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
909 primitive = glslangIntermediate->getOutputPrimitive();
910 } else {
911 primitive = glslangIntermediate->getInputPrimitive();
912 }
913
914 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -0700915 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
916 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
917 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600918 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600919 }
John Kessenich4016e382016-07-15 11:53:56 -0600920 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600921 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
922
John Kesseniche6903322015-10-13 16:29:02 -0600923 switch (glslangIntermediate->getVertexSpacing()) {
924 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
925 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
926 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600927 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600928 }
John Kessenich4016e382016-07-15 11:53:56 -0600929 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600930 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
931
932 switch (glslangIntermediate->getVertexOrder()) {
933 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
934 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600935 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600936 }
John Kessenich4016e382016-07-15 11:53:56 -0600937 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600938 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
939
940 if (glslangIntermediate->getPointMode())
941 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600942 break;
943
944 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600945 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600946 switch (glslangIntermediate->getInputPrimitive()) {
947 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
948 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
949 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700950 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600951 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600952 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600953 }
John Kessenich4016e382016-07-15 11:53:56 -0600954 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600955 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600956
John Kessenich140f3df2015-06-26 16:58:36 -0600957 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
958
959 switch (glslangIntermediate->getOutputPrimitive()) {
960 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
961 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
962 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600963 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600964 }
John Kessenich4016e382016-07-15 11:53:56 -0600965 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600966 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
967 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
968 break;
969
970 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600971 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600972 if (glslangIntermediate->getPixelCenterInteger())
973 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600974
John Kessenich140f3df2015-06-26 16:58:36 -0600975 if (glslangIntermediate->getOriginUpperLeft())
976 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600977 else
978 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600979
980 if (glslangIntermediate->getEarlyFragmentTests())
981 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
982
983 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600984 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
985 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -0600986 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600987 }
John Kessenich4016e382016-07-15 11:53:56 -0600988 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600989 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
990
991 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
992 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600993 break;
994
995 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600996 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600997 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
998 glslangIntermediate->getLocalSize(1),
999 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -06001000 break;
1001
1002 default:
1003 break;
1004 }
John Kessenich140f3df2015-06-26 16:58:36 -06001005}
1006
John Kessenichfca82622016-11-26 13:23:20 -07001007// Finish creating SPV, after the traversal is complete.
1008void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001009{
John Kessenich517fe7a2016-11-26 13:31:47 -07001010 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001011 builder.setBuildPoint(shaderEntry->getLastBlock());
1012 builder.leaveFunction();
1013 }
1014
John Kessenich7ba63412015-12-20 17:37:07 -07001015 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001016 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1017 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001018
qiningda397332016-03-09 19:54:03 -05001019 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -07001020}
1021
John Kessenichfca82622016-11-26 13:23:20 -07001022// Write the SPV into 'out'.
1023void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001024{
John Kessenichfca82622016-11-26 13:23:20 -07001025 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001026}
1027
1028//
1029// Implement the traversal functions.
1030//
1031// Return true from interior nodes to have the external traversal
1032// continue on to children. Return false if children were
1033// already processed.
1034//
1035
1036//
qining25262b32016-05-06 17:25:16 -04001037// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001038// - uniform/input reads
1039// - output writes
1040// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1041// - something simple that degenerates into the last bullet
1042//
1043void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1044{
qining75d1d802016-04-06 14:42:01 -04001045 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1046 if (symbol->getType().getQualifier().isSpecConstant())
1047 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1048
John Kessenich140f3df2015-06-26 16:58:36 -06001049 // getSymbolId() will set up all the IO decorations on the first call.
1050 // Formal function parameters were mapped during makeFunctions().
1051 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001052
1053 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1054 if (builder.isPointer(id)) {
1055 spv::StorageClass sc = builder.getStorageClass(id);
1056 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
1057 iOSet.insert(id);
1058 }
1059
1060 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001061 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001062 // Prepare to generate code for the access
1063
1064 // L-value chains will be computed left to right. We're on the symbol now,
1065 // which is the left-most part of the access chain, so now is "clear" time,
1066 // followed by setting the base.
1067 builder.clearAccessChain();
1068
1069 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001070 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001071 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001072 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001073 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001074 // These are also pure R-values.
1075 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001076 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001077 builder.setAccessChainRValue(id);
1078 else
1079 builder.setAccessChainLValue(id);
1080 }
1081}
1082
1083bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1084{
John Kesseniche485c7a2017-05-31 18:50:53 -06001085 builder.setLine(node->getLoc().line);
1086
qining40887662016-04-03 22:20:42 -04001087 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1088 if (node->getType().getQualifier().isSpecConstant())
1089 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1090
John Kessenich140f3df2015-06-26 16:58:36 -06001091 // First, handle special cases
1092 switch (node->getOp()) {
1093 case glslang::EOpAssign:
1094 case glslang::EOpAddAssign:
1095 case glslang::EOpSubAssign:
1096 case glslang::EOpMulAssign:
1097 case glslang::EOpVectorTimesMatrixAssign:
1098 case glslang::EOpVectorTimesScalarAssign:
1099 case glslang::EOpMatrixTimesScalarAssign:
1100 case glslang::EOpMatrixTimesMatrixAssign:
1101 case glslang::EOpDivAssign:
1102 case glslang::EOpModAssign:
1103 case glslang::EOpAndAssign:
1104 case glslang::EOpInclusiveOrAssign:
1105 case glslang::EOpExclusiveOrAssign:
1106 case glslang::EOpLeftShiftAssign:
1107 case glslang::EOpRightShiftAssign:
1108 // A bin-op assign "a += b" means the same thing as "a = a + b"
1109 // where a is evaluated before b. For a simple assignment, GLSL
1110 // says to evaluate the left before the right. So, always, left
1111 // node then right node.
1112 {
1113 // get the left l-value, save it away
1114 builder.clearAccessChain();
1115 node->getLeft()->traverse(this);
1116 spv::Builder::AccessChain lValue = builder.getAccessChain();
1117
1118 // evaluate the right
1119 builder.clearAccessChain();
1120 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001121 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001122
1123 if (node->getOp() != glslang::EOpAssign) {
1124 // the left is also an r-value
1125 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001126 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001127
1128 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001129 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001130 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001131 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1132 node->getType().getBasicType());
1133
1134 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001135 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001136 }
1137
1138 // store the result
1139 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001140 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001141
1142 // assignments are expressions having an rValue after they are evaluated...
1143 builder.clearAccessChain();
1144 builder.setAccessChainRValue(rValue);
1145 }
1146 return false;
1147 case glslang::EOpIndexDirect:
1148 case glslang::EOpIndexDirectStruct:
1149 {
1150 // Get the left part of the access chain.
1151 node->getLeft()->traverse(this);
1152
1153 // Add the next element in the chain
1154
David Netoa901ffe2016-06-08 14:11:40 +01001155 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001156 if (! node->getLeft()->getType().isArray() &&
1157 node->getLeft()->getType().isVector() &&
1158 node->getOp() == glslang::EOpIndexDirect) {
1159 // This is essentially a hard-coded vector swizzle of size 1,
1160 // so short circuit the access-chain stuff with a swizzle.
1161 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001162 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001163 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001164 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001165 int spvIndex = glslangIndex;
1166 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1167 node->getOp() == glslang::EOpIndexDirectStruct)
1168 {
1169 // This may be, e.g., an anonymous block-member selection, which generally need
1170 // index remapping due to hidden members in anonymous blocks.
1171 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1172 assert(remapper.size() > 0);
1173 spvIndex = remapper[glslangIndex];
1174 }
John Kessenichebb50532016-05-16 19:22:05 -06001175
David Netoa901ffe2016-06-08 14:11:40 +01001176 // normal case for indexing array or structure or block
1177 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1178
1179 // Add capabilities here for accessing PointSize and clip/cull distance.
1180 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001181 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001182 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001183 }
1184 }
1185 return false;
1186 case glslang::EOpIndexIndirect:
1187 {
1188 // Structure or array or vector indirection.
1189 // Will use native SPIR-V access-chain for struct and array indirection;
1190 // matrices are arrays of vectors, so will also work for a matrix.
1191 // Will use the access chain's 'component' for variable index into a vector.
1192
1193 // This adapter is building access chains left to right.
1194 // Set up the access chain to the left.
1195 node->getLeft()->traverse(this);
1196
1197 // save it so that computing the right side doesn't trash it
1198 spv::Builder::AccessChain partial = builder.getAccessChain();
1199
1200 // compute the next index in the chain
1201 builder.clearAccessChain();
1202 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001203 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001204
1205 // restore the saved access chain
1206 builder.setAccessChain(partial);
1207
1208 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001209 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001210 else
John Kessenichfa668da2015-09-13 14:46:30 -06001211 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001212 }
1213 return false;
1214 case glslang::EOpVectorSwizzle:
1215 {
1216 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001217 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001218 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001219 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001220 }
1221 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001222 case glslang::EOpMatrixSwizzle:
1223 logger->missingFunctionality("matrix swizzle");
1224 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001225 case glslang::EOpLogicalOr:
1226 case glslang::EOpLogicalAnd:
1227 {
1228
1229 // These may require short circuiting, but can sometimes be done as straight
1230 // binary operations. The right operand must be short circuited if it has
1231 // side effects, and should probably be if it is complex.
1232 if (isTrivial(node->getRight()->getAsTyped()))
1233 break; // handle below as a normal binary operation
1234 // otherwise, we need to do dynamic short circuiting on the right operand
1235 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1236 builder.clearAccessChain();
1237 builder.setAccessChainRValue(result);
1238 }
1239 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001240 default:
1241 break;
1242 }
1243
1244 // Assume generic binary op...
1245
John Kessenich32cfd492016-02-02 12:37:46 -07001246 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001247 builder.clearAccessChain();
1248 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001249 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001250
John Kessenich32cfd492016-02-02 12:37:46 -07001251 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001252 builder.clearAccessChain();
1253 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001254 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001255
John Kessenich32cfd492016-02-02 12:37:46 -07001256 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001257 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001258 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001259 convertGlslangToSpvType(node->getType()), left, right,
1260 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001261
John Kessenich50e57562015-12-21 21:21:11 -07001262 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001263 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001264 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001265 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001266 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001267 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001268 return false;
1269 }
John Kessenich140f3df2015-06-26 16:58:36 -06001270}
1271
1272bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1273{
John Kesseniche485c7a2017-05-31 18:50:53 -06001274 builder.setLine(node->getLoc().line);
1275
qining40887662016-04-03 22:20:42 -04001276 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1277 if (node->getType().getQualifier().isSpecConstant())
1278 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1279
John Kessenichfc51d282015-08-19 13:34:18 -06001280 spv::Id result = spv::NoResult;
1281
1282 // try texturing first
1283 result = createImageTextureFunctionCall(node);
1284 if (result != spv::NoResult) {
1285 builder.clearAccessChain();
1286 builder.setAccessChainRValue(result);
1287
1288 return false; // done with this node
1289 }
1290
1291 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001292
1293 if (node->getOp() == glslang::EOpArrayLength) {
1294 // Quite special; won't want to evaluate the operand.
1295
1296 // Normal .length() would have been constant folded by the front-end.
1297 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001298 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001299 assert(node->getOperand()->getType().isRuntimeSizedArray());
1300 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1301 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001302 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1303 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001304
1305 builder.clearAccessChain();
1306 builder.setAccessChainRValue(length);
1307
1308 return false;
1309 }
1310
John Kessenichfc51d282015-08-19 13:34:18 -06001311 // Start by evaluating the operand
1312
John Kessenich8c8505c2016-07-26 12:50:38 -06001313 // Does it need a swizzle inversion? If so, evaluation is inverted;
1314 // operate first on the swizzle base, then apply the swizzle.
1315 spv::Id invertedType = spv::NoType;
1316 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1317 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1318 invertedType = getInvertedSwizzleType(*node->getOperand());
1319
John Kessenich140f3df2015-06-26 16:58:36 -06001320 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001321 if (invertedType != spv::NoType)
1322 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1323 else
1324 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001325
Rex Xufc618912015-09-09 16:42:49 +08001326 spv::Id operand = spv::NoResult;
1327
1328 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1329 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001330 node->getOp() == glslang::EOpAtomicCounter ||
1331 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001332 operand = builder.accessChainGetLValue(); // Special case l-value operands
1333 else
John Kessenich32cfd492016-02-02 12:37:46 -07001334 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001335
John Kessenichf6640762016-08-01 19:44:00 -06001336 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001337 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001338
1339 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001340 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001341 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001342
1343 // if not, then possibly an operation
1344 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001345 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001346
1347 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001348 if (invertedType)
1349 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1350
John Kessenich140f3df2015-06-26 16:58:36 -06001351 builder.clearAccessChain();
1352 builder.setAccessChainRValue(result);
1353
1354 return false; // done with this node
1355 }
1356
1357 // it must be a special case, check...
1358 switch (node->getOp()) {
1359 case glslang::EOpPostIncrement:
1360 case glslang::EOpPostDecrement:
1361 case glslang::EOpPreIncrement:
1362 case glslang::EOpPreDecrement:
1363 {
1364 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001365 spv::Id one = 0;
1366 if (node->getBasicType() == glslang::EbtFloat)
1367 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001368 else if (node->getBasicType() == glslang::EbtDouble)
1369 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001370#ifdef AMD_EXTENSIONS
1371 else if (node->getBasicType() == glslang::EbtFloat16)
1372 one = builder.makeFloat16Constant(1.0F);
1373#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001374 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1375 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001376#ifdef AMD_EXTENSIONS
1377 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1378 one = builder.makeInt16Constant(1);
1379#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001380 else
1381 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001382 glslang::TOperator op;
1383 if (node->getOp() == glslang::EOpPreIncrement ||
1384 node->getOp() == glslang::EOpPostIncrement)
1385 op = glslang::EOpAdd;
1386 else
1387 op = glslang::EOpSub;
1388
John Kessenichf6640762016-08-01 19:44:00 -06001389 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001390 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001391 convertGlslangToSpvType(node->getType()), operand, one,
1392 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001393 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001394
1395 // The result of operation is always stored, but conditionally the
1396 // consumed result. The consumed result is always an r-value.
1397 builder.accessChainStore(result);
1398 builder.clearAccessChain();
1399 if (node->getOp() == glslang::EOpPreIncrement ||
1400 node->getOp() == glslang::EOpPreDecrement)
1401 builder.setAccessChainRValue(result);
1402 else
1403 builder.setAccessChainRValue(operand);
1404 }
1405
1406 return false;
1407
1408 case glslang::EOpEmitStreamVertex:
1409 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1410 return false;
1411 case glslang::EOpEndStreamPrimitive:
1412 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1413 return false;
1414
1415 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001416 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001417 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001418 }
John Kessenich140f3df2015-06-26 16:58:36 -06001419}
1420
1421bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1422{
qining27e04a02016-04-14 16:40:20 -04001423 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1424 if (node->getType().getQualifier().isSpecConstant())
1425 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1426
John Kessenichfc51d282015-08-19 13:34:18 -06001427 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001428 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1429 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001430
1431 // try texturing
1432 result = createImageTextureFunctionCall(node);
1433 if (result != spv::NoResult) {
1434 builder.clearAccessChain();
1435 builder.setAccessChainRValue(result);
1436
1437 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001438 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001439 // "imageStore" is a special case, which has no result
1440 return false;
1441 }
John Kessenichfc51d282015-08-19 13:34:18 -06001442
John Kessenich140f3df2015-06-26 16:58:36 -06001443 glslang::TOperator binOp = glslang::EOpNull;
1444 bool reduceComparison = true;
1445 bool isMatrix = false;
1446 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001447 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001448
1449 assert(node->getOp());
1450
John Kessenichf6640762016-08-01 19:44:00 -06001451 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001452
1453 switch (node->getOp()) {
1454 case glslang::EOpSequence:
1455 {
1456 if (preVisit)
1457 ++sequenceDepth;
1458 else
1459 --sequenceDepth;
1460
1461 if (sequenceDepth == 1) {
1462 // If this is the parent node of all the functions, we want to see them
1463 // early, so all call points have actual SPIR-V functions to reference.
1464 // In all cases, still let the traverser visit the children for us.
1465 makeFunctions(node->getAsAggregate()->getSequence());
1466
John Kessenich6fccb3c2016-09-19 16:01:41 -06001467 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001468 // anything else gets there, so visit out of order, doing them all now.
1469 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1470
John Kessenich6a60c2f2016-12-08 21:01:59 -07001471 // 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 -06001472 // so do them manually.
1473 visitFunctions(node->getAsAggregate()->getSequence());
1474
1475 return false;
1476 }
1477
1478 return true;
1479 }
1480 case glslang::EOpLinkerObjects:
1481 {
1482 if (visit == glslang::EvPreVisit)
1483 linkageOnly = true;
1484 else
1485 linkageOnly = false;
1486
1487 return true;
1488 }
1489 case glslang::EOpComma:
1490 {
1491 // processing from left to right naturally leaves the right-most
1492 // lying around in the access chain
1493 glslang::TIntermSequence& glslangOperands = node->getSequence();
1494 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1495 glslangOperands[i]->traverse(this);
1496
1497 return false;
1498 }
1499 case glslang::EOpFunction:
1500 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001501 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001502 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001503 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001504 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001505 } else {
1506 handleFunctionEntry(node);
1507 }
1508 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001509 if (inEntryPoint)
1510 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001511 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001512 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001513 }
1514
1515 return true;
1516 case glslang::EOpParameters:
1517 // Parameters will have been consumed by EOpFunction processing, but not
1518 // the body, so we still visited the function node's children, making this
1519 // child redundant.
1520 return false;
1521 case glslang::EOpFunctionCall:
1522 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001523 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001524 if (node->isUserDefined())
1525 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001526 // 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 -07001527 if (result) {
1528 builder.clearAccessChain();
1529 builder.setAccessChainRValue(result);
1530 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001531 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001532
1533 return false;
1534 }
1535 case glslang::EOpConstructMat2x2:
1536 case glslang::EOpConstructMat2x3:
1537 case glslang::EOpConstructMat2x4:
1538 case glslang::EOpConstructMat3x2:
1539 case glslang::EOpConstructMat3x3:
1540 case glslang::EOpConstructMat3x4:
1541 case glslang::EOpConstructMat4x2:
1542 case glslang::EOpConstructMat4x3:
1543 case glslang::EOpConstructMat4x4:
1544 case glslang::EOpConstructDMat2x2:
1545 case glslang::EOpConstructDMat2x3:
1546 case glslang::EOpConstructDMat2x4:
1547 case glslang::EOpConstructDMat3x2:
1548 case glslang::EOpConstructDMat3x3:
1549 case glslang::EOpConstructDMat3x4:
1550 case glslang::EOpConstructDMat4x2:
1551 case glslang::EOpConstructDMat4x3:
1552 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06001553 case glslang::EOpConstructIMat2x2:
1554 case glslang::EOpConstructIMat2x3:
1555 case glslang::EOpConstructIMat2x4:
1556 case glslang::EOpConstructIMat3x2:
1557 case glslang::EOpConstructIMat3x3:
1558 case glslang::EOpConstructIMat3x4:
1559 case glslang::EOpConstructIMat4x2:
1560 case glslang::EOpConstructIMat4x3:
1561 case glslang::EOpConstructIMat4x4:
1562 case glslang::EOpConstructUMat2x2:
1563 case glslang::EOpConstructUMat2x3:
1564 case glslang::EOpConstructUMat2x4:
1565 case glslang::EOpConstructUMat3x2:
1566 case glslang::EOpConstructUMat3x3:
1567 case glslang::EOpConstructUMat3x4:
1568 case glslang::EOpConstructUMat4x2:
1569 case glslang::EOpConstructUMat4x3:
1570 case glslang::EOpConstructUMat4x4:
1571 case glslang::EOpConstructBMat2x2:
1572 case glslang::EOpConstructBMat2x3:
1573 case glslang::EOpConstructBMat2x4:
1574 case glslang::EOpConstructBMat3x2:
1575 case glslang::EOpConstructBMat3x3:
1576 case glslang::EOpConstructBMat3x4:
1577 case glslang::EOpConstructBMat4x2:
1578 case glslang::EOpConstructBMat4x3:
1579 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001580#ifdef AMD_EXTENSIONS
1581 case glslang::EOpConstructF16Mat2x2:
1582 case glslang::EOpConstructF16Mat2x3:
1583 case glslang::EOpConstructF16Mat2x4:
1584 case glslang::EOpConstructF16Mat3x2:
1585 case glslang::EOpConstructF16Mat3x3:
1586 case glslang::EOpConstructF16Mat3x4:
1587 case glslang::EOpConstructF16Mat4x2:
1588 case glslang::EOpConstructF16Mat4x3:
1589 case glslang::EOpConstructF16Mat4x4:
1590#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001591 isMatrix = true;
1592 // fall through
1593 case glslang::EOpConstructFloat:
1594 case glslang::EOpConstructVec2:
1595 case glslang::EOpConstructVec3:
1596 case glslang::EOpConstructVec4:
1597 case glslang::EOpConstructDouble:
1598 case glslang::EOpConstructDVec2:
1599 case glslang::EOpConstructDVec3:
1600 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001601#ifdef AMD_EXTENSIONS
1602 case glslang::EOpConstructFloat16:
1603 case glslang::EOpConstructF16Vec2:
1604 case glslang::EOpConstructF16Vec3:
1605 case glslang::EOpConstructF16Vec4:
1606#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001607 case glslang::EOpConstructBool:
1608 case glslang::EOpConstructBVec2:
1609 case glslang::EOpConstructBVec3:
1610 case glslang::EOpConstructBVec4:
1611 case glslang::EOpConstructInt:
1612 case glslang::EOpConstructIVec2:
1613 case glslang::EOpConstructIVec3:
1614 case glslang::EOpConstructIVec4:
1615 case glslang::EOpConstructUint:
1616 case glslang::EOpConstructUVec2:
1617 case glslang::EOpConstructUVec3:
1618 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001619 case glslang::EOpConstructInt64:
1620 case glslang::EOpConstructI64Vec2:
1621 case glslang::EOpConstructI64Vec3:
1622 case glslang::EOpConstructI64Vec4:
1623 case glslang::EOpConstructUint64:
1624 case glslang::EOpConstructU64Vec2:
1625 case glslang::EOpConstructU64Vec3:
1626 case glslang::EOpConstructU64Vec4:
Rex Xucabbb782017-03-24 13:41:14 +08001627#ifdef AMD_EXTENSIONS
1628 case glslang::EOpConstructInt16:
1629 case glslang::EOpConstructI16Vec2:
1630 case glslang::EOpConstructI16Vec3:
1631 case glslang::EOpConstructI16Vec4:
1632 case glslang::EOpConstructUint16:
1633 case glslang::EOpConstructU16Vec2:
1634 case glslang::EOpConstructU16Vec3:
1635 case glslang::EOpConstructU16Vec4:
1636#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001637 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001638 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001639 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001640 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001641 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001642 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001643 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001644 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001645 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001646 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001647 std::vector<spv::Id> constituents;
1648 for (int c = 0; c < (int)arguments.size(); ++c)
1649 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001650 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001651 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001652 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001653 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001654 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001655
1656 builder.clearAccessChain();
1657 builder.setAccessChainRValue(constructed);
1658
1659 return false;
1660 }
1661
1662 // These six are component-wise compares with component-wise results.
1663 // Forward on to createBinaryOperation(), requesting a vector result.
1664 case glslang::EOpLessThan:
1665 case glslang::EOpGreaterThan:
1666 case glslang::EOpLessThanEqual:
1667 case glslang::EOpGreaterThanEqual:
1668 case glslang::EOpVectorEqual:
1669 case glslang::EOpVectorNotEqual:
1670 {
1671 // Map the operation to a binary
1672 binOp = node->getOp();
1673 reduceComparison = false;
1674 switch (node->getOp()) {
1675 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1676 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1677 default: binOp = node->getOp(); break;
1678 }
1679
1680 break;
1681 }
1682 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001683 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001684 binOp = glslang::EOpMul;
1685 break;
1686 case glslang::EOpOuterProduct:
1687 // two vectors multiplied to make a matrix
1688 binOp = glslang::EOpOuterProduct;
1689 break;
1690 case glslang::EOpDot:
1691 {
qining25262b32016-05-06 17:25:16 -04001692 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001693 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001694 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001695 binOp = glslang::EOpMul;
1696 break;
1697 }
1698 case glslang::EOpMod:
1699 // when an aggregate, this is the floating-point mod built-in function,
1700 // which can be emitted by the one in createBinaryOperation()
1701 binOp = glslang::EOpMod;
1702 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001703 case glslang::EOpEmitVertex:
1704 case glslang::EOpEndPrimitive:
1705 case glslang::EOpBarrier:
1706 case glslang::EOpMemoryBarrier:
1707 case glslang::EOpMemoryBarrierAtomicCounter:
1708 case glslang::EOpMemoryBarrierBuffer:
1709 case glslang::EOpMemoryBarrierImage:
1710 case glslang::EOpMemoryBarrierShared:
1711 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001712 case glslang::EOpAllMemoryBarrierWithGroupSync:
1713 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1714 case glslang::EOpWorkgroupMemoryBarrier:
1715 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001716 noReturnValue = true;
1717 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1718 break;
1719
John Kessenich426394d2015-07-23 10:22:48 -06001720 case glslang::EOpAtomicAdd:
1721 case glslang::EOpAtomicMin:
1722 case glslang::EOpAtomicMax:
1723 case glslang::EOpAtomicAnd:
1724 case glslang::EOpAtomicOr:
1725 case glslang::EOpAtomicXor:
1726 case glslang::EOpAtomicExchange:
1727 case glslang::EOpAtomicCompSwap:
1728 atomic = true;
1729 break;
1730
John Kessenich140f3df2015-06-26 16:58:36 -06001731 default:
1732 break;
1733 }
1734
1735 //
1736 // See if it maps to a regular operation.
1737 //
John Kessenich140f3df2015-06-26 16:58:36 -06001738 if (binOp != glslang::EOpNull) {
1739 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1740 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1741 assert(left && right);
1742
1743 builder.clearAccessChain();
1744 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001745 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001746
1747 builder.clearAccessChain();
1748 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001749 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001750
John Kesseniche485c7a2017-05-31 18:50:53 -06001751 builder.setLine(node->getLoc().line);
qining25262b32016-05-06 17:25:16 -04001752 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001753 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001754 left->getType().getBasicType(), reduceComparison);
1755
1756 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001757 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001758 builder.clearAccessChain();
1759 builder.setAccessChainRValue(result);
1760
1761 return false;
1762 }
1763
John Kessenich426394d2015-07-23 10:22:48 -06001764 //
1765 // Create the list of operands.
1766 //
John Kessenich140f3df2015-06-26 16:58:36 -06001767 glslang::TIntermSequence& glslangOperands = node->getSequence();
1768 std::vector<spv::Id> operands;
1769 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001770 // special case l-value operands; there are just a few
1771 bool lvalue = false;
1772 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001773 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001774 case glslang::EOpModf:
1775 if (arg == 1)
1776 lvalue = true;
1777 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001778 case glslang::EOpInterpolateAtSample:
1779 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001780#ifdef AMD_EXTENSIONS
1781 case glslang::EOpInterpolateAtVertex:
1782#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001783 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001784 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001785
1786 // Does it need a swizzle inversion? If so, evaluation is inverted;
1787 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001788 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001789 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1790 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1791 }
Rex Xu7a26c172015-12-08 17:12:09 +08001792 break;
Rex Xud4782c12015-09-06 16:30:11 +08001793 case glslang::EOpAtomicAdd:
1794 case glslang::EOpAtomicMin:
1795 case glslang::EOpAtomicMax:
1796 case glslang::EOpAtomicAnd:
1797 case glslang::EOpAtomicOr:
1798 case glslang::EOpAtomicXor:
1799 case glslang::EOpAtomicExchange:
1800 case glslang::EOpAtomicCompSwap:
1801 if (arg == 0)
1802 lvalue = true;
1803 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001804 case glslang::EOpAddCarry:
1805 case glslang::EOpSubBorrow:
1806 if (arg == 2)
1807 lvalue = true;
1808 break;
1809 case glslang::EOpUMulExtended:
1810 case glslang::EOpIMulExtended:
1811 if (arg >= 2)
1812 lvalue = true;
1813 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001814 default:
1815 break;
1816 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001817 builder.clearAccessChain();
1818 if (invertedType != spv::NoType && arg == 0)
1819 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1820 else
1821 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001822 if (lvalue)
1823 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06001824 else {
1825 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07001826 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06001827 }
John Kessenich140f3df2015-06-26 16:58:36 -06001828 }
John Kessenich426394d2015-07-23 10:22:48 -06001829
John Kesseniche485c7a2017-05-31 18:50:53 -06001830 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06001831 if (atomic) {
1832 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001833 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001834 } else {
1835 // Pass through to generic operations.
1836 switch (glslangOperands.size()) {
1837 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001838 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001839 break;
1840 case 1:
qining25262b32016-05-06 17:25:16 -04001841 result = createUnaryOperation(
1842 node->getOp(), precision,
1843 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001844 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001845 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001846 break;
1847 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001848 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001849 break;
1850 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001851 if (invertedType)
1852 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001853 }
1854
1855 if (noReturnValue)
1856 return false;
1857
1858 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001859 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001860 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001861 } else {
1862 builder.clearAccessChain();
1863 builder.setAccessChainRValue(result);
1864 return false;
1865 }
1866}
1867
John Kessenich433e9ff2017-01-26 20:31:11 -07001868// This path handles both if-then-else and ?:
1869// The if-then-else has a node type of void, while
1870// ?: has either a void or a non-void node type
1871//
1872// Leaving the result, when not void:
1873// GLSL only has r-values as the result of a :?, but
1874// if we have an l-value, that can be more efficient if it will
1875// become the base of a complex r-value expression, because the
1876// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001877bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1878{
John Kessenich433e9ff2017-01-26 20:31:11 -07001879 // See if it simple and safe to generate OpSelect instead of using control flow.
1880 // Crucially, side effects must be avoided, and there are performance trade-offs.
1881 // Return true if good idea (and safe) for OpSelect, false otherwise.
1882 const auto selectPolicy = [&]() -> bool {
John Kessenich04794372017-03-01 13:49:11 -07001883 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
1884 node->getBasicType() == glslang::EbtVoid)
John Kessenich433e9ff2017-01-26 20:31:11 -07001885 return false;
1886
1887 if (node->getTrueBlock() == nullptr ||
1888 node->getFalseBlock() == nullptr)
1889 return false;
1890
1891 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
1892 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
1893
1894 // return true if a single operand to ? : is okay for OpSelect
1895 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001896 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07001897 };
1898
1899 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
1900 operandOkay(node->getFalseBlock()->getAsTyped());
1901 };
1902
1903 // Emit OpSelect for this selection.
1904 const auto handleAsOpSelect = [&]() {
1905 node->getCondition()->traverse(this);
1906 spv::Id condition = accessChainLoad(node->getCondition()->getType());
1907 node->getTrueBlock()->traverse(this);
1908 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1909 node->getFalseBlock()->traverse(this);
1910 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1911
John Kesseniche485c7a2017-05-31 18:50:53 -06001912 builder.setLine(node->getLoc().line);
1913
John Kesseniche434ad92017-03-30 10:09:28 -06001914 // smear condition to vector, if necessary (AST is always scalar)
1915 if (builder.isVector(trueValue))
1916 condition = builder.smearScalar(spv::NoPrecision, condition,
1917 builder.makeVectorType(builder.makeBoolType(),
1918 builder.getNumComponents(trueValue)));
1919
1920 spv::Id select = builder.createTriOp(spv::OpSelect,
1921 convertGlslangToSpvType(node->getType()), condition,
1922 trueValue, falseValue);
John Kessenich433e9ff2017-01-26 20:31:11 -07001923 builder.clearAccessChain();
1924 builder.setAccessChainRValue(select);
1925 };
1926
1927 // Try for OpSelect
1928
1929 if (selectPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001930 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1931 if (node->getType().getQualifier().isSpecConstant())
1932 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1933
John Kessenich433e9ff2017-01-26 20:31:11 -07001934 handleAsOpSelect();
1935 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001936 }
1937
John Kessenich433e9ff2017-01-26 20:31:11 -07001938 // Instead, emit control flow...
1939
1940 // Don't handle results as temporaries, because there will be two names
1941 // and better to leave SSA to later passes.
1942 spv::Id result = (node->getBasicType() == glslang::EbtVoid)
1943 ? spv::NoResult
1944 : builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1945
John Kessenich140f3df2015-06-26 16:58:36 -06001946 // emit the condition before doing anything with selection
1947 node->getCondition()->traverse(this);
1948
1949 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001950 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001951
John Kessenich433e9ff2017-01-26 20:31:11 -07001952 // emit the "then" statement
1953 if (node->getTrueBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001954 node->getTrueBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001955 if (result != spv::NoResult)
1956 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001957 }
1958
John Kessenich433e9ff2017-01-26 20:31:11 -07001959 if (node->getFalseBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001960 ifBuilder.makeBeginElse();
1961 // emit the "else" statement
1962 node->getFalseBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001963 if (result != spv::NoResult)
John Kessenich32cfd492016-02-02 12:37:46 -07001964 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001965 }
1966
John Kessenich433e9ff2017-01-26 20:31:11 -07001967 // finish off the control flow
John Kessenich140f3df2015-06-26 16:58:36 -06001968 ifBuilder.makeEndIf();
1969
John Kessenich433e9ff2017-01-26 20:31:11 -07001970 if (result != spv::NoResult) {
John Kessenich140f3df2015-06-26 16:58:36 -06001971 // GLSL only has r-values as the result of a :?, but
1972 // if we have an l-value, that can be more efficient if it will
1973 // become the base of a complex r-value expression, because the
1974 // next layer copies r-values into memory to use the access-chain mechanism
1975 builder.clearAccessChain();
1976 builder.setAccessChainLValue(result);
1977 }
1978
1979 return false;
1980}
1981
1982bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1983{
1984 // emit and get the condition before doing anything with switch
1985 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001986 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001987
1988 // browse the children to sort out code segments
1989 int defaultSegment = -1;
1990 std::vector<TIntermNode*> codeSegments;
1991 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1992 std::vector<int> caseValues;
1993 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1994 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1995 TIntermNode* child = *c;
1996 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001997 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001998 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001999 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002000 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2001 } else
2002 codeSegments.push_back(child);
2003 }
2004
qining25262b32016-05-06 17:25:16 -04002005 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002006 // statements between the last case and the end of the switch statement
2007 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2008 (int)codeSegments.size() == defaultSegment)
2009 codeSegments.push_back(nullptr);
2010
2011 // make the switch statement
2012 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02002013 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002014
2015 // emit all the code in the segments
2016 breakForLoop.push(false);
2017 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2018 builder.nextSwitchSegment(segmentBlocks, s);
2019 if (codeSegments[s])
2020 codeSegments[s]->traverse(this);
2021 else
2022 builder.addSwitchBreak();
2023 }
2024 breakForLoop.pop();
2025
2026 builder.endSwitch(segmentBlocks);
2027
2028 return false;
2029}
2030
2031void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2032{
2033 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002034 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002035
2036 builder.clearAccessChain();
2037 builder.setAccessChainRValue(constant);
2038}
2039
2040bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2041{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002042 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002043 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002044
2045 // Loop control:
2046 const spv::LoopControlMask control = TranslateLoopControl(node->getLoopControl());
2047
2048 // TODO: dependency length
2049
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002050 // Spec requires back edges to target header blocks, and every header block
2051 // must dominate its merge block. Make a header block first to ensure these
2052 // conditions are met. By definition, it will contain OpLoopMerge, followed
2053 // by a block-ending branch. But we don't want to put any other body/test
2054 // instructions in it, since the body/test may have arbitrary instructions,
2055 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002056 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002057 builder.setBuildPoint(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002058 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002059 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002060 spv::Block& test = builder.makeNewBlock();
2061 builder.createBranch(&test);
2062
2063 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002064 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002065 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002066 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2067
2068 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002069 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002070 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002071 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002072 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002073 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002074
2075 builder.setBuildPoint(&blocks.continue_target);
2076 if (node->getTerminal())
2077 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002078 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002079 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002080 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002081 builder.createBranch(&blocks.body);
2082
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002083 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002084 builder.setBuildPoint(&blocks.body);
2085 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002086 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002087 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002088 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002089
2090 builder.setBuildPoint(&blocks.continue_target);
2091 if (node->getTerminal())
2092 node->getTerminal()->traverse(this);
2093 if (node->getTest()) {
2094 node->getTest()->traverse(this);
2095 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002096 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002097 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002098 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002099 // TODO: unless there was a break/return/discard instruction
2100 // somewhere in the body, this is an infinite loop, so we should
2101 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002102 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002103 }
John Kessenich140f3df2015-06-26 16:58:36 -06002104 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002105 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002106 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002107 return false;
2108}
2109
2110bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2111{
2112 if (node->getExpression())
2113 node->getExpression()->traverse(this);
2114
John Kesseniche485c7a2017-05-31 18:50:53 -06002115 builder.setLine(node->getLoc().line);
2116
John Kessenich140f3df2015-06-26 16:58:36 -06002117 switch (node->getFlowOp()) {
2118 case glslang::EOpKill:
2119 builder.makeDiscard();
2120 break;
2121 case glslang::EOpBreak:
2122 if (breakForLoop.top())
2123 builder.createLoopExit();
2124 else
2125 builder.addSwitchBreak();
2126 break;
2127 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002128 builder.createLoopContinue();
2129 break;
2130 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002131 if (node->getExpression()) {
2132 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2133 spv::Id returnId = accessChainLoad(glslangReturnType);
2134 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2135 builder.clearAccessChain();
2136 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2137 builder.setAccessChainLValue(copyId);
2138 multiTypeStore(glslangReturnType, returnId);
2139 returnId = builder.createLoad(copyId);
2140 }
2141 builder.makeReturn(false, returnId);
2142 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002143 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002144
2145 builder.clearAccessChain();
2146 break;
2147
2148 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002149 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002150 break;
2151 }
2152
2153 return false;
2154}
2155
2156spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2157{
qining25262b32016-05-06 17:25:16 -04002158 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002159 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002160 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002161 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002162 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002163 }
2164
2165 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002166 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002167 spv::Id spvType = convertGlslangToSpvType(node->getType());
2168
Rex Xuf89ad982017-04-07 23:22:33 +08002169#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08002170 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2171 node->getType().containsBasicType(glslang::EbtInt16) ||
2172 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002173 if (contains16BitType) {
2174 if (storageClass == spv::StorageClassInput || storageClass == spv::StorageClassOutput) {
2175 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2176 builder.addCapability(spv::CapabilityStorageInputOutput16);
2177 } else if (storageClass == spv::StorageClassPushConstant) {
2178 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2179 builder.addCapability(spv::CapabilityStoragePushConstant16);
2180 } else if (storageClass == spv::StorageClassUniform) {
2181 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2182 builder.addCapability(spv::CapabilityStorageUniform16);
2183 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2184 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2185 }
2186 }
2187#endif
2188
John Kessenich140f3df2015-06-26 16:58:36 -06002189 const char* name = node->getName().c_str();
2190 if (glslang::IsAnonymous(name))
2191 name = "";
2192
2193 return builder.createVariable(storageClass, spvType, name);
2194}
2195
2196// Return type Id of the sampled type.
2197spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2198{
2199 switch (sampler.type) {
2200 case glslang::EbtFloat: return builder.makeFloatType(32);
2201 case glslang::EbtInt: return builder.makeIntType(32);
2202 case glslang::EbtUint: return builder.makeUintType(32);
2203 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002204 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002205 return builder.makeFloatType(32);
2206 }
2207}
2208
John Kessenich8c8505c2016-07-26 12:50:38 -06002209// If node is a swizzle operation, return the type that should be used if
2210// the swizzle base is first consumed by another operation, before the swizzle
2211// is applied.
2212spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2213{
John Kessenichecba76f2017-01-06 00:34:48 -07002214 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002215 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2216 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2217 else
2218 return spv::NoType;
2219}
2220
2221// When inverting a swizzle with a parent op, this function
2222// will apply the swizzle operation to a completed parent operation.
2223spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2224{
2225 std::vector<unsigned> swizzle;
2226 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2227 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2228}
2229
John Kessenich8c8505c2016-07-26 12:50:38 -06002230// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2231void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2232{
2233 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2234 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2235 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2236}
2237
John Kessenich3ac051e2015-12-20 11:29:16 -07002238// Convert from a glslang type to an SPV type, by calling into a
2239// recursive version of this function. This establishes the inherited
2240// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002241spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2242{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002243 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002244}
2245
2246// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002247// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002248// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002249spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002250{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002251 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002252
2253 switch (type.getBasicType()) {
2254 case glslang::EbtVoid:
2255 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002256 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002257 break;
2258 case glslang::EbtFloat:
2259 spvType = builder.makeFloatType(32);
2260 break;
2261 case glslang::EbtDouble:
2262 spvType = builder.makeFloatType(64);
2263 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002264#ifdef AMD_EXTENSIONS
2265 case glslang::EbtFloat16:
2266 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002267 spvType = builder.makeFloatType(16);
2268 break;
2269#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002270 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002271 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2272 // a 32-bit int where non-0 means true.
2273 if (explicitLayout != glslang::ElpNone)
2274 spvType = builder.makeUintType(32);
2275 else
2276 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002277 break;
2278 case glslang::EbtInt:
2279 spvType = builder.makeIntType(32);
2280 break;
2281 case glslang::EbtUint:
2282 spvType = builder.makeUintType(32);
2283 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002284 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002285 spvType = builder.makeIntType(64);
2286 break;
2287 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002288 spvType = builder.makeUintType(64);
2289 break;
Rex Xucabbb782017-03-24 13:41:14 +08002290#ifdef AMD_EXTENSIONS
2291 case glslang::EbtInt16:
2292 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2293 spvType = builder.makeIntType(16);
2294 break;
2295 case glslang::EbtUint16:
2296 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2297 spvType = builder.makeUintType(16);
2298 break;
2299#endif
John Kessenich426394d2015-07-23 10:22:48 -06002300 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002301 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002302 spvType = builder.makeUintType(32);
2303 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002304 case glslang::EbtSampler:
2305 {
2306 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002307 if (sampler.sampler) {
2308 // pure sampler
2309 spvType = builder.makeSamplerType();
2310 } else {
2311 // an image is present, make its type
2312 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2313 sampler.image ? 2 : 1, TranslateImageFormat(type));
2314 if (sampler.combined) {
2315 // already has both image and sampler, make the combined type
2316 spvType = builder.makeSampledImageType(spvType);
2317 }
John Kessenich55e7d112015-11-15 21:33:39 -07002318 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002319 }
John Kessenich140f3df2015-06-26 16:58:36 -06002320 break;
2321 case glslang::EbtStruct:
2322 case glslang::EbtBlock:
2323 {
2324 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002325 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002326
2327 // Try to share structs for different layouts, but not yet for other
2328 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002329 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002330 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002331 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002332 break;
2333
2334 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002335 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002336 memberRemapper[glslangMembers].resize(glslangMembers->size());
2337 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002338 }
2339 break;
2340 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002341 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002342 break;
2343 }
2344
2345 if (type.isMatrix())
2346 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2347 else {
2348 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2349 if (type.getVectorSize() > 1)
2350 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2351 }
2352
2353 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002354 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2355
John Kessenichc9a80832015-09-12 12:17:44 -06002356 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002357 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002358 // We need to decorate array strides for types needing explicit layout, except blocks.
2359 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002360 // Use a dummy glslang type for querying internal strides of
2361 // arrays of arrays, but using just a one-dimensional array.
2362 glslang::TType simpleArrayType(type, 0); // deference type of the array
2363 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2364 simpleArrayType.getArraySizes().dereference();
2365
2366 // Will compute the higher-order strides here, rather than making a whole
2367 // pile of types and doing repetitive recursion on their contents.
2368 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2369 }
John Kessenichf8842e52016-01-04 19:22:56 -07002370
2371 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002372 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002373 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002374 if (stride > 0)
2375 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002376 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002377 }
2378 } else {
2379 // single-dimensional array, and don't yet have stride
2380
John Kessenichf8842e52016-01-04 19:22:56 -07002381 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002382 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2383 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002384 }
John Kessenich31ed4832015-09-09 17:51:38 -06002385
John Kessenichc9a80832015-09-12 12:17:44 -06002386 // Do the outer dimension, which might not be known for a runtime-sized array
2387 if (type.isRuntimeSizedArray()) {
2388 spvType = builder.makeRuntimeArray(spvType);
2389 } else {
2390 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002391 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002392 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002393 if (stride > 0)
2394 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002395 }
2396
2397 return spvType;
2398}
2399
John Kessenich0e737842017-03-24 18:38:16 -06002400// TODO: this functionality should exist at a higher level, in creating the AST
2401//
2402// Identify interface members that don't have their required extension turned on.
2403//
2404bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2405{
2406 auto& extensions = glslangIntermediate->getRequestedExtensions();
2407
Rex Xubcf291a2017-03-29 23:01:36 +08002408 if (member.getFieldName() == "gl_ViewportMask" &&
2409 extensions.find("GL_NV_viewport_array2") == extensions.end())
2410 return true;
2411 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2412 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2413 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002414 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2415 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2416 return true;
2417 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2418 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2419 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002420 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2421 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2422 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002423
2424 return false;
2425};
2426
John Kessenich6090df02016-06-30 21:18:02 -06002427// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2428// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2429// Mutually recursive with convertGlslangToSpvType().
2430spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2431 const glslang::TTypeList* glslangMembers,
2432 glslang::TLayoutPacking explicitLayout,
2433 const glslang::TQualifier& qualifier)
2434{
2435 // Create a vector of struct types for SPIR-V to consume
2436 std::vector<spv::Id> spvMembers;
2437 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 -06002438 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2439 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2440 if (glslangMember.hiddenMember()) {
2441 ++memberDelta;
2442 if (type.getBasicType() == glslang::EbtBlock)
2443 memberRemapper[glslangMembers][i] = -1;
2444 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002445 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002446 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002447 if (filterMember(glslangMember))
2448 continue;
2449 }
John Kessenich6090df02016-06-30 21:18:02 -06002450 // modify just this child's view of the qualifier
2451 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2452 InheritQualifiers(memberQualifier, qualifier);
2453
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002454 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06002455 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002456 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06002457
2458 // recurse
2459 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2460 }
2461 }
2462
2463 // Make the SPIR-V type
2464 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002465 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002466 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2467
2468 // Decorate it
2469 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2470
2471 return spvType;
2472}
2473
2474void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2475 const glslang::TTypeList* glslangMembers,
2476 glslang::TLayoutPacking explicitLayout,
2477 const glslang::TQualifier& qualifier,
2478 spv::Id spvType)
2479{
2480 // Name and decorate the non-hidden members
2481 int offset = -1;
2482 int locationOffset = 0; // for use within the members of this struct
2483 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2484 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2485 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002486 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002487 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002488 if (filterMember(glslangMember))
2489 continue;
2490 }
John Kessenich6090df02016-06-30 21:18:02 -06002491
2492 // modify just this child's view of the qualifier
2493 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2494 InheritQualifiers(memberQualifier, qualifier);
2495
2496 // using -1 above to indicate a hidden member
2497 if (member >= 0) {
2498 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2499 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2500 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2501 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002502 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2503 type.getQualifier().storage == glslang::EvqVaryingOut) {
2504 if (type.getBasicType() == glslang::EbtBlock ||
2505 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002506 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2507 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2508 }
2509 }
2510 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2511
2512 if (qualifier.storage == glslang::EvqBuffer) {
2513 std::vector<spv::Decoration> memory;
2514 TranslateMemoryDecoration(memberQualifier, memory);
2515 for (unsigned int i = 0; i < memory.size(); ++i)
2516 addMemberDecoration(spvType, member, memory[i]);
2517 }
2518
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002519 // Location assignment was already completed correctly by the front end,
2520 // just track whether a member needs to be decorated.
John Kessenich2f47bc92016-06-30 21:47:35 -06002521 // Ignore member locations if the container is an array, as that's
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002522 // ill-specified and decisions have been made to not allow this.
2523 if (! type.isArray() && memberQualifier.hasLocation())
2524 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06002525
John Kessenich2f47bc92016-06-30 21:47:35 -06002526 if (qualifier.hasLocation()) // track for upcoming inheritance
2527 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2528
John Kessenich6090df02016-06-30 21:18:02 -06002529 // component, XFB, others
2530 if (glslangMember.getQualifier().hasComponent())
2531 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2532 if (glslangMember.getQualifier().hasXfbOffset())
2533 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2534 else if (explicitLayout != glslang::ElpNone) {
2535 // figure out what to do with offset, which is accumulating
2536 int nextOffset;
2537 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2538 if (offset >= 0)
2539 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2540 offset = nextOffset;
2541 }
2542
2543 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2544 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2545
2546 // built-in variable decorations
2547 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002548 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002549 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002550
2551#ifdef NV_EXTENSIONS
2552 if (builtIn == spv::BuiltInLayer) {
2553 // SPV_NV_viewport_array2 extension
2554 if (glslangMember.getQualifier().layoutViewportRelative){
2555 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2556 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2557 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2558 }
2559 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2560 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2561 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2562 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2563 }
2564 }
chaocdf3956c2017-02-14 14:52:34 -08002565 if (glslangMember.getQualifier().layoutPassthrough) {
2566 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2567 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2568 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2569 }
chaoc771d89f2017-01-13 01:10:53 -08002570#endif
John Kessenich6090df02016-06-30 21:18:02 -06002571 }
2572 }
2573
2574 // Decorate the structure
2575 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich67027182017-04-19 18:34:49 -06002576 addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002577 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2578 builder.addCapability(spv::CapabilityGeometryStreams);
2579 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2580 }
2581 if (glslangIntermediate->getXfbMode()) {
2582 builder.addCapability(spv::CapabilityTransformFeedback);
2583 if (type.getQualifier().hasXfbStride())
2584 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2585 if (type.getQualifier().hasXfbBuffer())
2586 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2587 }
2588}
2589
John Kessenich6c292d32016-02-15 20:58:50 -07002590// Turn the expression forming the array size into an id.
2591// This is not quite trivial, because of specialization constants.
2592// Sometimes, a raw constant is turned into an Id, and sometimes
2593// a specialization constant expression is.
2594spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2595{
2596 // First, see if this is sized with a node, meaning a specialization constant:
2597 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2598 if (specNode != nullptr) {
2599 builder.clearAccessChain();
2600 specNode->traverse(this);
2601 return accessChainLoad(specNode->getAsTyped()->getType());
2602 }
qining25262b32016-05-06 17:25:16 -04002603
John Kessenich6c292d32016-02-15 20:58:50 -07002604 // Otherwise, need a compile-time (front end) size, get it:
2605 int size = arraySizes.getDimSize(dim);
2606 assert(size > 0);
2607 return builder.makeUintConstant(size);
2608}
2609
John Kessenich103bef92016-02-08 21:38:15 -07002610// Wrap the builder's accessChainLoad to:
2611// - localize handling of RelaxedPrecision
2612// - use the SPIR-V inferred type instead of another conversion of the glslang type
2613// (avoids unnecessary work and possible type punning for structures)
2614// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002615spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2616{
John Kessenich103bef92016-02-08 21:38:15 -07002617 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2618 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2619
2620 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002621 if (type.getBasicType() == glslang::EbtBool) {
2622 if (builder.isScalarType(nominalTypeId)) {
2623 // Conversion for bool
2624 spv::Id boolType = builder.makeBoolType();
2625 if (nominalTypeId != boolType)
2626 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2627 } else if (builder.isVectorType(nominalTypeId)) {
2628 // Conversion for bvec
2629 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2630 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2631 if (nominalTypeId != bvecType)
2632 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2633 }
2634 }
John Kessenich103bef92016-02-08 21:38:15 -07002635
2636 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002637}
2638
Rex Xu27253232016-02-23 17:51:09 +08002639// Wrap the builder's accessChainStore to:
2640// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002641//
2642// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002643void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2644{
2645 // Need to convert to abstract types when necessary
2646 if (type.getBasicType() == glslang::EbtBool) {
2647 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2648
2649 if (builder.isScalarType(nominalTypeId)) {
2650 // Conversion for bool
2651 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06002652 if (nominalTypeId != boolType) {
2653 // keep these outside arguments, for determinant order-of-evaluation
2654 spv::Id one = builder.makeUintConstant(1);
2655 spv::Id zero = builder.makeUintConstant(0);
2656 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2657 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06002658 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08002659 } else if (builder.isVectorType(nominalTypeId)) {
2660 // Conversion for bvec
2661 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2662 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06002663 if (nominalTypeId != bvecType) {
2664 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06002665 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2666 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2667 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06002668 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06002669 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
2670 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08002671 }
2672 }
2673
2674 builder.accessChainStore(rvalue);
2675}
2676
John Kessenich4bf71552016-09-02 11:20:21 -06002677// For storing when types match at the glslang level, but not might match at the
2678// SPIR-V level.
2679//
2680// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002681// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002682// as in a member-decorated way.
2683//
2684// NOTE: This function can handle any store request; if it's not special it
2685// simplifies to a simple OpStore.
2686//
2687// Implicitly uses the existing builder.accessChain as the storage target.
2688void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2689{
John Kessenichb3e24e42016-09-11 12:33:43 -06002690 // we only do the complex path here if it's an aggregate
2691 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002692 accessChainStore(type, rValue);
2693 return;
2694 }
2695
John Kessenichb3e24e42016-09-11 12:33:43 -06002696 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002697 spv::Id rType = builder.getTypeId(rValue);
2698 spv::Id lValue = builder.accessChainGetLValue();
2699 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2700 if (lType == rType) {
2701 accessChainStore(type, rValue);
2702 return;
2703 }
2704
John Kessenichb3e24e42016-09-11 12:33:43 -06002705 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002706 // where the two types were the same type in GLSL. This requires member
2707 // by member copy, recursively.
2708
John Kessenichb3e24e42016-09-11 12:33:43 -06002709 // If an array, copy element by element.
2710 if (type.isArray()) {
2711 glslang::TType glslangElementType(type, 0);
2712 spv::Id elementRType = builder.getContainedTypeId(rType);
2713 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2714 // get the source member
2715 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002716
John Kessenichb3e24e42016-09-11 12:33:43 -06002717 // set up the target storage
2718 builder.clearAccessChain();
2719 builder.setAccessChainLValue(lValue);
2720 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002721
John Kessenichb3e24e42016-09-11 12:33:43 -06002722 // store the member
2723 multiTypeStore(glslangElementType, elementRValue);
2724 }
2725 } else {
2726 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002727
John Kessenichb3e24e42016-09-11 12:33:43 -06002728 // loop over structure members
2729 const glslang::TTypeList& members = *type.getStruct();
2730 for (int m = 0; m < (int)members.size(); ++m) {
2731 const glslang::TType& glslangMemberType = *members[m].type;
2732
2733 // get the source member
2734 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2735 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2736
2737 // set up the target storage
2738 builder.clearAccessChain();
2739 builder.setAccessChainLValue(lValue);
2740 builder.accessChainPush(builder.makeIntConstant(m));
2741
2742 // store the member
2743 multiTypeStore(glslangMemberType, memberRValue);
2744 }
John Kessenich4bf71552016-09-02 11:20:21 -06002745 }
2746}
2747
John Kessenichf85e8062015-12-19 13:57:10 -07002748// Decide whether or not this type should be
2749// decorated with offsets and strides, and if so
2750// whether std140 or std430 rules should be applied.
2751glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002752{
John Kessenichf85e8062015-12-19 13:57:10 -07002753 // has to be a block
2754 if (type.getBasicType() != glslang::EbtBlock)
2755 return glslang::ElpNone;
2756
2757 // has to be a uniform or buffer block
2758 if (type.getQualifier().storage != glslang::EvqUniform &&
2759 type.getQualifier().storage != glslang::EvqBuffer)
2760 return glslang::ElpNone;
2761
2762 // return the layout to use
2763 switch (type.getQualifier().layoutPacking) {
2764 case glslang::ElpStd140:
2765 case glslang::ElpStd430:
2766 return type.getQualifier().layoutPacking;
2767 default:
2768 return glslang::ElpNone;
2769 }
John Kessenich31ed4832015-09-09 17:51:38 -06002770}
2771
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002772// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002773int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002774{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002775 int size;
John Kessenich49987892015-12-29 17:11:44 -07002776 int stride;
2777 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002778
2779 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002780}
2781
John Kessenich49987892015-12-29 17:11:44 -07002782// 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 -07002783// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002784int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002785{
John Kessenich49987892015-12-29 17:11:44 -07002786 glslang::TType elementType;
2787 elementType.shallowCopy(matrixType);
2788 elementType.clearArraySizes();
2789
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002790 int size;
John Kessenich49987892015-12-29 17:11:44 -07002791 int stride;
2792 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2793
2794 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002795}
2796
John Kessenich5e4b1242015-08-06 22:53:06 -06002797// Given a member type of a struct, realign the current offset for it, and compute
2798// the next (not yet aligned) offset for the next member, which will get aligned
2799// on the next call.
2800// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2801// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2802// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002803void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002804 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002805{
2806 // this will get a positive value when deemed necessary
2807 nextOffset = -1;
2808
John Kessenich5e4b1242015-08-06 22:53:06 -06002809 // override anything in currentOffset with user-set offset
2810 if (memberType.getQualifier().hasOffset())
2811 currentOffset = memberType.getQualifier().layoutOffset;
2812
2813 // It could be that current linker usage in glslang updated all the layoutOffset,
2814 // in which case the following code does not matter. But, that's not quite right
2815 // once cross-compilation unit GLSL validation is done, as the original user
2816 // settings are needed in layoutOffset, and then the following will come into play.
2817
John Kessenichf85e8062015-12-19 13:57:10 -07002818 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002819 if (! memberType.getQualifier().hasOffset())
2820 currentOffset = -1;
2821
2822 return;
2823 }
2824
John Kessenichf85e8062015-12-19 13:57:10 -07002825 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002826 if (currentOffset < 0)
2827 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002828
John Kessenich5e4b1242015-08-06 22:53:06 -06002829 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2830 // but possibly not yet correctly aligned.
2831
2832 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002833 int dummyStride;
2834 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06002835
2836 // Adjust alignment for HLSL rules
2837 if (glslangIntermediate->usingHlslOFfsets() &&
2838 ! memberType.isArray() && memberType.isVector()) {
2839 int dummySize;
2840 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
2841 if (componentAlignment <= 4)
2842 memberAlignment = componentAlignment;
2843 }
2844
2845 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06002846 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06002847
2848 // Bump up to vec4 if there is a bad straddle
2849 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
2850 glslang::RoundToPow2(currentOffset, 16);
2851
John Kessenich5e4b1242015-08-06 22:53:06 -06002852 nextOffset = currentOffset + memberSize;
2853}
2854
David Netoa901ffe2016-06-08 14:11:40 +01002855void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002856{
David Netoa901ffe2016-06-08 14:11:40 +01002857 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2858 switch (glslangBuiltIn)
2859 {
2860 case glslang::EbvClipDistance:
2861 case glslang::EbvCullDistance:
2862 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08002863#ifdef NV_EXTENSIONS
2864 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +08002865 case glslang::EbvViewportIndex:
chaoc771d89f2017-01-13 01:10:53 -08002866 case glslang::EbvViewportMaskNV:
2867 case glslang::EbvSecondaryPositionNV:
2868 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08002869 case glslang::EbvPositionPerViewNV:
2870 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08002871#endif
David Netoa901ffe2016-06-08 14:11:40 +01002872 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2873 // Alternately, we could just call this for any glslang built-in, since the
2874 // capability already guards against duplicates.
2875 TranslateBuiltInDecoration(glslangBuiltIn, false);
2876 break;
2877 default:
2878 // Capabilities were already generated when the struct was declared.
2879 break;
2880 }
John Kessenichebb50532016-05-16 19:22:05 -06002881}
2882
John Kessenich6fccb3c2016-09-19 16:01:41 -06002883bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002884{
John Kessenicheee9d532016-09-19 18:09:30 -06002885 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002886}
2887
2888// Make all the functions, skeletally, without actually visiting their bodies.
2889void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2890{
2891 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2892 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002893 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002894 continue;
2895
2896 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002897 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002898 //
qining25262b32016-05-06 17:25:16 -04002899 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002900 // function. What it is an address of varies:
2901 //
John Kessenich4bf71552016-09-02 11:20:21 -06002902 // - "in" parameters not marked as "const" can be written to without modifying the calling
2903 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002904 //
2905 // - "const in" parameters can just be the r-value, as no writes need occur.
2906 //
John Kessenich4bf71552016-09-02 11:20:21 -06002907 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2908 // 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 -06002909
2910 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002911 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002912 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2913
John Kessenich37789792017-03-21 23:56:40 -06002914 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() == glslangIntermediate->implicitThisName;
2915
John Kessenich140f3df2015-06-26 16:58:36 -06002916 for (int p = 0; p < (int)parameters.size(); ++p) {
2917 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2918 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenich37789792017-03-21 23:56:40 -06002919 // can we pass by reference?
2920 if (paramType.containsOpaque() || // sampler, etc.
John Kessenich4960baa2017-03-19 18:09:59 -06002921 (paramType.getBasicType() == glslang::EbtBlock &&
John Kessenich37789792017-03-21 23:56:40 -06002922 paramType.getQualifier().storage == glslang::EvqBuffer) || // SSBO
John Kessenichaa3c64c2017-03-28 09:52:38 -06002923 (p == 0 && implicitThis)) // implicit 'this'
John Kessenicha5c5fb62017-05-05 05:09:58 -06002924 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002925 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002926 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2927 else
John Kessenich4bf71552016-09-02 11:20:21 -06002928 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002929 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002930 paramTypes.push_back(typeId);
2931 }
2932
2933 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002934 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2935 convertGlslangToSpvType(glslFunction->getType()),
2936 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06002937 if (implicitThis)
2938 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06002939
2940 // Track function to emit/call later
2941 functionMap[glslFunction->getName().c_str()] = function;
2942
2943 // Set the parameter id's
2944 for (int p = 0; p < (int)parameters.size(); ++p) {
2945 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2946 // give a name too
2947 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2948 }
2949 }
2950}
2951
2952// Process all the initializers, while skipping the functions and link objects
2953void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2954{
2955 builder.setBuildPoint(shaderEntry->getLastBlock());
2956 for (int i = 0; i < (int)initializers.size(); ++i) {
2957 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2958 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2959
2960 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06002961 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06002962 initializer->traverse(this);
2963 }
2964 }
2965}
2966
2967// Process all the functions, while skipping initializers.
2968void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2969{
2970 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2971 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07002972 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06002973 node->traverse(this);
2974 }
2975}
2976
2977void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2978{
qining25262b32016-05-06 17:25:16 -04002979 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002980 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06002981 currentFunction = functionMap[node->getName().c_str()];
2982 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06002983 builder.setBuildPoint(functionBlock);
2984}
2985
Rex Xu04db3f52015-09-16 11:44:02 +08002986void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002987{
Rex Xufc618912015-09-09 16:42:49 +08002988 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002989
2990 glslang::TSampler sampler = {};
2991 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002992 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002993 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2994 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2995 }
2996
John Kessenich140f3df2015-06-26 16:58:36 -06002997 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2998 builder.clearAccessChain();
2999 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003000
3001 // Special case l-value operands
3002 bool lvalue = false;
3003 switch (node.getOp()) {
3004 case glslang::EOpImageAtomicAdd:
3005 case glslang::EOpImageAtomicMin:
3006 case glslang::EOpImageAtomicMax:
3007 case glslang::EOpImageAtomicAnd:
3008 case glslang::EOpImageAtomicOr:
3009 case glslang::EOpImageAtomicXor:
3010 case glslang::EOpImageAtomicExchange:
3011 case glslang::EOpImageAtomicCompSwap:
3012 if (i == 0)
3013 lvalue = true;
3014 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003015 case glslang::EOpSparseImageLoad:
3016 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3017 lvalue = true;
3018 break;
Rex Xu48edadf2015-12-31 16:11:41 +08003019 case glslang::EOpSparseTexture:
3020 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3021 lvalue = true;
3022 break;
3023 case glslang::EOpSparseTextureClamp:
3024 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3025 lvalue = true;
3026 break;
3027 case glslang::EOpSparseTextureLod:
3028 case glslang::EOpSparseTextureOffset:
3029 if (i == 3)
3030 lvalue = true;
3031 break;
3032 case glslang::EOpSparseTextureFetch:
3033 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3034 lvalue = true;
3035 break;
3036 case glslang::EOpSparseTextureFetchOffset:
3037 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3038 lvalue = true;
3039 break;
3040 case glslang::EOpSparseTextureLodOffset:
3041 case glslang::EOpSparseTextureGrad:
3042 case glslang::EOpSparseTextureOffsetClamp:
3043 if (i == 4)
3044 lvalue = true;
3045 break;
3046 case glslang::EOpSparseTextureGradOffset:
3047 case glslang::EOpSparseTextureGradClamp:
3048 if (i == 5)
3049 lvalue = true;
3050 break;
3051 case glslang::EOpSparseTextureGradOffsetClamp:
3052 if (i == 6)
3053 lvalue = true;
3054 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003055 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003056 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3057 lvalue = true;
3058 break;
3059 case glslang::EOpSparseTextureGatherOffset:
3060 case glslang::EOpSparseTextureGatherOffsets:
3061 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3062 lvalue = true;
3063 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003064#ifdef AMD_EXTENSIONS
3065 case glslang::EOpSparseTextureGatherLod:
3066 if (i == 3)
3067 lvalue = true;
3068 break;
3069 case glslang::EOpSparseTextureGatherLodOffset:
3070 case glslang::EOpSparseTextureGatherLodOffsets:
3071 if (i == 4)
3072 lvalue = true;
3073 break;
3074#endif
Rex Xufc618912015-09-09 16:42:49 +08003075 default:
3076 break;
3077 }
3078
Rex Xu6b86d492015-09-16 17:48:22 +08003079 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003080 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003081 else
John Kessenich32cfd492016-02-02 12:37:46 -07003082 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003083 }
3084}
3085
John Kessenichfc51d282015-08-19 13:34:18 -06003086void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003087{
John Kessenichfc51d282015-08-19 13:34:18 -06003088 builder.clearAccessChain();
3089 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003090 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003091}
John Kessenich140f3df2015-06-26 16:58:36 -06003092
John Kessenichfc51d282015-08-19 13:34:18 -06003093spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3094{
John Kesseniche485c7a2017-05-31 18:50:53 -06003095 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003096 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003097
3098 builder.setLine(node->getLoc().line);
3099
John Kessenich8c8505c2016-07-26 12:50:38 -06003100 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06003101
John Kessenichfc51d282015-08-19 13:34:18 -06003102 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003103 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3104 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
3105 std::vector<spv::Id> arguments;
3106 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003107 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003108 else
3109 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003110 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003111
3112 spv::Builder::TextureParameters params = { };
3113 params.sampler = arguments[0];
3114
Rex Xu04db3f52015-09-16 11:44:02 +08003115 glslang::TCrackedTextureOp cracked;
3116 node->crackTexture(sampler, cracked);
3117
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003118 const bool isUnsignedResult =
3119 node->getType().getBasicType() == glslang::EbtUint64 ||
3120 node->getType().getBasicType() == glslang::EbtUint;
3121
John Kessenichfc51d282015-08-19 13:34:18 -06003122 // Check for queries
3123 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003124 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3125 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003126 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003127
John Kessenichfc51d282015-08-19 13:34:18 -06003128 switch (node->getOp()) {
3129 case glslang::EOpImageQuerySize:
3130 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003131 if (arguments.size() > 1) {
3132 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003133 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003134 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003135 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003136 case glslang::EOpImageQuerySamples:
3137 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003138 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003139 case glslang::EOpTextureQueryLod:
3140 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003141 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003142 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003143 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003144 case glslang::EOpSparseTexelsResident:
3145 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003146 default:
3147 assert(0);
3148 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003149 }
John Kessenich140f3df2015-06-26 16:58:36 -06003150 }
3151
Rex Xufc618912015-09-09 16:42:49 +08003152 // Check for image functions other than queries
3153 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003154 std::vector<spv::Id> operands;
3155 auto opIt = arguments.begin();
3156 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003157
3158 // Handle subpass operations
3159 // TODO: GLSL should change to have the "MS" only on the type rather than the
3160 // built-in function.
3161 if (cracked.subpass) {
3162 // add on the (0,0) coordinate
3163 spv::Id zero = builder.makeIntConstant(0);
3164 std::vector<spv::Id> comps;
3165 comps.push_back(zero);
3166 comps.push_back(zero);
3167 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3168 if (sampler.ms) {
3169 operands.push_back(spv::ImageOperandsSampleMask);
3170 operands.push_back(*(opIt++));
3171 }
John Kessenich8c8505c2016-07-26 12:50:38 -06003172 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07003173 }
3174
John Kessenich56bab042015-09-16 10:54:31 -06003175 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06003176 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07003177 if (sampler.ms) {
3178 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003179 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07003180 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003181 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3182 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06003183 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06003184 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08003185 if (sampler.ms) {
3186 operands.push_back(*(opIt + 1));
3187 operands.push_back(spv::ImageOperandsSampleMask);
3188 operands.push_back(*opIt);
3189 } else
3190 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003191 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003192 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3193 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003194 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08003195 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
3196 builder.addCapability(spv::CapabilitySparseResidency);
3197 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3198 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3199
3200 if (sampler.ms) {
3201 operands.push_back(spv::ImageOperandsSampleMask);
3202 operands.push_back(*opIt++);
3203 }
3204
3205 // Create the return type that was a special structure
3206 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003207 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003208 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3209 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3210
3211 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3212
3213 // Decode the return type
3214 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3215 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003216 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003217 // Process image atomic operations
3218
3219 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3220 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003221 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003222
John Kessenich8c8505c2016-07-26 12:50:38 -06003223 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003224 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003225
3226 std::vector<spv::Id> operands;
3227 operands.push_back(pointer);
3228 for (; opIt != arguments.end(); ++opIt)
3229 operands.push_back(*opIt);
3230
John Kessenich8c8505c2016-07-26 12:50:38 -06003231 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003232 }
3233 }
3234
3235 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003236 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003237 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3238
John Kessenichfc51d282015-08-19 13:34:18 -06003239 // check for bias argument
3240 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08003241#ifdef AMD_EXTENSIONS
3242 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
3243#else
Rex Xu71519fe2015-11-11 15:35:47 +08003244 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08003245#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003246 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08003247#ifdef AMD_EXTENSIONS
3248 if (cracked.gather)
3249 ++nonBiasArgCount; // comp argument should be present when bias argument is present
3250#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003251 if (cracked.offset)
3252 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003253#ifdef AMD_EXTENSIONS
3254 else if (cracked.offsets)
3255 ++nonBiasArgCount;
3256#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003257 if (cracked.grad)
3258 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003259 if (cracked.lodClamp)
3260 ++nonBiasArgCount;
3261 if (sparse)
3262 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003263
3264 if ((int)arguments.size() > nonBiasArgCount)
3265 bias = true;
3266 }
3267
John Kessenicha5c33d62016-06-02 23:45:21 -06003268 // See if the sampler param should really be just the SPV image part
3269 if (cracked.fetch) {
3270 // a fetch needs to have the image extracted first
3271 if (builder.isSampledImage(params.sampler))
3272 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3273 }
3274
Rex Xu225e0fc2016-11-17 17:47:59 +08003275#ifdef AMD_EXTENSIONS
3276 if (cracked.gather) {
3277 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
3278 if (bias || cracked.lod ||
3279 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
3280 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08003281 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08003282 }
3283 }
3284#endif
3285
John Kessenichfc51d282015-08-19 13:34:18 -06003286 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003287
John Kessenichfc51d282015-08-19 13:34:18 -06003288 params.coords = arguments[1];
3289 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003290 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003291
3292 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003293 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003294 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003295 ++extraArgs;
3296 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003297 params.Dref = arguments[2];
3298 ++extraArgs;
3299 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003300 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003301 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003302 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003303 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003304 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003305 dRefComp = builder.getNumComponents(params.coords) - 1;
3306 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003307 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3308 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003309
3310 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003311 if (cracked.lod) {
3312 params.lod = arguments[2];
3313 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003314 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3315 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3316 noImplicitLod = true;
3317 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003318
3319 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003320 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08003321 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003322 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003323 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003324
3325 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003326 if (cracked.grad) {
3327 params.gradX = arguments[2 + extraArgs];
3328 params.gradY = arguments[3 + extraArgs];
3329 extraArgs += 2;
3330 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003331
3332 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003333 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003334 params.offset = arguments[2 + extraArgs];
3335 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003336 } else if (cracked.offsets) {
3337 params.offsets = arguments[2 + extraArgs];
3338 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003339 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003340
3341 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003342 if (cracked.lodClamp) {
3343 params.lodClamp = arguments[2 + extraArgs];
3344 ++extraArgs;
3345 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003346
3347 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003348 if (sparse) {
3349 params.texelOut = arguments[2 + extraArgs];
3350 ++extraArgs;
3351 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003352
John Kessenich76d4dfc2016-06-16 12:43:23 -06003353 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003354 if (cracked.gather && ! sampler.shadow) {
3355 // default component is 0, if missing, otherwise an argument
3356 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003357 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003358 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08003359 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003360 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08003361 }
3362
3363 // bias
3364 if (bias) {
3365 params.bias = arguments[2 + extraArgs];
3366 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003367 }
John Kessenichfc51d282015-08-19 13:34:18 -06003368
John Kessenich65336482016-06-16 14:06:26 -06003369 // projective component (might not to move)
3370 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3371 // are divided by the last component of P."
3372 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3373 // unused components will appear after all used components."
3374 if (cracked.proj) {
3375 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3376 int projTargetComp;
3377 switch (sampler.dim) {
3378 case glslang::Esd1D: projTargetComp = 1; break;
3379 case glslang::Esd2D: projTargetComp = 2; break;
3380 case glslang::EsdRect: projTargetComp = 2; break;
3381 default: projTargetComp = projSourceComp; break;
3382 }
3383 // copy the projective coordinate if we have to
3384 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003385 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003386 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3387 projSourceComp);
3388 params.coords = builder.createCompositeInsert(projComp, params.coords,
3389 builder.getTypeId(params.coords), projTargetComp);
3390 }
3391 }
3392
John Kessenich8c8505c2016-07-26 12:50:38 -06003393 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003394}
3395
3396spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3397{
3398 // Grab the function's pointer from the previously created function
3399 spv::Function* function = functionMap[node->getName().c_str()];
3400 if (! function)
3401 return 0;
3402
3403 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3404 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3405
3406 // See comments in makeFunctions() for details about the semantics for parameter passing.
3407 //
3408 // These imply we need a four step process:
3409 // 1. Evaluate the arguments
3410 // 2. Allocate and make copies of in, out, and inout arguments
3411 // 3. Make the call
3412 // 4. Copy back the results
3413
3414 // 1. Evaluate the arguments
3415 std::vector<spv::Builder::AccessChain> lValues;
3416 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003417 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003418 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003419 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003420 // build l-value
3421 builder.clearAccessChain();
3422 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003423 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06003424 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
John Kessenich4a57dce2017-02-24 19:15:46 -07003425 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.containsOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06003426 // save l-value
3427 lValues.push_back(builder.getAccessChain());
3428 } else {
3429 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003430 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003431 }
3432 }
3433
3434 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3435 // copy the original into that space.
3436 //
3437 // Also, build up the list of actual arguments to pass in for the call
3438 int lValueCount = 0;
3439 int rValueCount = 0;
3440 std::vector<spv::Id> spvArgs;
3441 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003442 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003443 spv::Id arg;
steve-lunargdd8287a2017-02-23 18:04:12 -07003444 if (paramType.containsOpaque() ||
John Kessenich37789792017-03-21 23:56:40 -06003445 (paramType.getBasicType() == glslang::EbtBlock && qualifiers[a] == glslang::EvqBuffer) ||
3446 (a == 0 && function->hasImplicitThis())) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003447 builder.setAccessChain(lValues[lValueCount]);
3448 arg = builder.accessChainGetLValue();
3449 ++lValueCount;
3450 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06003451 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003452 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3453 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3454 // need to copy the input into output space
3455 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003456 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003457 builder.clearAccessChain();
3458 builder.setAccessChainLValue(arg);
3459 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003460 }
3461 ++lValueCount;
3462 } else {
3463 arg = rValues[rValueCount];
3464 ++rValueCount;
3465 }
3466 spvArgs.push_back(arg);
3467 }
3468
3469 // 3. Make the call.
3470 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003471 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003472
3473 // 4. Copy back out an "out" arguments.
3474 lValueCount = 0;
3475 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003476 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003477 if (qualifiers[a] != glslang::EvqConstReadOnly) {
3478 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3479 spv::Id copy = builder.createLoad(spvArgs[a]);
3480 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003481 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003482 }
3483 ++lValueCount;
3484 }
3485 }
3486
3487 return result;
3488}
3489
3490// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003491spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3492 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003493 spv::Id typeId, spv::Id left, spv::Id right,
3494 glslang::TBasicType typeProxy, bool reduceComparison)
3495{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003496#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08003497 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003498 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3499#else
Rex Xucabbb782017-03-24 13:41:14 +08003500 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06003501 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003502#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003503 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003504
3505 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003506 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003507 bool comparison = false;
3508
3509 switch (op) {
3510 case glslang::EOpAdd:
3511 case glslang::EOpAddAssign:
3512 if (isFloat)
3513 binOp = spv::OpFAdd;
3514 else
3515 binOp = spv::OpIAdd;
3516 break;
3517 case glslang::EOpSub:
3518 case glslang::EOpSubAssign:
3519 if (isFloat)
3520 binOp = spv::OpFSub;
3521 else
3522 binOp = spv::OpISub;
3523 break;
3524 case glslang::EOpMul:
3525 case glslang::EOpMulAssign:
3526 if (isFloat)
3527 binOp = spv::OpFMul;
3528 else
3529 binOp = spv::OpIMul;
3530 break;
3531 case glslang::EOpVectorTimesScalar:
3532 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003533 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003534 if (builder.isVector(right))
3535 std::swap(left, right);
3536 assert(builder.isScalar(right));
3537 needMatchingVectors = false;
3538 binOp = spv::OpVectorTimesScalar;
3539 } else
3540 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003541 break;
3542 case glslang::EOpVectorTimesMatrix:
3543 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003544 binOp = spv::OpVectorTimesMatrix;
3545 break;
3546 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003547 binOp = spv::OpMatrixTimesVector;
3548 break;
3549 case glslang::EOpMatrixTimesScalar:
3550 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003551 binOp = spv::OpMatrixTimesScalar;
3552 break;
3553 case glslang::EOpMatrixTimesMatrix:
3554 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003555 binOp = spv::OpMatrixTimesMatrix;
3556 break;
3557 case glslang::EOpOuterProduct:
3558 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003559 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003560 break;
3561
3562 case glslang::EOpDiv:
3563 case glslang::EOpDivAssign:
3564 if (isFloat)
3565 binOp = spv::OpFDiv;
3566 else if (isUnsigned)
3567 binOp = spv::OpUDiv;
3568 else
3569 binOp = spv::OpSDiv;
3570 break;
3571 case glslang::EOpMod:
3572 case glslang::EOpModAssign:
3573 if (isFloat)
3574 binOp = spv::OpFMod;
3575 else if (isUnsigned)
3576 binOp = spv::OpUMod;
3577 else
3578 binOp = spv::OpSMod;
3579 break;
3580 case glslang::EOpRightShift:
3581 case glslang::EOpRightShiftAssign:
3582 if (isUnsigned)
3583 binOp = spv::OpShiftRightLogical;
3584 else
3585 binOp = spv::OpShiftRightArithmetic;
3586 break;
3587 case glslang::EOpLeftShift:
3588 case glslang::EOpLeftShiftAssign:
3589 binOp = spv::OpShiftLeftLogical;
3590 break;
3591 case glslang::EOpAnd:
3592 case glslang::EOpAndAssign:
3593 binOp = spv::OpBitwiseAnd;
3594 break;
3595 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003596 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003597 binOp = spv::OpLogicalAnd;
3598 break;
3599 case glslang::EOpInclusiveOr:
3600 case glslang::EOpInclusiveOrAssign:
3601 binOp = spv::OpBitwiseOr;
3602 break;
3603 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003604 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003605 binOp = spv::OpLogicalOr;
3606 break;
3607 case glslang::EOpExclusiveOr:
3608 case glslang::EOpExclusiveOrAssign:
3609 binOp = spv::OpBitwiseXor;
3610 break;
3611 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003612 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003613 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003614 break;
3615
3616 case glslang::EOpLessThan:
3617 case glslang::EOpGreaterThan:
3618 case glslang::EOpLessThanEqual:
3619 case glslang::EOpGreaterThanEqual:
3620 case glslang::EOpEqual:
3621 case glslang::EOpNotEqual:
3622 case glslang::EOpVectorEqual:
3623 case glslang::EOpVectorNotEqual:
3624 comparison = true;
3625 break;
3626 default:
3627 break;
3628 }
3629
John Kessenich7c1aa102015-10-15 13:29:11 -06003630 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003631 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003632 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003633 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003634 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003635
3636 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003637 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003638 builder.promoteScalar(precision, left, right);
3639
qining25262b32016-05-06 17:25:16 -04003640 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3641 addDecoration(result, noContraction);
3642 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003643 }
3644
3645 if (! comparison)
3646 return 0;
3647
John Kessenich7c1aa102015-10-15 13:29:11 -06003648 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003649
John Kessenich4583b612016-08-07 19:14:22 -06003650 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3651 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003652 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003653
3654 switch (op) {
3655 case glslang::EOpLessThan:
3656 if (isFloat)
3657 binOp = spv::OpFOrdLessThan;
3658 else if (isUnsigned)
3659 binOp = spv::OpULessThan;
3660 else
3661 binOp = spv::OpSLessThan;
3662 break;
3663 case glslang::EOpGreaterThan:
3664 if (isFloat)
3665 binOp = spv::OpFOrdGreaterThan;
3666 else if (isUnsigned)
3667 binOp = spv::OpUGreaterThan;
3668 else
3669 binOp = spv::OpSGreaterThan;
3670 break;
3671 case glslang::EOpLessThanEqual:
3672 if (isFloat)
3673 binOp = spv::OpFOrdLessThanEqual;
3674 else if (isUnsigned)
3675 binOp = spv::OpULessThanEqual;
3676 else
3677 binOp = spv::OpSLessThanEqual;
3678 break;
3679 case glslang::EOpGreaterThanEqual:
3680 if (isFloat)
3681 binOp = spv::OpFOrdGreaterThanEqual;
3682 else if (isUnsigned)
3683 binOp = spv::OpUGreaterThanEqual;
3684 else
3685 binOp = spv::OpSGreaterThanEqual;
3686 break;
3687 case glslang::EOpEqual:
3688 case glslang::EOpVectorEqual:
3689 if (isFloat)
3690 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003691 else if (isBool)
3692 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003693 else
3694 binOp = spv::OpIEqual;
3695 break;
3696 case glslang::EOpNotEqual:
3697 case glslang::EOpVectorNotEqual:
3698 if (isFloat)
3699 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003700 else if (isBool)
3701 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003702 else
3703 binOp = spv::OpINotEqual;
3704 break;
3705 default:
3706 break;
3707 }
3708
qining25262b32016-05-06 17:25:16 -04003709 if (binOp != spv::OpNop) {
3710 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3711 addDecoration(result, noContraction);
3712 return builder.setPrecision(result, precision);
3713 }
John Kessenich140f3df2015-06-26 16:58:36 -06003714
3715 return 0;
3716}
3717
John Kessenich04bb8a02015-12-12 12:28:14 -07003718//
3719// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3720// These can be any of:
3721//
3722// matrix * scalar
3723// scalar * matrix
3724// matrix * matrix linear algebraic
3725// matrix * vector
3726// vector * matrix
3727// matrix * matrix componentwise
3728// matrix op matrix op in {+, -, /}
3729// matrix op scalar op in {+, -, /}
3730// scalar op matrix op in {+, -, /}
3731//
qining25262b32016-05-06 17:25:16 -04003732spv::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 -07003733{
3734 bool firstClass = true;
3735
3736 // First, handle first-class matrix operations (* and matrix/scalar)
3737 switch (op) {
3738 case spv::OpFDiv:
3739 if (builder.isMatrix(left) && builder.isScalar(right)) {
3740 // turn matrix / scalar into a multiply...
3741 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3742 op = spv::OpMatrixTimesScalar;
3743 } else
3744 firstClass = false;
3745 break;
3746 case spv::OpMatrixTimesScalar:
3747 if (builder.isMatrix(right))
3748 std::swap(left, right);
3749 assert(builder.isScalar(right));
3750 break;
3751 case spv::OpVectorTimesMatrix:
3752 assert(builder.isVector(left));
3753 assert(builder.isMatrix(right));
3754 break;
3755 case spv::OpMatrixTimesVector:
3756 assert(builder.isMatrix(left));
3757 assert(builder.isVector(right));
3758 break;
3759 case spv::OpMatrixTimesMatrix:
3760 assert(builder.isMatrix(left));
3761 assert(builder.isMatrix(right));
3762 break;
3763 default:
3764 firstClass = false;
3765 break;
3766 }
3767
qining25262b32016-05-06 17:25:16 -04003768 if (firstClass) {
3769 spv::Id result = builder.createBinOp(op, typeId, left, right);
3770 addDecoration(result, noContraction);
3771 return builder.setPrecision(result, precision);
3772 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003773
LoopDawg592860c2016-06-09 08:57:35 -06003774 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003775 // The result type of all of them is the same type as the (a) matrix operand.
3776 // The algorithm is to:
3777 // - break the matrix(es) into vectors
3778 // - smear any scalar to a vector
3779 // - do vector operations
3780 // - make a matrix out the vector results
3781 switch (op) {
3782 case spv::OpFAdd:
3783 case spv::OpFSub:
3784 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003785 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003786 case spv::OpFMul:
3787 {
3788 // one time set up...
3789 bool leftMat = builder.isMatrix(left);
3790 bool rightMat = builder.isMatrix(right);
3791 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3792 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3793 spv::Id scalarType = builder.getScalarTypeId(typeId);
3794 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3795 std::vector<spv::Id> results;
3796 spv::Id smearVec = spv::NoResult;
3797 if (builder.isScalar(left))
3798 smearVec = builder.smearScalar(precision, left, vecType);
3799 else if (builder.isScalar(right))
3800 smearVec = builder.smearScalar(precision, right, vecType);
3801
3802 // do each vector op
3803 for (unsigned int c = 0; c < numCols; ++c) {
3804 std::vector<unsigned int> indexes;
3805 indexes.push_back(c);
3806 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3807 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003808 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3809 addDecoration(result, noContraction);
3810 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003811 }
3812
3813 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003814 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003815 }
3816 default:
3817 assert(0);
3818 return spv::NoResult;
3819 }
3820}
3821
qining25262b32016-05-06 17:25:16 -04003822spv::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 -06003823{
3824 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003825 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003826 int libCall = -1;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003827#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08003828 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003829 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3830#else
Rex Xucabbb782017-03-24 13:41:14 +08003831 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08003832 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003833#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003834
3835 switch (op) {
3836 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003837 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003838 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003839 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003840 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003841 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003842 unaryOp = spv::OpSNegate;
3843 break;
3844
3845 case glslang::EOpLogicalNot:
3846 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003847 unaryOp = spv::OpLogicalNot;
3848 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003849 case glslang::EOpBitwiseNot:
3850 unaryOp = spv::OpNot;
3851 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003852
John Kessenich140f3df2015-06-26 16:58:36 -06003853 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003854 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003855 break;
3856 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003857 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003858 break;
3859 case glslang::EOpTranspose:
3860 unaryOp = spv::OpTranspose;
3861 break;
3862
3863 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003864 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003865 break;
3866 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003867 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003868 break;
3869 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003870 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003871 break;
3872 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003873 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003874 break;
3875 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003876 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003877 break;
3878 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003879 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003880 break;
3881 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003882 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003883 break;
3884 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003885 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003886 break;
3887
3888 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003889 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003890 break;
3891 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003892 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003893 break;
3894 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003895 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003896 break;
3897 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003898 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003899 break;
3900 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003901 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003902 break;
3903 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003904 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003905 break;
3906
3907 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003908 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003909 break;
3910 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003911 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003912 break;
3913
3914 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003915 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003916 break;
3917 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003918 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003919 break;
3920 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003921 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003922 break;
3923 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003924 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003925 break;
3926 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003927 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003928 break;
3929 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003930 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003931 break;
3932
3933 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003934 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003935 break;
3936 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003937 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003938 break;
3939 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003940 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003941 break;
3942 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003943 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003944 break;
3945 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003946 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003947 break;
3948 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003949 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003950 break;
3951
3952 case glslang::EOpIsNan:
3953 unaryOp = spv::OpIsNan;
3954 break;
3955 case glslang::EOpIsInf:
3956 unaryOp = spv::OpIsInf;
3957 break;
LoopDawg592860c2016-06-09 08:57:35 -06003958 case glslang::EOpIsFinite:
3959 unaryOp = spv::OpIsFinite;
3960 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003961
Rex Xucbc426e2015-12-15 16:03:10 +08003962 case glslang::EOpFloatBitsToInt:
3963 case glslang::EOpFloatBitsToUint:
3964 case glslang::EOpIntBitsToFloat:
3965 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003966 case glslang::EOpDoubleBitsToInt64:
3967 case glslang::EOpDoubleBitsToUint64:
3968 case glslang::EOpInt64BitsToDouble:
3969 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08003970#ifdef AMD_EXTENSIONS
3971 case glslang::EOpFloat16BitsToInt16:
3972 case glslang::EOpFloat16BitsToUint16:
3973 case glslang::EOpInt16BitsToFloat16:
3974 case glslang::EOpUint16BitsToFloat16:
3975#endif
Rex Xucbc426e2015-12-15 16:03:10 +08003976 unaryOp = spv::OpBitcast;
3977 break;
3978
John Kessenich140f3df2015-06-26 16:58:36 -06003979 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003980 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003981 break;
3982 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003983 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003984 break;
3985 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003986 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003987 break;
3988 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003989 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003990 break;
3991 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003992 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003993 break;
3994 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003995 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003996 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003997 case glslang::EOpPackSnorm4x8:
3998 libCall = spv::GLSLstd450PackSnorm4x8;
3999 break;
4000 case glslang::EOpUnpackSnorm4x8:
4001 libCall = spv::GLSLstd450UnpackSnorm4x8;
4002 break;
4003 case glslang::EOpPackUnorm4x8:
4004 libCall = spv::GLSLstd450PackUnorm4x8;
4005 break;
4006 case glslang::EOpUnpackUnorm4x8:
4007 libCall = spv::GLSLstd450UnpackUnorm4x8;
4008 break;
4009 case glslang::EOpPackDouble2x32:
4010 libCall = spv::GLSLstd450PackDouble2x32;
4011 break;
4012 case glslang::EOpUnpackDouble2x32:
4013 libCall = spv::GLSLstd450UnpackDouble2x32;
4014 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004015
Rex Xu8ff43de2016-04-22 16:51:45 +08004016 case glslang::EOpPackInt2x32:
4017 case glslang::EOpUnpackInt2x32:
4018 case glslang::EOpPackUint2x32:
4019 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08004020 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08004021 break;
4022
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004023#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004024 case glslang::EOpPackInt2x16:
4025 case glslang::EOpUnpackInt2x16:
4026 case glslang::EOpPackUint2x16:
4027 case glslang::EOpUnpackUint2x16:
4028 case glslang::EOpPackInt4x16:
4029 case glslang::EOpUnpackInt4x16:
4030 case glslang::EOpPackUint4x16:
4031 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004032 case glslang::EOpPackFloat2x16:
4033 case glslang::EOpUnpackFloat2x16:
4034 unaryOp = spv::OpBitcast;
4035 break;
4036#endif
4037
John Kessenich140f3df2015-06-26 16:58:36 -06004038 case glslang::EOpDPdx:
4039 unaryOp = spv::OpDPdx;
4040 break;
4041 case glslang::EOpDPdy:
4042 unaryOp = spv::OpDPdy;
4043 break;
4044 case glslang::EOpFwidth:
4045 unaryOp = spv::OpFwidth;
4046 break;
4047 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07004048 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004049 unaryOp = spv::OpDPdxFine;
4050 break;
4051 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07004052 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004053 unaryOp = spv::OpDPdyFine;
4054 break;
4055 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07004056 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004057 unaryOp = spv::OpFwidthFine;
4058 break;
4059 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004060 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004061 unaryOp = spv::OpDPdxCoarse;
4062 break;
4063 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004064 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004065 unaryOp = spv::OpDPdyCoarse;
4066 break;
4067 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004068 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004069 unaryOp = spv::OpFwidthCoarse;
4070 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004071 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07004072 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004073 libCall = spv::GLSLstd450InterpolateAtCentroid;
4074 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004075 case glslang::EOpAny:
4076 unaryOp = spv::OpAny;
4077 break;
4078 case glslang::EOpAll:
4079 unaryOp = spv::OpAll;
4080 break;
4081
4082 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004083 if (isFloat)
4084 libCall = spv::GLSLstd450FAbs;
4085 else
4086 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004087 break;
4088 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004089 if (isFloat)
4090 libCall = spv::GLSLstd450FSign;
4091 else
4092 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004093 break;
4094
John Kessenichfc51d282015-08-19 13:34:18 -06004095 case glslang::EOpAtomicCounterIncrement:
4096 case glslang::EOpAtomicCounterDecrement:
4097 case glslang::EOpAtomicCounter:
4098 {
4099 // Handle all of the atomics in one place, in createAtomicOperation()
4100 std::vector<spv::Id> operands;
4101 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08004102 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004103 }
4104
John Kessenichfc51d282015-08-19 13:34:18 -06004105 case glslang::EOpBitFieldReverse:
4106 unaryOp = spv::OpBitReverse;
4107 break;
4108 case glslang::EOpBitCount:
4109 unaryOp = spv::OpBitCount;
4110 break;
4111 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004112 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004113 break;
4114 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004115 if (isUnsigned)
4116 libCall = spv::GLSLstd450FindUMsb;
4117 else
4118 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004119 break;
4120
Rex Xu574ab042016-04-14 16:53:07 +08004121 case glslang::EOpBallot:
4122 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004123 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004124 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004125 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004126#ifdef AMD_EXTENSIONS
4127 case glslang::EOpMinInvocations:
4128 case glslang::EOpMaxInvocations:
4129 case glslang::EOpAddInvocations:
4130 case glslang::EOpMinInvocationsNonUniform:
4131 case glslang::EOpMaxInvocationsNonUniform:
4132 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004133 case glslang::EOpMinInvocationsInclusiveScan:
4134 case glslang::EOpMaxInvocationsInclusiveScan:
4135 case glslang::EOpAddInvocationsInclusiveScan:
4136 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4137 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4138 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4139 case glslang::EOpMinInvocationsExclusiveScan:
4140 case glslang::EOpMaxInvocationsExclusiveScan:
4141 case glslang::EOpAddInvocationsExclusiveScan:
4142 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4143 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4144 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004145#endif
Rex Xu51596642016-09-21 18:56:12 +08004146 {
4147 std::vector<spv::Id> operands;
4148 operands.push_back(operand);
4149 return createInvocationsOperation(op, typeId, operands, typeProxy);
4150 }
Rex Xu9d93a232016-05-05 12:30:44 +08004151
4152#ifdef AMD_EXTENSIONS
4153 case glslang::EOpMbcnt:
4154 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4155 libCall = spv::MbcntAMD;
4156 break;
4157
4158 case glslang::EOpCubeFaceIndex:
4159 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4160 libCall = spv::CubeFaceIndexAMD;
4161 break;
4162
4163 case glslang::EOpCubeFaceCoord:
4164 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4165 libCall = spv::CubeFaceCoordAMD;
4166 break;
4167#endif
Rex Xu338b1852016-05-05 20:38:33 +08004168
John Kessenich140f3df2015-06-26 16:58:36 -06004169 default:
4170 return 0;
4171 }
4172
4173 spv::Id id;
4174 if (libCall >= 0) {
4175 std::vector<spv::Id> args;
4176 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004177 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004178 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004179 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004180 }
John Kessenich140f3df2015-06-26 16:58:36 -06004181
qining25262b32016-05-06 17:25:16 -04004182 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07004183 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004184}
4185
John Kessenich7a53f762016-01-20 11:19:27 -07004186// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04004187spv::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 -07004188{
4189 // Handle unary operations vector by vector.
4190 // The result type is the same type as the original type.
4191 // The algorithm is to:
4192 // - break the matrix into vectors
4193 // - apply the operation to each vector
4194 // - make a matrix out the vector results
4195
4196 // get the types sorted out
4197 int numCols = builder.getNumColumns(operand);
4198 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004199 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4200 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004201 std::vector<spv::Id> results;
4202
4203 // do each vector op
4204 for (int c = 0; c < numCols; ++c) {
4205 std::vector<unsigned int> indexes;
4206 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004207 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4208 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
4209 addDecoration(destVec, noContraction);
4210 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004211 }
4212
4213 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004214 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07004215}
4216
Rex Xu73e3ce72016-04-27 18:48:17 +08004217spv::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 -06004218{
4219 spv::Op convOp = spv::OpNop;
4220 spv::Id zero = 0;
4221 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08004222 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004223
4224 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4225
4226 switch (op) {
4227 case glslang::EOpConvIntToBool:
4228 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08004229 case glslang::EOpConvInt64ToBool:
4230 case glslang::EOpConvUint64ToBool:
Rex Xucabbb782017-03-24 13:41:14 +08004231#ifdef AMD_EXTENSIONS
4232 case glslang::EOpConvInt16ToBool:
4233 case glslang::EOpConvUint16ToBool:
4234#endif
4235 if (op == glslang::EOpConvInt64ToBool || op == glslang::EOpConvUint64ToBool)
4236 zero = builder.makeUint64Constant(0);
4237#ifdef AMD_EXTENSIONS
4238 else if (op == glslang::EOpConvInt16ToBool || op == glslang::EOpConvUint16ToBool)
4239 zero = builder.makeUint16Constant(0);
4240#endif
4241 else
4242 zero = builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004243 zero = makeSmearedConstant(zero, vectorSize);
4244 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4245
4246 case glslang::EOpConvFloatToBool:
4247 zero = builder.makeFloatConstant(0.0F);
4248 zero = makeSmearedConstant(zero, vectorSize);
4249 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4250
4251 case glslang::EOpConvDoubleToBool:
4252 zero = builder.makeDoubleConstant(0.0);
4253 zero = makeSmearedConstant(zero, vectorSize);
4254 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4255
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004256#ifdef AMD_EXTENSIONS
4257 case glslang::EOpConvFloat16ToBool:
4258 zero = builder.makeFloat16Constant(0.0F);
4259 zero = makeSmearedConstant(zero, vectorSize);
4260 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4261#endif
4262
John Kessenich140f3df2015-06-26 16:58:36 -06004263 case glslang::EOpConvBoolToFloat:
4264 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004265 zero = builder.makeFloatConstant(0.0F);
4266 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004267 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004268
John Kessenich140f3df2015-06-26 16:58:36 -06004269 case glslang::EOpConvBoolToDouble:
4270 convOp = spv::OpSelect;
4271 zero = builder.makeDoubleConstant(0.0);
4272 one = builder.makeDoubleConstant(1.0);
4273 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004274
4275#ifdef AMD_EXTENSIONS
4276 case glslang::EOpConvBoolToFloat16:
4277 convOp = spv::OpSelect;
4278 zero = builder.makeFloat16Constant(0.0F);
4279 one = builder.makeFloat16Constant(1.0F);
4280 break;
4281#endif
4282
John Kessenich140f3df2015-06-26 16:58:36 -06004283 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004284 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004285#ifdef AMD_EXTENSIONS
4286 case glslang::EOpConvBoolToInt16:
4287#endif
4288 if (op == glslang::EOpConvBoolToInt64)
4289 zero = builder.makeInt64Constant(0);
4290#ifdef AMD_EXTENSIONS
4291 else if (op == glslang::EOpConvBoolToInt16)
4292 zero = builder.makeInt16Constant(0);
4293#endif
4294 else
4295 zero = builder.makeIntConstant(0);
4296
4297 if (op == glslang::EOpConvBoolToInt64)
4298 one = builder.makeInt64Constant(1);
4299#ifdef AMD_EXTENSIONS
4300 else if (op == glslang::EOpConvBoolToInt16)
4301 one = builder.makeInt16Constant(1);
4302#endif
4303 else
4304 one = builder.makeIntConstant(1);
4305
John Kessenich140f3df2015-06-26 16:58:36 -06004306 convOp = spv::OpSelect;
4307 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004308
John Kessenich140f3df2015-06-26 16:58:36 -06004309 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004310 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004311#ifdef AMD_EXTENSIONS
4312 case glslang::EOpConvBoolToUint16:
4313#endif
4314 if (op == glslang::EOpConvBoolToUint64)
4315 zero = builder.makeUint64Constant(0);
4316#ifdef AMD_EXTENSIONS
4317 else if (op == glslang::EOpConvBoolToUint16)
4318 zero = builder.makeUint16Constant(0);
4319#endif
4320 else
4321 zero = builder.makeUintConstant(0);
4322
4323 if (op == glslang::EOpConvBoolToUint64)
4324 one = builder.makeUint64Constant(1);
4325#ifdef AMD_EXTENSIONS
4326 else if (op == glslang::EOpConvBoolToUint16)
4327 one = builder.makeUint16Constant(1);
4328#endif
4329 else
4330 one = builder.makeUintConstant(1);
4331
John Kessenich140f3df2015-06-26 16:58:36 -06004332 convOp = spv::OpSelect;
4333 break;
4334
4335 case glslang::EOpConvIntToFloat:
4336 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004337 case glslang::EOpConvInt64ToFloat:
4338 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004339#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004340 case glslang::EOpConvInt16ToFloat:
4341 case glslang::EOpConvInt16ToDouble:
4342 case glslang::EOpConvInt16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004343 case glslang::EOpConvIntToFloat16:
4344 case glslang::EOpConvInt64ToFloat16:
4345#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004346 convOp = spv::OpConvertSToF;
4347 break;
4348
4349 case glslang::EOpConvUintToFloat:
4350 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004351 case glslang::EOpConvUint64ToFloat:
4352 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004353#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004354 case glslang::EOpConvUint16ToFloat:
4355 case glslang::EOpConvUint16ToDouble:
4356 case glslang::EOpConvUint16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004357 case glslang::EOpConvUintToFloat16:
4358 case glslang::EOpConvUint64ToFloat16:
4359#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004360 convOp = spv::OpConvertUToF;
4361 break;
4362
4363 case glslang::EOpConvDoubleToFloat:
4364 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004365#ifdef AMD_EXTENSIONS
4366 case glslang::EOpConvDoubleToFloat16:
4367 case glslang::EOpConvFloat16ToDouble:
4368 case glslang::EOpConvFloatToFloat16:
4369 case glslang::EOpConvFloat16ToFloat:
4370#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004371 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004372 if (builder.isMatrixType(destType))
4373 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004374 break;
4375
4376 case glslang::EOpConvFloatToInt:
4377 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004378 case glslang::EOpConvFloatToInt64:
4379 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004380#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004381 case glslang::EOpConvFloatToInt16:
4382 case glslang::EOpConvDoubleToInt16:
4383 case glslang::EOpConvFloat16ToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004384 case glslang::EOpConvFloat16ToInt:
4385 case glslang::EOpConvFloat16ToInt64:
4386#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004387 convOp = spv::OpConvertFToS;
4388 break;
4389
4390 case glslang::EOpConvUintToInt:
4391 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004392 case glslang::EOpConvUint64ToInt64:
4393 case glslang::EOpConvInt64ToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004394#ifdef AMD_EXTENSIONS
4395 case glslang::EOpConvUint16ToInt16:
4396 case glslang::EOpConvInt16ToUint16:
4397#endif
qininge24aa5e2016-04-07 15:40:27 -04004398 if (builder.isInSpecConstCodeGenMode()) {
4399 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004400 if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64)
4401 zero = builder.makeUint64Constant(0);
4402#ifdef AMD_EXTENSIONS
4403 else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16)
4404 zero = builder.makeUint16Constant(0);
4405#endif
4406 else
4407 zero = builder.makeUintConstant(0);
4408
qining189b2032016-04-12 23:16:20 -04004409 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004410 // Use OpIAdd, instead of OpBitcast to do the conversion when
4411 // generating for OpSpecConstantOp instruction.
4412 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4413 }
4414 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004415 convOp = spv::OpBitcast;
4416 break;
4417
4418 case glslang::EOpConvFloatToUint:
4419 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004420 case glslang::EOpConvFloatToUint64:
4421 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004422#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004423 case glslang::EOpConvFloatToUint16:
4424 case glslang::EOpConvDoubleToUint16:
4425 case glslang::EOpConvFloat16ToUint16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004426 case glslang::EOpConvFloat16ToUint:
4427 case glslang::EOpConvFloat16ToUint64:
4428#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004429 convOp = spv::OpConvertFToU;
4430 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004431
4432 case glslang::EOpConvIntToInt64:
4433 case glslang::EOpConvInt64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004434#ifdef AMD_EXTENSIONS
4435 case glslang::EOpConvIntToInt16:
4436 case glslang::EOpConvInt16ToInt:
4437 case glslang::EOpConvInt64ToInt16:
4438 case glslang::EOpConvInt16ToInt64:
4439#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004440 convOp = spv::OpSConvert;
4441 break;
4442
4443 case glslang::EOpConvUintToUint64:
4444 case glslang::EOpConvUint64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004445#ifdef AMD_EXTENSIONS
4446 case glslang::EOpConvUintToUint16:
4447 case glslang::EOpConvUint16ToUint:
4448 case glslang::EOpConvUint64ToUint16:
4449 case glslang::EOpConvUint16ToUint64:
4450#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004451 convOp = spv::OpUConvert;
4452 break;
4453
4454 case glslang::EOpConvIntToUint64:
4455 case glslang::EOpConvInt64ToUint:
4456 case glslang::EOpConvUint64ToInt:
4457 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004458#ifdef AMD_EXTENSIONS
4459 case glslang::EOpConvInt16ToUint:
4460 case glslang::EOpConvUintToInt16:
4461 case glslang::EOpConvInt16ToUint64:
4462 case glslang::EOpConvUint64ToInt16:
4463 case glslang::EOpConvUint16ToInt:
4464 case glslang::EOpConvIntToUint16:
4465 case glslang::EOpConvUint16ToInt64:
4466 case glslang::EOpConvInt64ToUint16:
4467#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004468 // OpSConvert/OpUConvert + OpBitCast
4469 switch (op) {
4470 case glslang::EOpConvIntToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004471#ifdef AMD_EXTENSIONS
4472 case glslang::EOpConvInt16ToUint64:
4473#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004474 convOp = spv::OpSConvert;
4475 type = builder.makeIntType(64);
4476 break;
4477 case glslang::EOpConvInt64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004478#ifdef AMD_EXTENSIONS
4479 case glslang::EOpConvInt16ToUint:
4480#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004481 convOp = spv::OpSConvert;
4482 type = builder.makeIntType(32);
4483 break;
4484 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004485#ifdef AMD_EXTENSIONS
4486 case glslang::EOpConvUint16ToInt:
4487#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004488 convOp = spv::OpUConvert;
4489 type = builder.makeUintType(32);
4490 break;
4491 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004492#ifdef AMD_EXTENSIONS
4493 case glslang::EOpConvUint16ToInt64:
4494#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004495 convOp = spv::OpUConvert;
4496 type = builder.makeUintType(64);
4497 break;
Rex Xucabbb782017-03-24 13:41:14 +08004498#ifdef AMD_EXTENSIONS
4499 case glslang::EOpConvUintToInt16:
4500 case glslang::EOpConvUint64ToInt16:
4501 convOp = spv::OpUConvert;
4502 type = builder.makeUintType(16);
4503 break;
4504 case glslang::EOpConvIntToUint16:
4505 case glslang::EOpConvInt64ToUint16:
4506 convOp = spv::OpSConvert;
4507 type = builder.makeIntType(16);
4508 break;
4509#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004510 default:
4511 assert(0);
4512 break;
4513 }
4514
4515 if (vectorSize > 0)
4516 type = builder.makeVectorType(type, vectorSize);
4517
4518 operand = builder.createUnaryOp(convOp, type, operand);
4519
4520 if (builder.isInSpecConstCodeGenMode()) {
4521 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004522#ifdef AMD_EXTENSIONS
4523 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64 ||
4524 op == glslang::EOpConvInt16ToUint64 || op == glslang::EOpConvUint16ToInt64)
4525 zero = builder.makeUint64Constant(0);
4526 else if (op == glslang::EOpConvIntToUint16 || op == glslang::EOpConvUintToInt16 ||
4527 op == glslang::EOpConvInt64ToUint16 || op == glslang::EOpConvUint64ToInt16)
4528 zero = builder.makeUint16Constant(0);
4529 else
4530 zero = builder.makeUintConstant(0);
4531#else
4532 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64)
4533 zero = builder.makeUint64Constant(0);
4534 else
4535 zero = builder.makeUintConstant(0);
4536#endif
4537
Rex Xu8ff43de2016-04-22 16:51:45 +08004538 zero = makeSmearedConstant(zero, vectorSize);
4539 // Use OpIAdd, instead of OpBitcast to do the conversion when
4540 // generating for OpSpecConstantOp instruction.
4541 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4542 }
4543 // For normal run-time conversion instruction, use OpBitcast.
4544 convOp = spv::OpBitcast;
4545 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004546 default:
4547 break;
4548 }
4549
4550 spv::Id result = 0;
4551 if (convOp == spv::OpNop)
4552 return result;
4553
4554 if (convOp == spv::OpSelect) {
4555 zero = makeSmearedConstant(zero, vectorSize);
4556 one = makeSmearedConstant(one, vectorSize);
4557 result = builder.createTriOp(convOp, destType, operand, one, zero);
4558 } else
4559 result = builder.createUnaryOp(convOp, destType, operand);
4560
John Kessenich32cfd492016-02-02 12:37:46 -07004561 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004562}
4563
4564spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4565{
4566 if (vectorSize == 0)
4567 return constant;
4568
4569 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4570 std::vector<spv::Id> components;
4571 for (int c = 0; c < vectorSize; ++c)
4572 components.push_back(constant);
4573 return builder.makeCompositeConstant(vectorTypeId, components);
4574}
4575
John Kessenich426394d2015-07-23 10:22:48 -06004576// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004577spv::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 -06004578{
4579 spv::Op opCode = spv::OpNop;
4580
4581 switch (op) {
4582 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004583 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004584 opCode = spv::OpAtomicIAdd;
4585 break;
4586 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004587 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08004588 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004589 break;
4590 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004591 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08004592 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004593 break;
4594 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004595 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004596 opCode = spv::OpAtomicAnd;
4597 break;
4598 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004599 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06004600 opCode = spv::OpAtomicOr;
4601 break;
4602 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004603 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06004604 opCode = spv::OpAtomicXor;
4605 break;
4606 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004607 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004608 opCode = spv::OpAtomicExchange;
4609 break;
4610 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004611 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004612 opCode = spv::OpAtomicCompareExchange;
4613 break;
4614 case glslang::EOpAtomicCounterIncrement:
4615 opCode = spv::OpAtomicIIncrement;
4616 break;
4617 case glslang::EOpAtomicCounterDecrement:
4618 opCode = spv::OpAtomicIDecrement;
4619 break;
4620 case glslang::EOpAtomicCounter:
4621 opCode = spv::OpAtomicLoad;
4622 break;
4623 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004624 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004625 break;
4626 }
4627
4628 // Sort out the operands
4629 // - mapping from glslang -> SPV
4630 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004631 // - compare-exchange swaps the value and comparator
4632 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004633 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4634 auto opIt = operands.begin(); // walk the glslang operands
4635 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004636 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4637 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4638 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004639 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4640 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004641 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004642 spvAtomicOperands.push_back(*(opIt + 1));
4643 spvAtomicOperands.push_back(*opIt);
4644 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004645 }
John Kessenich426394d2015-07-23 10:22:48 -06004646
John Kessenich3e60a6f2015-09-14 22:45:16 -06004647 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004648 for (; opIt != operands.end(); ++opIt)
4649 spvAtomicOperands.push_back(*opIt);
4650
4651 return builder.createOp(opCode, typeId, spvAtomicOperands);
4652}
4653
John Kessenich91cef522016-05-05 16:45:40 -06004654// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004655spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004656{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004657#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004658 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004659 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004660#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004661
Rex Xu51596642016-09-21 18:56:12 +08004662 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004663 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004664 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4665
chaocf200da82016-12-20 12:44:35 -08004666 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4667 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004668 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4669 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004670 } else if (op == glslang::EOpAnyInvocation ||
4671 op == glslang::EOpAllInvocations ||
4672 op == glslang::EOpAllInvocationsEqual) {
4673 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4674 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004675 } else {
4676 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004677#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004678 if (op == glslang::EOpMinInvocationsNonUniform ||
4679 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004680 op == glslang::EOpAddInvocationsNonUniform ||
4681 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4682 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4683 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4684 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4685 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4686 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004687 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004688#endif
Rex Xu51596642016-09-21 18:56:12 +08004689
4690 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004691#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004692 switch (op) {
4693 case glslang::EOpMinInvocations:
4694 case glslang::EOpMaxInvocations:
4695 case glslang::EOpAddInvocations:
4696 case glslang::EOpMinInvocationsNonUniform:
4697 case glslang::EOpMaxInvocationsNonUniform:
4698 case glslang::EOpAddInvocationsNonUniform:
4699 groupOperation = spv::GroupOperationReduce;
4700 spvGroupOperands.push_back(groupOperation);
4701 break;
4702 case glslang::EOpMinInvocationsInclusiveScan:
4703 case glslang::EOpMaxInvocationsInclusiveScan:
4704 case glslang::EOpAddInvocationsInclusiveScan:
4705 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4706 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4707 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4708 groupOperation = spv::GroupOperationInclusiveScan;
4709 spvGroupOperands.push_back(groupOperation);
4710 break;
4711 case glslang::EOpMinInvocationsExclusiveScan:
4712 case glslang::EOpMaxInvocationsExclusiveScan:
4713 case glslang::EOpAddInvocationsExclusiveScan:
4714 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4715 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4716 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4717 groupOperation = spv::GroupOperationExclusiveScan;
4718 spvGroupOperands.push_back(groupOperation);
4719 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004720 default:
4721 break;
Rex Xu430ef402016-10-14 17:22:23 +08004722 }
Rex Xu9d93a232016-05-05 12:30:44 +08004723#endif
Rex Xu51596642016-09-21 18:56:12 +08004724 }
4725
4726 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4727 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004728
4729 switch (op) {
4730 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004731 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004732 break;
John Kessenich91cef522016-05-05 16:45:40 -06004733 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004734 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004735 break;
John Kessenich91cef522016-05-05 16:45:40 -06004736 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004737 opCode = spv::OpSubgroupAllEqualKHR;
4738 break;
Rex Xu51596642016-09-21 18:56:12 +08004739 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004740 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004741 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004742 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004743 break;
4744 case glslang::EOpReadFirstInvocation:
4745 opCode = spv::OpSubgroupFirstInvocationKHR;
4746 break;
4747 case glslang::EOpBallot:
4748 {
4749 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4750 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4751 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4752 //
4753 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4754 //
4755 spv::Id uintType = builder.makeUintType(32);
4756 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4757 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4758
4759 std::vector<spv::Id> components;
4760 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4761 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4762
4763 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4764 return builder.createUnaryOp(spv::OpBitcast, typeId,
4765 builder.createCompositeConstruct(uvec2Type, components));
4766 }
4767
Rex Xu9d93a232016-05-05 12:30:44 +08004768#ifdef AMD_EXTENSIONS
4769 case glslang::EOpMinInvocations:
4770 case glslang::EOpMaxInvocations:
4771 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08004772 case glslang::EOpMinInvocationsInclusiveScan:
4773 case glslang::EOpMaxInvocationsInclusiveScan:
4774 case glslang::EOpAddInvocationsInclusiveScan:
4775 case glslang::EOpMinInvocationsExclusiveScan:
4776 case glslang::EOpMaxInvocationsExclusiveScan:
4777 case glslang::EOpAddInvocationsExclusiveScan:
4778 if (op == glslang::EOpMinInvocations ||
4779 op == glslang::EOpMinInvocationsInclusiveScan ||
4780 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004781 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004782 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004783 else {
4784 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004785 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004786 else
Rex Xu51596642016-09-21 18:56:12 +08004787 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004788 }
Rex Xu430ef402016-10-14 17:22:23 +08004789 } else if (op == glslang::EOpMaxInvocations ||
4790 op == glslang::EOpMaxInvocationsInclusiveScan ||
4791 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004792 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004793 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004794 else {
4795 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004796 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004797 else
Rex Xu51596642016-09-21 18:56:12 +08004798 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004799 }
4800 } else {
4801 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004802 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004803 else
Rex Xu51596642016-09-21 18:56:12 +08004804 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004805 }
4806
Rex Xu2bbbe062016-08-23 15:41:05 +08004807 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004808 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004809
4810 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004811 case glslang::EOpMinInvocationsNonUniform:
4812 case glslang::EOpMaxInvocationsNonUniform:
4813 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004814 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4815 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4816 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4817 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4818 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4819 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4820 if (op == glslang::EOpMinInvocationsNonUniform ||
4821 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4822 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004823 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004824 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004825 else {
4826 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004827 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004828 else
Rex Xu51596642016-09-21 18:56:12 +08004829 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004830 }
4831 }
Rex Xu430ef402016-10-14 17:22:23 +08004832 else if (op == glslang::EOpMaxInvocationsNonUniform ||
4833 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4834 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004835 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004836 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004837 else {
4838 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004839 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004840 else
Rex Xu51596642016-09-21 18:56:12 +08004841 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004842 }
4843 }
4844 else {
4845 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004846 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004847 else
Rex Xu51596642016-09-21 18:56:12 +08004848 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004849 }
4850
Rex Xu2bbbe062016-08-23 15:41:05 +08004851 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004852 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004853
4854 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004855#endif
John Kessenich91cef522016-05-05 16:45:40 -06004856 default:
4857 logger->missingFunctionality("invocation operation");
4858 return spv::NoResult;
4859 }
Rex Xu51596642016-09-21 18:56:12 +08004860
4861 assert(opCode != spv::OpNop);
4862 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004863}
4864
Rex Xu2bbbe062016-08-23 15:41:05 +08004865// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08004866spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08004867{
Rex Xub7072052016-09-26 15:53:40 +08004868#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08004869 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4870 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08004871 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08004872 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08004873 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
4874 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
4875 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08004876#else
4877 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4878 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08004879 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
4880 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08004881#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08004882
4883 // Handle group invocation operations scalar by scalar.
4884 // The result type is the same type as the original type.
4885 // The algorithm is to:
4886 // - break the vector into scalars
4887 // - apply the operation to each scalar
4888 // - make a vector out the scalar results
4889
4890 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08004891 int numComponents = builder.getNumComponents(operands[0]);
4892 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08004893 std::vector<spv::Id> results;
4894
4895 // do each scalar op
4896 for (int comp = 0; comp < numComponents; ++comp) {
4897 std::vector<unsigned int> indexes;
4898 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08004899 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08004900 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08004901 if (op == spv::OpSubgroupReadInvocationKHR) {
4902 spvGroupOperands.push_back(scalar);
4903 spvGroupOperands.push_back(operands[1]);
4904 } else if (op == spv::OpGroupBroadcast) {
4905 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08004906 spvGroupOperands.push_back(scalar);
4907 spvGroupOperands.push_back(operands[1]);
4908 } else {
chaocf200da82016-12-20 12:44:35 -08004909 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08004910 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08004911 spvGroupOperands.push_back(scalar);
4912 }
Rex Xu2bbbe062016-08-23 15:41:05 +08004913
Rex Xub7072052016-09-26 15:53:40 +08004914 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08004915 }
4916
4917 // put the pieces together
4918 return builder.createCompositeConstruct(typeId, results);
4919}
Rex Xu2bbbe062016-08-23 15:41:05 +08004920
John Kessenich5e4b1242015-08-06 22:53:06 -06004921spv::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 -06004922{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004923#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004924 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004925 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4926#else
Rex Xucabbb782017-03-24 13:41:14 +08004927 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06004928 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004929#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06004930
John Kessenich140f3df2015-06-26 16:58:36 -06004931 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004932 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004933 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05004934 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07004935 spv::Id typeId0 = 0;
4936 if (consumedOperands > 0)
4937 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08004938 spv::Id typeId1 = 0;
4939 if (consumedOperands > 1)
4940 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07004941 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004942
4943 switch (op) {
4944 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004945 if (isFloat)
4946 libCall = spv::GLSLstd450FMin;
4947 else if (isUnsigned)
4948 libCall = spv::GLSLstd450UMin;
4949 else
4950 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004951 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004952 break;
4953 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004954 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004955 break;
4956 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004957 if (isFloat)
4958 libCall = spv::GLSLstd450FMax;
4959 else if (isUnsigned)
4960 libCall = spv::GLSLstd450UMax;
4961 else
4962 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004963 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004964 break;
4965 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004966 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004967 break;
4968 case glslang::EOpDot:
4969 opCode = spv::OpDot;
4970 break;
4971 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004972 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004973 break;
4974
4975 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004976 if (isFloat)
4977 libCall = spv::GLSLstd450FClamp;
4978 else if (isUnsigned)
4979 libCall = spv::GLSLstd450UClamp;
4980 else
4981 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004982 builder.promoteScalar(precision, operands.front(), operands[1]);
4983 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004984 break;
4985 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08004986 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
4987 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07004988 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08004989 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07004990 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08004991 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07004992 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07004993 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004994 break;
4995 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004996 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004997 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004998 break;
4999 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005000 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005001 builder.promoteScalar(precision, operands[0], operands[2]);
5002 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005003 break;
5004
5005 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06005006 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06005007 break;
5008 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06005009 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06005010 break;
5011 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06005012 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06005013 break;
5014 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06005015 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06005016 break;
5017 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005018 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06005019 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005020 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07005021 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005022 libCall = spv::GLSLstd450InterpolateAtSample;
5023 break;
5024 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07005025 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005026 libCall = spv::GLSLstd450InterpolateAtOffset;
5027 break;
John Kessenich55e7d112015-11-15 21:33:39 -07005028 case glslang::EOpAddCarry:
5029 opCode = spv::OpIAddCarry;
5030 typeId = builder.makeStructResultType(typeId0, typeId0);
5031 consumedOperands = 2;
5032 break;
5033 case glslang::EOpSubBorrow:
5034 opCode = spv::OpISubBorrow;
5035 typeId = builder.makeStructResultType(typeId0, typeId0);
5036 consumedOperands = 2;
5037 break;
5038 case glslang::EOpUMulExtended:
5039 opCode = spv::OpUMulExtended;
5040 typeId = builder.makeStructResultType(typeId0, typeId0);
5041 consumedOperands = 2;
5042 break;
5043 case glslang::EOpIMulExtended:
5044 opCode = spv::OpSMulExtended;
5045 typeId = builder.makeStructResultType(typeId0, typeId0);
5046 consumedOperands = 2;
5047 break;
5048 case glslang::EOpBitfieldExtract:
5049 if (isUnsigned)
5050 opCode = spv::OpBitFieldUExtract;
5051 else
5052 opCode = spv::OpBitFieldSExtract;
5053 break;
5054 case glslang::EOpBitfieldInsert:
5055 opCode = spv::OpBitFieldInsert;
5056 break;
5057
5058 case glslang::EOpFma:
5059 libCall = spv::GLSLstd450Fma;
5060 break;
5061 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005062 {
5063 libCall = spv::GLSLstd450FrexpStruct;
5064 assert(builder.isPointerType(typeId1));
5065 typeId1 = builder.getContainedTypeId(typeId1);
5066#ifdef AMD_EXTENSIONS
5067 int width = builder.getScalarTypeWidth(typeId1);
5068#else
5069 int width = 32;
5070#endif
5071 if (builder.getNumComponents(operands[0]) == 1)
5072 frexpIntType = builder.makeIntegerType(width, true);
5073 else
5074 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
5075 typeId = builder.makeStructResultType(typeId0, frexpIntType);
5076 consumedOperands = 1;
5077 }
John Kessenich55e7d112015-11-15 21:33:39 -07005078 break;
5079 case glslang::EOpLdexp:
5080 libCall = spv::GLSLstd450Ldexp;
5081 break;
5082
Rex Xu574ab042016-04-14 16:53:07 +08005083 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08005084 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08005085
Rex Xu9d93a232016-05-05 12:30:44 +08005086#ifdef AMD_EXTENSIONS
5087 case glslang::EOpSwizzleInvocations:
5088 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5089 libCall = spv::SwizzleInvocationsAMD;
5090 break;
5091 case glslang::EOpSwizzleInvocationsMasked:
5092 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5093 libCall = spv::SwizzleInvocationsMaskedAMD;
5094 break;
5095 case glslang::EOpWriteInvocation:
5096 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5097 libCall = spv::WriteInvocationAMD;
5098 break;
5099
5100 case glslang::EOpMin3:
5101 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5102 if (isFloat)
5103 libCall = spv::FMin3AMD;
5104 else {
5105 if (isUnsigned)
5106 libCall = spv::UMin3AMD;
5107 else
5108 libCall = spv::SMin3AMD;
5109 }
5110 break;
5111 case glslang::EOpMax3:
5112 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5113 if (isFloat)
5114 libCall = spv::FMax3AMD;
5115 else {
5116 if (isUnsigned)
5117 libCall = spv::UMax3AMD;
5118 else
5119 libCall = spv::SMax3AMD;
5120 }
5121 break;
5122 case glslang::EOpMid3:
5123 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5124 if (isFloat)
5125 libCall = spv::FMid3AMD;
5126 else {
5127 if (isUnsigned)
5128 libCall = spv::UMid3AMD;
5129 else
5130 libCall = spv::SMid3AMD;
5131 }
5132 break;
5133
5134 case glslang::EOpInterpolateAtVertex:
5135 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
5136 libCall = spv::InterpolateAtVertexAMD;
5137 break;
5138#endif
5139
John Kessenich140f3df2015-06-26 16:58:36 -06005140 default:
5141 return 0;
5142 }
5143
5144 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07005145 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05005146 // Use an extended instruction from the standard library.
5147 // Construct the call arguments, without modifying the original operands vector.
5148 // We might need the remaining arguments, e.g. in the EOpFrexp case.
5149 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08005150 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07005151 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07005152 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06005153 case 0:
5154 // should all be handled by visitAggregate and createNoArgOperation
5155 assert(0);
5156 return 0;
5157 case 1:
5158 // should all be handled by createUnaryOperation
5159 assert(0);
5160 return 0;
5161 case 2:
5162 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
5163 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005164 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005165 // anything 3 or over doesn't have l-value operands, so all should be consumed
5166 assert(consumedOperands == operands.size());
5167 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06005168 break;
5169 }
5170 }
5171
John Kessenich55e7d112015-11-15 21:33:39 -07005172 // Decode the return types that were structures
5173 switch (op) {
5174 case glslang::EOpAddCarry:
5175 case glslang::EOpSubBorrow:
5176 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5177 id = builder.createCompositeExtract(id, typeId0, 0);
5178 break;
5179 case glslang::EOpUMulExtended:
5180 case glslang::EOpIMulExtended:
5181 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
5182 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5183 break;
5184 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005185 {
5186 assert(operands.size() == 2);
5187 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
5188 // "exp" is floating-point type (from HLSL intrinsic)
5189 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
5190 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
5191 builder.createStore(member1, operands[1]);
5192 } else
5193 // "exp" is integer type (from GLSL built-in function)
5194 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
5195 id = builder.createCompositeExtract(id, typeId0, 0);
5196 }
John Kessenich55e7d112015-11-15 21:33:39 -07005197 break;
5198 default:
5199 break;
5200 }
5201
John Kessenich32cfd492016-02-02 12:37:46 -07005202 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005203}
5204
Rex Xu9d93a232016-05-05 12:30:44 +08005205// Intrinsics with no arguments (or no return value, and no precision).
5206spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06005207{
5208 // TODO: get the barrier operands correct
5209
5210 switch (op) {
5211 case glslang::EOpEmitVertex:
5212 builder.createNoResultOp(spv::OpEmitVertex);
5213 return 0;
5214 case glslang::EOpEndPrimitive:
5215 builder.createNoResultOp(spv::OpEndPrimitive);
5216 return 0;
5217 case glslang::EOpBarrier:
chrgau01@arm.comc3f1cdf2016-11-14 10:10:05 +01005218 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06005219 return 0;
5220 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06005221 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06005222 return 0;
5223 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06005224 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005225 return 0;
5226 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06005227 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005228 return 0;
5229 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06005230 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005231 return 0;
5232 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07005233 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005234 return 0;
5235 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07005236 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005237 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06005238 case glslang::EOpAllMemoryBarrierWithGroupSync:
5239 // Control barrier with non-"None" semantic is also a memory barrier.
5240 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
5241 return 0;
5242 case glslang::EOpGroupMemoryBarrierWithGroupSync:
5243 // Control barrier with non-"None" semantic is also a memory barrier.
5244 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
5245 return 0;
5246 case glslang::EOpWorkgroupMemoryBarrier:
5247 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5248 return 0;
5249 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
5250 // Control barrier with non-"None" semantic is also a memory barrier.
5251 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5252 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08005253#ifdef AMD_EXTENSIONS
5254 case glslang::EOpTime:
5255 {
5256 std::vector<spv::Id> args; // Dummy arguments
5257 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
5258 return builder.setPrecision(id, precision);
5259 }
5260#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005261 default:
Lei Zhang17535f72016-05-04 15:55:59 -04005262 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06005263 return 0;
5264 }
5265}
5266
5267spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
5268{
John Kessenich2f273362015-07-18 22:34:27 -06005269 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06005270 spv::Id id;
5271 if (symbolValues.end() != iter) {
5272 id = iter->second;
5273 return id;
5274 }
5275
5276 // it was not found, create it
5277 id = createSpvVariable(symbol);
5278 symbolValues[symbol->getId()] = id;
5279
Rex Xuc884b4a2016-06-29 15:03:44 +08005280 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06005281 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07005282 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08005283 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07005284 if (symbol->getType().getQualifier().hasSpecConstantId())
5285 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06005286 if (symbol->getQualifier().hasIndex())
5287 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
5288 if (symbol->getQualifier().hasComponent())
5289 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
5290 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005291 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005292 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005293 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005294 if (symbol->getQualifier().hasXfbBuffer())
5295 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5296 if (symbol->getQualifier().hasXfbOffset())
5297 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
5298 }
John Kessenich91e4aa52016-07-07 17:46:42 -06005299 // atomic counters use this:
5300 if (symbol->getQualifier().hasOffset())
5301 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005302 }
5303
scygan2c864272016-05-18 18:09:17 +02005304 if (symbol->getQualifier().hasLocation())
5305 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07005306 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07005307 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07005308 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06005309 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07005310 }
John Kessenich140f3df2015-06-26 16:58:36 -06005311 if (symbol->getQualifier().hasSet())
5312 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07005313 else if (IsDescriptorResource(symbol->getType())) {
5314 // default to 0
5315 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
5316 }
John Kessenich140f3df2015-06-26 16:58:36 -06005317 if (symbol->getQualifier().hasBinding())
5318 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07005319 if (symbol->getQualifier().hasAttachment())
5320 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06005321 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005322 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005323 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005324 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005325 if (symbol->getQualifier().hasXfbBuffer())
5326 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5327 }
5328
Rex Xu1da878f2016-02-21 20:59:01 +08005329 if (symbol->getType().isImage()) {
5330 std::vector<spv::Decoration> memory;
5331 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
5332 for (unsigned int i = 0; i < memory.size(); ++i)
5333 addDecoration(id, memory[i]);
5334 }
5335
John Kessenich140f3df2015-06-26 16:58:36 -06005336 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06005337 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06005338 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07005339 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06005340
John Kessenichecba76f2017-01-06 00:34:48 -07005341#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08005342 if (builtIn == spv::BuiltInSampleMask) {
5343 spv::Decoration decoration;
5344 // GL_NV_sample_mask_override_coverage extension
5345 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08005346 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08005347 else
5348 decoration = (spv::Decoration)spv::DecorationMax;
5349 addDecoration(id, decoration);
5350 if (decoration != spv::DecorationMax) {
5351 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
5352 }
5353 }
chaoc771d89f2017-01-13 01:10:53 -08005354 else if (builtIn == spv::BuiltInLayer) {
5355 // SPV_NV_viewport_array2 extension
5356 if (symbol->getQualifier().layoutViewportRelative)
5357 {
5358 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
5359 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
5360 builder.addExtension(spv::E_SPV_NV_viewport_array2);
5361 }
5362 if(symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048)
5363 {
5364 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
5365 builder.addCapability(spv::CapabilityShaderStereoViewNV);
5366 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
5367 }
5368 }
5369
chaoc6e5acae2016-12-20 13:28:52 -08005370 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08005371 addDecoration(id, spv::DecorationPassthroughNV);
5372 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08005373 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
5374 }
chaoc0ad6a4e2016-12-19 16:29:34 -08005375#endif
5376
John Kessenich140f3df2015-06-26 16:58:36 -06005377 return id;
5378}
5379
John Kessenich55e7d112015-11-15 21:33:39 -07005380// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06005381void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
5382{
John Kessenich4016e382016-07-15 11:53:56 -06005383 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005384 builder.addDecoration(id, dec);
5385}
5386
John Kessenich55e7d112015-11-15 21:33:39 -07005387// If 'dec' is valid, add a one-operand decoration to an object
5388void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
5389{
John Kessenich4016e382016-07-15 11:53:56 -06005390 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07005391 builder.addDecoration(id, dec, value);
5392}
5393
5394// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005395void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5396{
John Kessenich4016e382016-07-15 11:53:56 -06005397 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005398 builder.addMemberDecoration(id, (unsigned)member, dec);
5399}
5400
John Kessenich92187592016-02-01 13:45:25 -07005401// If 'dec' is valid, add a one-operand decoration to a struct member
5402void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5403{
John Kessenich4016e382016-07-15 11:53:56 -06005404 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005405 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5406}
5407
John Kessenich55e7d112015-11-15 21:33:39 -07005408// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005409// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005410//
5411// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5412//
5413// Recursively walk the nodes. The nodes form a tree whose leaves are
5414// regular constants, which themselves are trees that createSpvConstant()
5415// recursively walks. So, this function walks the "top" of the tree:
5416// - emit specialization constant-building instructions for specConstant
5417// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005418spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005419{
John Kessenich7cc0e282016-03-20 00:46:02 -06005420 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005421
qining4f4bb812016-04-03 23:55:17 -04005422 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005423 if (! node.getQualifier().specConstant) {
5424 // hand off to the non-spec-constant path
5425 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5426 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005427 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005428 nextConst, false);
5429 }
5430
5431 // We now know we have a specialization constant to build
5432
John Kessenichd94c0032016-05-30 19:29:40 -06005433 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005434 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5435 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5436 std::vector<spv::Id> dimConstId;
5437 for (int dim = 0; dim < 3; ++dim) {
5438 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5439 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5440 if (specConst)
5441 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5442 }
5443 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5444 }
5445
5446 // An AST node labelled as specialization constant should be a symbol node.
5447 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5448 if (auto* sn = node.getAsSymbolNode()) {
5449 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005450 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5451 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5452 // will set the builder into spec constant op instruction generating mode.
5453 sub_tree->traverse(this);
5454 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005455 } else if (auto* const_union_array = &sn->getConstArray()){
5456 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005457 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5458 builder.addName(id, sn->getName().c_str());
5459 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005460 }
5461 }
qining4f4bb812016-04-03 23:55:17 -04005462
5463 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5464 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005465 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005466 exit(1);
5467 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005468}
5469
John Kessenich140f3df2015-06-26 16:58:36 -06005470// Use 'consts' as the flattened glslang source of scalar constants to recursively
5471// build the aggregate SPIR-V constant.
5472//
5473// If there are not enough elements present in 'consts', 0 will be substituted;
5474// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5475//
qining08408382016-03-21 09:51:37 -04005476spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005477{
5478 // vector of constants for SPIR-V
5479 std::vector<spv::Id> spvConsts;
5480
5481 // Type is used for struct and array constants
5482 spv::Id typeId = convertGlslangToSpvType(glslangType);
5483
5484 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005485 glslang::TType elementType(glslangType, 0);
5486 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005487 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005488 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005489 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005490 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005491 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005492 } else if (glslangType.getStruct()) {
5493 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5494 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005495 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005496 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005497 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5498 bool zero = nextConst >= consts.size();
5499 switch (glslangType.getBasicType()) {
5500 case glslang::EbtInt:
5501 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5502 break;
5503 case glslang::EbtUint:
5504 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5505 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005506 case glslang::EbtInt64:
5507 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5508 break;
5509 case glslang::EbtUint64:
5510 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5511 break;
Rex Xucabbb782017-03-24 13:41:14 +08005512#ifdef AMD_EXTENSIONS
5513 case glslang::EbtInt16:
5514 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst()));
5515 break;
5516 case glslang::EbtUint16:
5517 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst()));
5518 break;
5519#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005520 case glslang::EbtFloat:
5521 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5522 break;
5523 case glslang::EbtDouble:
5524 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5525 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005526#ifdef AMD_EXTENSIONS
5527 case glslang::EbtFloat16:
5528 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5529 break;
5530#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005531 case glslang::EbtBool:
5532 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5533 break;
5534 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005535 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005536 break;
5537 }
5538 ++nextConst;
5539 }
5540 } else {
5541 // we have a non-aggregate (scalar) constant
5542 bool zero = nextConst >= consts.size();
5543 spv::Id scalar = 0;
5544 switch (glslangType.getBasicType()) {
5545 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005546 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005547 break;
5548 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005549 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005550 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005551 case glslang::EbtInt64:
5552 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5553 break;
5554 case glslang::EbtUint64:
5555 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5556 break;
Rex Xucabbb782017-03-24 13:41:14 +08005557#ifdef AMD_EXTENSIONS
5558 case glslang::EbtInt16:
5559 scalar = builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst(), specConstant);
5560 break;
5561 case glslang::EbtUint16:
5562 scalar = builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst(), specConstant);
5563 break;
5564#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005565 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005566 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005567 break;
5568 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005569 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005570 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005571#ifdef AMD_EXTENSIONS
5572 case glslang::EbtFloat16:
5573 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5574 break;
5575#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005576 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005577 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005578 break;
5579 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005580 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005581 break;
5582 }
5583 ++nextConst;
5584 return scalar;
5585 }
5586
5587 return builder.makeCompositeConstant(typeId, spvConsts);
5588}
5589
John Kessenich7c1aa102015-10-15 13:29:11 -06005590// Return true if the node is a constant or symbol whose reading has no
5591// non-trivial observable cost or effect.
5592bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5593{
5594 // don't know what this is
5595 if (node == nullptr)
5596 return false;
5597
5598 // a constant is safe
5599 if (node->getAsConstantUnion() != nullptr)
5600 return true;
5601
5602 // not a symbol means non-trivial
5603 if (node->getAsSymbolNode() == nullptr)
5604 return false;
5605
5606 // a symbol, depends on what's being read
5607 switch (node->getType().getQualifier().storage) {
5608 case glslang::EvqTemporary:
5609 case glslang::EvqGlobal:
5610 case glslang::EvqIn:
5611 case glslang::EvqInOut:
5612 case glslang::EvqConst:
5613 case glslang::EvqConstReadOnly:
5614 case glslang::EvqUniform:
5615 return true;
5616 default:
5617 return false;
5618 }
qining25262b32016-05-06 17:25:16 -04005619}
John Kessenich7c1aa102015-10-15 13:29:11 -06005620
5621// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06005622// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06005623// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06005624// Return true if trivial.
5625bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5626{
5627 if (node == nullptr)
5628 return false;
5629
John Kessenich84cc15f2017-05-24 16:44:47 -06005630 // count non scalars as trivial, as well as anything coming from HLSL
5631 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06005632 return true;
5633
John Kessenich7c1aa102015-10-15 13:29:11 -06005634 // symbols and constants are trivial
5635 if (isTrivialLeaf(node))
5636 return true;
5637
5638 // otherwise, it needs to be a simple operation or one or two leaf nodes
5639
5640 // not a simple operation
5641 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5642 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5643 if (binaryNode == nullptr && unaryNode == nullptr)
5644 return false;
5645
5646 // not on leaf nodes
5647 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5648 return false;
5649
5650 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5651 return false;
5652 }
5653
5654 switch (node->getAsOperator()->getOp()) {
5655 case glslang::EOpLogicalNot:
5656 case glslang::EOpConvIntToBool:
5657 case glslang::EOpConvUintToBool:
5658 case glslang::EOpConvFloatToBool:
5659 case glslang::EOpConvDoubleToBool:
5660 case glslang::EOpEqual:
5661 case glslang::EOpNotEqual:
5662 case glslang::EOpLessThan:
5663 case glslang::EOpGreaterThan:
5664 case glslang::EOpLessThanEqual:
5665 case glslang::EOpGreaterThanEqual:
5666 case glslang::EOpIndexDirect:
5667 case glslang::EOpIndexDirectStruct:
5668 case glslang::EOpLogicalXor:
5669 case glslang::EOpAny:
5670 case glslang::EOpAll:
5671 return true;
5672 default:
5673 return false;
5674 }
5675}
5676
5677// Emit short-circuiting code, where 'right' is never evaluated unless
5678// the left side is true (for &&) or false (for ||).
5679spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5680{
5681 spv::Id boolTypeId = builder.makeBoolType();
5682
5683 // emit left operand
5684 builder.clearAccessChain();
5685 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005686 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005687
5688 // Operands to accumulate OpPhi operands
5689 std::vector<spv::Id> phiOperands;
5690 // accumulate left operand's phi information
5691 phiOperands.push_back(leftId);
5692 phiOperands.push_back(builder.getBuildPoint()->getId());
5693
5694 // Make the two kinds of operation symmetric with a "!"
5695 // || => emit "if (! left) result = right"
5696 // && => emit "if ( left) result = right"
5697 //
5698 // TODO: this runtime "not" for || could be avoided by adding functionality
5699 // to 'builder' to have an "else" without an "then"
5700 if (op == glslang::EOpLogicalOr)
5701 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5702
5703 // make an "if" based on the left value
5704 spv::Builder::If ifBuilder(leftId, builder);
5705
5706 // emit right operand as the "then" part of the "if"
5707 builder.clearAccessChain();
5708 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005709 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005710
5711 // accumulate left operand's phi information
5712 phiOperands.push_back(rightId);
5713 phiOperands.push_back(builder.getBuildPoint()->getId());
5714
5715 // finish the "if"
5716 ifBuilder.makeEndIf();
5717
5718 // phi together the two results
5719 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5720}
5721
Rex Xu9d93a232016-05-05 12:30:44 +08005722// Return type Id of the imported set of extended instructions corresponds to the name.
5723// Import this set if it has not been imported yet.
5724spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5725{
5726 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5727 return extBuiltinMap[name];
5728 else {
Rex Xu51596642016-09-21 18:56:12 +08005729 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005730 spv::Id extBuiltins = builder.import(name);
5731 extBuiltinMap[name] = extBuiltins;
5732 return extBuiltins;
5733 }
5734}
5735
John Kessenich140f3df2015-06-26 16:58:36 -06005736}; // end anonymous namespace
5737
5738namespace glslang {
5739
John Kessenich68d78fd2015-07-12 19:28:10 -06005740void GetSpirvVersion(std::string& version)
5741{
John Kessenich9e55f632015-07-15 10:03:39 -06005742 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005743 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005744 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005745 version = buf;
5746}
5747
John Kessenich140f3df2015-06-26 16:58:36 -06005748// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005749void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005750{
5751 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005752 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005753 if (out.fail())
5754 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06005755 for (int i = 0; i < (int)spirv.size(); ++i) {
5756 unsigned int word = spirv[i];
5757 out.write((const char*)&word, 4);
5758 }
5759 out.close();
5760}
5761
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005762// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08005763void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005764{
5765 std::ofstream out;
5766 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005767 if (out.fail())
5768 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005769 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08005770 if (varName != nullptr) {
5771 out << "\t #pragma once" << std::endl;
5772 out << "const uint32_t " << varName << "[] = {" << std::endl;
5773 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005774 const int WORDS_PER_LINE = 8;
5775 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5776 out << "\t";
5777 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5778 const unsigned int word = spirv[i + j];
5779 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5780 if (i + j + 1 < (int)spirv.size()) {
5781 out << ",";
5782 }
5783 }
5784 out << std::endl;
5785 }
Flavio15017db2017-02-15 14:29:33 -08005786 if (varName != nullptr) {
5787 out << "};";
5788 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005789 out.close();
5790}
5791
John Kessenich140f3df2015-06-26 16:58:36 -06005792//
5793// Set up the glslang traversal
5794//
John Kessenich121853f2017-05-31 17:11:16 -06005795void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06005796{
Lei Zhang17535f72016-05-04 15:55:59 -04005797 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06005798 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04005799}
5800
John Kessenich121853f2017-05-31 17:11:16 -06005801void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv,
5802 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04005803{
John Kessenich140f3df2015-06-26 16:58:36 -06005804 TIntermNode* root = intermediate.getTreeRoot();
5805
5806 if (root == 0)
5807 return;
5808
John Kessenich121853f2017-05-31 17:11:16 -06005809 glslang::SpvOptions defaultOptions;
5810 if (options == nullptr)
5811 options = &defaultOptions;
5812
John Kessenich140f3df2015-06-26 16:58:36 -06005813 glslang::GetThreadPoolAllocator().push();
5814
John Kessenich121853f2017-05-31 17:11:16 -06005815 TGlslangToSpvTraverser it(&intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06005816 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07005817 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06005818 it.dumpSpv(spirv);
5819
5820 glslang::GetThreadPoolAllocator().pop();
5821}
5822
5823}; // end namespace glslang