blob: 92dab960d556e61692bbdc8c29188e9e228d0fbb [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
John Kessenich140f3df2015-06-26 16:58:36 -0600523 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600524 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
525 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
526 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
527 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
528 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
529 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
530 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600531 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
532 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
533 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
534 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
535 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
536 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
537 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
538 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800539
Rex Xu574ab042016-04-14 16:53:07 +0800540 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800541 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800542 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
543 return spv::BuiltInSubgroupSize;
544
Rex Xu574ab042016-04-14 16:53:07 +0800545 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800546 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800547 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
548 return spv::BuiltInSubgroupLocalInvocationId;
549
Rex Xu574ab042016-04-14 16:53:07 +0800550 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800551 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
552 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
553 return spv::BuiltInSubgroupEqMaskKHR;
554
Rex Xu574ab042016-04-14 16:53:07 +0800555 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800556 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
557 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
558 return spv::BuiltInSubgroupGeMaskKHR;
559
Rex Xu574ab042016-04-14 16:53:07 +0800560 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800561 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
562 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
563 return spv::BuiltInSubgroupGtMaskKHR;
564
Rex Xu574ab042016-04-14 16:53:07 +0800565 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800566 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
567 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
568 return spv::BuiltInSubgroupLeMaskKHR;
569
Rex Xu574ab042016-04-14 16:53:07 +0800570 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800571 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
572 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
573 return spv::BuiltInSubgroupLtMaskKHR;
574
Rex Xu9d93a232016-05-05 12:30:44 +0800575#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800576 case glslang::EbvBaryCoordNoPersp:
577 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
578 return spv::BuiltInBaryCoordNoPerspAMD;
579
580 case glslang::EbvBaryCoordNoPerspCentroid:
581 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
582 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
583
584 case glslang::EbvBaryCoordNoPerspSample:
585 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
586 return spv::BuiltInBaryCoordNoPerspSampleAMD;
587
588 case glslang::EbvBaryCoordSmooth:
589 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
590 return spv::BuiltInBaryCoordSmoothAMD;
591
592 case glslang::EbvBaryCoordSmoothCentroid:
593 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
594 return spv::BuiltInBaryCoordSmoothCentroidAMD;
595
596 case glslang::EbvBaryCoordSmoothSample:
597 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
598 return spv::BuiltInBaryCoordSmoothSampleAMD;
599
600 case glslang::EbvBaryCoordPullModel:
601 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
602 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800603#endif
chaoc771d89f2017-01-13 01:10:53 -0800604
John Kessenich6c8aaac2017-02-27 01:20:51 -0700605 case glslang::EbvDeviceIndex:
606 builder.addExtension(spv::E_SPV_KHR_device_group);
607 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700608 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700609
610 case glslang::EbvViewIndex:
611 builder.addExtension(spv::E_SPV_KHR_multiview);
612 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700613 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700614
chaoc771d89f2017-01-13 01:10:53 -0800615#ifdef NV_EXTENSIONS
616 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800617 if (!memberDeclaration) {
618 builder.addExtension(spv::E_SPV_NV_viewport_array2);
619 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
620 }
chaoc771d89f2017-01-13 01:10:53 -0800621 return spv::BuiltInViewportMaskNV;
622 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800623 if (!memberDeclaration) {
624 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
625 builder.addCapability(spv::CapabilityShaderStereoViewNV);
626 }
chaoc771d89f2017-01-13 01:10:53 -0800627 return spv::BuiltInSecondaryPositionNV;
628 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800629 if (!memberDeclaration) {
630 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
631 builder.addCapability(spv::CapabilityShaderStereoViewNV);
632 }
chaoc771d89f2017-01-13 01:10:53 -0800633 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800634 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800635 if (!memberDeclaration) {
636 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
637 builder.addCapability(spv::CapabilityPerViewAttributesNV);
638 }
chaocdf3956c2017-02-14 14:52:34 -0800639 return spv::BuiltInPositionPerViewNV;
640 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800641 if (!memberDeclaration) {
642 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
643 builder.addCapability(spv::CapabilityPerViewAttributesNV);
644 }
chaocdf3956c2017-02-14 14:52:34 -0800645 return spv::BuiltInViewportMaskPerViewNV;
chaoc771d89f2017-01-13 01:10:53 -0800646#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800647 default:
648 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600649 }
650}
651
Rex Xufc618912015-09-09 16:42:49 +0800652// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700653spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800654{
655 assert(type.getBasicType() == glslang::EbtSampler);
656
John Kessenich5d0fa972016-02-15 11:57:00 -0700657 // Check for capabilities
658 switch (type.getQualifier().layoutFormat) {
659 case glslang::ElfRg32f:
660 case glslang::ElfRg16f:
661 case glslang::ElfR11fG11fB10f:
662 case glslang::ElfR16f:
663 case glslang::ElfRgba16:
664 case glslang::ElfRgb10A2:
665 case glslang::ElfRg16:
666 case glslang::ElfRg8:
667 case glslang::ElfR16:
668 case glslang::ElfR8:
669 case glslang::ElfRgba16Snorm:
670 case glslang::ElfRg16Snorm:
671 case glslang::ElfRg8Snorm:
672 case glslang::ElfR16Snorm:
673 case glslang::ElfR8Snorm:
674
675 case glslang::ElfRg32i:
676 case glslang::ElfRg16i:
677 case glslang::ElfRg8i:
678 case glslang::ElfR16i:
679 case glslang::ElfR8i:
680
681 case glslang::ElfRgb10a2ui:
682 case glslang::ElfRg32ui:
683 case glslang::ElfRg16ui:
684 case glslang::ElfRg8ui:
685 case glslang::ElfR16ui:
686 case glslang::ElfR8ui:
687 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
688 break;
689
690 default:
691 break;
692 }
693
694 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800695 switch (type.getQualifier().layoutFormat) {
696 case glslang::ElfNone: return spv::ImageFormatUnknown;
697 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
698 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
699 case glslang::ElfR32f: return spv::ImageFormatR32f;
700 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
701 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
702 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
703 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
704 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
705 case glslang::ElfR16f: return spv::ImageFormatR16f;
706 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
707 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
708 case glslang::ElfRg16: return spv::ImageFormatRg16;
709 case glslang::ElfRg8: return spv::ImageFormatRg8;
710 case glslang::ElfR16: return spv::ImageFormatR16;
711 case glslang::ElfR8: return spv::ImageFormatR8;
712 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
713 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
714 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
715 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
716 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
717 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
718 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
719 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
720 case glslang::ElfR32i: return spv::ImageFormatR32i;
721 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
722 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
723 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
724 case glslang::ElfR16i: return spv::ImageFormatR16i;
725 case glslang::ElfR8i: return spv::ImageFormatR8i;
726 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
727 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
728 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
729 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
730 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
731 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
732 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
733 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
734 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
735 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600736 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800737 }
738}
739
steve-lunargf1709e72017-05-02 20:14:50 -0600740spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(glslang::TLoopControl loopControl) const
741{
742 switch (loopControl) {
743 case glslang::ELoopControlNone: return spv::LoopControlMaskNone;
744 case glslang::ELoopControlUnroll: return spv::LoopControlUnrollMask;
745 case glslang::ELoopControlDontUnroll: return spv::LoopControlDontUnrollMask;
746 // TODO: DependencyInfinite
747 // TODO: DependencyLength
748 default: return spv::LoopControlMaskNone;
749 }
750}
751
John Kessenicha5c5fb62017-05-05 05:09:58 -0600752// Translate glslang type to SPIR-V storage class.
753spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
754{
755 if (type.getQualifier().isPipeInput())
756 return spv::StorageClassInput;
757 else if (type.getQualifier().isPipeOutput())
758 return spv::StorageClassOutput;
759 else if (type.getBasicType() == glslang::EbtAtomicUint)
760 return spv::StorageClassAtomicCounter;
761 else if (type.containsOpaque())
762 return spv::StorageClassUniformConstant;
763 else if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
764 builder.addExtension(spv::E_SPV_KHR_storage_buffer_storage_class);
765 return spv::StorageClassStorageBuffer;
766 } else if (type.getQualifier().isUniformOrBuffer()) {
767 if (type.getQualifier().layoutPushConstant)
768 return spv::StorageClassPushConstant;
769 if (type.getBasicType() == glslang::EbtBlock)
770 return spv::StorageClassUniform;
771 else
772 return spv::StorageClassUniformConstant;
773 } else {
774 switch (type.getQualifier().storage) {
775 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
776 case glslang::EvqGlobal: return spv::StorageClassPrivate;
777 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
778 case glslang::EvqTemporary: return spv::StorageClassFunction;
779 default:
780 assert(0);
781 return spv::StorageClassFunction;
782 }
783 }
784}
785
qining25262b32016-05-06 17:25:16 -0400786// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700787// descriptor set.
788bool IsDescriptorResource(const glslang::TType& type)
789{
John Kessenichf7497e22016-03-08 21:36:22 -0700790 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700791 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700792 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700793
794 // non block...
795 // basically samplerXXX/subpass/sampler/texture are all included
796 // if they are the global-scope-class, not the function parameter
797 // (or local, if they ever exist) class.
798 if (type.getBasicType() == glslang::EbtSampler)
799 return type.getQualifier().isUniformOrBuffer();
800
801 // None of the above.
802 return false;
803}
804
John Kesseniche0b6cad2015-12-24 10:30:13 -0700805void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
806{
807 if (child.layoutMatrix == glslang::ElmNone)
808 child.layoutMatrix = parent.layoutMatrix;
809
810 if (parent.invariant)
811 child.invariant = true;
812 if (parent.nopersp)
813 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800814#ifdef AMD_EXTENSIONS
815 if (parent.explicitInterp)
816 child.explicitInterp = true;
817#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700818 if (parent.flat)
819 child.flat = true;
820 if (parent.centroid)
821 child.centroid = true;
822 if (parent.patch)
823 child.patch = true;
824 if (parent.sample)
825 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800826 if (parent.coherent)
827 child.coherent = true;
828 if (parent.volatil)
829 child.volatil = true;
830 if (parent.restrict)
831 child.restrict = true;
832 if (parent.readonly)
833 child.readonly = true;
834 if (parent.writeonly)
835 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700836}
837
John Kessenichf2b7f332016-09-01 17:05:23 -0600838bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700839{
John Kessenich7b9fa252016-01-21 18:56:57 -0700840 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600841 // - struct members might inherit from a struct declaration
842 // (note that non-block structs don't explicitly inherit,
843 // only implicitly, meaning no decoration involved)
844 // - affect decorations on the struct members
845 // (note smooth does not, and expecting something like volatile
846 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700847 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600848 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700849}
850
John Kessenich140f3df2015-06-26 16:58:36 -0600851//
852// Implement the TGlslangToSpvTraverser class.
853//
854
John Kessenich121853f2017-05-31 17:11:16 -0600855TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate,
856 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
857 : TIntermTraverser(true, false, true),
858 options(options),
859 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -0600860 sequenceDepth(0), logger(buildLogger),
Lei Zhang17535f72016-05-04 15:55:59 -0400861 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700862 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600863 glslangIntermediate(glslangIntermediate)
864{
865 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
866
867 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700868 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich121853f2017-05-31 17:11:16 -0600869 if (options.generateDebugInfo) {
870 builder.setSourceFile(glslangIntermediate->getSourceFile());
871 builder.setSourceText(glslangIntermediate->getSourceText());
John Kesseniche485c7a2017-05-31 18:50:53 -0600872 builder.setEmitOpLines();
John Kessenich121853f2017-05-31 17:11:16 -0600873 }
John Kessenich140f3df2015-06-26 16:58:36 -0600874 stdBuiltins = builder.import("GLSL.std.450");
875 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600876 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
877 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600878
879 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600880 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
881 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600882 builder.addSourceExtension(it->c_str());
883
884 // Add the top-level modes for this shader.
885
John Kessenich92187592016-02-01 13:45:25 -0700886 if (glslangIntermediate->getXfbMode()) {
887 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600888 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700889 }
John Kessenich140f3df2015-06-26 16:58:36 -0600890
891 unsigned int mode;
892 switch (glslangIntermediate->getStage()) {
893 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600894 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600895 break;
896
steve-lunarge7412492017-03-23 11:56:07 -0600897 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -0600898 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600899 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600900
steve-lunarge7412492017-03-23 11:56:07 -0600901 glslang::TLayoutGeometry primitive;
902
903 if (glslangIntermediate->getStage() == EShLangTessControl) {
904 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
905 primitive = glslangIntermediate->getOutputPrimitive();
906 } else {
907 primitive = glslangIntermediate->getInputPrimitive();
908 }
909
910 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -0700911 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
912 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
913 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600914 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600915 }
John Kessenich4016e382016-07-15 11:53:56 -0600916 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600917 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
918
John Kesseniche6903322015-10-13 16:29:02 -0600919 switch (glslangIntermediate->getVertexSpacing()) {
920 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
921 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
922 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600923 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600924 }
John Kessenich4016e382016-07-15 11:53:56 -0600925 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600926 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
927
928 switch (glslangIntermediate->getVertexOrder()) {
929 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
930 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600931 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600932 }
John Kessenich4016e382016-07-15 11:53:56 -0600933 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600934 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
935
936 if (glslangIntermediate->getPointMode())
937 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600938 break;
939
940 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600941 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600942 switch (glslangIntermediate->getInputPrimitive()) {
943 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
944 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
945 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700946 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600947 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600948 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600949 }
John Kessenich4016e382016-07-15 11:53:56 -0600950 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600951 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600952
John Kessenich140f3df2015-06-26 16:58:36 -0600953 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
954
955 switch (glslangIntermediate->getOutputPrimitive()) {
956 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
957 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
958 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600959 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600960 }
John Kessenich4016e382016-07-15 11:53:56 -0600961 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600962 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
963 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
964 break;
965
966 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600967 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600968 if (glslangIntermediate->getPixelCenterInteger())
969 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600970
John Kessenich140f3df2015-06-26 16:58:36 -0600971 if (glslangIntermediate->getOriginUpperLeft())
972 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600973 else
974 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600975
976 if (glslangIntermediate->getEarlyFragmentTests())
977 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
978
979 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600980 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
981 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -0600982 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600983 }
John Kessenich4016e382016-07-15 11:53:56 -0600984 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600985 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
986
987 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
988 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600989 break;
990
991 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600992 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600993 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
994 glslangIntermediate->getLocalSize(1),
995 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600996 break;
997
998 default:
999 break;
1000 }
John Kessenich140f3df2015-06-26 16:58:36 -06001001}
1002
John Kessenichfca82622016-11-26 13:23:20 -07001003// Finish creating SPV, after the traversal is complete.
1004void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001005{
John Kessenich517fe7a2016-11-26 13:31:47 -07001006 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001007 builder.setBuildPoint(shaderEntry->getLastBlock());
1008 builder.leaveFunction();
1009 }
1010
John Kessenich7ba63412015-12-20 17:37:07 -07001011 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001012 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1013 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001014
qiningda397332016-03-09 19:54:03 -05001015 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -07001016}
1017
John Kessenichfca82622016-11-26 13:23:20 -07001018// Write the SPV into 'out'.
1019void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001020{
John Kessenichfca82622016-11-26 13:23:20 -07001021 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001022}
1023
1024//
1025// Implement the traversal functions.
1026//
1027// Return true from interior nodes to have the external traversal
1028// continue on to children. Return false if children were
1029// already processed.
1030//
1031
1032//
qining25262b32016-05-06 17:25:16 -04001033// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001034// - uniform/input reads
1035// - output writes
1036// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1037// - something simple that degenerates into the last bullet
1038//
1039void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1040{
qining75d1d802016-04-06 14:42:01 -04001041 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1042 if (symbol->getType().getQualifier().isSpecConstant())
1043 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1044
John Kessenich140f3df2015-06-26 16:58:36 -06001045 // getSymbolId() will set up all the IO decorations on the first call.
1046 // Formal function parameters were mapped during makeFunctions().
1047 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001048
1049 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1050 if (builder.isPointer(id)) {
1051 spv::StorageClass sc = builder.getStorageClass(id);
1052 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
1053 iOSet.insert(id);
1054 }
1055
1056 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001057 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001058 // Prepare to generate code for the access
1059
1060 // L-value chains will be computed left to right. We're on the symbol now,
1061 // which is the left-most part of the access chain, so now is "clear" time,
1062 // followed by setting the base.
1063 builder.clearAccessChain();
1064
1065 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001066 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001067 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001068 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001069 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001070 // These are also pure R-values.
1071 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001072 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001073 builder.setAccessChainRValue(id);
1074 else
1075 builder.setAccessChainLValue(id);
1076 }
1077}
1078
1079bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1080{
John Kesseniche485c7a2017-05-31 18:50:53 -06001081 builder.setLine(node->getLoc().line);
1082
qining40887662016-04-03 22:20:42 -04001083 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1084 if (node->getType().getQualifier().isSpecConstant())
1085 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1086
John Kessenich140f3df2015-06-26 16:58:36 -06001087 // First, handle special cases
1088 switch (node->getOp()) {
1089 case glslang::EOpAssign:
1090 case glslang::EOpAddAssign:
1091 case glslang::EOpSubAssign:
1092 case glslang::EOpMulAssign:
1093 case glslang::EOpVectorTimesMatrixAssign:
1094 case glslang::EOpVectorTimesScalarAssign:
1095 case glslang::EOpMatrixTimesScalarAssign:
1096 case glslang::EOpMatrixTimesMatrixAssign:
1097 case glslang::EOpDivAssign:
1098 case glslang::EOpModAssign:
1099 case glslang::EOpAndAssign:
1100 case glslang::EOpInclusiveOrAssign:
1101 case glslang::EOpExclusiveOrAssign:
1102 case glslang::EOpLeftShiftAssign:
1103 case glslang::EOpRightShiftAssign:
1104 // A bin-op assign "a += b" means the same thing as "a = a + b"
1105 // where a is evaluated before b. For a simple assignment, GLSL
1106 // says to evaluate the left before the right. So, always, left
1107 // node then right node.
1108 {
1109 // get the left l-value, save it away
1110 builder.clearAccessChain();
1111 node->getLeft()->traverse(this);
1112 spv::Builder::AccessChain lValue = builder.getAccessChain();
1113
1114 // evaluate the right
1115 builder.clearAccessChain();
1116 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001117 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001118
1119 if (node->getOp() != glslang::EOpAssign) {
1120 // the left is also an r-value
1121 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001122 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001123
1124 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001125 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001126 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001127 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1128 node->getType().getBasicType());
1129
1130 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001131 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001132 }
1133
1134 // store the result
1135 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001136 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001137
1138 // assignments are expressions having an rValue after they are evaluated...
1139 builder.clearAccessChain();
1140 builder.setAccessChainRValue(rValue);
1141 }
1142 return false;
1143 case glslang::EOpIndexDirect:
1144 case glslang::EOpIndexDirectStruct:
1145 {
1146 // Get the left part of the access chain.
1147 node->getLeft()->traverse(this);
1148
1149 // Add the next element in the chain
1150
David Netoa901ffe2016-06-08 14:11:40 +01001151 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001152 if (! node->getLeft()->getType().isArray() &&
1153 node->getLeft()->getType().isVector() &&
1154 node->getOp() == glslang::EOpIndexDirect) {
1155 // This is essentially a hard-coded vector swizzle of size 1,
1156 // so short circuit the access-chain stuff with a swizzle.
1157 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001158 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001159 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001160 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001161 int spvIndex = glslangIndex;
1162 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1163 node->getOp() == glslang::EOpIndexDirectStruct)
1164 {
1165 // This may be, e.g., an anonymous block-member selection, which generally need
1166 // index remapping due to hidden members in anonymous blocks.
1167 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1168 assert(remapper.size() > 0);
1169 spvIndex = remapper[glslangIndex];
1170 }
John Kessenichebb50532016-05-16 19:22:05 -06001171
David Netoa901ffe2016-06-08 14:11:40 +01001172 // normal case for indexing array or structure or block
1173 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1174
1175 // Add capabilities here for accessing PointSize and clip/cull distance.
1176 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001177 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001178 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001179 }
1180 }
1181 return false;
1182 case glslang::EOpIndexIndirect:
1183 {
1184 // Structure or array or vector indirection.
1185 // Will use native SPIR-V access-chain for struct and array indirection;
1186 // matrices are arrays of vectors, so will also work for a matrix.
1187 // Will use the access chain's 'component' for variable index into a vector.
1188
1189 // This adapter is building access chains left to right.
1190 // Set up the access chain to the left.
1191 node->getLeft()->traverse(this);
1192
1193 // save it so that computing the right side doesn't trash it
1194 spv::Builder::AccessChain partial = builder.getAccessChain();
1195
1196 // compute the next index in the chain
1197 builder.clearAccessChain();
1198 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001199 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001200
1201 // restore the saved access chain
1202 builder.setAccessChain(partial);
1203
1204 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001205 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001206 else
John Kessenichfa668da2015-09-13 14:46:30 -06001207 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001208 }
1209 return false;
1210 case glslang::EOpVectorSwizzle:
1211 {
1212 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001213 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001214 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001215 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001216 }
1217 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001218 case glslang::EOpMatrixSwizzle:
1219 logger->missingFunctionality("matrix swizzle");
1220 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001221 case glslang::EOpLogicalOr:
1222 case glslang::EOpLogicalAnd:
1223 {
1224
1225 // These may require short circuiting, but can sometimes be done as straight
1226 // binary operations. The right operand must be short circuited if it has
1227 // side effects, and should probably be if it is complex.
1228 if (isTrivial(node->getRight()->getAsTyped()))
1229 break; // handle below as a normal binary operation
1230 // otherwise, we need to do dynamic short circuiting on the right operand
1231 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1232 builder.clearAccessChain();
1233 builder.setAccessChainRValue(result);
1234 }
1235 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001236 default:
1237 break;
1238 }
1239
1240 // Assume generic binary op...
1241
John Kessenich32cfd492016-02-02 12:37:46 -07001242 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001243 builder.clearAccessChain();
1244 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001245 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001246
John Kessenich32cfd492016-02-02 12:37:46 -07001247 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001248 builder.clearAccessChain();
1249 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001250 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001251
John Kessenich32cfd492016-02-02 12:37:46 -07001252 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001253 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001254 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001255 convertGlslangToSpvType(node->getType()), left, right,
1256 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001257
John Kessenich50e57562015-12-21 21:21:11 -07001258 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001259 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001260 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001261 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001262 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001263 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001264 return false;
1265 }
John Kessenich140f3df2015-06-26 16:58:36 -06001266}
1267
1268bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1269{
John Kesseniche485c7a2017-05-31 18:50:53 -06001270 builder.setLine(node->getLoc().line);
1271
qining40887662016-04-03 22:20:42 -04001272 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1273 if (node->getType().getQualifier().isSpecConstant())
1274 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1275
John Kessenichfc51d282015-08-19 13:34:18 -06001276 spv::Id result = spv::NoResult;
1277
1278 // try texturing first
1279 result = createImageTextureFunctionCall(node);
1280 if (result != spv::NoResult) {
1281 builder.clearAccessChain();
1282 builder.setAccessChainRValue(result);
1283
1284 return false; // done with this node
1285 }
1286
1287 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001288
1289 if (node->getOp() == glslang::EOpArrayLength) {
1290 // Quite special; won't want to evaluate the operand.
1291
1292 // Normal .length() would have been constant folded by the front-end.
1293 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001294 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001295 assert(node->getOperand()->getType().isRuntimeSizedArray());
1296 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1297 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001298 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1299 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001300
1301 builder.clearAccessChain();
1302 builder.setAccessChainRValue(length);
1303
1304 return false;
1305 }
1306
John Kessenichfc51d282015-08-19 13:34:18 -06001307 // Start by evaluating the operand
1308
John Kessenich8c8505c2016-07-26 12:50:38 -06001309 // Does it need a swizzle inversion? If so, evaluation is inverted;
1310 // operate first on the swizzle base, then apply the swizzle.
1311 spv::Id invertedType = spv::NoType;
1312 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1313 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1314 invertedType = getInvertedSwizzleType(*node->getOperand());
1315
John Kessenich140f3df2015-06-26 16:58:36 -06001316 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001317 if (invertedType != spv::NoType)
1318 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1319 else
1320 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001321
Rex Xufc618912015-09-09 16:42:49 +08001322 spv::Id operand = spv::NoResult;
1323
1324 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1325 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001326 node->getOp() == glslang::EOpAtomicCounter ||
1327 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001328 operand = builder.accessChainGetLValue(); // Special case l-value operands
1329 else
John Kessenich32cfd492016-02-02 12:37:46 -07001330 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001331
John Kessenichf6640762016-08-01 19:44:00 -06001332 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001333 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001334
1335 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001336 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001337 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001338
1339 // if not, then possibly an operation
1340 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001341 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001342
1343 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001344 if (invertedType)
1345 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1346
John Kessenich140f3df2015-06-26 16:58:36 -06001347 builder.clearAccessChain();
1348 builder.setAccessChainRValue(result);
1349
1350 return false; // done with this node
1351 }
1352
1353 // it must be a special case, check...
1354 switch (node->getOp()) {
1355 case glslang::EOpPostIncrement:
1356 case glslang::EOpPostDecrement:
1357 case glslang::EOpPreIncrement:
1358 case glslang::EOpPreDecrement:
1359 {
1360 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001361 spv::Id one = 0;
1362 if (node->getBasicType() == glslang::EbtFloat)
1363 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001364 else if (node->getBasicType() == glslang::EbtDouble)
1365 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001366#ifdef AMD_EXTENSIONS
1367 else if (node->getBasicType() == glslang::EbtFloat16)
1368 one = builder.makeFloat16Constant(1.0F);
1369#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001370 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1371 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001372#ifdef AMD_EXTENSIONS
1373 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1374 one = builder.makeInt16Constant(1);
1375#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001376 else
1377 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001378 glslang::TOperator op;
1379 if (node->getOp() == glslang::EOpPreIncrement ||
1380 node->getOp() == glslang::EOpPostIncrement)
1381 op = glslang::EOpAdd;
1382 else
1383 op = glslang::EOpSub;
1384
John Kessenichf6640762016-08-01 19:44:00 -06001385 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001386 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001387 convertGlslangToSpvType(node->getType()), operand, one,
1388 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001389 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001390
1391 // The result of operation is always stored, but conditionally the
1392 // consumed result. The consumed result is always an r-value.
1393 builder.accessChainStore(result);
1394 builder.clearAccessChain();
1395 if (node->getOp() == glslang::EOpPreIncrement ||
1396 node->getOp() == glslang::EOpPreDecrement)
1397 builder.setAccessChainRValue(result);
1398 else
1399 builder.setAccessChainRValue(operand);
1400 }
1401
1402 return false;
1403
1404 case glslang::EOpEmitStreamVertex:
1405 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1406 return false;
1407 case glslang::EOpEndStreamPrimitive:
1408 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1409 return false;
1410
1411 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001412 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001413 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001414 }
John Kessenich140f3df2015-06-26 16:58:36 -06001415}
1416
1417bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1418{
qining27e04a02016-04-14 16:40:20 -04001419 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1420 if (node->getType().getQualifier().isSpecConstant())
1421 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1422
John Kessenichfc51d282015-08-19 13:34:18 -06001423 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001424 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1425 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001426
1427 // try texturing
1428 result = createImageTextureFunctionCall(node);
1429 if (result != spv::NoResult) {
1430 builder.clearAccessChain();
1431 builder.setAccessChainRValue(result);
1432
1433 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001434 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001435 // "imageStore" is a special case, which has no result
1436 return false;
1437 }
John Kessenichfc51d282015-08-19 13:34:18 -06001438
John Kessenich140f3df2015-06-26 16:58:36 -06001439 glslang::TOperator binOp = glslang::EOpNull;
1440 bool reduceComparison = true;
1441 bool isMatrix = false;
1442 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001443 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001444
1445 assert(node->getOp());
1446
John Kessenichf6640762016-08-01 19:44:00 -06001447 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001448
1449 switch (node->getOp()) {
1450 case glslang::EOpSequence:
1451 {
1452 if (preVisit)
1453 ++sequenceDepth;
1454 else
1455 --sequenceDepth;
1456
1457 if (sequenceDepth == 1) {
1458 // If this is the parent node of all the functions, we want to see them
1459 // early, so all call points have actual SPIR-V functions to reference.
1460 // In all cases, still let the traverser visit the children for us.
1461 makeFunctions(node->getAsAggregate()->getSequence());
1462
John Kessenich6fccb3c2016-09-19 16:01:41 -06001463 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001464 // anything else gets there, so visit out of order, doing them all now.
1465 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1466
John Kessenich6a60c2f2016-12-08 21:01:59 -07001467 // 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 -06001468 // so do them manually.
1469 visitFunctions(node->getAsAggregate()->getSequence());
1470
1471 return false;
1472 }
1473
1474 return true;
1475 }
1476 case glslang::EOpLinkerObjects:
1477 {
1478 if (visit == glslang::EvPreVisit)
1479 linkageOnly = true;
1480 else
1481 linkageOnly = false;
1482
1483 return true;
1484 }
1485 case glslang::EOpComma:
1486 {
1487 // processing from left to right naturally leaves the right-most
1488 // lying around in the access chain
1489 glslang::TIntermSequence& glslangOperands = node->getSequence();
1490 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1491 glslangOperands[i]->traverse(this);
1492
1493 return false;
1494 }
1495 case glslang::EOpFunction:
1496 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001497 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001498 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001499 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001500 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001501 } else {
1502 handleFunctionEntry(node);
1503 }
1504 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001505 if (inEntryPoint)
1506 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001507 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001508 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001509 }
1510
1511 return true;
1512 case glslang::EOpParameters:
1513 // Parameters will have been consumed by EOpFunction processing, but not
1514 // the body, so we still visited the function node's children, making this
1515 // child redundant.
1516 return false;
1517 case glslang::EOpFunctionCall:
1518 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001519 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001520 if (node->isUserDefined())
1521 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001522 // 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 -07001523 if (result) {
1524 builder.clearAccessChain();
1525 builder.setAccessChainRValue(result);
1526 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001527 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001528
1529 return false;
1530 }
1531 case glslang::EOpConstructMat2x2:
1532 case glslang::EOpConstructMat2x3:
1533 case glslang::EOpConstructMat2x4:
1534 case glslang::EOpConstructMat3x2:
1535 case glslang::EOpConstructMat3x3:
1536 case glslang::EOpConstructMat3x4:
1537 case glslang::EOpConstructMat4x2:
1538 case glslang::EOpConstructMat4x3:
1539 case glslang::EOpConstructMat4x4:
1540 case glslang::EOpConstructDMat2x2:
1541 case glslang::EOpConstructDMat2x3:
1542 case glslang::EOpConstructDMat2x4:
1543 case glslang::EOpConstructDMat3x2:
1544 case glslang::EOpConstructDMat3x3:
1545 case glslang::EOpConstructDMat3x4:
1546 case glslang::EOpConstructDMat4x2:
1547 case glslang::EOpConstructDMat4x3:
1548 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06001549 case glslang::EOpConstructIMat2x2:
1550 case glslang::EOpConstructIMat2x3:
1551 case glslang::EOpConstructIMat2x4:
1552 case glslang::EOpConstructIMat3x2:
1553 case glslang::EOpConstructIMat3x3:
1554 case glslang::EOpConstructIMat3x4:
1555 case glslang::EOpConstructIMat4x2:
1556 case glslang::EOpConstructIMat4x3:
1557 case glslang::EOpConstructIMat4x4:
1558 case glslang::EOpConstructUMat2x2:
1559 case glslang::EOpConstructUMat2x3:
1560 case glslang::EOpConstructUMat2x4:
1561 case glslang::EOpConstructUMat3x2:
1562 case glslang::EOpConstructUMat3x3:
1563 case glslang::EOpConstructUMat3x4:
1564 case glslang::EOpConstructUMat4x2:
1565 case glslang::EOpConstructUMat4x3:
1566 case glslang::EOpConstructUMat4x4:
1567 case glslang::EOpConstructBMat2x2:
1568 case glslang::EOpConstructBMat2x3:
1569 case glslang::EOpConstructBMat2x4:
1570 case glslang::EOpConstructBMat3x2:
1571 case glslang::EOpConstructBMat3x3:
1572 case glslang::EOpConstructBMat3x4:
1573 case glslang::EOpConstructBMat4x2:
1574 case glslang::EOpConstructBMat4x3:
1575 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001576#ifdef AMD_EXTENSIONS
1577 case glslang::EOpConstructF16Mat2x2:
1578 case glslang::EOpConstructF16Mat2x3:
1579 case glslang::EOpConstructF16Mat2x4:
1580 case glslang::EOpConstructF16Mat3x2:
1581 case glslang::EOpConstructF16Mat3x3:
1582 case glslang::EOpConstructF16Mat3x4:
1583 case glslang::EOpConstructF16Mat4x2:
1584 case glslang::EOpConstructF16Mat4x3:
1585 case glslang::EOpConstructF16Mat4x4:
1586#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001587 isMatrix = true;
1588 // fall through
1589 case glslang::EOpConstructFloat:
1590 case glslang::EOpConstructVec2:
1591 case glslang::EOpConstructVec3:
1592 case glslang::EOpConstructVec4:
1593 case glslang::EOpConstructDouble:
1594 case glslang::EOpConstructDVec2:
1595 case glslang::EOpConstructDVec3:
1596 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001597#ifdef AMD_EXTENSIONS
1598 case glslang::EOpConstructFloat16:
1599 case glslang::EOpConstructF16Vec2:
1600 case glslang::EOpConstructF16Vec3:
1601 case glslang::EOpConstructF16Vec4:
1602#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001603 case glslang::EOpConstructBool:
1604 case glslang::EOpConstructBVec2:
1605 case glslang::EOpConstructBVec3:
1606 case glslang::EOpConstructBVec4:
1607 case glslang::EOpConstructInt:
1608 case glslang::EOpConstructIVec2:
1609 case glslang::EOpConstructIVec3:
1610 case glslang::EOpConstructIVec4:
1611 case glslang::EOpConstructUint:
1612 case glslang::EOpConstructUVec2:
1613 case glslang::EOpConstructUVec3:
1614 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001615 case glslang::EOpConstructInt64:
1616 case glslang::EOpConstructI64Vec2:
1617 case glslang::EOpConstructI64Vec3:
1618 case glslang::EOpConstructI64Vec4:
1619 case glslang::EOpConstructUint64:
1620 case glslang::EOpConstructU64Vec2:
1621 case glslang::EOpConstructU64Vec3:
1622 case glslang::EOpConstructU64Vec4:
Rex Xucabbb782017-03-24 13:41:14 +08001623#ifdef AMD_EXTENSIONS
1624 case glslang::EOpConstructInt16:
1625 case glslang::EOpConstructI16Vec2:
1626 case glslang::EOpConstructI16Vec3:
1627 case glslang::EOpConstructI16Vec4:
1628 case glslang::EOpConstructUint16:
1629 case glslang::EOpConstructU16Vec2:
1630 case glslang::EOpConstructU16Vec3:
1631 case glslang::EOpConstructU16Vec4:
1632#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001633 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001634 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001635 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001636 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001637 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001638 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001639 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001640 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001641 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001642 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001643 std::vector<spv::Id> constituents;
1644 for (int c = 0; c < (int)arguments.size(); ++c)
1645 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001646 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001647 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001648 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001649 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001650 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001651
1652 builder.clearAccessChain();
1653 builder.setAccessChainRValue(constructed);
1654
1655 return false;
1656 }
1657
1658 // These six are component-wise compares with component-wise results.
1659 // Forward on to createBinaryOperation(), requesting a vector result.
1660 case glslang::EOpLessThan:
1661 case glslang::EOpGreaterThan:
1662 case glslang::EOpLessThanEqual:
1663 case glslang::EOpGreaterThanEqual:
1664 case glslang::EOpVectorEqual:
1665 case glslang::EOpVectorNotEqual:
1666 {
1667 // Map the operation to a binary
1668 binOp = node->getOp();
1669 reduceComparison = false;
1670 switch (node->getOp()) {
1671 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1672 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1673 default: binOp = node->getOp(); break;
1674 }
1675
1676 break;
1677 }
1678 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001679 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001680 binOp = glslang::EOpMul;
1681 break;
1682 case glslang::EOpOuterProduct:
1683 // two vectors multiplied to make a matrix
1684 binOp = glslang::EOpOuterProduct;
1685 break;
1686 case glslang::EOpDot:
1687 {
qining25262b32016-05-06 17:25:16 -04001688 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001689 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001690 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001691 binOp = glslang::EOpMul;
1692 break;
1693 }
1694 case glslang::EOpMod:
1695 // when an aggregate, this is the floating-point mod built-in function,
1696 // which can be emitted by the one in createBinaryOperation()
1697 binOp = glslang::EOpMod;
1698 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001699 case glslang::EOpEmitVertex:
1700 case glslang::EOpEndPrimitive:
1701 case glslang::EOpBarrier:
1702 case glslang::EOpMemoryBarrier:
1703 case glslang::EOpMemoryBarrierAtomicCounter:
1704 case glslang::EOpMemoryBarrierBuffer:
1705 case glslang::EOpMemoryBarrierImage:
1706 case glslang::EOpMemoryBarrierShared:
1707 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001708 case glslang::EOpAllMemoryBarrierWithGroupSync:
1709 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1710 case glslang::EOpWorkgroupMemoryBarrier:
1711 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001712 noReturnValue = true;
1713 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1714 break;
1715
John Kessenich426394d2015-07-23 10:22:48 -06001716 case glslang::EOpAtomicAdd:
1717 case glslang::EOpAtomicMin:
1718 case glslang::EOpAtomicMax:
1719 case glslang::EOpAtomicAnd:
1720 case glslang::EOpAtomicOr:
1721 case glslang::EOpAtomicXor:
1722 case glslang::EOpAtomicExchange:
1723 case glslang::EOpAtomicCompSwap:
1724 atomic = true;
1725 break;
1726
John Kessenich140f3df2015-06-26 16:58:36 -06001727 default:
1728 break;
1729 }
1730
1731 //
1732 // See if it maps to a regular operation.
1733 //
John Kessenich140f3df2015-06-26 16:58:36 -06001734 if (binOp != glslang::EOpNull) {
1735 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1736 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1737 assert(left && right);
1738
1739 builder.clearAccessChain();
1740 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001741 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001742
1743 builder.clearAccessChain();
1744 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001745 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001746
John Kesseniche485c7a2017-05-31 18:50:53 -06001747 builder.setLine(node->getLoc().line);
qining25262b32016-05-06 17:25:16 -04001748 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001749 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001750 left->getType().getBasicType(), reduceComparison);
1751
1752 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001753 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001754 builder.clearAccessChain();
1755 builder.setAccessChainRValue(result);
1756
1757 return false;
1758 }
1759
John Kessenich426394d2015-07-23 10:22:48 -06001760 //
1761 // Create the list of operands.
1762 //
John Kessenich140f3df2015-06-26 16:58:36 -06001763 glslang::TIntermSequence& glslangOperands = node->getSequence();
1764 std::vector<spv::Id> operands;
1765 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001766 // special case l-value operands; there are just a few
1767 bool lvalue = false;
1768 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001769 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001770 case glslang::EOpModf:
1771 if (arg == 1)
1772 lvalue = true;
1773 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001774 case glslang::EOpInterpolateAtSample:
1775 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001776#ifdef AMD_EXTENSIONS
1777 case glslang::EOpInterpolateAtVertex:
1778#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001779 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001780 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001781
1782 // Does it need a swizzle inversion? If so, evaluation is inverted;
1783 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001784 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001785 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1786 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1787 }
Rex Xu7a26c172015-12-08 17:12:09 +08001788 break;
Rex Xud4782c12015-09-06 16:30:11 +08001789 case glslang::EOpAtomicAdd:
1790 case glslang::EOpAtomicMin:
1791 case glslang::EOpAtomicMax:
1792 case glslang::EOpAtomicAnd:
1793 case glslang::EOpAtomicOr:
1794 case glslang::EOpAtomicXor:
1795 case glslang::EOpAtomicExchange:
1796 case glslang::EOpAtomicCompSwap:
1797 if (arg == 0)
1798 lvalue = true;
1799 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001800 case glslang::EOpAddCarry:
1801 case glslang::EOpSubBorrow:
1802 if (arg == 2)
1803 lvalue = true;
1804 break;
1805 case glslang::EOpUMulExtended:
1806 case glslang::EOpIMulExtended:
1807 if (arg >= 2)
1808 lvalue = true;
1809 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001810 default:
1811 break;
1812 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001813 builder.clearAccessChain();
1814 if (invertedType != spv::NoType && arg == 0)
1815 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1816 else
1817 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001818 if (lvalue)
1819 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06001820 else {
1821 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07001822 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06001823 }
John Kessenich140f3df2015-06-26 16:58:36 -06001824 }
John Kessenich426394d2015-07-23 10:22:48 -06001825
John Kesseniche485c7a2017-05-31 18:50:53 -06001826 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06001827 if (atomic) {
1828 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001829 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001830 } else {
1831 // Pass through to generic operations.
1832 switch (glslangOperands.size()) {
1833 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001834 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001835 break;
1836 case 1:
qining25262b32016-05-06 17:25:16 -04001837 result = createUnaryOperation(
1838 node->getOp(), precision,
1839 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001840 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001841 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001842 break;
1843 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001844 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001845 break;
1846 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001847 if (invertedType)
1848 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001849 }
1850
1851 if (noReturnValue)
1852 return false;
1853
1854 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001855 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001856 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001857 } else {
1858 builder.clearAccessChain();
1859 builder.setAccessChainRValue(result);
1860 return false;
1861 }
1862}
1863
John Kessenich433e9ff2017-01-26 20:31:11 -07001864// This path handles both if-then-else and ?:
1865// The if-then-else has a node type of void, while
1866// ?: has either a void or a non-void node type
1867//
1868// Leaving the result, when not void:
1869// GLSL only has r-values as the result of a :?, but
1870// if we have an l-value, that can be more efficient if it will
1871// become the base of a complex r-value expression, because the
1872// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001873bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1874{
John Kessenich433e9ff2017-01-26 20:31:11 -07001875 // See if it simple and safe to generate OpSelect instead of using control flow.
1876 // Crucially, side effects must be avoided, and there are performance trade-offs.
1877 // Return true if good idea (and safe) for OpSelect, false otherwise.
1878 const auto selectPolicy = [&]() -> bool {
John Kessenich04794372017-03-01 13:49:11 -07001879 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
1880 node->getBasicType() == glslang::EbtVoid)
John Kessenich433e9ff2017-01-26 20:31:11 -07001881 return false;
1882
1883 if (node->getTrueBlock() == nullptr ||
1884 node->getFalseBlock() == nullptr)
1885 return false;
1886
1887 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
1888 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
1889
1890 // return true if a single operand to ? : is okay for OpSelect
1891 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001892 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07001893 };
1894
1895 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
1896 operandOkay(node->getFalseBlock()->getAsTyped());
1897 };
1898
1899 // Emit OpSelect for this selection.
1900 const auto handleAsOpSelect = [&]() {
1901 node->getCondition()->traverse(this);
1902 spv::Id condition = accessChainLoad(node->getCondition()->getType());
1903 node->getTrueBlock()->traverse(this);
1904 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1905 node->getFalseBlock()->traverse(this);
1906 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1907
John Kesseniche485c7a2017-05-31 18:50:53 -06001908 builder.setLine(node->getLoc().line);
1909
John Kesseniche434ad92017-03-30 10:09:28 -06001910 // smear condition to vector, if necessary (AST is always scalar)
1911 if (builder.isVector(trueValue))
1912 condition = builder.smearScalar(spv::NoPrecision, condition,
1913 builder.makeVectorType(builder.makeBoolType(),
1914 builder.getNumComponents(trueValue)));
1915
1916 spv::Id select = builder.createTriOp(spv::OpSelect,
1917 convertGlslangToSpvType(node->getType()), condition,
1918 trueValue, falseValue);
John Kessenich433e9ff2017-01-26 20:31:11 -07001919 builder.clearAccessChain();
1920 builder.setAccessChainRValue(select);
1921 };
1922
1923 // Try for OpSelect
1924
1925 if (selectPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001926 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1927 if (node->getType().getQualifier().isSpecConstant())
1928 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1929
John Kessenich433e9ff2017-01-26 20:31:11 -07001930 handleAsOpSelect();
1931 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001932 }
1933
John Kessenich433e9ff2017-01-26 20:31:11 -07001934 // Instead, emit control flow...
1935
1936 // Don't handle results as temporaries, because there will be two names
1937 // and better to leave SSA to later passes.
1938 spv::Id result = (node->getBasicType() == glslang::EbtVoid)
1939 ? spv::NoResult
1940 : builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1941
John Kessenich140f3df2015-06-26 16:58:36 -06001942 // emit the condition before doing anything with selection
1943 node->getCondition()->traverse(this);
1944
1945 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001946 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001947
John Kessenich433e9ff2017-01-26 20:31:11 -07001948 // emit the "then" statement
1949 if (node->getTrueBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001950 node->getTrueBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001951 if (result != spv::NoResult)
1952 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001953 }
1954
John Kessenich433e9ff2017-01-26 20:31:11 -07001955 if (node->getFalseBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001956 ifBuilder.makeBeginElse();
1957 // emit the "else" statement
1958 node->getFalseBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001959 if (result != spv::NoResult)
John Kessenich32cfd492016-02-02 12:37:46 -07001960 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001961 }
1962
John Kessenich433e9ff2017-01-26 20:31:11 -07001963 // finish off the control flow
John Kessenich140f3df2015-06-26 16:58:36 -06001964 ifBuilder.makeEndIf();
1965
John Kessenich433e9ff2017-01-26 20:31:11 -07001966 if (result != spv::NoResult) {
John Kessenich140f3df2015-06-26 16:58:36 -06001967 // GLSL only has r-values as the result of a :?, but
1968 // if we have an l-value, that can be more efficient if it will
1969 // become the base of a complex r-value expression, because the
1970 // next layer copies r-values into memory to use the access-chain mechanism
1971 builder.clearAccessChain();
1972 builder.setAccessChainLValue(result);
1973 }
1974
1975 return false;
1976}
1977
1978bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1979{
1980 // emit and get the condition before doing anything with switch
1981 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001982 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001983
1984 // browse the children to sort out code segments
1985 int defaultSegment = -1;
1986 std::vector<TIntermNode*> codeSegments;
1987 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1988 std::vector<int> caseValues;
1989 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1990 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1991 TIntermNode* child = *c;
1992 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001993 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001994 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001995 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001996 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1997 } else
1998 codeSegments.push_back(child);
1999 }
2000
qining25262b32016-05-06 17:25:16 -04002001 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002002 // statements between the last case and the end of the switch statement
2003 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2004 (int)codeSegments.size() == defaultSegment)
2005 codeSegments.push_back(nullptr);
2006
2007 // make the switch statement
2008 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02002009 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002010
2011 // emit all the code in the segments
2012 breakForLoop.push(false);
2013 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2014 builder.nextSwitchSegment(segmentBlocks, s);
2015 if (codeSegments[s])
2016 codeSegments[s]->traverse(this);
2017 else
2018 builder.addSwitchBreak();
2019 }
2020 breakForLoop.pop();
2021
2022 builder.endSwitch(segmentBlocks);
2023
2024 return false;
2025}
2026
2027void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2028{
2029 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002030 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002031
2032 builder.clearAccessChain();
2033 builder.setAccessChainRValue(constant);
2034}
2035
2036bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2037{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002038 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002039 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002040
2041 // Loop control:
2042 const spv::LoopControlMask control = TranslateLoopControl(node->getLoopControl());
2043
2044 // TODO: dependency length
2045
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002046 // Spec requires back edges to target header blocks, and every header block
2047 // must dominate its merge block. Make a header block first to ensure these
2048 // conditions are met. By definition, it will contain OpLoopMerge, followed
2049 // by a block-ending branch. But we don't want to put any other body/test
2050 // instructions in it, since the body/test may have arbitrary instructions,
2051 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002052 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002053 builder.setBuildPoint(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002054 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002055 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002056 spv::Block& test = builder.makeNewBlock();
2057 builder.createBranch(&test);
2058
2059 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002060 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002061 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002062 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2063
2064 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002065 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002066 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002067 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002068 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002069 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002070
2071 builder.setBuildPoint(&blocks.continue_target);
2072 if (node->getTerminal())
2073 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002074 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002075 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002076 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002077 builder.createBranch(&blocks.body);
2078
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002079 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002080 builder.setBuildPoint(&blocks.body);
2081 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002082 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002083 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002084 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002085
2086 builder.setBuildPoint(&blocks.continue_target);
2087 if (node->getTerminal())
2088 node->getTerminal()->traverse(this);
2089 if (node->getTest()) {
2090 node->getTest()->traverse(this);
2091 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002092 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002093 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002094 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002095 // TODO: unless there was a break/return/discard instruction
2096 // somewhere in the body, this is an infinite loop, so we should
2097 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002098 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002099 }
John Kessenich140f3df2015-06-26 16:58:36 -06002100 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002101 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002102 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002103 return false;
2104}
2105
2106bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2107{
2108 if (node->getExpression())
2109 node->getExpression()->traverse(this);
2110
John Kesseniche485c7a2017-05-31 18:50:53 -06002111 builder.setLine(node->getLoc().line);
2112
John Kessenich140f3df2015-06-26 16:58:36 -06002113 switch (node->getFlowOp()) {
2114 case glslang::EOpKill:
2115 builder.makeDiscard();
2116 break;
2117 case glslang::EOpBreak:
2118 if (breakForLoop.top())
2119 builder.createLoopExit();
2120 else
2121 builder.addSwitchBreak();
2122 break;
2123 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002124 builder.createLoopContinue();
2125 break;
2126 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002127 if (node->getExpression()) {
2128 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2129 spv::Id returnId = accessChainLoad(glslangReturnType);
2130 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2131 builder.clearAccessChain();
2132 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2133 builder.setAccessChainLValue(copyId);
2134 multiTypeStore(glslangReturnType, returnId);
2135 returnId = builder.createLoad(copyId);
2136 }
2137 builder.makeReturn(false, returnId);
2138 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002139 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002140
2141 builder.clearAccessChain();
2142 break;
2143
2144 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002145 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002146 break;
2147 }
2148
2149 return false;
2150}
2151
2152spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2153{
qining25262b32016-05-06 17:25:16 -04002154 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002155 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002156 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002157 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002158 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002159 }
2160
2161 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002162 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002163 spv::Id spvType = convertGlslangToSpvType(node->getType());
2164
Rex Xuf89ad982017-04-07 23:22:33 +08002165#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08002166 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2167 node->getType().containsBasicType(glslang::EbtInt16) ||
2168 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002169 if (contains16BitType) {
2170 if (storageClass == spv::StorageClassInput || storageClass == spv::StorageClassOutput) {
2171 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2172 builder.addCapability(spv::CapabilityStorageInputOutput16);
2173 } else if (storageClass == spv::StorageClassPushConstant) {
2174 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2175 builder.addCapability(spv::CapabilityStoragePushConstant16);
2176 } else if (storageClass == spv::StorageClassUniform) {
2177 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2178 builder.addCapability(spv::CapabilityStorageUniform16);
2179 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2180 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2181 }
2182 }
2183#endif
2184
John Kessenich140f3df2015-06-26 16:58:36 -06002185 const char* name = node->getName().c_str();
2186 if (glslang::IsAnonymous(name))
2187 name = "";
2188
2189 return builder.createVariable(storageClass, spvType, name);
2190}
2191
2192// Return type Id of the sampled type.
2193spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2194{
2195 switch (sampler.type) {
2196 case glslang::EbtFloat: return builder.makeFloatType(32);
2197 case glslang::EbtInt: return builder.makeIntType(32);
2198 case glslang::EbtUint: return builder.makeUintType(32);
2199 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002200 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002201 return builder.makeFloatType(32);
2202 }
2203}
2204
John Kessenich8c8505c2016-07-26 12:50:38 -06002205// If node is a swizzle operation, return the type that should be used if
2206// the swizzle base is first consumed by another operation, before the swizzle
2207// is applied.
2208spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2209{
John Kessenichecba76f2017-01-06 00:34:48 -07002210 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002211 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2212 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2213 else
2214 return spv::NoType;
2215}
2216
2217// When inverting a swizzle with a parent op, this function
2218// will apply the swizzle operation to a completed parent operation.
2219spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2220{
2221 std::vector<unsigned> swizzle;
2222 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2223 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2224}
2225
John Kessenich8c8505c2016-07-26 12:50:38 -06002226// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2227void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2228{
2229 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2230 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2231 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2232}
2233
John Kessenich3ac051e2015-12-20 11:29:16 -07002234// Convert from a glslang type to an SPV type, by calling into a
2235// recursive version of this function. This establishes the inherited
2236// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002237spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2238{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002239 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002240}
2241
2242// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002243// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002244// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002245spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002246{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002247 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002248
2249 switch (type.getBasicType()) {
2250 case glslang::EbtVoid:
2251 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002252 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002253 break;
2254 case glslang::EbtFloat:
2255 spvType = builder.makeFloatType(32);
2256 break;
2257 case glslang::EbtDouble:
2258 spvType = builder.makeFloatType(64);
2259 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002260#ifdef AMD_EXTENSIONS
2261 case glslang::EbtFloat16:
2262 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002263 spvType = builder.makeFloatType(16);
2264 break;
2265#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002266 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002267 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2268 // a 32-bit int where non-0 means true.
2269 if (explicitLayout != glslang::ElpNone)
2270 spvType = builder.makeUintType(32);
2271 else
2272 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002273 break;
2274 case glslang::EbtInt:
2275 spvType = builder.makeIntType(32);
2276 break;
2277 case glslang::EbtUint:
2278 spvType = builder.makeUintType(32);
2279 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002280 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002281 spvType = builder.makeIntType(64);
2282 break;
2283 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002284 spvType = builder.makeUintType(64);
2285 break;
Rex Xucabbb782017-03-24 13:41:14 +08002286#ifdef AMD_EXTENSIONS
2287 case glslang::EbtInt16:
2288 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2289 spvType = builder.makeIntType(16);
2290 break;
2291 case glslang::EbtUint16:
2292 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2293 spvType = builder.makeUintType(16);
2294 break;
2295#endif
John Kessenich426394d2015-07-23 10:22:48 -06002296 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002297 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002298 spvType = builder.makeUintType(32);
2299 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002300 case glslang::EbtSampler:
2301 {
2302 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002303 if (sampler.sampler) {
2304 // pure sampler
2305 spvType = builder.makeSamplerType();
2306 } else {
2307 // an image is present, make its type
2308 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2309 sampler.image ? 2 : 1, TranslateImageFormat(type));
2310 if (sampler.combined) {
2311 // already has both image and sampler, make the combined type
2312 spvType = builder.makeSampledImageType(spvType);
2313 }
John Kessenich55e7d112015-11-15 21:33:39 -07002314 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002315 }
John Kessenich140f3df2015-06-26 16:58:36 -06002316 break;
2317 case glslang::EbtStruct:
2318 case glslang::EbtBlock:
2319 {
2320 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002321 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002322
2323 // Try to share structs for different layouts, but not yet for other
2324 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002325 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002326 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002327 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002328 break;
2329
2330 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002331 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002332 memberRemapper[glslangMembers].resize(glslangMembers->size());
2333 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002334 }
2335 break;
2336 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002337 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002338 break;
2339 }
2340
2341 if (type.isMatrix())
2342 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2343 else {
2344 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2345 if (type.getVectorSize() > 1)
2346 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2347 }
2348
2349 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002350 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2351
John Kessenichc9a80832015-09-12 12:17:44 -06002352 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002353 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002354 // We need to decorate array strides for types needing explicit layout, except blocks.
2355 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002356 // Use a dummy glslang type for querying internal strides of
2357 // arrays of arrays, but using just a one-dimensional array.
2358 glslang::TType simpleArrayType(type, 0); // deference type of the array
2359 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2360 simpleArrayType.getArraySizes().dereference();
2361
2362 // Will compute the higher-order strides here, rather than making a whole
2363 // pile of types and doing repetitive recursion on their contents.
2364 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2365 }
John Kessenichf8842e52016-01-04 19:22:56 -07002366
2367 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002368 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002369 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002370 if (stride > 0)
2371 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002372 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002373 }
2374 } else {
2375 // single-dimensional array, and don't yet have stride
2376
John Kessenichf8842e52016-01-04 19:22:56 -07002377 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002378 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2379 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002380 }
John Kessenich31ed4832015-09-09 17:51:38 -06002381
John Kessenichc9a80832015-09-12 12:17:44 -06002382 // Do the outer dimension, which might not be known for a runtime-sized array
2383 if (type.isRuntimeSizedArray()) {
2384 spvType = builder.makeRuntimeArray(spvType);
2385 } else {
2386 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002387 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002388 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002389 if (stride > 0)
2390 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002391 }
2392
2393 return spvType;
2394}
2395
John Kessenich0e737842017-03-24 18:38:16 -06002396// TODO: this functionality should exist at a higher level, in creating the AST
2397//
2398// Identify interface members that don't have their required extension turned on.
2399//
2400bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2401{
2402 auto& extensions = glslangIntermediate->getRequestedExtensions();
2403
Rex Xubcf291a2017-03-29 23:01:36 +08002404 if (member.getFieldName() == "gl_ViewportMask" &&
2405 extensions.find("GL_NV_viewport_array2") == extensions.end())
2406 return true;
2407 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2408 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2409 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002410 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2411 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2412 return true;
2413 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2414 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2415 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002416 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2417 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2418 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002419
2420 return false;
2421};
2422
John Kessenich6090df02016-06-30 21:18:02 -06002423// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2424// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2425// Mutually recursive with convertGlslangToSpvType().
2426spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2427 const glslang::TTypeList* glslangMembers,
2428 glslang::TLayoutPacking explicitLayout,
2429 const glslang::TQualifier& qualifier)
2430{
2431 // Create a vector of struct types for SPIR-V to consume
2432 std::vector<spv::Id> spvMembers;
2433 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
2434 int locationOffset = 0; // for use across struct members, when they are called recursively
2435 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2436 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2437 if (glslangMember.hiddenMember()) {
2438 ++memberDelta;
2439 if (type.getBasicType() == glslang::EbtBlock)
2440 memberRemapper[glslangMembers][i] = -1;
2441 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002442 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002443 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002444 if (filterMember(glslangMember))
2445 continue;
2446 }
John Kessenich6090df02016-06-30 21:18:02 -06002447 // modify just this child's view of the qualifier
2448 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2449 InheritQualifiers(memberQualifier, qualifier);
2450
2451 // manually inherit location; it's more complex
2452 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
2453 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
2454 if (qualifier.hasLocation())
2455 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2456
2457 // recurse
2458 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2459 }
2460 }
2461
2462 // Make the SPIR-V type
2463 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002464 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002465 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2466
2467 // Decorate it
2468 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2469
2470 return spvType;
2471}
2472
2473void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2474 const glslang::TTypeList* glslangMembers,
2475 glslang::TLayoutPacking explicitLayout,
2476 const glslang::TQualifier& qualifier,
2477 spv::Id spvType)
2478{
2479 // Name and decorate the non-hidden members
2480 int offset = -1;
2481 int locationOffset = 0; // for use within the members of this struct
2482 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2483 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2484 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002485 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002486 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002487 if (filterMember(glslangMember))
2488 continue;
2489 }
John Kessenich6090df02016-06-30 21:18:02 -06002490
2491 // modify just this child's view of the qualifier
2492 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2493 InheritQualifiers(memberQualifier, qualifier);
2494
2495 // using -1 above to indicate a hidden member
2496 if (member >= 0) {
2497 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2498 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2499 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2500 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002501 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2502 type.getQualifier().storage == glslang::EvqVaryingOut) {
2503 if (type.getBasicType() == glslang::EbtBlock ||
2504 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002505 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2506 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2507 }
2508 }
2509 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2510
2511 if (qualifier.storage == glslang::EvqBuffer) {
2512 std::vector<spv::Decoration> memory;
2513 TranslateMemoryDecoration(memberQualifier, memory);
2514 for (unsigned int i = 0; i < memory.size(); ++i)
2515 addMemberDecoration(spvType, member, memory[i]);
2516 }
2517
John Kessenich2f47bc92016-06-30 21:47:35 -06002518 // Compute location decoration; tricky based on whether inheritance is at play and
2519 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002520 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2521 // probably move to the linker stage of the front end proper, and just have the
2522 // answer sitting already distributed throughout the individual member locations.
2523 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002524 // Ignore member locations if the container is an array, as that's
2525 // ill-specified and decisions have been made to not allow this anyway.
2526 // The object itself must have a location, and that comes out from decorating the object,
2527 // not the type (this code decorates types).
2528 if (! type.isArray()) {
2529 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2530 // struct members should not have explicit locations
2531 assert(type.getBasicType() != glslang::EbtStruct);
2532 location = memberQualifier.layoutLocation;
2533 } else if (type.getBasicType() != glslang::EbtBlock) {
2534 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2535 // The members, and their nested types, must not themselves have Location decorations.
2536 } else if (qualifier.hasLocation()) // inheritance
2537 location = qualifier.layoutLocation + locationOffset;
2538 }
John Kessenich6090df02016-06-30 21:18:02 -06002539 if (location >= 0)
2540 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2541
John Kessenich2f47bc92016-06-30 21:47:35 -06002542 if (qualifier.hasLocation()) // track for upcoming inheritance
2543 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2544
John Kessenich6090df02016-06-30 21:18:02 -06002545 // component, XFB, others
2546 if (glslangMember.getQualifier().hasComponent())
2547 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2548 if (glslangMember.getQualifier().hasXfbOffset())
2549 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2550 else if (explicitLayout != glslang::ElpNone) {
2551 // figure out what to do with offset, which is accumulating
2552 int nextOffset;
2553 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2554 if (offset >= 0)
2555 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2556 offset = nextOffset;
2557 }
2558
2559 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2560 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2561
2562 // built-in variable decorations
2563 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002564 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002565 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002566
2567#ifdef NV_EXTENSIONS
2568 if (builtIn == spv::BuiltInLayer) {
2569 // SPV_NV_viewport_array2 extension
2570 if (glslangMember.getQualifier().layoutViewportRelative){
2571 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2572 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2573 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2574 }
2575 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2576 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2577 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2578 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2579 }
2580 }
chaocdf3956c2017-02-14 14:52:34 -08002581 if (glslangMember.getQualifier().layoutPassthrough) {
2582 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2583 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2584 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2585 }
chaoc771d89f2017-01-13 01:10:53 -08002586#endif
John Kessenich6090df02016-06-30 21:18:02 -06002587 }
2588 }
2589
2590 // Decorate the structure
2591 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich67027182017-04-19 18:34:49 -06002592 addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002593 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2594 builder.addCapability(spv::CapabilityGeometryStreams);
2595 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2596 }
2597 if (glslangIntermediate->getXfbMode()) {
2598 builder.addCapability(spv::CapabilityTransformFeedback);
2599 if (type.getQualifier().hasXfbStride())
2600 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2601 if (type.getQualifier().hasXfbBuffer())
2602 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2603 }
2604}
2605
John Kessenich6c292d32016-02-15 20:58:50 -07002606// Turn the expression forming the array size into an id.
2607// This is not quite trivial, because of specialization constants.
2608// Sometimes, a raw constant is turned into an Id, and sometimes
2609// a specialization constant expression is.
2610spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2611{
2612 // First, see if this is sized with a node, meaning a specialization constant:
2613 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2614 if (specNode != nullptr) {
2615 builder.clearAccessChain();
2616 specNode->traverse(this);
2617 return accessChainLoad(specNode->getAsTyped()->getType());
2618 }
qining25262b32016-05-06 17:25:16 -04002619
John Kessenich6c292d32016-02-15 20:58:50 -07002620 // Otherwise, need a compile-time (front end) size, get it:
2621 int size = arraySizes.getDimSize(dim);
2622 assert(size > 0);
2623 return builder.makeUintConstant(size);
2624}
2625
John Kessenich103bef92016-02-08 21:38:15 -07002626// Wrap the builder's accessChainLoad to:
2627// - localize handling of RelaxedPrecision
2628// - use the SPIR-V inferred type instead of another conversion of the glslang type
2629// (avoids unnecessary work and possible type punning for structures)
2630// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002631spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2632{
John Kessenich103bef92016-02-08 21:38:15 -07002633 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2634 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2635
2636 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002637 if (type.getBasicType() == glslang::EbtBool) {
2638 if (builder.isScalarType(nominalTypeId)) {
2639 // Conversion for bool
2640 spv::Id boolType = builder.makeBoolType();
2641 if (nominalTypeId != boolType)
2642 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2643 } else if (builder.isVectorType(nominalTypeId)) {
2644 // Conversion for bvec
2645 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2646 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2647 if (nominalTypeId != bvecType)
2648 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2649 }
2650 }
John Kessenich103bef92016-02-08 21:38:15 -07002651
2652 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002653}
2654
Rex Xu27253232016-02-23 17:51:09 +08002655// Wrap the builder's accessChainStore to:
2656// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002657//
2658// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002659void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2660{
2661 // Need to convert to abstract types when necessary
2662 if (type.getBasicType() == glslang::EbtBool) {
2663 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2664
2665 if (builder.isScalarType(nominalTypeId)) {
2666 // Conversion for bool
2667 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06002668 if (nominalTypeId != boolType) {
2669 // keep these outside arguments, for determinant order-of-evaluation
2670 spv::Id one = builder.makeUintConstant(1);
2671 spv::Id zero = builder.makeUintConstant(0);
2672 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2673 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06002674 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08002675 } else if (builder.isVectorType(nominalTypeId)) {
2676 // Conversion for bvec
2677 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2678 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06002679 if (nominalTypeId != bvecType) {
2680 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06002681 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2682 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2683 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06002684 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06002685 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
2686 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08002687 }
2688 }
2689
2690 builder.accessChainStore(rvalue);
2691}
2692
John Kessenich4bf71552016-09-02 11:20:21 -06002693// For storing when types match at the glslang level, but not might match at the
2694// SPIR-V level.
2695//
2696// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002697// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002698// as in a member-decorated way.
2699//
2700// NOTE: This function can handle any store request; if it's not special it
2701// simplifies to a simple OpStore.
2702//
2703// Implicitly uses the existing builder.accessChain as the storage target.
2704void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2705{
John Kessenichb3e24e42016-09-11 12:33:43 -06002706 // we only do the complex path here if it's an aggregate
2707 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002708 accessChainStore(type, rValue);
2709 return;
2710 }
2711
John Kessenichb3e24e42016-09-11 12:33:43 -06002712 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002713 spv::Id rType = builder.getTypeId(rValue);
2714 spv::Id lValue = builder.accessChainGetLValue();
2715 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2716 if (lType == rType) {
2717 accessChainStore(type, rValue);
2718 return;
2719 }
2720
John Kessenichb3e24e42016-09-11 12:33:43 -06002721 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002722 // where the two types were the same type in GLSL. This requires member
2723 // by member copy, recursively.
2724
John Kessenichb3e24e42016-09-11 12:33:43 -06002725 // If an array, copy element by element.
2726 if (type.isArray()) {
2727 glslang::TType glslangElementType(type, 0);
2728 spv::Id elementRType = builder.getContainedTypeId(rType);
2729 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2730 // get the source member
2731 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002732
John Kessenichb3e24e42016-09-11 12:33:43 -06002733 // set up the target storage
2734 builder.clearAccessChain();
2735 builder.setAccessChainLValue(lValue);
2736 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002737
John Kessenichb3e24e42016-09-11 12:33:43 -06002738 // store the member
2739 multiTypeStore(glslangElementType, elementRValue);
2740 }
2741 } else {
2742 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002743
John Kessenichb3e24e42016-09-11 12:33:43 -06002744 // loop over structure members
2745 const glslang::TTypeList& members = *type.getStruct();
2746 for (int m = 0; m < (int)members.size(); ++m) {
2747 const glslang::TType& glslangMemberType = *members[m].type;
2748
2749 // get the source member
2750 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2751 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2752
2753 // set up the target storage
2754 builder.clearAccessChain();
2755 builder.setAccessChainLValue(lValue);
2756 builder.accessChainPush(builder.makeIntConstant(m));
2757
2758 // store the member
2759 multiTypeStore(glslangMemberType, memberRValue);
2760 }
John Kessenich4bf71552016-09-02 11:20:21 -06002761 }
2762}
2763
John Kessenichf85e8062015-12-19 13:57:10 -07002764// Decide whether or not this type should be
2765// decorated with offsets and strides, and if so
2766// whether std140 or std430 rules should be applied.
2767glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002768{
John Kessenichf85e8062015-12-19 13:57:10 -07002769 // has to be a block
2770 if (type.getBasicType() != glslang::EbtBlock)
2771 return glslang::ElpNone;
2772
2773 // has to be a uniform or buffer block
2774 if (type.getQualifier().storage != glslang::EvqUniform &&
2775 type.getQualifier().storage != glslang::EvqBuffer)
2776 return glslang::ElpNone;
2777
2778 // return the layout to use
2779 switch (type.getQualifier().layoutPacking) {
2780 case glslang::ElpStd140:
2781 case glslang::ElpStd430:
2782 return type.getQualifier().layoutPacking;
2783 default:
2784 return glslang::ElpNone;
2785 }
John Kessenich31ed4832015-09-09 17:51:38 -06002786}
2787
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002788// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002789int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002790{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002791 int size;
John Kessenich49987892015-12-29 17:11:44 -07002792 int stride;
2793 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002794
2795 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002796}
2797
John Kessenich49987892015-12-29 17:11:44 -07002798// 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 -07002799// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002800int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002801{
John Kessenich49987892015-12-29 17:11:44 -07002802 glslang::TType elementType;
2803 elementType.shallowCopy(matrixType);
2804 elementType.clearArraySizes();
2805
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002806 int size;
John Kessenich49987892015-12-29 17:11:44 -07002807 int stride;
2808 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2809
2810 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002811}
2812
John Kessenich5e4b1242015-08-06 22:53:06 -06002813// Given a member type of a struct, realign the current offset for it, and compute
2814// the next (not yet aligned) offset for the next member, which will get aligned
2815// on the next call.
2816// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2817// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2818// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002819void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002820 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002821{
2822 // this will get a positive value when deemed necessary
2823 nextOffset = -1;
2824
John Kessenich5e4b1242015-08-06 22:53:06 -06002825 // override anything in currentOffset with user-set offset
2826 if (memberType.getQualifier().hasOffset())
2827 currentOffset = memberType.getQualifier().layoutOffset;
2828
2829 // It could be that current linker usage in glslang updated all the layoutOffset,
2830 // in which case the following code does not matter. But, that's not quite right
2831 // once cross-compilation unit GLSL validation is done, as the original user
2832 // settings are needed in layoutOffset, and then the following will come into play.
2833
John Kessenichf85e8062015-12-19 13:57:10 -07002834 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002835 if (! memberType.getQualifier().hasOffset())
2836 currentOffset = -1;
2837
2838 return;
2839 }
2840
John Kessenichf85e8062015-12-19 13:57:10 -07002841 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002842 if (currentOffset < 0)
2843 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002844
John Kessenich5e4b1242015-08-06 22:53:06 -06002845 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2846 // but possibly not yet correctly aligned.
2847
2848 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002849 int dummyStride;
2850 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06002851
2852 // Adjust alignment for HLSL rules
2853 if (glslangIntermediate->usingHlslOFfsets() &&
2854 ! memberType.isArray() && memberType.isVector()) {
2855 int dummySize;
2856 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
2857 if (componentAlignment <= 4)
2858 memberAlignment = componentAlignment;
2859 }
2860
2861 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06002862 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06002863
2864 // Bump up to vec4 if there is a bad straddle
2865 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
2866 glslang::RoundToPow2(currentOffset, 16);
2867
John Kessenich5e4b1242015-08-06 22:53:06 -06002868 nextOffset = currentOffset + memberSize;
2869}
2870
David Netoa901ffe2016-06-08 14:11:40 +01002871void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002872{
David Netoa901ffe2016-06-08 14:11:40 +01002873 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2874 switch (glslangBuiltIn)
2875 {
2876 case glslang::EbvClipDistance:
2877 case glslang::EbvCullDistance:
2878 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08002879#ifdef NV_EXTENSIONS
2880 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +08002881 case glslang::EbvViewportIndex:
chaoc771d89f2017-01-13 01:10:53 -08002882 case glslang::EbvViewportMaskNV:
2883 case glslang::EbvSecondaryPositionNV:
2884 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08002885 case glslang::EbvPositionPerViewNV:
2886 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08002887#endif
David Netoa901ffe2016-06-08 14:11:40 +01002888 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2889 // Alternately, we could just call this for any glslang built-in, since the
2890 // capability already guards against duplicates.
2891 TranslateBuiltInDecoration(glslangBuiltIn, false);
2892 break;
2893 default:
2894 // Capabilities were already generated when the struct was declared.
2895 break;
2896 }
John Kessenichebb50532016-05-16 19:22:05 -06002897}
2898
John Kessenich6fccb3c2016-09-19 16:01:41 -06002899bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002900{
John Kessenicheee9d532016-09-19 18:09:30 -06002901 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002902}
2903
2904// Make all the functions, skeletally, without actually visiting their bodies.
2905void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2906{
2907 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2908 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002909 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002910 continue;
2911
2912 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002913 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002914 //
qining25262b32016-05-06 17:25:16 -04002915 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002916 // function. What it is an address of varies:
2917 //
John Kessenich4bf71552016-09-02 11:20:21 -06002918 // - "in" parameters not marked as "const" can be written to without modifying the calling
2919 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002920 //
2921 // - "const in" parameters can just be the r-value, as no writes need occur.
2922 //
John Kessenich4bf71552016-09-02 11:20:21 -06002923 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2924 // 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 -06002925
2926 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002927 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002928 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2929
John Kessenich37789792017-03-21 23:56:40 -06002930 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() == glslangIntermediate->implicitThisName;
2931
John Kessenich140f3df2015-06-26 16:58:36 -06002932 for (int p = 0; p < (int)parameters.size(); ++p) {
2933 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2934 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenich37789792017-03-21 23:56:40 -06002935 // can we pass by reference?
2936 if (paramType.containsOpaque() || // sampler, etc.
John Kessenich4960baa2017-03-19 18:09:59 -06002937 (paramType.getBasicType() == glslang::EbtBlock &&
John Kessenich37789792017-03-21 23:56:40 -06002938 paramType.getQualifier().storage == glslang::EvqBuffer) || // SSBO
John Kessenichaa3c64c2017-03-28 09:52:38 -06002939 (p == 0 && implicitThis)) // implicit 'this'
John Kessenicha5c5fb62017-05-05 05:09:58 -06002940 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002941 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002942 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2943 else
John Kessenich4bf71552016-09-02 11:20:21 -06002944 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002945 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002946 paramTypes.push_back(typeId);
2947 }
2948
2949 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002950 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2951 convertGlslangToSpvType(glslFunction->getType()),
2952 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06002953 if (implicitThis)
2954 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06002955
2956 // Track function to emit/call later
2957 functionMap[glslFunction->getName().c_str()] = function;
2958
2959 // Set the parameter id's
2960 for (int p = 0; p < (int)parameters.size(); ++p) {
2961 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2962 // give a name too
2963 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2964 }
2965 }
2966}
2967
2968// Process all the initializers, while skipping the functions and link objects
2969void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2970{
2971 builder.setBuildPoint(shaderEntry->getLastBlock());
2972 for (int i = 0; i < (int)initializers.size(); ++i) {
2973 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2974 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2975
2976 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06002977 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06002978 initializer->traverse(this);
2979 }
2980 }
2981}
2982
2983// Process all the functions, while skipping initializers.
2984void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2985{
2986 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2987 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07002988 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06002989 node->traverse(this);
2990 }
2991}
2992
2993void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2994{
qining25262b32016-05-06 17:25:16 -04002995 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002996 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06002997 currentFunction = functionMap[node->getName().c_str()];
2998 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06002999 builder.setBuildPoint(functionBlock);
3000}
3001
Rex Xu04db3f52015-09-16 11:44:02 +08003002void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003003{
Rex Xufc618912015-09-09 16:42:49 +08003004 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003005
3006 glslang::TSampler sampler = {};
3007 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08003008 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003009 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3010 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3011 }
3012
John Kessenich140f3df2015-06-26 16:58:36 -06003013 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3014 builder.clearAccessChain();
3015 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003016
3017 // Special case l-value operands
3018 bool lvalue = false;
3019 switch (node.getOp()) {
3020 case glslang::EOpImageAtomicAdd:
3021 case glslang::EOpImageAtomicMin:
3022 case glslang::EOpImageAtomicMax:
3023 case glslang::EOpImageAtomicAnd:
3024 case glslang::EOpImageAtomicOr:
3025 case glslang::EOpImageAtomicXor:
3026 case glslang::EOpImageAtomicExchange:
3027 case glslang::EOpImageAtomicCompSwap:
3028 if (i == 0)
3029 lvalue = true;
3030 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003031 case glslang::EOpSparseImageLoad:
3032 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3033 lvalue = true;
3034 break;
Rex Xu48edadf2015-12-31 16:11:41 +08003035 case glslang::EOpSparseTexture:
3036 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3037 lvalue = true;
3038 break;
3039 case glslang::EOpSparseTextureClamp:
3040 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3041 lvalue = true;
3042 break;
3043 case glslang::EOpSparseTextureLod:
3044 case glslang::EOpSparseTextureOffset:
3045 if (i == 3)
3046 lvalue = true;
3047 break;
3048 case glslang::EOpSparseTextureFetch:
3049 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3050 lvalue = true;
3051 break;
3052 case glslang::EOpSparseTextureFetchOffset:
3053 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3054 lvalue = true;
3055 break;
3056 case glslang::EOpSparseTextureLodOffset:
3057 case glslang::EOpSparseTextureGrad:
3058 case glslang::EOpSparseTextureOffsetClamp:
3059 if (i == 4)
3060 lvalue = true;
3061 break;
3062 case glslang::EOpSparseTextureGradOffset:
3063 case glslang::EOpSparseTextureGradClamp:
3064 if (i == 5)
3065 lvalue = true;
3066 break;
3067 case glslang::EOpSparseTextureGradOffsetClamp:
3068 if (i == 6)
3069 lvalue = true;
3070 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003071 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003072 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3073 lvalue = true;
3074 break;
3075 case glslang::EOpSparseTextureGatherOffset:
3076 case glslang::EOpSparseTextureGatherOffsets:
3077 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3078 lvalue = true;
3079 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003080#ifdef AMD_EXTENSIONS
3081 case glslang::EOpSparseTextureGatherLod:
3082 if (i == 3)
3083 lvalue = true;
3084 break;
3085 case glslang::EOpSparseTextureGatherLodOffset:
3086 case glslang::EOpSparseTextureGatherLodOffsets:
3087 if (i == 4)
3088 lvalue = true;
3089 break;
3090#endif
Rex Xufc618912015-09-09 16:42:49 +08003091 default:
3092 break;
3093 }
3094
Rex Xu6b86d492015-09-16 17:48:22 +08003095 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003096 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003097 else
John Kessenich32cfd492016-02-02 12:37:46 -07003098 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003099 }
3100}
3101
John Kessenichfc51d282015-08-19 13:34:18 -06003102void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003103{
John Kessenichfc51d282015-08-19 13:34:18 -06003104 builder.clearAccessChain();
3105 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003106 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003107}
John Kessenich140f3df2015-06-26 16:58:36 -06003108
John Kessenichfc51d282015-08-19 13:34:18 -06003109spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3110{
John Kesseniche485c7a2017-05-31 18:50:53 -06003111 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003112 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003113
3114 builder.setLine(node->getLoc().line);
3115
John Kessenich8c8505c2016-07-26 12:50:38 -06003116 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06003117
John Kessenichfc51d282015-08-19 13:34:18 -06003118 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003119 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3120 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
3121 std::vector<spv::Id> arguments;
3122 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003123 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003124 else
3125 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003126 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003127
3128 spv::Builder::TextureParameters params = { };
3129 params.sampler = arguments[0];
3130
Rex Xu04db3f52015-09-16 11:44:02 +08003131 glslang::TCrackedTextureOp cracked;
3132 node->crackTexture(sampler, cracked);
3133
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003134 const bool isUnsignedResult =
3135 node->getType().getBasicType() == glslang::EbtUint64 ||
3136 node->getType().getBasicType() == glslang::EbtUint;
3137
John Kessenichfc51d282015-08-19 13:34:18 -06003138 // Check for queries
3139 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003140 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3141 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003142 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003143
John Kessenichfc51d282015-08-19 13:34:18 -06003144 switch (node->getOp()) {
3145 case glslang::EOpImageQuerySize:
3146 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003147 if (arguments.size() > 1) {
3148 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003149 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003150 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003151 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003152 case glslang::EOpImageQuerySamples:
3153 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003154 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003155 case glslang::EOpTextureQueryLod:
3156 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003157 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003158 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003159 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003160 case glslang::EOpSparseTexelsResident:
3161 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003162 default:
3163 assert(0);
3164 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003165 }
John Kessenich140f3df2015-06-26 16:58:36 -06003166 }
3167
Rex Xufc618912015-09-09 16:42:49 +08003168 // Check for image functions other than queries
3169 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003170 std::vector<spv::Id> operands;
3171 auto opIt = arguments.begin();
3172 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003173
3174 // Handle subpass operations
3175 // TODO: GLSL should change to have the "MS" only on the type rather than the
3176 // built-in function.
3177 if (cracked.subpass) {
3178 // add on the (0,0) coordinate
3179 spv::Id zero = builder.makeIntConstant(0);
3180 std::vector<spv::Id> comps;
3181 comps.push_back(zero);
3182 comps.push_back(zero);
3183 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3184 if (sampler.ms) {
3185 operands.push_back(spv::ImageOperandsSampleMask);
3186 operands.push_back(*(opIt++));
3187 }
John Kessenich8c8505c2016-07-26 12:50:38 -06003188 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07003189 }
3190
John Kessenich56bab042015-09-16 10:54:31 -06003191 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06003192 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07003193 if (sampler.ms) {
3194 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003195 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07003196 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003197 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3198 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06003199 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06003200 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08003201 if (sampler.ms) {
3202 operands.push_back(*(opIt + 1));
3203 operands.push_back(spv::ImageOperandsSampleMask);
3204 operands.push_back(*opIt);
3205 } else
3206 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003207 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003208 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3209 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003210 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08003211 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
3212 builder.addCapability(spv::CapabilitySparseResidency);
3213 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3214 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3215
3216 if (sampler.ms) {
3217 operands.push_back(spv::ImageOperandsSampleMask);
3218 operands.push_back(*opIt++);
3219 }
3220
3221 // Create the return type that was a special structure
3222 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003223 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003224 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3225 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3226
3227 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3228
3229 // Decode the return type
3230 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3231 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003232 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003233 // Process image atomic operations
3234
3235 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3236 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003237 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003238
John Kessenich8c8505c2016-07-26 12:50:38 -06003239 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003240 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003241
3242 std::vector<spv::Id> operands;
3243 operands.push_back(pointer);
3244 for (; opIt != arguments.end(); ++opIt)
3245 operands.push_back(*opIt);
3246
John Kessenich8c8505c2016-07-26 12:50:38 -06003247 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003248 }
3249 }
3250
3251 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003252 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003253 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3254
John Kessenichfc51d282015-08-19 13:34:18 -06003255 // check for bias argument
3256 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08003257#ifdef AMD_EXTENSIONS
3258 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
3259#else
Rex Xu71519fe2015-11-11 15:35:47 +08003260 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08003261#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003262 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08003263#ifdef AMD_EXTENSIONS
3264 if (cracked.gather)
3265 ++nonBiasArgCount; // comp argument should be present when bias argument is present
3266#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003267 if (cracked.offset)
3268 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003269#ifdef AMD_EXTENSIONS
3270 else if (cracked.offsets)
3271 ++nonBiasArgCount;
3272#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003273 if (cracked.grad)
3274 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003275 if (cracked.lodClamp)
3276 ++nonBiasArgCount;
3277 if (sparse)
3278 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003279
3280 if ((int)arguments.size() > nonBiasArgCount)
3281 bias = true;
3282 }
3283
John Kessenicha5c33d62016-06-02 23:45:21 -06003284 // See if the sampler param should really be just the SPV image part
3285 if (cracked.fetch) {
3286 // a fetch needs to have the image extracted first
3287 if (builder.isSampledImage(params.sampler))
3288 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3289 }
3290
Rex Xu225e0fc2016-11-17 17:47:59 +08003291#ifdef AMD_EXTENSIONS
3292 if (cracked.gather) {
3293 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
3294 if (bias || cracked.lod ||
3295 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
3296 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08003297 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08003298 }
3299 }
3300#endif
3301
John Kessenichfc51d282015-08-19 13:34:18 -06003302 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003303
John Kessenichfc51d282015-08-19 13:34:18 -06003304 params.coords = arguments[1];
3305 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003306 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003307
3308 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003309 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003310 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003311 ++extraArgs;
3312 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003313 params.Dref = arguments[2];
3314 ++extraArgs;
3315 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003316 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003317 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003318 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003319 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003320 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003321 dRefComp = builder.getNumComponents(params.coords) - 1;
3322 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003323 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3324 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003325
3326 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003327 if (cracked.lod) {
3328 params.lod = arguments[2];
3329 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003330 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3331 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3332 noImplicitLod = true;
3333 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003334
3335 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003336 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08003337 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003338 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003339 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003340
3341 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003342 if (cracked.grad) {
3343 params.gradX = arguments[2 + extraArgs];
3344 params.gradY = arguments[3 + extraArgs];
3345 extraArgs += 2;
3346 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003347
3348 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003349 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003350 params.offset = arguments[2 + extraArgs];
3351 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003352 } else if (cracked.offsets) {
3353 params.offsets = arguments[2 + extraArgs];
3354 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003355 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003356
3357 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003358 if (cracked.lodClamp) {
3359 params.lodClamp = arguments[2 + extraArgs];
3360 ++extraArgs;
3361 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003362
3363 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003364 if (sparse) {
3365 params.texelOut = arguments[2 + extraArgs];
3366 ++extraArgs;
3367 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003368
John Kessenich76d4dfc2016-06-16 12:43:23 -06003369 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003370 if (cracked.gather && ! sampler.shadow) {
3371 // default component is 0, if missing, otherwise an argument
3372 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003373 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003374 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08003375 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003376 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08003377 }
3378
3379 // bias
3380 if (bias) {
3381 params.bias = arguments[2 + extraArgs];
3382 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003383 }
John Kessenichfc51d282015-08-19 13:34:18 -06003384
John Kessenich65336482016-06-16 14:06:26 -06003385 // projective component (might not to move)
3386 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3387 // are divided by the last component of P."
3388 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3389 // unused components will appear after all used components."
3390 if (cracked.proj) {
3391 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3392 int projTargetComp;
3393 switch (sampler.dim) {
3394 case glslang::Esd1D: projTargetComp = 1; break;
3395 case glslang::Esd2D: projTargetComp = 2; break;
3396 case glslang::EsdRect: projTargetComp = 2; break;
3397 default: projTargetComp = projSourceComp; break;
3398 }
3399 // copy the projective coordinate if we have to
3400 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003401 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003402 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3403 projSourceComp);
3404 params.coords = builder.createCompositeInsert(projComp, params.coords,
3405 builder.getTypeId(params.coords), projTargetComp);
3406 }
3407 }
3408
John Kessenich8c8505c2016-07-26 12:50:38 -06003409 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003410}
3411
3412spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3413{
3414 // Grab the function's pointer from the previously created function
3415 spv::Function* function = functionMap[node->getName().c_str()];
3416 if (! function)
3417 return 0;
3418
3419 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3420 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3421
3422 // See comments in makeFunctions() for details about the semantics for parameter passing.
3423 //
3424 // These imply we need a four step process:
3425 // 1. Evaluate the arguments
3426 // 2. Allocate and make copies of in, out, and inout arguments
3427 // 3. Make the call
3428 // 4. Copy back the results
3429
3430 // 1. Evaluate the arguments
3431 std::vector<spv::Builder::AccessChain> lValues;
3432 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003433 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003434 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003435 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003436 // build l-value
3437 builder.clearAccessChain();
3438 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003439 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06003440 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
John Kessenich4a57dce2017-02-24 19:15:46 -07003441 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.containsOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06003442 // save l-value
3443 lValues.push_back(builder.getAccessChain());
3444 } else {
3445 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003446 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003447 }
3448 }
3449
3450 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3451 // copy the original into that space.
3452 //
3453 // Also, build up the list of actual arguments to pass in for the call
3454 int lValueCount = 0;
3455 int rValueCount = 0;
3456 std::vector<spv::Id> spvArgs;
3457 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003458 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003459 spv::Id arg;
steve-lunargdd8287a2017-02-23 18:04:12 -07003460 if (paramType.containsOpaque() ||
John Kessenich37789792017-03-21 23:56:40 -06003461 (paramType.getBasicType() == glslang::EbtBlock && qualifiers[a] == glslang::EvqBuffer) ||
3462 (a == 0 && function->hasImplicitThis())) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003463 builder.setAccessChain(lValues[lValueCount]);
3464 arg = builder.accessChainGetLValue();
3465 ++lValueCount;
3466 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06003467 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003468 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3469 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3470 // need to copy the input into output space
3471 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003472 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003473 builder.clearAccessChain();
3474 builder.setAccessChainLValue(arg);
3475 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003476 }
3477 ++lValueCount;
3478 } else {
3479 arg = rValues[rValueCount];
3480 ++rValueCount;
3481 }
3482 spvArgs.push_back(arg);
3483 }
3484
3485 // 3. Make the call.
3486 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003487 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003488
3489 // 4. Copy back out an "out" arguments.
3490 lValueCount = 0;
3491 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003492 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003493 if (qualifiers[a] != glslang::EvqConstReadOnly) {
3494 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3495 spv::Id copy = builder.createLoad(spvArgs[a]);
3496 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003497 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003498 }
3499 ++lValueCount;
3500 }
3501 }
3502
3503 return result;
3504}
3505
3506// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003507spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3508 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003509 spv::Id typeId, spv::Id left, spv::Id right,
3510 glslang::TBasicType typeProxy, bool reduceComparison)
3511{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003512#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08003513 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003514 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3515#else
Rex Xucabbb782017-03-24 13:41:14 +08003516 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06003517 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003518#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003519 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003520
3521 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003522 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003523 bool comparison = false;
3524
3525 switch (op) {
3526 case glslang::EOpAdd:
3527 case glslang::EOpAddAssign:
3528 if (isFloat)
3529 binOp = spv::OpFAdd;
3530 else
3531 binOp = spv::OpIAdd;
3532 break;
3533 case glslang::EOpSub:
3534 case glslang::EOpSubAssign:
3535 if (isFloat)
3536 binOp = spv::OpFSub;
3537 else
3538 binOp = spv::OpISub;
3539 break;
3540 case glslang::EOpMul:
3541 case glslang::EOpMulAssign:
3542 if (isFloat)
3543 binOp = spv::OpFMul;
3544 else
3545 binOp = spv::OpIMul;
3546 break;
3547 case glslang::EOpVectorTimesScalar:
3548 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003549 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003550 if (builder.isVector(right))
3551 std::swap(left, right);
3552 assert(builder.isScalar(right));
3553 needMatchingVectors = false;
3554 binOp = spv::OpVectorTimesScalar;
3555 } else
3556 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003557 break;
3558 case glslang::EOpVectorTimesMatrix:
3559 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003560 binOp = spv::OpVectorTimesMatrix;
3561 break;
3562 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003563 binOp = spv::OpMatrixTimesVector;
3564 break;
3565 case glslang::EOpMatrixTimesScalar:
3566 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003567 binOp = spv::OpMatrixTimesScalar;
3568 break;
3569 case glslang::EOpMatrixTimesMatrix:
3570 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003571 binOp = spv::OpMatrixTimesMatrix;
3572 break;
3573 case glslang::EOpOuterProduct:
3574 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003575 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003576 break;
3577
3578 case glslang::EOpDiv:
3579 case glslang::EOpDivAssign:
3580 if (isFloat)
3581 binOp = spv::OpFDiv;
3582 else if (isUnsigned)
3583 binOp = spv::OpUDiv;
3584 else
3585 binOp = spv::OpSDiv;
3586 break;
3587 case glslang::EOpMod:
3588 case glslang::EOpModAssign:
3589 if (isFloat)
3590 binOp = spv::OpFMod;
3591 else if (isUnsigned)
3592 binOp = spv::OpUMod;
3593 else
3594 binOp = spv::OpSMod;
3595 break;
3596 case glslang::EOpRightShift:
3597 case glslang::EOpRightShiftAssign:
3598 if (isUnsigned)
3599 binOp = spv::OpShiftRightLogical;
3600 else
3601 binOp = spv::OpShiftRightArithmetic;
3602 break;
3603 case glslang::EOpLeftShift:
3604 case glslang::EOpLeftShiftAssign:
3605 binOp = spv::OpShiftLeftLogical;
3606 break;
3607 case glslang::EOpAnd:
3608 case glslang::EOpAndAssign:
3609 binOp = spv::OpBitwiseAnd;
3610 break;
3611 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003612 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003613 binOp = spv::OpLogicalAnd;
3614 break;
3615 case glslang::EOpInclusiveOr:
3616 case glslang::EOpInclusiveOrAssign:
3617 binOp = spv::OpBitwiseOr;
3618 break;
3619 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003620 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003621 binOp = spv::OpLogicalOr;
3622 break;
3623 case glslang::EOpExclusiveOr:
3624 case glslang::EOpExclusiveOrAssign:
3625 binOp = spv::OpBitwiseXor;
3626 break;
3627 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003628 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003629 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003630 break;
3631
3632 case glslang::EOpLessThan:
3633 case glslang::EOpGreaterThan:
3634 case glslang::EOpLessThanEqual:
3635 case glslang::EOpGreaterThanEqual:
3636 case glslang::EOpEqual:
3637 case glslang::EOpNotEqual:
3638 case glslang::EOpVectorEqual:
3639 case glslang::EOpVectorNotEqual:
3640 comparison = true;
3641 break;
3642 default:
3643 break;
3644 }
3645
John Kessenich7c1aa102015-10-15 13:29:11 -06003646 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003647 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003648 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003649 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003650 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003651
3652 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003653 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003654 builder.promoteScalar(precision, left, right);
3655
qining25262b32016-05-06 17:25:16 -04003656 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3657 addDecoration(result, noContraction);
3658 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003659 }
3660
3661 if (! comparison)
3662 return 0;
3663
John Kessenich7c1aa102015-10-15 13:29:11 -06003664 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003665
John Kessenich4583b612016-08-07 19:14:22 -06003666 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3667 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003668 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003669
3670 switch (op) {
3671 case glslang::EOpLessThan:
3672 if (isFloat)
3673 binOp = spv::OpFOrdLessThan;
3674 else if (isUnsigned)
3675 binOp = spv::OpULessThan;
3676 else
3677 binOp = spv::OpSLessThan;
3678 break;
3679 case glslang::EOpGreaterThan:
3680 if (isFloat)
3681 binOp = spv::OpFOrdGreaterThan;
3682 else if (isUnsigned)
3683 binOp = spv::OpUGreaterThan;
3684 else
3685 binOp = spv::OpSGreaterThan;
3686 break;
3687 case glslang::EOpLessThanEqual:
3688 if (isFloat)
3689 binOp = spv::OpFOrdLessThanEqual;
3690 else if (isUnsigned)
3691 binOp = spv::OpULessThanEqual;
3692 else
3693 binOp = spv::OpSLessThanEqual;
3694 break;
3695 case glslang::EOpGreaterThanEqual:
3696 if (isFloat)
3697 binOp = spv::OpFOrdGreaterThanEqual;
3698 else if (isUnsigned)
3699 binOp = spv::OpUGreaterThanEqual;
3700 else
3701 binOp = spv::OpSGreaterThanEqual;
3702 break;
3703 case glslang::EOpEqual:
3704 case glslang::EOpVectorEqual:
3705 if (isFloat)
3706 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003707 else if (isBool)
3708 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003709 else
3710 binOp = spv::OpIEqual;
3711 break;
3712 case glslang::EOpNotEqual:
3713 case glslang::EOpVectorNotEqual:
3714 if (isFloat)
3715 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003716 else if (isBool)
3717 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003718 else
3719 binOp = spv::OpINotEqual;
3720 break;
3721 default:
3722 break;
3723 }
3724
qining25262b32016-05-06 17:25:16 -04003725 if (binOp != spv::OpNop) {
3726 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3727 addDecoration(result, noContraction);
3728 return builder.setPrecision(result, precision);
3729 }
John Kessenich140f3df2015-06-26 16:58:36 -06003730
3731 return 0;
3732}
3733
John Kessenich04bb8a02015-12-12 12:28:14 -07003734//
3735// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3736// These can be any of:
3737//
3738// matrix * scalar
3739// scalar * matrix
3740// matrix * matrix linear algebraic
3741// matrix * vector
3742// vector * matrix
3743// matrix * matrix componentwise
3744// matrix op matrix op in {+, -, /}
3745// matrix op scalar op in {+, -, /}
3746// scalar op matrix op in {+, -, /}
3747//
qining25262b32016-05-06 17:25:16 -04003748spv::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 -07003749{
3750 bool firstClass = true;
3751
3752 // First, handle first-class matrix operations (* and matrix/scalar)
3753 switch (op) {
3754 case spv::OpFDiv:
3755 if (builder.isMatrix(left) && builder.isScalar(right)) {
3756 // turn matrix / scalar into a multiply...
3757 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3758 op = spv::OpMatrixTimesScalar;
3759 } else
3760 firstClass = false;
3761 break;
3762 case spv::OpMatrixTimesScalar:
3763 if (builder.isMatrix(right))
3764 std::swap(left, right);
3765 assert(builder.isScalar(right));
3766 break;
3767 case spv::OpVectorTimesMatrix:
3768 assert(builder.isVector(left));
3769 assert(builder.isMatrix(right));
3770 break;
3771 case spv::OpMatrixTimesVector:
3772 assert(builder.isMatrix(left));
3773 assert(builder.isVector(right));
3774 break;
3775 case spv::OpMatrixTimesMatrix:
3776 assert(builder.isMatrix(left));
3777 assert(builder.isMatrix(right));
3778 break;
3779 default:
3780 firstClass = false;
3781 break;
3782 }
3783
qining25262b32016-05-06 17:25:16 -04003784 if (firstClass) {
3785 spv::Id result = builder.createBinOp(op, typeId, left, right);
3786 addDecoration(result, noContraction);
3787 return builder.setPrecision(result, precision);
3788 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003789
LoopDawg592860c2016-06-09 08:57:35 -06003790 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003791 // The result type of all of them is the same type as the (a) matrix operand.
3792 // The algorithm is to:
3793 // - break the matrix(es) into vectors
3794 // - smear any scalar to a vector
3795 // - do vector operations
3796 // - make a matrix out the vector results
3797 switch (op) {
3798 case spv::OpFAdd:
3799 case spv::OpFSub:
3800 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003801 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003802 case spv::OpFMul:
3803 {
3804 // one time set up...
3805 bool leftMat = builder.isMatrix(left);
3806 bool rightMat = builder.isMatrix(right);
3807 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3808 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3809 spv::Id scalarType = builder.getScalarTypeId(typeId);
3810 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3811 std::vector<spv::Id> results;
3812 spv::Id smearVec = spv::NoResult;
3813 if (builder.isScalar(left))
3814 smearVec = builder.smearScalar(precision, left, vecType);
3815 else if (builder.isScalar(right))
3816 smearVec = builder.smearScalar(precision, right, vecType);
3817
3818 // do each vector op
3819 for (unsigned int c = 0; c < numCols; ++c) {
3820 std::vector<unsigned int> indexes;
3821 indexes.push_back(c);
3822 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3823 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003824 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3825 addDecoration(result, noContraction);
3826 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003827 }
3828
3829 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003830 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003831 }
3832 default:
3833 assert(0);
3834 return spv::NoResult;
3835 }
3836}
3837
qining25262b32016-05-06 17:25:16 -04003838spv::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 -06003839{
3840 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003841 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003842 int libCall = -1;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003843#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08003844 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003845 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3846#else
Rex Xucabbb782017-03-24 13:41:14 +08003847 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08003848 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003849#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003850
3851 switch (op) {
3852 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003853 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003854 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003855 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003856 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003857 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003858 unaryOp = spv::OpSNegate;
3859 break;
3860
3861 case glslang::EOpLogicalNot:
3862 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003863 unaryOp = spv::OpLogicalNot;
3864 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003865 case glslang::EOpBitwiseNot:
3866 unaryOp = spv::OpNot;
3867 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003868
John Kessenich140f3df2015-06-26 16:58:36 -06003869 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003870 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003871 break;
3872 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003873 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003874 break;
3875 case glslang::EOpTranspose:
3876 unaryOp = spv::OpTranspose;
3877 break;
3878
3879 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003880 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003881 break;
3882 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003883 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003884 break;
3885 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003886 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003887 break;
3888 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003889 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003890 break;
3891 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003892 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003893 break;
3894 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003895 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003896 break;
3897 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003898 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003899 break;
3900 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003901 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003902 break;
3903
3904 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003905 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003906 break;
3907 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003908 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003909 break;
3910 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003911 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003912 break;
3913 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003914 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003915 break;
3916 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003917 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003918 break;
3919 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003920 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003921 break;
3922
3923 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003924 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003925 break;
3926 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003927 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003928 break;
3929
3930 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003931 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003932 break;
3933 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003934 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003935 break;
3936 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003937 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003938 break;
3939 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003940 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003941 break;
3942 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003943 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003944 break;
3945 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003946 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003947 break;
3948
3949 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003950 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003951 break;
3952 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003953 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003954 break;
3955 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003956 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003957 break;
3958 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003959 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003960 break;
3961 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003962 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003963 break;
3964 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003965 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003966 break;
3967
3968 case glslang::EOpIsNan:
3969 unaryOp = spv::OpIsNan;
3970 break;
3971 case glslang::EOpIsInf:
3972 unaryOp = spv::OpIsInf;
3973 break;
LoopDawg592860c2016-06-09 08:57:35 -06003974 case glslang::EOpIsFinite:
3975 unaryOp = spv::OpIsFinite;
3976 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003977
Rex Xucbc426e2015-12-15 16:03:10 +08003978 case glslang::EOpFloatBitsToInt:
3979 case glslang::EOpFloatBitsToUint:
3980 case glslang::EOpIntBitsToFloat:
3981 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003982 case glslang::EOpDoubleBitsToInt64:
3983 case glslang::EOpDoubleBitsToUint64:
3984 case glslang::EOpInt64BitsToDouble:
3985 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08003986#ifdef AMD_EXTENSIONS
3987 case glslang::EOpFloat16BitsToInt16:
3988 case glslang::EOpFloat16BitsToUint16:
3989 case glslang::EOpInt16BitsToFloat16:
3990 case glslang::EOpUint16BitsToFloat16:
3991#endif
Rex Xucbc426e2015-12-15 16:03:10 +08003992 unaryOp = spv::OpBitcast;
3993 break;
3994
John Kessenich140f3df2015-06-26 16:58:36 -06003995 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003996 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003997 break;
3998 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003999 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004000 break;
4001 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004002 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004003 break;
4004 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004005 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004006 break;
4007 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004008 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004009 break;
4010 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004011 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004012 break;
John Kessenichfc51d282015-08-19 13:34:18 -06004013 case glslang::EOpPackSnorm4x8:
4014 libCall = spv::GLSLstd450PackSnorm4x8;
4015 break;
4016 case glslang::EOpUnpackSnorm4x8:
4017 libCall = spv::GLSLstd450UnpackSnorm4x8;
4018 break;
4019 case glslang::EOpPackUnorm4x8:
4020 libCall = spv::GLSLstd450PackUnorm4x8;
4021 break;
4022 case glslang::EOpUnpackUnorm4x8:
4023 libCall = spv::GLSLstd450UnpackUnorm4x8;
4024 break;
4025 case glslang::EOpPackDouble2x32:
4026 libCall = spv::GLSLstd450PackDouble2x32;
4027 break;
4028 case glslang::EOpUnpackDouble2x32:
4029 libCall = spv::GLSLstd450UnpackDouble2x32;
4030 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004031
Rex Xu8ff43de2016-04-22 16:51:45 +08004032 case glslang::EOpPackInt2x32:
4033 case glslang::EOpUnpackInt2x32:
4034 case glslang::EOpPackUint2x32:
4035 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08004036 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08004037 break;
4038
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004039#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004040 case glslang::EOpPackInt2x16:
4041 case glslang::EOpUnpackInt2x16:
4042 case glslang::EOpPackUint2x16:
4043 case glslang::EOpUnpackUint2x16:
4044 case glslang::EOpPackInt4x16:
4045 case glslang::EOpUnpackInt4x16:
4046 case glslang::EOpPackUint4x16:
4047 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004048 case glslang::EOpPackFloat2x16:
4049 case glslang::EOpUnpackFloat2x16:
4050 unaryOp = spv::OpBitcast;
4051 break;
4052#endif
4053
John Kessenich140f3df2015-06-26 16:58:36 -06004054 case glslang::EOpDPdx:
4055 unaryOp = spv::OpDPdx;
4056 break;
4057 case glslang::EOpDPdy:
4058 unaryOp = spv::OpDPdy;
4059 break;
4060 case glslang::EOpFwidth:
4061 unaryOp = spv::OpFwidth;
4062 break;
4063 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07004064 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004065 unaryOp = spv::OpDPdxFine;
4066 break;
4067 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07004068 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004069 unaryOp = spv::OpDPdyFine;
4070 break;
4071 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07004072 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004073 unaryOp = spv::OpFwidthFine;
4074 break;
4075 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004076 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004077 unaryOp = spv::OpDPdxCoarse;
4078 break;
4079 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004080 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004081 unaryOp = spv::OpDPdyCoarse;
4082 break;
4083 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004084 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004085 unaryOp = spv::OpFwidthCoarse;
4086 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004087 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07004088 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004089 libCall = spv::GLSLstd450InterpolateAtCentroid;
4090 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004091 case glslang::EOpAny:
4092 unaryOp = spv::OpAny;
4093 break;
4094 case glslang::EOpAll:
4095 unaryOp = spv::OpAll;
4096 break;
4097
4098 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004099 if (isFloat)
4100 libCall = spv::GLSLstd450FAbs;
4101 else
4102 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004103 break;
4104 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004105 if (isFloat)
4106 libCall = spv::GLSLstd450FSign;
4107 else
4108 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004109 break;
4110
John Kessenichfc51d282015-08-19 13:34:18 -06004111 case glslang::EOpAtomicCounterIncrement:
4112 case glslang::EOpAtomicCounterDecrement:
4113 case glslang::EOpAtomicCounter:
4114 {
4115 // Handle all of the atomics in one place, in createAtomicOperation()
4116 std::vector<spv::Id> operands;
4117 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08004118 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004119 }
4120
John Kessenichfc51d282015-08-19 13:34:18 -06004121 case glslang::EOpBitFieldReverse:
4122 unaryOp = spv::OpBitReverse;
4123 break;
4124 case glslang::EOpBitCount:
4125 unaryOp = spv::OpBitCount;
4126 break;
4127 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004128 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004129 break;
4130 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004131 if (isUnsigned)
4132 libCall = spv::GLSLstd450FindUMsb;
4133 else
4134 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004135 break;
4136
Rex Xu574ab042016-04-14 16:53:07 +08004137 case glslang::EOpBallot:
4138 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004139 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004140 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004141 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004142#ifdef AMD_EXTENSIONS
4143 case glslang::EOpMinInvocations:
4144 case glslang::EOpMaxInvocations:
4145 case glslang::EOpAddInvocations:
4146 case glslang::EOpMinInvocationsNonUniform:
4147 case glslang::EOpMaxInvocationsNonUniform:
4148 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004149 case glslang::EOpMinInvocationsInclusiveScan:
4150 case glslang::EOpMaxInvocationsInclusiveScan:
4151 case glslang::EOpAddInvocationsInclusiveScan:
4152 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4153 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4154 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4155 case glslang::EOpMinInvocationsExclusiveScan:
4156 case glslang::EOpMaxInvocationsExclusiveScan:
4157 case glslang::EOpAddInvocationsExclusiveScan:
4158 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4159 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4160 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004161#endif
Rex Xu51596642016-09-21 18:56:12 +08004162 {
4163 std::vector<spv::Id> operands;
4164 operands.push_back(operand);
4165 return createInvocationsOperation(op, typeId, operands, typeProxy);
4166 }
Rex Xu9d93a232016-05-05 12:30:44 +08004167
4168#ifdef AMD_EXTENSIONS
4169 case glslang::EOpMbcnt:
4170 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4171 libCall = spv::MbcntAMD;
4172 break;
4173
4174 case glslang::EOpCubeFaceIndex:
4175 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4176 libCall = spv::CubeFaceIndexAMD;
4177 break;
4178
4179 case glslang::EOpCubeFaceCoord:
4180 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4181 libCall = spv::CubeFaceCoordAMD;
4182 break;
4183#endif
Rex Xu338b1852016-05-05 20:38:33 +08004184
John Kessenich140f3df2015-06-26 16:58:36 -06004185 default:
4186 return 0;
4187 }
4188
4189 spv::Id id;
4190 if (libCall >= 0) {
4191 std::vector<spv::Id> args;
4192 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004193 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004194 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004195 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004196 }
John Kessenich140f3df2015-06-26 16:58:36 -06004197
qining25262b32016-05-06 17:25:16 -04004198 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07004199 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004200}
4201
John Kessenich7a53f762016-01-20 11:19:27 -07004202// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04004203spv::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 -07004204{
4205 // Handle unary operations vector by vector.
4206 // The result type is the same type as the original type.
4207 // The algorithm is to:
4208 // - break the matrix into vectors
4209 // - apply the operation to each vector
4210 // - make a matrix out the vector results
4211
4212 // get the types sorted out
4213 int numCols = builder.getNumColumns(operand);
4214 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004215 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4216 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004217 std::vector<spv::Id> results;
4218
4219 // do each vector op
4220 for (int c = 0; c < numCols; ++c) {
4221 std::vector<unsigned int> indexes;
4222 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004223 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4224 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
4225 addDecoration(destVec, noContraction);
4226 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004227 }
4228
4229 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004230 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07004231}
4232
Rex Xu73e3ce72016-04-27 18:48:17 +08004233spv::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 -06004234{
4235 spv::Op convOp = spv::OpNop;
4236 spv::Id zero = 0;
4237 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08004238 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004239
4240 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4241
4242 switch (op) {
4243 case glslang::EOpConvIntToBool:
4244 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08004245 case glslang::EOpConvInt64ToBool:
4246 case glslang::EOpConvUint64ToBool:
Rex Xucabbb782017-03-24 13:41:14 +08004247#ifdef AMD_EXTENSIONS
4248 case glslang::EOpConvInt16ToBool:
4249 case glslang::EOpConvUint16ToBool:
4250#endif
4251 if (op == glslang::EOpConvInt64ToBool || op == glslang::EOpConvUint64ToBool)
4252 zero = builder.makeUint64Constant(0);
4253#ifdef AMD_EXTENSIONS
4254 else if (op == glslang::EOpConvInt16ToBool || op == glslang::EOpConvUint16ToBool)
4255 zero = builder.makeUint16Constant(0);
4256#endif
4257 else
4258 zero = builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004259 zero = makeSmearedConstant(zero, vectorSize);
4260 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4261
4262 case glslang::EOpConvFloatToBool:
4263 zero = builder.makeFloatConstant(0.0F);
4264 zero = makeSmearedConstant(zero, vectorSize);
4265 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4266
4267 case glslang::EOpConvDoubleToBool:
4268 zero = builder.makeDoubleConstant(0.0);
4269 zero = makeSmearedConstant(zero, vectorSize);
4270 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4271
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004272#ifdef AMD_EXTENSIONS
4273 case glslang::EOpConvFloat16ToBool:
4274 zero = builder.makeFloat16Constant(0.0F);
4275 zero = makeSmearedConstant(zero, vectorSize);
4276 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4277#endif
4278
John Kessenich140f3df2015-06-26 16:58:36 -06004279 case glslang::EOpConvBoolToFloat:
4280 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004281 zero = builder.makeFloatConstant(0.0F);
4282 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004283 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004284
John Kessenich140f3df2015-06-26 16:58:36 -06004285 case glslang::EOpConvBoolToDouble:
4286 convOp = spv::OpSelect;
4287 zero = builder.makeDoubleConstant(0.0);
4288 one = builder.makeDoubleConstant(1.0);
4289 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004290
4291#ifdef AMD_EXTENSIONS
4292 case glslang::EOpConvBoolToFloat16:
4293 convOp = spv::OpSelect;
4294 zero = builder.makeFloat16Constant(0.0F);
4295 one = builder.makeFloat16Constant(1.0F);
4296 break;
4297#endif
4298
John Kessenich140f3df2015-06-26 16:58:36 -06004299 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004300 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004301#ifdef AMD_EXTENSIONS
4302 case glslang::EOpConvBoolToInt16:
4303#endif
4304 if (op == glslang::EOpConvBoolToInt64)
4305 zero = builder.makeInt64Constant(0);
4306#ifdef AMD_EXTENSIONS
4307 else if (op == glslang::EOpConvBoolToInt16)
4308 zero = builder.makeInt16Constant(0);
4309#endif
4310 else
4311 zero = builder.makeIntConstant(0);
4312
4313 if (op == glslang::EOpConvBoolToInt64)
4314 one = builder.makeInt64Constant(1);
4315#ifdef AMD_EXTENSIONS
4316 else if (op == glslang::EOpConvBoolToInt16)
4317 one = builder.makeInt16Constant(1);
4318#endif
4319 else
4320 one = builder.makeIntConstant(1);
4321
John Kessenich140f3df2015-06-26 16:58:36 -06004322 convOp = spv::OpSelect;
4323 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004324
John Kessenich140f3df2015-06-26 16:58:36 -06004325 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004326 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004327#ifdef AMD_EXTENSIONS
4328 case glslang::EOpConvBoolToUint16:
4329#endif
4330 if (op == glslang::EOpConvBoolToUint64)
4331 zero = builder.makeUint64Constant(0);
4332#ifdef AMD_EXTENSIONS
4333 else if (op == glslang::EOpConvBoolToUint16)
4334 zero = builder.makeUint16Constant(0);
4335#endif
4336 else
4337 zero = builder.makeUintConstant(0);
4338
4339 if (op == glslang::EOpConvBoolToUint64)
4340 one = builder.makeUint64Constant(1);
4341#ifdef AMD_EXTENSIONS
4342 else if (op == glslang::EOpConvBoolToUint16)
4343 one = builder.makeUint16Constant(1);
4344#endif
4345 else
4346 one = builder.makeUintConstant(1);
4347
John Kessenich140f3df2015-06-26 16:58:36 -06004348 convOp = spv::OpSelect;
4349 break;
4350
4351 case glslang::EOpConvIntToFloat:
4352 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004353 case glslang::EOpConvInt64ToFloat:
4354 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004355#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004356 case glslang::EOpConvInt16ToFloat:
4357 case glslang::EOpConvInt16ToDouble:
4358 case glslang::EOpConvInt16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004359 case glslang::EOpConvIntToFloat16:
4360 case glslang::EOpConvInt64ToFloat16:
4361#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004362 convOp = spv::OpConvertSToF;
4363 break;
4364
4365 case glslang::EOpConvUintToFloat:
4366 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004367 case glslang::EOpConvUint64ToFloat:
4368 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004369#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004370 case glslang::EOpConvUint16ToFloat:
4371 case glslang::EOpConvUint16ToDouble:
4372 case glslang::EOpConvUint16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004373 case glslang::EOpConvUintToFloat16:
4374 case glslang::EOpConvUint64ToFloat16:
4375#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004376 convOp = spv::OpConvertUToF;
4377 break;
4378
4379 case glslang::EOpConvDoubleToFloat:
4380 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004381#ifdef AMD_EXTENSIONS
4382 case glslang::EOpConvDoubleToFloat16:
4383 case glslang::EOpConvFloat16ToDouble:
4384 case glslang::EOpConvFloatToFloat16:
4385 case glslang::EOpConvFloat16ToFloat:
4386#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004387 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004388 if (builder.isMatrixType(destType))
4389 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004390 break;
4391
4392 case glslang::EOpConvFloatToInt:
4393 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004394 case glslang::EOpConvFloatToInt64:
4395 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004396#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004397 case glslang::EOpConvFloatToInt16:
4398 case glslang::EOpConvDoubleToInt16:
4399 case glslang::EOpConvFloat16ToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004400 case glslang::EOpConvFloat16ToInt:
4401 case glslang::EOpConvFloat16ToInt64:
4402#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004403 convOp = spv::OpConvertFToS;
4404 break;
4405
4406 case glslang::EOpConvUintToInt:
4407 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004408 case glslang::EOpConvUint64ToInt64:
4409 case glslang::EOpConvInt64ToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004410#ifdef AMD_EXTENSIONS
4411 case glslang::EOpConvUint16ToInt16:
4412 case glslang::EOpConvInt16ToUint16:
4413#endif
qininge24aa5e2016-04-07 15:40:27 -04004414 if (builder.isInSpecConstCodeGenMode()) {
4415 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004416 if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64)
4417 zero = builder.makeUint64Constant(0);
4418#ifdef AMD_EXTENSIONS
4419 else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16)
4420 zero = builder.makeUint16Constant(0);
4421#endif
4422 else
4423 zero = builder.makeUintConstant(0);
4424
qining189b2032016-04-12 23:16:20 -04004425 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004426 // Use OpIAdd, instead of OpBitcast to do the conversion when
4427 // generating for OpSpecConstantOp instruction.
4428 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4429 }
4430 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004431 convOp = spv::OpBitcast;
4432 break;
4433
4434 case glslang::EOpConvFloatToUint:
4435 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004436 case glslang::EOpConvFloatToUint64:
4437 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004438#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004439 case glslang::EOpConvFloatToUint16:
4440 case glslang::EOpConvDoubleToUint16:
4441 case glslang::EOpConvFloat16ToUint16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004442 case glslang::EOpConvFloat16ToUint:
4443 case glslang::EOpConvFloat16ToUint64:
4444#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004445 convOp = spv::OpConvertFToU;
4446 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004447
4448 case glslang::EOpConvIntToInt64:
4449 case glslang::EOpConvInt64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004450#ifdef AMD_EXTENSIONS
4451 case glslang::EOpConvIntToInt16:
4452 case glslang::EOpConvInt16ToInt:
4453 case glslang::EOpConvInt64ToInt16:
4454 case glslang::EOpConvInt16ToInt64:
4455#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004456 convOp = spv::OpSConvert;
4457 break;
4458
4459 case glslang::EOpConvUintToUint64:
4460 case glslang::EOpConvUint64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004461#ifdef AMD_EXTENSIONS
4462 case glslang::EOpConvUintToUint16:
4463 case glslang::EOpConvUint16ToUint:
4464 case glslang::EOpConvUint64ToUint16:
4465 case glslang::EOpConvUint16ToUint64:
4466#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004467 convOp = spv::OpUConvert;
4468 break;
4469
4470 case glslang::EOpConvIntToUint64:
4471 case glslang::EOpConvInt64ToUint:
4472 case glslang::EOpConvUint64ToInt:
4473 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004474#ifdef AMD_EXTENSIONS
4475 case glslang::EOpConvInt16ToUint:
4476 case glslang::EOpConvUintToInt16:
4477 case glslang::EOpConvInt16ToUint64:
4478 case glslang::EOpConvUint64ToInt16:
4479 case glslang::EOpConvUint16ToInt:
4480 case glslang::EOpConvIntToUint16:
4481 case glslang::EOpConvUint16ToInt64:
4482 case glslang::EOpConvInt64ToUint16:
4483#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004484 // OpSConvert/OpUConvert + OpBitCast
4485 switch (op) {
4486 case glslang::EOpConvIntToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004487#ifdef AMD_EXTENSIONS
4488 case glslang::EOpConvInt16ToUint64:
4489#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004490 convOp = spv::OpSConvert;
4491 type = builder.makeIntType(64);
4492 break;
4493 case glslang::EOpConvInt64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004494#ifdef AMD_EXTENSIONS
4495 case glslang::EOpConvInt16ToUint:
4496#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004497 convOp = spv::OpSConvert;
4498 type = builder.makeIntType(32);
4499 break;
4500 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004501#ifdef AMD_EXTENSIONS
4502 case glslang::EOpConvUint16ToInt:
4503#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004504 convOp = spv::OpUConvert;
4505 type = builder.makeUintType(32);
4506 break;
4507 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004508#ifdef AMD_EXTENSIONS
4509 case glslang::EOpConvUint16ToInt64:
4510#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004511 convOp = spv::OpUConvert;
4512 type = builder.makeUintType(64);
4513 break;
Rex Xucabbb782017-03-24 13:41:14 +08004514#ifdef AMD_EXTENSIONS
4515 case glslang::EOpConvUintToInt16:
4516 case glslang::EOpConvUint64ToInt16:
4517 convOp = spv::OpUConvert;
4518 type = builder.makeUintType(16);
4519 break;
4520 case glslang::EOpConvIntToUint16:
4521 case glslang::EOpConvInt64ToUint16:
4522 convOp = spv::OpSConvert;
4523 type = builder.makeIntType(16);
4524 break;
4525#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004526 default:
4527 assert(0);
4528 break;
4529 }
4530
4531 if (vectorSize > 0)
4532 type = builder.makeVectorType(type, vectorSize);
4533
4534 operand = builder.createUnaryOp(convOp, type, operand);
4535
4536 if (builder.isInSpecConstCodeGenMode()) {
4537 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004538#ifdef AMD_EXTENSIONS
4539 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64 ||
4540 op == glslang::EOpConvInt16ToUint64 || op == glslang::EOpConvUint16ToInt64)
4541 zero = builder.makeUint64Constant(0);
4542 else if (op == glslang::EOpConvIntToUint16 || op == glslang::EOpConvUintToInt16 ||
4543 op == glslang::EOpConvInt64ToUint16 || op == glslang::EOpConvUint64ToInt16)
4544 zero = builder.makeUint16Constant(0);
4545 else
4546 zero = builder.makeUintConstant(0);
4547#else
4548 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64)
4549 zero = builder.makeUint64Constant(0);
4550 else
4551 zero = builder.makeUintConstant(0);
4552#endif
4553
Rex Xu8ff43de2016-04-22 16:51:45 +08004554 zero = makeSmearedConstant(zero, vectorSize);
4555 // Use OpIAdd, instead of OpBitcast to do the conversion when
4556 // generating for OpSpecConstantOp instruction.
4557 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4558 }
4559 // For normal run-time conversion instruction, use OpBitcast.
4560 convOp = spv::OpBitcast;
4561 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004562 default:
4563 break;
4564 }
4565
4566 spv::Id result = 0;
4567 if (convOp == spv::OpNop)
4568 return result;
4569
4570 if (convOp == spv::OpSelect) {
4571 zero = makeSmearedConstant(zero, vectorSize);
4572 one = makeSmearedConstant(one, vectorSize);
4573 result = builder.createTriOp(convOp, destType, operand, one, zero);
4574 } else
4575 result = builder.createUnaryOp(convOp, destType, operand);
4576
John Kessenich32cfd492016-02-02 12:37:46 -07004577 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004578}
4579
4580spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4581{
4582 if (vectorSize == 0)
4583 return constant;
4584
4585 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4586 std::vector<spv::Id> components;
4587 for (int c = 0; c < vectorSize; ++c)
4588 components.push_back(constant);
4589 return builder.makeCompositeConstant(vectorTypeId, components);
4590}
4591
John Kessenich426394d2015-07-23 10:22:48 -06004592// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004593spv::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 -06004594{
4595 spv::Op opCode = spv::OpNop;
4596
4597 switch (op) {
4598 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004599 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004600 opCode = spv::OpAtomicIAdd;
4601 break;
4602 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004603 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08004604 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004605 break;
4606 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004607 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08004608 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004609 break;
4610 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004611 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004612 opCode = spv::OpAtomicAnd;
4613 break;
4614 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004615 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06004616 opCode = spv::OpAtomicOr;
4617 break;
4618 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004619 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06004620 opCode = spv::OpAtomicXor;
4621 break;
4622 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004623 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004624 opCode = spv::OpAtomicExchange;
4625 break;
4626 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004627 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004628 opCode = spv::OpAtomicCompareExchange;
4629 break;
4630 case glslang::EOpAtomicCounterIncrement:
4631 opCode = spv::OpAtomicIIncrement;
4632 break;
4633 case glslang::EOpAtomicCounterDecrement:
4634 opCode = spv::OpAtomicIDecrement;
4635 break;
4636 case glslang::EOpAtomicCounter:
4637 opCode = spv::OpAtomicLoad;
4638 break;
4639 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004640 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004641 break;
4642 }
4643
4644 // Sort out the operands
4645 // - mapping from glslang -> SPV
4646 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004647 // - compare-exchange swaps the value and comparator
4648 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004649 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4650 auto opIt = operands.begin(); // walk the glslang operands
4651 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004652 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4653 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4654 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004655 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4656 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004657 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004658 spvAtomicOperands.push_back(*(opIt + 1));
4659 spvAtomicOperands.push_back(*opIt);
4660 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004661 }
John Kessenich426394d2015-07-23 10:22:48 -06004662
John Kessenich3e60a6f2015-09-14 22:45:16 -06004663 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004664 for (; opIt != operands.end(); ++opIt)
4665 spvAtomicOperands.push_back(*opIt);
4666
4667 return builder.createOp(opCode, typeId, spvAtomicOperands);
4668}
4669
John Kessenich91cef522016-05-05 16:45:40 -06004670// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004671spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004672{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004673#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004674 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004675 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004676#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004677
Rex Xu51596642016-09-21 18:56:12 +08004678 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004679 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004680 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4681
chaocf200da82016-12-20 12:44:35 -08004682 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4683 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004684 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4685 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004686 } else if (op == glslang::EOpAnyInvocation ||
4687 op == glslang::EOpAllInvocations ||
4688 op == glslang::EOpAllInvocationsEqual) {
4689 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4690 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004691 } else {
4692 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004693#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004694 if (op == glslang::EOpMinInvocationsNonUniform ||
4695 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004696 op == glslang::EOpAddInvocationsNonUniform ||
4697 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4698 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4699 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4700 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4701 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4702 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004703 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004704#endif
Rex Xu51596642016-09-21 18:56:12 +08004705
4706 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004707#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004708 switch (op) {
4709 case glslang::EOpMinInvocations:
4710 case glslang::EOpMaxInvocations:
4711 case glslang::EOpAddInvocations:
4712 case glslang::EOpMinInvocationsNonUniform:
4713 case glslang::EOpMaxInvocationsNonUniform:
4714 case glslang::EOpAddInvocationsNonUniform:
4715 groupOperation = spv::GroupOperationReduce;
4716 spvGroupOperands.push_back(groupOperation);
4717 break;
4718 case glslang::EOpMinInvocationsInclusiveScan:
4719 case glslang::EOpMaxInvocationsInclusiveScan:
4720 case glslang::EOpAddInvocationsInclusiveScan:
4721 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4722 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4723 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4724 groupOperation = spv::GroupOperationInclusiveScan;
4725 spvGroupOperands.push_back(groupOperation);
4726 break;
4727 case glslang::EOpMinInvocationsExclusiveScan:
4728 case glslang::EOpMaxInvocationsExclusiveScan:
4729 case glslang::EOpAddInvocationsExclusiveScan:
4730 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4731 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4732 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4733 groupOperation = spv::GroupOperationExclusiveScan;
4734 spvGroupOperands.push_back(groupOperation);
4735 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004736 default:
4737 break;
Rex Xu430ef402016-10-14 17:22:23 +08004738 }
Rex Xu9d93a232016-05-05 12:30:44 +08004739#endif
Rex Xu51596642016-09-21 18:56:12 +08004740 }
4741
4742 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4743 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004744
4745 switch (op) {
4746 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004747 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004748 break;
John Kessenich91cef522016-05-05 16:45:40 -06004749 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004750 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004751 break;
John Kessenich91cef522016-05-05 16:45:40 -06004752 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004753 opCode = spv::OpSubgroupAllEqualKHR;
4754 break;
Rex Xu51596642016-09-21 18:56:12 +08004755 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004756 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004757 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004758 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004759 break;
4760 case glslang::EOpReadFirstInvocation:
4761 opCode = spv::OpSubgroupFirstInvocationKHR;
4762 break;
4763 case glslang::EOpBallot:
4764 {
4765 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4766 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4767 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4768 //
4769 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4770 //
4771 spv::Id uintType = builder.makeUintType(32);
4772 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4773 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4774
4775 std::vector<spv::Id> components;
4776 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4777 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4778
4779 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4780 return builder.createUnaryOp(spv::OpBitcast, typeId,
4781 builder.createCompositeConstruct(uvec2Type, components));
4782 }
4783
Rex Xu9d93a232016-05-05 12:30:44 +08004784#ifdef AMD_EXTENSIONS
4785 case glslang::EOpMinInvocations:
4786 case glslang::EOpMaxInvocations:
4787 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08004788 case glslang::EOpMinInvocationsInclusiveScan:
4789 case glslang::EOpMaxInvocationsInclusiveScan:
4790 case glslang::EOpAddInvocationsInclusiveScan:
4791 case glslang::EOpMinInvocationsExclusiveScan:
4792 case glslang::EOpMaxInvocationsExclusiveScan:
4793 case glslang::EOpAddInvocationsExclusiveScan:
4794 if (op == glslang::EOpMinInvocations ||
4795 op == glslang::EOpMinInvocationsInclusiveScan ||
4796 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004797 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004798 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004799 else {
4800 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004801 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004802 else
Rex Xu51596642016-09-21 18:56:12 +08004803 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004804 }
Rex Xu430ef402016-10-14 17:22:23 +08004805 } else if (op == glslang::EOpMaxInvocations ||
4806 op == glslang::EOpMaxInvocationsInclusiveScan ||
4807 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004808 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004809 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004810 else {
4811 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004812 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004813 else
Rex Xu51596642016-09-21 18:56:12 +08004814 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004815 }
4816 } else {
4817 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004818 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004819 else
Rex Xu51596642016-09-21 18:56:12 +08004820 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004821 }
4822
Rex Xu2bbbe062016-08-23 15:41:05 +08004823 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004824 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004825
4826 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004827 case glslang::EOpMinInvocationsNonUniform:
4828 case glslang::EOpMaxInvocationsNonUniform:
4829 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004830 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4831 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4832 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4833 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4834 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4835 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4836 if (op == glslang::EOpMinInvocationsNonUniform ||
4837 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4838 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004839 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004840 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004841 else {
4842 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004843 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004844 else
Rex Xu51596642016-09-21 18:56:12 +08004845 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004846 }
4847 }
Rex Xu430ef402016-10-14 17:22:23 +08004848 else if (op == glslang::EOpMaxInvocationsNonUniform ||
4849 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4850 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004851 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004852 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004853 else {
4854 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004855 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004856 else
Rex Xu51596642016-09-21 18:56:12 +08004857 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004858 }
4859 }
4860 else {
4861 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004862 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004863 else
Rex Xu51596642016-09-21 18:56:12 +08004864 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004865 }
4866
Rex Xu2bbbe062016-08-23 15:41:05 +08004867 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004868 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004869
4870 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004871#endif
John Kessenich91cef522016-05-05 16:45:40 -06004872 default:
4873 logger->missingFunctionality("invocation operation");
4874 return spv::NoResult;
4875 }
Rex Xu51596642016-09-21 18:56:12 +08004876
4877 assert(opCode != spv::OpNop);
4878 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004879}
4880
Rex Xu2bbbe062016-08-23 15:41:05 +08004881// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08004882spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08004883{
Rex Xub7072052016-09-26 15:53:40 +08004884#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08004885 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4886 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08004887 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08004888 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08004889 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
4890 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
4891 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08004892#else
4893 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4894 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08004895 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
4896 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08004897#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08004898
4899 // Handle group invocation operations scalar by scalar.
4900 // The result type is the same type as the original type.
4901 // The algorithm is to:
4902 // - break the vector into scalars
4903 // - apply the operation to each scalar
4904 // - make a vector out the scalar results
4905
4906 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08004907 int numComponents = builder.getNumComponents(operands[0]);
4908 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08004909 std::vector<spv::Id> results;
4910
4911 // do each scalar op
4912 for (int comp = 0; comp < numComponents; ++comp) {
4913 std::vector<unsigned int> indexes;
4914 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08004915 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08004916 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08004917 if (op == spv::OpSubgroupReadInvocationKHR) {
4918 spvGroupOperands.push_back(scalar);
4919 spvGroupOperands.push_back(operands[1]);
4920 } else if (op == spv::OpGroupBroadcast) {
4921 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08004922 spvGroupOperands.push_back(scalar);
4923 spvGroupOperands.push_back(operands[1]);
4924 } else {
chaocf200da82016-12-20 12:44:35 -08004925 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08004926 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08004927 spvGroupOperands.push_back(scalar);
4928 }
Rex Xu2bbbe062016-08-23 15:41:05 +08004929
Rex Xub7072052016-09-26 15:53:40 +08004930 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08004931 }
4932
4933 // put the pieces together
4934 return builder.createCompositeConstruct(typeId, results);
4935}
Rex Xu2bbbe062016-08-23 15:41:05 +08004936
John Kessenich5e4b1242015-08-06 22:53:06 -06004937spv::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 -06004938{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004939#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004940 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004941 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4942#else
Rex Xucabbb782017-03-24 13:41:14 +08004943 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06004944 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004945#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06004946
John Kessenich140f3df2015-06-26 16:58:36 -06004947 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004948 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004949 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05004950 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07004951 spv::Id typeId0 = 0;
4952 if (consumedOperands > 0)
4953 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08004954 spv::Id typeId1 = 0;
4955 if (consumedOperands > 1)
4956 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07004957 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004958
4959 switch (op) {
4960 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004961 if (isFloat)
4962 libCall = spv::GLSLstd450FMin;
4963 else if (isUnsigned)
4964 libCall = spv::GLSLstd450UMin;
4965 else
4966 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004967 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004968 break;
4969 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004970 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004971 break;
4972 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004973 if (isFloat)
4974 libCall = spv::GLSLstd450FMax;
4975 else if (isUnsigned)
4976 libCall = spv::GLSLstd450UMax;
4977 else
4978 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004979 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004980 break;
4981 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004982 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004983 break;
4984 case glslang::EOpDot:
4985 opCode = spv::OpDot;
4986 break;
4987 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004988 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004989 break;
4990
4991 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004992 if (isFloat)
4993 libCall = spv::GLSLstd450FClamp;
4994 else if (isUnsigned)
4995 libCall = spv::GLSLstd450UClamp;
4996 else
4997 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004998 builder.promoteScalar(precision, operands.front(), operands[1]);
4999 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005000 break;
5001 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08005002 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
5003 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07005004 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08005005 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07005006 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08005007 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07005008 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07005009 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005010 break;
5011 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005012 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005013 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005014 break;
5015 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005016 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005017 builder.promoteScalar(precision, operands[0], operands[2]);
5018 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005019 break;
5020
5021 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06005022 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06005023 break;
5024 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06005025 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06005026 break;
5027 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06005028 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06005029 break;
5030 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06005031 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06005032 break;
5033 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005034 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06005035 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005036 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07005037 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005038 libCall = spv::GLSLstd450InterpolateAtSample;
5039 break;
5040 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07005041 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005042 libCall = spv::GLSLstd450InterpolateAtOffset;
5043 break;
John Kessenich55e7d112015-11-15 21:33:39 -07005044 case glslang::EOpAddCarry:
5045 opCode = spv::OpIAddCarry;
5046 typeId = builder.makeStructResultType(typeId0, typeId0);
5047 consumedOperands = 2;
5048 break;
5049 case glslang::EOpSubBorrow:
5050 opCode = spv::OpISubBorrow;
5051 typeId = builder.makeStructResultType(typeId0, typeId0);
5052 consumedOperands = 2;
5053 break;
5054 case glslang::EOpUMulExtended:
5055 opCode = spv::OpUMulExtended;
5056 typeId = builder.makeStructResultType(typeId0, typeId0);
5057 consumedOperands = 2;
5058 break;
5059 case glslang::EOpIMulExtended:
5060 opCode = spv::OpSMulExtended;
5061 typeId = builder.makeStructResultType(typeId0, typeId0);
5062 consumedOperands = 2;
5063 break;
5064 case glslang::EOpBitfieldExtract:
5065 if (isUnsigned)
5066 opCode = spv::OpBitFieldUExtract;
5067 else
5068 opCode = spv::OpBitFieldSExtract;
5069 break;
5070 case glslang::EOpBitfieldInsert:
5071 opCode = spv::OpBitFieldInsert;
5072 break;
5073
5074 case glslang::EOpFma:
5075 libCall = spv::GLSLstd450Fma;
5076 break;
5077 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005078 {
5079 libCall = spv::GLSLstd450FrexpStruct;
5080 assert(builder.isPointerType(typeId1));
5081 typeId1 = builder.getContainedTypeId(typeId1);
5082#ifdef AMD_EXTENSIONS
5083 int width = builder.getScalarTypeWidth(typeId1);
5084#else
5085 int width = 32;
5086#endif
5087 if (builder.getNumComponents(operands[0]) == 1)
5088 frexpIntType = builder.makeIntegerType(width, true);
5089 else
5090 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
5091 typeId = builder.makeStructResultType(typeId0, frexpIntType);
5092 consumedOperands = 1;
5093 }
John Kessenich55e7d112015-11-15 21:33:39 -07005094 break;
5095 case glslang::EOpLdexp:
5096 libCall = spv::GLSLstd450Ldexp;
5097 break;
5098
Rex Xu574ab042016-04-14 16:53:07 +08005099 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08005100 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08005101
Rex Xu9d93a232016-05-05 12:30:44 +08005102#ifdef AMD_EXTENSIONS
5103 case glslang::EOpSwizzleInvocations:
5104 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5105 libCall = spv::SwizzleInvocationsAMD;
5106 break;
5107 case glslang::EOpSwizzleInvocationsMasked:
5108 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5109 libCall = spv::SwizzleInvocationsMaskedAMD;
5110 break;
5111 case glslang::EOpWriteInvocation:
5112 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5113 libCall = spv::WriteInvocationAMD;
5114 break;
5115
5116 case glslang::EOpMin3:
5117 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5118 if (isFloat)
5119 libCall = spv::FMin3AMD;
5120 else {
5121 if (isUnsigned)
5122 libCall = spv::UMin3AMD;
5123 else
5124 libCall = spv::SMin3AMD;
5125 }
5126 break;
5127 case glslang::EOpMax3:
5128 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5129 if (isFloat)
5130 libCall = spv::FMax3AMD;
5131 else {
5132 if (isUnsigned)
5133 libCall = spv::UMax3AMD;
5134 else
5135 libCall = spv::SMax3AMD;
5136 }
5137 break;
5138 case glslang::EOpMid3:
5139 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5140 if (isFloat)
5141 libCall = spv::FMid3AMD;
5142 else {
5143 if (isUnsigned)
5144 libCall = spv::UMid3AMD;
5145 else
5146 libCall = spv::SMid3AMD;
5147 }
5148 break;
5149
5150 case glslang::EOpInterpolateAtVertex:
5151 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
5152 libCall = spv::InterpolateAtVertexAMD;
5153 break;
5154#endif
5155
John Kessenich140f3df2015-06-26 16:58:36 -06005156 default:
5157 return 0;
5158 }
5159
5160 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07005161 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05005162 // Use an extended instruction from the standard library.
5163 // Construct the call arguments, without modifying the original operands vector.
5164 // We might need the remaining arguments, e.g. in the EOpFrexp case.
5165 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08005166 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07005167 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07005168 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06005169 case 0:
5170 // should all be handled by visitAggregate and createNoArgOperation
5171 assert(0);
5172 return 0;
5173 case 1:
5174 // should all be handled by createUnaryOperation
5175 assert(0);
5176 return 0;
5177 case 2:
5178 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
5179 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005180 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005181 // anything 3 or over doesn't have l-value operands, so all should be consumed
5182 assert(consumedOperands == operands.size());
5183 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06005184 break;
5185 }
5186 }
5187
John Kessenich55e7d112015-11-15 21:33:39 -07005188 // Decode the return types that were structures
5189 switch (op) {
5190 case glslang::EOpAddCarry:
5191 case glslang::EOpSubBorrow:
5192 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5193 id = builder.createCompositeExtract(id, typeId0, 0);
5194 break;
5195 case glslang::EOpUMulExtended:
5196 case glslang::EOpIMulExtended:
5197 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
5198 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5199 break;
5200 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005201 {
5202 assert(operands.size() == 2);
5203 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
5204 // "exp" is floating-point type (from HLSL intrinsic)
5205 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
5206 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
5207 builder.createStore(member1, operands[1]);
5208 } else
5209 // "exp" is integer type (from GLSL built-in function)
5210 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
5211 id = builder.createCompositeExtract(id, typeId0, 0);
5212 }
John Kessenich55e7d112015-11-15 21:33:39 -07005213 break;
5214 default:
5215 break;
5216 }
5217
John Kessenich32cfd492016-02-02 12:37:46 -07005218 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005219}
5220
Rex Xu9d93a232016-05-05 12:30:44 +08005221// Intrinsics with no arguments (or no return value, and no precision).
5222spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06005223{
5224 // TODO: get the barrier operands correct
5225
5226 switch (op) {
5227 case glslang::EOpEmitVertex:
5228 builder.createNoResultOp(spv::OpEmitVertex);
5229 return 0;
5230 case glslang::EOpEndPrimitive:
5231 builder.createNoResultOp(spv::OpEndPrimitive);
5232 return 0;
5233 case glslang::EOpBarrier:
chrgau01@arm.comc3f1cdf2016-11-14 10:10:05 +01005234 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06005235 return 0;
5236 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06005237 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06005238 return 0;
5239 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06005240 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005241 return 0;
5242 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06005243 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005244 return 0;
5245 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06005246 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005247 return 0;
5248 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07005249 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005250 return 0;
5251 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07005252 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005253 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06005254 case glslang::EOpAllMemoryBarrierWithGroupSync:
5255 // Control barrier with non-"None" semantic is also a memory barrier.
5256 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
5257 return 0;
5258 case glslang::EOpGroupMemoryBarrierWithGroupSync:
5259 // Control barrier with non-"None" semantic is also a memory barrier.
5260 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
5261 return 0;
5262 case glslang::EOpWorkgroupMemoryBarrier:
5263 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5264 return 0;
5265 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
5266 // Control barrier with non-"None" semantic is also a memory barrier.
5267 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5268 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08005269#ifdef AMD_EXTENSIONS
5270 case glslang::EOpTime:
5271 {
5272 std::vector<spv::Id> args; // Dummy arguments
5273 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
5274 return builder.setPrecision(id, precision);
5275 }
5276#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005277 default:
Lei Zhang17535f72016-05-04 15:55:59 -04005278 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06005279 return 0;
5280 }
5281}
5282
5283spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
5284{
John Kessenich2f273362015-07-18 22:34:27 -06005285 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06005286 spv::Id id;
5287 if (symbolValues.end() != iter) {
5288 id = iter->second;
5289 return id;
5290 }
5291
5292 // it was not found, create it
5293 id = createSpvVariable(symbol);
5294 symbolValues[symbol->getId()] = id;
5295
Rex Xuc884b4a2016-06-29 15:03:44 +08005296 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06005297 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07005298 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08005299 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07005300 if (symbol->getType().getQualifier().hasSpecConstantId())
5301 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06005302 if (symbol->getQualifier().hasIndex())
5303 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
5304 if (symbol->getQualifier().hasComponent())
5305 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
5306 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005307 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005308 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005309 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005310 if (symbol->getQualifier().hasXfbBuffer())
5311 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5312 if (symbol->getQualifier().hasXfbOffset())
5313 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
5314 }
John Kessenich91e4aa52016-07-07 17:46:42 -06005315 // atomic counters use this:
5316 if (symbol->getQualifier().hasOffset())
5317 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005318 }
5319
scygan2c864272016-05-18 18:09:17 +02005320 if (symbol->getQualifier().hasLocation())
5321 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07005322 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07005323 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07005324 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06005325 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07005326 }
John Kessenich140f3df2015-06-26 16:58:36 -06005327 if (symbol->getQualifier().hasSet())
5328 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07005329 else if (IsDescriptorResource(symbol->getType())) {
5330 // default to 0
5331 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
5332 }
John Kessenich140f3df2015-06-26 16:58:36 -06005333 if (symbol->getQualifier().hasBinding())
5334 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07005335 if (symbol->getQualifier().hasAttachment())
5336 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06005337 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005338 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005339 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005340 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005341 if (symbol->getQualifier().hasXfbBuffer())
5342 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5343 }
5344
Rex Xu1da878f2016-02-21 20:59:01 +08005345 if (symbol->getType().isImage()) {
5346 std::vector<spv::Decoration> memory;
5347 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
5348 for (unsigned int i = 0; i < memory.size(); ++i)
5349 addDecoration(id, memory[i]);
5350 }
5351
John Kessenich140f3df2015-06-26 16:58:36 -06005352 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06005353 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06005354 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07005355 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06005356
John Kessenichecba76f2017-01-06 00:34:48 -07005357#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08005358 if (builtIn == spv::BuiltInSampleMask) {
5359 spv::Decoration decoration;
5360 // GL_NV_sample_mask_override_coverage extension
5361 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08005362 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08005363 else
5364 decoration = (spv::Decoration)spv::DecorationMax;
5365 addDecoration(id, decoration);
5366 if (decoration != spv::DecorationMax) {
5367 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
5368 }
5369 }
chaoc771d89f2017-01-13 01:10:53 -08005370 else if (builtIn == spv::BuiltInLayer) {
5371 // SPV_NV_viewport_array2 extension
5372 if (symbol->getQualifier().layoutViewportRelative)
5373 {
5374 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
5375 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
5376 builder.addExtension(spv::E_SPV_NV_viewport_array2);
5377 }
5378 if(symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048)
5379 {
5380 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
5381 builder.addCapability(spv::CapabilityShaderStereoViewNV);
5382 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
5383 }
5384 }
5385
chaoc6e5acae2016-12-20 13:28:52 -08005386 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08005387 addDecoration(id, spv::DecorationPassthroughNV);
5388 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08005389 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
5390 }
chaoc0ad6a4e2016-12-19 16:29:34 -08005391#endif
5392
John Kessenich140f3df2015-06-26 16:58:36 -06005393 return id;
5394}
5395
John Kessenich55e7d112015-11-15 21:33:39 -07005396// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06005397void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
5398{
John Kessenich4016e382016-07-15 11:53:56 -06005399 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005400 builder.addDecoration(id, dec);
5401}
5402
John Kessenich55e7d112015-11-15 21:33:39 -07005403// If 'dec' is valid, add a one-operand decoration to an object
5404void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
5405{
John Kessenich4016e382016-07-15 11:53:56 -06005406 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07005407 builder.addDecoration(id, dec, value);
5408}
5409
5410// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005411void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5412{
John Kessenich4016e382016-07-15 11:53:56 -06005413 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005414 builder.addMemberDecoration(id, (unsigned)member, dec);
5415}
5416
John Kessenich92187592016-02-01 13:45:25 -07005417// If 'dec' is valid, add a one-operand decoration to a struct member
5418void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5419{
John Kessenich4016e382016-07-15 11:53:56 -06005420 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005421 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5422}
5423
John Kessenich55e7d112015-11-15 21:33:39 -07005424// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005425// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005426//
5427// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5428//
5429// Recursively walk the nodes. The nodes form a tree whose leaves are
5430// regular constants, which themselves are trees that createSpvConstant()
5431// recursively walks. So, this function walks the "top" of the tree:
5432// - emit specialization constant-building instructions for specConstant
5433// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005434spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005435{
John Kessenich7cc0e282016-03-20 00:46:02 -06005436 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005437
qining4f4bb812016-04-03 23:55:17 -04005438 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005439 if (! node.getQualifier().specConstant) {
5440 // hand off to the non-spec-constant path
5441 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5442 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005443 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005444 nextConst, false);
5445 }
5446
5447 // We now know we have a specialization constant to build
5448
John Kessenichd94c0032016-05-30 19:29:40 -06005449 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005450 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5451 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5452 std::vector<spv::Id> dimConstId;
5453 for (int dim = 0; dim < 3; ++dim) {
5454 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5455 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5456 if (specConst)
5457 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5458 }
5459 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5460 }
5461
5462 // An AST node labelled as specialization constant should be a symbol node.
5463 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5464 if (auto* sn = node.getAsSymbolNode()) {
5465 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005466 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5467 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5468 // will set the builder into spec constant op instruction generating mode.
5469 sub_tree->traverse(this);
5470 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005471 } else if (auto* const_union_array = &sn->getConstArray()){
5472 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005473 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5474 builder.addName(id, sn->getName().c_str());
5475 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005476 }
5477 }
qining4f4bb812016-04-03 23:55:17 -04005478
5479 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5480 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005481 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005482 exit(1);
5483 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005484}
5485
John Kessenich140f3df2015-06-26 16:58:36 -06005486// Use 'consts' as the flattened glslang source of scalar constants to recursively
5487// build the aggregate SPIR-V constant.
5488//
5489// If there are not enough elements present in 'consts', 0 will be substituted;
5490// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5491//
qining08408382016-03-21 09:51:37 -04005492spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005493{
5494 // vector of constants for SPIR-V
5495 std::vector<spv::Id> spvConsts;
5496
5497 // Type is used for struct and array constants
5498 spv::Id typeId = convertGlslangToSpvType(glslangType);
5499
5500 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005501 glslang::TType elementType(glslangType, 0);
5502 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005503 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005504 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005505 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005506 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005507 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005508 } else if (glslangType.getStruct()) {
5509 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5510 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005511 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005512 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005513 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5514 bool zero = nextConst >= consts.size();
5515 switch (glslangType.getBasicType()) {
5516 case glslang::EbtInt:
5517 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5518 break;
5519 case glslang::EbtUint:
5520 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5521 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005522 case glslang::EbtInt64:
5523 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5524 break;
5525 case glslang::EbtUint64:
5526 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5527 break;
Rex Xucabbb782017-03-24 13:41:14 +08005528#ifdef AMD_EXTENSIONS
5529 case glslang::EbtInt16:
5530 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst()));
5531 break;
5532 case glslang::EbtUint16:
5533 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst()));
5534 break;
5535#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005536 case glslang::EbtFloat:
5537 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5538 break;
5539 case glslang::EbtDouble:
5540 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5541 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005542#ifdef AMD_EXTENSIONS
5543 case glslang::EbtFloat16:
5544 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5545 break;
5546#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005547 case glslang::EbtBool:
5548 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5549 break;
5550 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005551 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005552 break;
5553 }
5554 ++nextConst;
5555 }
5556 } else {
5557 // we have a non-aggregate (scalar) constant
5558 bool zero = nextConst >= consts.size();
5559 spv::Id scalar = 0;
5560 switch (glslangType.getBasicType()) {
5561 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005562 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005563 break;
5564 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005565 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005566 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005567 case glslang::EbtInt64:
5568 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5569 break;
5570 case glslang::EbtUint64:
5571 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5572 break;
Rex Xucabbb782017-03-24 13:41:14 +08005573#ifdef AMD_EXTENSIONS
5574 case glslang::EbtInt16:
5575 scalar = builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst(), specConstant);
5576 break;
5577 case glslang::EbtUint16:
5578 scalar = builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst(), specConstant);
5579 break;
5580#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005581 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005582 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005583 break;
5584 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005585 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005586 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005587#ifdef AMD_EXTENSIONS
5588 case glslang::EbtFloat16:
5589 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5590 break;
5591#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005592 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005593 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005594 break;
5595 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005596 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005597 break;
5598 }
5599 ++nextConst;
5600 return scalar;
5601 }
5602
5603 return builder.makeCompositeConstant(typeId, spvConsts);
5604}
5605
John Kessenich7c1aa102015-10-15 13:29:11 -06005606// Return true if the node is a constant or symbol whose reading has no
5607// non-trivial observable cost or effect.
5608bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5609{
5610 // don't know what this is
5611 if (node == nullptr)
5612 return false;
5613
5614 // a constant is safe
5615 if (node->getAsConstantUnion() != nullptr)
5616 return true;
5617
5618 // not a symbol means non-trivial
5619 if (node->getAsSymbolNode() == nullptr)
5620 return false;
5621
5622 // a symbol, depends on what's being read
5623 switch (node->getType().getQualifier().storage) {
5624 case glslang::EvqTemporary:
5625 case glslang::EvqGlobal:
5626 case glslang::EvqIn:
5627 case glslang::EvqInOut:
5628 case glslang::EvqConst:
5629 case glslang::EvqConstReadOnly:
5630 case glslang::EvqUniform:
5631 return true;
5632 default:
5633 return false;
5634 }
qining25262b32016-05-06 17:25:16 -04005635}
John Kessenich7c1aa102015-10-15 13:29:11 -06005636
5637// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06005638// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06005639// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06005640// Return true if trivial.
5641bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5642{
5643 if (node == nullptr)
5644 return false;
5645
John Kessenich84cc15f2017-05-24 16:44:47 -06005646 // count non scalars as trivial, as well as anything coming from HLSL
5647 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06005648 return true;
5649
John Kessenich7c1aa102015-10-15 13:29:11 -06005650 // symbols and constants are trivial
5651 if (isTrivialLeaf(node))
5652 return true;
5653
5654 // otherwise, it needs to be a simple operation or one or two leaf nodes
5655
5656 // not a simple operation
5657 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5658 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5659 if (binaryNode == nullptr && unaryNode == nullptr)
5660 return false;
5661
5662 // not on leaf nodes
5663 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5664 return false;
5665
5666 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5667 return false;
5668 }
5669
5670 switch (node->getAsOperator()->getOp()) {
5671 case glslang::EOpLogicalNot:
5672 case glslang::EOpConvIntToBool:
5673 case glslang::EOpConvUintToBool:
5674 case glslang::EOpConvFloatToBool:
5675 case glslang::EOpConvDoubleToBool:
5676 case glslang::EOpEqual:
5677 case glslang::EOpNotEqual:
5678 case glslang::EOpLessThan:
5679 case glslang::EOpGreaterThan:
5680 case glslang::EOpLessThanEqual:
5681 case glslang::EOpGreaterThanEqual:
5682 case glslang::EOpIndexDirect:
5683 case glslang::EOpIndexDirectStruct:
5684 case glslang::EOpLogicalXor:
5685 case glslang::EOpAny:
5686 case glslang::EOpAll:
5687 return true;
5688 default:
5689 return false;
5690 }
5691}
5692
5693// Emit short-circuiting code, where 'right' is never evaluated unless
5694// the left side is true (for &&) or false (for ||).
5695spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5696{
5697 spv::Id boolTypeId = builder.makeBoolType();
5698
5699 // emit left operand
5700 builder.clearAccessChain();
5701 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005702 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005703
5704 // Operands to accumulate OpPhi operands
5705 std::vector<spv::Id> phiOperands;
5706 // accumulate left operand's phi information
5707 phiOperands.push_back(leftId);
5708 phiOperands.push_back(builder.getBuildPoint()->getId());
5709
5710 // Make the two kinds of operation symmetric with a "!"
5711 // || => emit "if (! left) result = right"
5712 // && => emit "if ( left) result = right"
5713 //
5714 // TODO: this runtime "not" for || could be avoided by adding functionality
5715 // to 'builder' to have an "else" without an "then"
5716 if (op == glslang::EOpLogicalOr)
5717 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5718
5719 // make an "if" based on the left value
5720 spv::Builder::If ifBuilder(leftId, builder);
5721
5722 // emit right operand as the "then" part of the "if"
5723 builder.clearAccessChain();
5724 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005725 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005726
5727 // accumulate left operand's phi information
5728 phiOperands.push_back(rightId);
5729 phiOperands.push_back(builder.getBuildPoint()->getId());
5730
5731 // finish the "if"
5732 ifBuilder.makeEndIf();
5733
5734 // phi together the two results
5735 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5736}
5737
Rex Xu9d93a232016-05-05 12:30:44 +08005738// Return type Id of the imported set of extended instructions corresponds to the name.
5739// Import this set if it has not been imported yet.
5740spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5741{
5742 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5743 return extBuiltinMap[name];
5744 else {
Rex Xu51596642016-09-21 18:56:12 +08005745 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005746 spv::Id extBuiltins = builder.import(name);
5747 extBuiltinMap[name] = extBuiltins;
5748 return extBuiltins;
5749 }
5750}
5751
John Kessenich140f3df2015-06-26 16:58:36 -06005752}; // end anonymous namespace
5753
5754namespace glslang {
5755
John Kessenich68d78fd2015-07-12 19:28:10 -06005756void GetSpirvVersion(std::string& version)
5757{
John Kessenich9e55f632015-07-15 10:03:39 -06005758 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005759 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005760 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005761 version = buf;
5762}
5763
John Kessenich140f3df2015-06-26 16:58:36 -06005764// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005765void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005766{
5767 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005768 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005769 if (out.fail())
5770 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06005771 for (int i = 0; i < (int)spirv.size(); ++i) {
5772 unsigned int word = spirv[i];
5773 out.write((const char*)&word, 4);
5774 }
5775 out.close();
5776}
5777
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005778// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08005779void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005780{
5781 std::ofstream out;
5782 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005783 if (out.fail())
5784 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005785 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08005786 if (varName != nullptr) {
5787 out << "\t #pragma once" << std::endl;
5788 out << "const uint32_t " << varName << "[] = {" << std::endl;
5789 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005790 const int WORDS_PER_LINE = 8;
5791 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5792 out << "\t";
5793 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5794 const unsigned int word = spirv[i + j];
5795 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5796 if (i + j + 1 < (int)spirv.size()) {
5797 out << ",";
5798 }
5799 }
5800 out << std::endl;
5801 }
Flavio15017db2017-02-15 14:29:33 -08005802 if (varName != nullptr) {
5803 out << "};";
5804 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005805 out.close();
5806}
5807
John Kessenich140f3df2015-06-26 16:58:36 -06005808//
5809// Set up the glslang traversal
5810//
John Kessenich121853f2017-05-31 17:11:16 -06005811void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06005812{
Lei Zhang17535f72016-05-04 15:55:59 -04005813 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06005814 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04005815}
5816
John Kessenich121853f2017-05-31 17:11:16 -06005817void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv,
5818 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04005819{
John Kessenich140f3df2015-06-26 16:58:36 -06005820 TIntermNode* root = intermediate.getTreeRoot();
5821
5822 if (root == 0)
5823 return;
5824
John Kessenich121853f2017-05-31 17:11:16 -06005825 glslang::SpvOptions defaultOptions;
5826 if (options == nullptr)
5827 options = &defaultOptions;
5828
John Kessenich140f3df2015-06-26 16:58:36 -06005829 glslang::GetThreadPoolAllocator().push();
5830
John Kessenich121853f2017-05-31 17:11:16 -06005831 TGlslangToSpvTraverser it(&intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06005832 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07005833 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06005834 it.dumpSpv(spirv);
5835
5836 glslang::GetThreadPoolAllocator().pop();
5837}
5838
5839}; // end namespace glslang