blob: bc483c7e6d092124b6745bbaba1d8525096a603c [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);
1372 else
1373 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001374 glslang::TOperator op;
1375 if (node->getOp() == glslang::EOpPreIncrement ||
1376 node->getOp() == glslang::EOpPostIncrement)
1377 op = glslang::EOpAdd;
1378 else
1379 op = glslang::EOpSub;
1380
John Kessenichf6640762016-08-01 19:44:00 -06001381 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001382 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001383 convertGlslangToSpvType(node->getType()), operand, one,
1384 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001385 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001386
1387 // The result of operation is always stored, but conditionally the
1388 // consumed result. The consumed result is always an r-value.
1389 builder.accessChainStore(result);
1390 builder.clearAccessChain();
1391 if (node->getOp() == glslang::EOpPreIncrement ||
1392 node->getOp() == glslang::EOpPreDecrement)
1393 builder.setAccessChainRValue(result);
1394 else
1395 builder.setAccessChainRValue(operand);
1396 }
1397
1398 return false;
1399
1400 case glslang::EOpEmitStreamVertex:
1401 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1402 return false;
1403 case glslang::EOpEndStreamPrimitive:
1404 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1405 return false;
1406
1407 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001408 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001409 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001410 }
John Kessenich140f3df2015-06-26 16:58:36 -06001411}
1412
1413bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1414{
qining27e04a02016-04-14 16:40:20 -04001415 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1416 if (node->getType().getQualifier().isSpecConstant())
1417 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1418
John Kessenichfc51d282015-08-19 13:34:18 -06001419 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001420 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1421 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001422
1423 // try texturing
1424 result = createImageTextureFunctionCall(node);
1425 if (result != spv::NoResult) {
1426 builder.clearAccessChain();
1427 builder.setAccessChainRValue(result);
1428
1429 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001430 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001431 // "imageStore" is a special case, which has no result
1432 return false;
1433 }
John Kessenichfc51d282015-08-19 13:34:18 -06001434
John Kessenich140f3df2015-06-26 16:58:36 -06001435 glslang::TOperator binOp = glslang::EOpNull;
1436 bool reduceComparison = true;
1437 bool isMatrix = false;
1438 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001439 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001440
1441 assert(node->getOp());
1442
John Kessenichf6640762016-08-01 19:44:00 -06001443 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001444
1445 switch (node->getOp()) {
1446 case glslang::EOpSequence:
1447 {
1448 if (preVisit)
1449 ++sequenceDepth;
1450 else
1451 --sequenceDepth;
1452
1453 if (sequenceDepth == 1) {
1454 // If this is the parent node of all the functions, we want to see them
1455 // early, so all call points have actual SPIR-V functions to reference.
1456 // In all cases, still let the traverser visit the children for us.
1457 makeFunctions(node->getAsAggregate()->getSequence());
1458
John Kessenich6fccb3c2016-09-19 16:01:41 -06001459 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001460 // anything else gets there, so visit out of order, doing them all now.
1461 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1462
John Kessenich6a60c2f2016-12-08 21:01:59 -07001463 // 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 -06001464 // so do them manually.
1465 visitFunctions(node->getAsAggregate()->getSequence());
1466
1467 return false;
1468 }
1469
1470 return true;
1471 }
1472 case glslang::EOpLinkerObjects:
1473 {
1474 if (visit == glslang::EvPreVisit)
1475 linkageOnly = true;
1476 else
1477 linkageOnly = false;
1478
1479 return true;
1480 }
1481 case glslang::EOpComma:
1482 {
1483 // processing from left to right naturally leaves the right-most
1484 // lying around in the access chain
1485 glslang::TIntermSequence& glslangOperands = node->getSequence();
1486 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1487 glslangOperands[i]->traverse(this);
1488
1489 return false;
1490 }
1491 case glslang::EOpFunction:
1492 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001493 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001494 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001495 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001496 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001497 } else {
1498 handleFunctionEntry(node);
1499 }
1500 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001501 if (inEntryPoint)
1502 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001503 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001504 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001505 }
1506
1507 return true;
1508 case glslang::EOpParameters:
1509 // Parameters will have been consumed by EOpFunction processing, but not
1510 // the body, so we still visited the function node's children, making this
1511 // child redundant.
1512 return false;
1513 case glslang::EOpFunctionCall:
1514 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001515 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001516 if (node->isUserDefined())
1517 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001518 // 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 -07001519 if (result) {
1520 builder.clearAccessChain();
1521 builder.setAccessChainRValue(result);
1522 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001523 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001524
1525 return false;
1526 }
1527 case glslang::EOpConstructMat2x2:
1528 case glslang::EOpConstructMat2x3:
1529 case glslang::EOpConstructMat2x4:
1530 case glslang::EOpConstructMat3x2:
1531 case glslang::EOpConstructMat3x3:
1532 case glslang::EOpConstructMat3x4:
1533 case glslang::EOpConstructMat4x2:
1534 case glslang::EOpConstructMat4x3:
1535 case glslang::EOpConstructMat4x4:
1536 case glslang::EOpConstructDMat2x2:
1537 case glslang::EOpConstructDMat2x3:
1538 case glslang::EOpConstructDMat2x4:
1539 case glslang::EOpConstructDMat3x2:
1540 case glslang::EOpConstructDMat3x3:
1541 case glslang::EOpConstructDMat3x4:
1542 case glslang::EOpConstructDMat4x2:
1543 case glslang::EOpConstructDMat4x3:
1544 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06001545 case glslang::EOpConstructIMat2x2:
1546 case glslang::EOpConstructIMat2x3:
1547 case glslang::EOpConstructIMat2x4:
1548 case glslang::EOpConstructIMat3x2:
1549 case glslang::EOpConstructIMat3x3:
1550 case glslang::EOpConstructIMat3x4:
1551 case glslang::EOpConstructIMat4x2:
1552 case glslang::EOpConstructIMat4x3:
1553 case glslang::EOpConstructIMat4x4:
1554 case glslang::EOpConstructUMat2x2:
1555 case glslang::EOpConstructUMat2x3:
1556 case glslang::EOpConstructUMat2x4:
1557 case glslang::EOpConstructUMat3x2:
1558 case glslang::EOpConstructUMat3x3:
1559 case glslang::EOpConstructUMat3x4:
1560 case glslang::EOpConstructUMat4x2:
1561 case glslang::EOpConstructUMat4x3:
1562 case glslang::EOpConstructUMat4x4:
1563 case glslang::EOpConstructBMat2x2:
1564 case glslang::EOpConstructBMat2x3:
1565 case glslang::EOpConstructBMat2x4:
1566 case glslang::EOpConstructBMat3x2:
1567 case glslang::EOpConstructBMat3x3:
1568 case glslang::EOpConstructBMat3x4:
1569 case glslang::EOpConstructBMat4x2:
1570 case glslang::EOpConstructBMat4x3:
1571 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001572#ifdef AMD_EXTENSIONS
1573 case glslang::EOpConstructF16Mat2x2:
1574 case glslang::EOpConstructF16Mat2x3:
1575 case glslang::EOpConstructF16Mat2x4:
1576 case glslang::EOpConstructF16Mat3x2:
1577 case glslang::EOpConstructF16Mat3x3:
1578 case glslang::EOpConstructF16Mat3x4:
1579 case glslang::EOpConstructF16Mat4x2:
1580 case glslang::EOpConstructF16Mat4x3:
1581 case glslang::EOpConstructF16Mat4x4:
1582#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001583 isMatrix = true;
1584 // fall through
1585 case glslang::EOpConstructFloat:
1586 case glslang::EOpConstructVec2:
1587 case glslang::EOpConstructVec3:
1588 case glslang::EOpConstructVec4:
1589 case glslang::EOpConstructDouble:
1590 case glslang::EOpConstructDVec2:
1591 case glslang::EOpConstructDVec3:
1592 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001593#ifdef AMD_EXTENSIONS
1594 case glslang::EOpConstructFloat16:
1595 case glslang::EOpConstructF16Vec2:
1596 case glslang::EOpConstructF16Vec3:
1597 case glslang::EOpConstructF16Vec4:
1598#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001599 case glslang::EOpConstructBool:
1600 case glslang::EOpConstructBVec2:
1601 case glslang::EOpConstructBVec3:
1602 case glslang::EOpConstructBVec4:
1603 case glslang::EOpConstructInt:
1604 case glslang::EOpConstructIVec2:
1605 case glslang::EOpConstructIVec3:
1606 case glslang::EOpConstructIVec4:
1607 case glslang::EOpConstructUint:
1608 case glslang::EOpConstructUVec2:
1609 case glslang::EOpConstructUVec3:
1610 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001611 case glslang::EOpConstructInt64:
1612 case glslang::EOpConstructI64Vec2:
1613 case glslang::EOpConstructI64Vec3:
1614 case glslang::EOpConstructI64Vec4:
1615 case glslang::EOpConstructUint64:
1616 case glslang::EOpConstructU64Vec2:
1617 case glslang::EOpConstructU64Vec3:
1618 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001619 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001620 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001621 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001622 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001623 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001624 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001625 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001626 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001627 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001628 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001629 std::vector<spv::Id> constituents;
1630 for (int c = 0; c < (int)arguments.size(); ++c)
1631 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001632 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001633 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001634 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001635 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001636 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001637
1638 builder.clearAccessChain();
1639 builder.setAccessChainRValue(constructed);
1640
1641 return false;
1642 }
1643
1644 // These six are component-wise compares with component-wise results.
1645 // Forward on to createBinaryOperation(), requesting a vector result.
1646 case glslang::EOpLessThan:
1647 case glslang::EOpGreaterThan:
1648 case glslang::EOpLessThanEqual:
1649 case glslang::EOpGreaterThanEqual:
1650 case glslang::EOpVectorEqual:
1651 case glslang::EOpVectorNotEqual:
1652 {
1653 // Map the operation to a binary
1654 binOp = node->getOp();
1655 reduceComparison = false;
1656 switch (node->getOp()) {
1657 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1658 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1659 default: binOp = node->getOp(); break;
1660 }
1661
1662 break;
1663 }
1664 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001665 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001666 binOp = glslang::EOpMul;
1667 break;
1668 case glslang::EOpOuterProduct:
1669 // two vectors multiplied to make a matrix
1670 binOp = glslang::EOpOuterProduct;
1671 break;
1672 case glslang::EOpDot:
1673 {
qining25262b32016-05-06 17:25:16 -04001674 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001675 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001676 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001677 binOp = glslang::EOpMul;
1678 break;
1679 }
1680 case glslang::EOpMod:
1681 // when an aggregate, this is the floating-point mod built-in function,
1682 // which can be emitted by the one in createBinaryOperation()
1683 binOp = glslang::EOpMod;
1684 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001685 case glslang::EOpEmitVertex:
1686 case glslang::EOpEndPrimitive:
1687 case glslang::EOpBarrier:
1688 case glslang::EOpMemoryBarrier:
1689 case glslang::EOpMemoryBarrierAtomicCounter:
1690 case glslang::EOpMemoryBarrierBuffer:
1691 case glslang::EOpMemoryBarrierImage:
1692 case glslang::EOpMemoryBarrierShared:
1693 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001694 case glslang::EOpAllMemoryBarrierWithGroupSync:
1695 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1696 case glslang::EOpWorkgroupMemoryBarrier:
1697 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001698 noReturnValue = true;
1699 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1700 break;
1701
John Kessenich426394d2015-07-23 10:22:48 -06001702 case glslang::EOpAtomicAdd:
1703 case glslang::EOpAtomicMin:
1704 case glslang::EOpAtomicMax:
1705 case glslang::EOpAtomicAnd:
1706 case glslang::EOpAtomicOr:
1707 case glslang::EOpAtomicXor:
1708 case glslang::EOpAtomicExchange:
1709 case glslang::EOpAtomicCompSwap:
1710 atomic = true;
1711 break;
1712
John Kessenich140f3df2015-06-26 16:58:36 -06001713 default:
1714 break;
1715 }
1716
1717 //
1718 // See if it maps to a regular operation.
1719 //
John Kessenich140f3df2015-06-26 16:58:36 -06001720 if (binOp != glslang::EOpNull) {
1721 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1722 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1723 assert(left && right);
1724
1725 builder.clearAccessChain();
1726 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001727 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001728
1729 builder.clearAccessChain();
1730 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001731 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001732
John Kesseniche485c7a2017-05-31 18:50:53 -06001733 builder.setLine(node->getLoc().line);
qining25262b32016-05-06 17:25:16 -04001734 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001735 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001736 left->getType().getBasicType(), reduceComparison);
1737
1738 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001739 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001740 builder.clearAccessChain();
1741 builder.setAccessChainRValue(result);
1742
1743 return false;
1744 }
1745
John Kessenich426394d2015-07-23 10:22:48 -06001746 //
1747 // Create the list of operands.
1748 //
John Kessenich140f3df2015-06-26 16:58:36 -06001749 glslang::TIntermSequence& glslangOperands = node->getSequence();
1750 std::vector<spv::Id> operands;
1751 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001752 // special case l-value operands; there are just a few
1753 bool lvalue = false;
1754 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001755 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001756 case glslang::EOpModf:
1757 if (arg == 1)
1758 lvalue = true;
1759 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001760 case glslang::EOpInterpolateAtSample:
1761 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001762#ifdef AMD_EXTENSIONS
1763 case glslang::EOpInterpolateAtVertex:
1764#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001765 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001766 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001767
1768 // Does it need a swizzle inversion? If so, evaluation is inverted;
1769 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001770 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001771 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1772 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1773 }
Rex Xu7a26c172015-12-08 17:12:09 +08001774 break;
Rex Xud4782c12015-09-06 16:30:11 +08001775 case glslang::EOpAtomicAdd:
1776 case glslang::EOpAtomicMin:
1777 case glslang::EOpAtomicMax:
1778 case glslang::EOpAtomicAnd:
1779 case glslang::EOpAtomicOr:
1780 case glslang::EOpAtomicXor:
1781 case glslang::EOpAtomicExchange:
1782 case glslang::EOpAtomicCompSwap:
1783 if (arg == 0)
1784 lvalue = true;
1785 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001786 case glslang::EOpAddCarry:
1787 case glslang::EOpSubBorrow:
1788 if (arg == 2)
1789 lvalue = true;
1790 break;
1791 case glslang::EOpUMulExtended:
1792 case glslang::EOpIMulExtended:
1793 if (arg >= 2)
1794 lvalue = true;
1795 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001796 default:
1797 break;
1798 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001799 builder.clearAccessChain();
1800 if (invertedType != spv::NoType && arg == 0)
1801 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1802 else
1803 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001804 if (lvalue)
1805 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06001806 else {
1807 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07001808 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06001809 }
John Kessenich140f3df2015-06-26 16:58:36 -06001810 }
John Kessenich426394d2015-07-23 10:22:48 -06001811
John Kesseniche485c7a2017-05-31 18:50:53 -06001812 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06001813 if (atomic) {
1814 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001815 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001816 } else {
1817 // Pass through to generic operations.
1818 switch (glslangOperands.size()) {
1819 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001820 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001821 break;
1822 case 1:
qining25262b32016-05-06 17:25:16 -04001823 result = createUnaryOperation(
1824 node->getOp(), precision,
1825 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001826 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001827 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001828 break;
1829 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001830 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001831 break;
1832 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001833 if (invertedType)
1834 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001835 }
1836
1837 if (noReturnValue)
1838 return false;
1839
1840 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001841 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001842 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001843 } else {
1844 builder.clearAccessChain();
1845 builder.setAccessChainRValue(result);
1846 return false;
1847 }
1848}
1849
John Kessenich433e9ff2017-01-26 20:31:11 -07001850// This path handles both if-then-else and ?:
1851// The if-then-else has a node type of void, while
1852// ?: has either a void or a non-void node type
1853//
1854// Leaving the result, when not void:
1855// GLSL only has r-values as the result of a :?, but
1856// if we have an l-value, that can be more efficient if it will
1857// become the base of a complex r-value expression, because the
1858// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001859bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1860{
John Kessenich433e9ff2017-01-26 20:31:11 -07001861 // See if it simple and safe to generate OpSelect instead of using control flow.
1862 // Crucially, side effects must be avoided, and there are performance trade-offs.
1863 // Return true if good idea (and safe) for OpSelect, false otherwise.
1864 const auto selectPolicy = [&]() -> bool {
John Kessenich04794372017-03-01 13:49:11 -07001865 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
1866 node->getBasicType() == glslang::EbtVoid)
John Kessenich433e9ff2017-01-26 20:31:11 -07001867 return false;
1868
1869 if (node->getTrueBlock() == nullptr ||
1870 node->getFalseBlock() == nullptr)
1871 return false;
1872
1873 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
1874 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
1875
1876 // return true if a single operand to ? : is okay for OpSelect
1877 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001878 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07001879 };
1880
1881 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
1882 operandOkay(node->getFalseBlock()->getAsTyped());
1883 };
1884
1885 // Emit OpSelect for this selection.
1886 const auto handleAsOpSelect = [&]() {
1887 node->getCondition()->traverse(this);
1888 spv::Id condition = accessChainLoad(node->getCondition()->getType());
1889 node->getTrueBlock()->traverse(this);
1890 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1891 node->getFalseBlock()->traverse(this);
1892 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1893
John Kesseniche485c7a2017-05-31 18:50:53 -06001894 builder.setLine(node->getLoc().line);
1895
John Kesseniche434ad92017-03-30 10:09:28 -06001896 // smear condition to vector, if necessary (AST is always scalar)
1897 if (builder.isVector(trueValue))
1898 condition = builder.smearScalar(spv::NoPrecision, condition,
1899 builder.makeVectorType(builder.makeBoolType(),
1900 builder.getNumComponents(trueValue)));
1901
1902 spv::Id select = builder.createTriOp(spv::OpSelect,
1903 convertGlslangToSpvType(node->getType()), condition,
1904 trueValue, falseValue);
John Kessenich433e9ff2017-01-26 20:31:11 -07001905 builder.clearAccessChain();
1906 builder.setAccessChainRValue(select);
1907 };
1908
1909 // Try for OpSelect
1910
1911 if (selectPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001912 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1913 if (node->getType().getQualifier().isSpecConstant())
1914 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1915
John Kessenich433e9ff2017-01-26 20:31:11 -07001916 handleAsOpSelect();
1917 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001918 }
1919
John Kessenich433e9ff2017-01-26 20:31:11 -07001920 // Instead, emit control flow...
1921
1922 // Don't handle results as temporaries, because there will be two names
1923 // and better to leave SSA to later passes.
1924 spv::Id result = (node->getBasicType() == glslang::EbtVoid)
1925 ? spv::NoResult
1926 : builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1927
John Kessenich140f3df2015-06-26 16:58:36 -06001928 // emit the condition before doing anything with selection
1929 node->getCondition()->traverse(this);
1930
1931 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001932 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001933
John Kessenich433e9ff2017-01-26 20:31:11 -07001934 // emit the "then" statement
1935 if (node->getTrueBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001936 node->getTrueBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001937 if (result != spv::NoResult)
1938 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001939 }
1940
John Kessenich433e9ff2017-01-26 20:31:11 -07001941 if (node->getFalseBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001942 ifBuilder.makeBeginElse();
1943 // emit the "else" statement
1944 node->getFalseBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001945 if (result != spv::NoResult)
John Kessenich32cfd492016-02-02 12:37:46 -07001946 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001947 }
1948
John Kessenich433e9ff2017-01-26 20:31:11 -07001949 // finish off the control flow
John Kessenich140f3df2015-06-26 16:58:36 -06001950 ifBuilder.makeEndIf();
1951
John Kessenich433e9ff2017-01-26 20:31:11 -07001952 if (result != spv::NoResult) {
John Kessenich140f3df2015-06-26 16:58:36 -06001953 // GLSL only has r-values as the result of a :?, but
1954 // if we have an l-value, that can be more efficient if it will
1955 // become the base of a complex r-value expression, because the
1956 // next layer copies r-values into memory to use the access-chain mechanism
1957 builder.clearAccessChain();
1958 builder.setAccessChainLValue(result);
1959 }
1960
1961 return false;
1962}
1963
1964bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1965{
1966 // emit and get the condition before doing anything with switch
1967 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001968 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001969
1970 // browse the children to sort out code segments
1971 int defaultSegment = -1;
1972 std::vector<TIntermNode*> codeSegments;
1973 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1974 std::vector<int> caseValues;
1975 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1976 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1977 TIntermNode* child = *c;
1978 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001979 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001980 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001981 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001982 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1983 } else
1984 codeSegments.push_back(child);
1985 }
1986
qining25262b32016-05-06 17:25:16 -04001987 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001988 // statements between the last case and the end of the switch statement
1989 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1990 (int)codeSegments.size() == defaultSegment)
1991 codeSegments.push_back(nullptr);
1992
1993 // make the switch statement
1994 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001995 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001996
1997 // emit all the code in the segments
1998 breakForLoop.push(false);
1999 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2000 builder.nextSwitchSegment(segmentBlocks, s);
2001 if (codeSegments[s])
2002 codeSegments[s]->traverse(this);
2003 else
2004 builder.addSwitchBreak();
2005 }
2006 breakForLoop.pop();
2007
2008 builder.endSwitch(segmentBlocks);
2009
2010 return false;
2011}
2012
2013void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2014{
2015 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002016 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002017
2018 builder.clearAccessChain();
2019 builder.setAccessChainRValue(constant);
2020}
2021
2022bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2023{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002024 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002025 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002026
2027 // Loop control:
2028 const spv::LoopControlMask control = TranslateLoopControl(node->getLoopControl());
2029
2030 // TODO: dependency length
2031
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002032 // Spec requires back edges to target header blocks, and every header block
2033 // must dominate its merge block. Make a header block first to ensure these
2034 // conditions are met. By definition, it will contain OpLoopMerge, followed
2035 // by a block-ending branch. But we don't want to put any other body/test
2036 // instructions in it, since the body/test may have arbitrary instructions,
2037 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002038 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002039 builder.setBuildPoint(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002040 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002041 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002042 spv::Block& test = builder.makeNewBlock();
2043 builder.createBranch(&test);
2044
2045 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002046 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002047 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002048 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2049
2050 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002051 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002052 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002053 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002054 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002055 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002056
2057 builder.setBuildPoint(&blocks.continue_target);
2058 if (node->getTerminal())
2059 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002060 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002061 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002062 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002063 builder.createBranch(&blocks.body);
2064
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002065 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002066 builder.setBuildPoint(&blocks.body);
2067 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002068 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002069 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002070 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002071
2072 builder.setBuildPoint(&blocks.continue_target);
2073 if (node->getTerminal())
2074 node->getTerminal()->traverse(this);
2075 if (node->getTest()) {
2076 node->getTest()->traverse(this);
2077 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002078 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002079 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002080 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002081 // TODO: unless there was a break/return/discard instruction
2082 // somewhere in the body, this is an infinite loop, so we should
2083 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002084 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002085 }
John Kessenich140f3df2015-06-26 16:58:36 -06002086 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002087 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002088 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002089 return false;
2090}
2091
2092bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2093{
2094 if (node->getExpression())
2095 node->getExpression()->traverse(this);
2096
John Kesseniche485c7a2017-05-31 18:50:53 -06002097 builder.setLine(node->getLoc().line);
2098
John Kessenich140f3df2015-06-26 16:58:36 -06002099 switch (node->getFlowOp()) {
2100 case glslang::EOpKill:
2101 builder.makeDiscard();
2102 break;
2103 case glslang::EOpBreak:
2104 if (breakForLoop.top())
2105 builder.createLoopExit();
2106 else
2107 builder.addSwitchBreak();
2108 break;
2109 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002110 builder.createLoopContinue();
2111 break;
2112 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002113 if (node->getExpression()) {
2114 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2115 spv::Id returnId = accessChainLoad(glslangReturnType);
2116 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2117 builder.clearAccessChain();
2118 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2119 builder.setAccessChainLValue(copyId);
2120 multiTypeStore(glslangReturnType, returnId);
2121 returnId = builder.createLoad(copyId);
2122 }
2123 builder.makeReturn(false, returnId);
2124 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002125 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002126
2127 builder.clearAccessChain();
2128 break;
2129
2130 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002131 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002132 break;
2133 }
2134
2135 return false;
2136}
2137
2138spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2139{
qining25262b32016-05-06 17:25:16 -04002140 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002141 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002142 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002143 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002144 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002145 }
2146
2147 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002148 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002149 spv::Id spvType = convertGlslangToSpvType(node->getType());
2150
Rex Xuf89ad982017-04-07 23:22:33 +08002151#ifdef AMD_EXTENSIONS
2152 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16);
2153 if (contains16BitType) {
2154 if (storageClass == spv::StorageClassInput || storageClass == spv::StorageClassOutput) {
2155 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2156 builder.addCapability(spv::CapabilityStorageInputOutput16);
2157 } else if (storageClass == spv::StorageClassPushConstant) {
2158 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2159 builder.addCapability(spv::CapabilityStoragePushConstant16);
2160 } else if (storageClass == spv::StorageClassUniform) {
2161 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2162 builder.addCapability(spv::CapabilityStorageUniform16);
2163 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2164 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2165 }
2166 }
2167#endif
2168
John Kessenich140f3df2015-06-26 16:58:36 -06002169 const char* name = node->getName().c_str();
2170 if (glslang::IsAnonymous(name))
2171 name = "";
2172
2173 return builder.createVariable(storageClass, spvType, name);
2174}
2175
2176// Return type Id of the sampled type.
2177spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2178{
2179 switch (sampler.type) {
2180 case glslang::EbtFloat: return builder.makeFloatType(32);
2181 case glslang::EbtInt: return builder.makeIntType(32);
2182 case glslang::EbtUint: return builder.makeUintType(32);
2183 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002184 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002185 return builder.makeFloatType(32);
2186 }
2187}
2188
John Kessenich8c8505c2016-07-26 12:50:38 -06002189// If node is a swizzle operation, return the type that should be used if
2190// the swizzle base is first consumed by another operation, before the swizzle
2191// is applied.
2192spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2193{
John Kessenichecba76f2017-01-06 00:34:48 -07002194 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002195 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2196 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2197 else
2198 return spv::NoType;
2199}
2200
2201// When inverting a swizzle with a parent op, this function
2202// will apply the swizzle operation to a completed parent operation.
2203spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2204{
2205 std::vector<unsigned> swizzle;
2206 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2207 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2208}
2209
John Kessenich8c8505c2016-07-26 12:50:38 -06002210// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2211void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2212{
2213 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2214 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2215 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2216}
2217
John Kessenich3ac051e2015-12-20 11:29:16 -07002218// Convert from a glslang type to an SPV type, by calling into a
2219// recursive version of this function. This establishes the inherited
2220// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002221spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2222{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002223 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002224}
2225
2226// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002227// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002228// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002229spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002230{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002231 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002232
2233 switch (type.getBasicType()) {
2234 case glslang::EbtVoid:
2235 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002236 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002237 break;
2238 case glslang::EbtFloat:
2239 spvType = builder.makeFloatType(32);
2240 break;
2241 case glslang::EbtDouble:
2242 spvType = builder.makeFloatType(64);
2243 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002244#ifdef AMD_EXTENSIONS
2245 case glslang::EbtFloat16:
2246 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002247 spvType = builder.makeFloatType(16);
2248 break;
2249#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002250 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002251 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2252 // a 32-bit int where non-0 means true.
2253 if (explicitLayout != glslang::ElpNone)
2254 spvType = builder.makeUintType(32);
2255 else
2256 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002257 break;
2258 case glslang::EbtInt:
2259 spvType = builder.makeIntType(32);
2260 break;
2261 case glslang::EbtUint:
2262 spvType = builder.makeUintType(32);
2263 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002264 case glslang::EbtInt64:
2265 builder.addCapability(spv::CapabilityInt64);
2266 spvType = builder.makeIntType(64);
2267 break;
2268 case glslang::EbtUint64:
2269 builder.addCapability(spv::CapabilityInt64);
2270 spvType = builder.makeUintType(64);
2271 break;
John Kessenich426394d2015-07-23 10:22:48 -06002272 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002273 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002274 spvType = builder.makeUintType(32);
2275 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002276 case glslang::EbtSampler:
2277 {
2278 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002279 if (sampler.sampler) {
2280 // pure sampler
2281 spvType = builder.makeSamplerType();
2282 } else {
2283 // an image is present, make its type
2284 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2285 sampler.image ? 2 : 1, TranslateImageFormat(type));
2286 if (sampler.combined) {
2287 // already has both image and sampler, make the combined type
2288 spvType = builder.makeSampledImageType(spvType);
2289 }
John Kessenich55e7d112015-11-15 21:33:39 -07002290 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002291 }
John Kessenich140f3df2015-06-26 16:58:36 -06002292 break;
2293 case glslang::EbtStruct:
2294 case glslang::EbtBlock:
2295 {
2296 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002297 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002298
2299 // Try to share structs for different layouts, but not yet for other
2300 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002301 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002302 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002303 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002304 break;
2305
2306 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002307 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002308 memberRemapper[glslangMembers].resize(glslangMembers->size());
2309 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002310 }
2311 break;
2312 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002313 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002314 break;
2315 }
2316
2317 if (type.isMatrix())
2318 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2319 else {
2320 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2321 if (type.getVectorSize() > 1)
2322 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2323 }
2324
2325 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002326 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2327
John Kessenichc9a80832015-09-12 12:17:44 -06002328 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002329 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002330 // We need to decorate array strides for types needing explicit layout, except blocks.
2331 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002332 // Use a dummy glslang type for querying internal strides of
2333 // arrays of arrays, but using just a one-dimensional array.
2334 glslang::TType simpleArrayType(type, 0); // deference type of the array
2335 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2336 simpleArrayType.getArraySizes().dereference();
2337
2338 // Will compute the higher-order strides here, rather than making a whole
2339 // pile of types and doing repetitive recursion on their contents.
2340 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2341 }
John Kessenichf8842e52016-01-04 19:22:56 -07002342
2343 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002344 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002345 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002346 if (stride > 0)
2347 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002348 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002349 }
2350 } else {
2351 // single-dimensional array, and don't yet have stride
2352
John Kessenichf8842e52016-01-04 19:22:56 -07002353 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002354 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2355 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002356 }
John Kessenich31ed4832015-09-09 17:51:38 -06002357
John Kessenichc9a80832015-09-12 12:17:44 -06002358 // Do the outer dimension, which might not be known for a runtime-sized array
2359 if (type.isRuntimeSizedArray()) {
2360 spvType = builder.makeRuntimeArray(spvType);
2361 } else {
2362 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002363 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002364 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002365 if (stride > 0)
2366 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002367 }
2368
2369 return spvType;
2370}
2371
John Kessenich0e737842017-03-24 18:38:16 -06002372// TODO: this functionality should exist at a higher level, in creating the AST
2373//
2374// Identify interface members that don't have their required extension turned on.
2375//
2376bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2377{
2378 auto& extensions = glslangIntermediate->getRequestedExtensions();
2379
Rex Xubcf291a2017-03-29 23:01:36 +08002380 if (member.getFieldName() == "gl_ViewportMask" &&
2381 extensions.find("GL_NV_viewport_array2") == extensions.end())
2382 return true;
2383 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2384 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2385 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002386 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2387 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2388 return true;
2389 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2390 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2391 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002392 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2393 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2394 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002395
2396 return false;
2397};
2398
John Kessenich6090df02016-06-30 21:18:02 -06002399// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2400// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2401// Mutually recursive with convertGlslangToSpvType().
2402spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2403 const glslang::TTypeList* glslangMembers,
2404 glslang::TLayoutPacking explicitLayout,
2405 const glslang::TQualifier& qualifier)
2406{
2407 // Create a vector of struct types for SPIR-V to consume
2408 std::vector<spv::Id> spvMembers;
2409 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
John Kessenich6090df02016-06-30 21:18:02 -06002410 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2411 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2412 if (glslangMember.hiddenMember()) {
2413 ++memberDelta;
2414 if (type.getBasicType() == glslang::EbtBlock)
2415 memberRemapper[glslangMembers][i] = -1;
2416 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002417 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002418 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002419 if (filterMember(glslangMember))
2420 continue;
2421 }
John Kessenich6090df02016-06-30 21:18:02 -06002422 // modify just this child's view of the qualifier
2423 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2424 InheritQualifiers(memberQualifier, qualifier);
2425
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002426 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06002427 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002428 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06002429
2430 // recurse
2431 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2432 }
2433 }
2434
2435 // Make the SPIR-V type
2436 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002437 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002438 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2439
2440 // Decorate it
2441 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2442
2443 return spvType;
2444}
2445
2446void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2447 const glslang::TTypeList* glslangMembers,
2448 glslang::TLayoutPacking explicitLayout,
2449 const glslang::TQualifier& qualifier,
2450 spv::Id spvType)
2451{
2452 // Name and decorate the non-hidden members
2453 int offset = -1;
2454 int locationOffset = 0; // for use within the members of this struct
2455 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2456 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2457 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002458 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002459 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002460 if (filterMember(glslangMember))
2461 continue;
2462 }
John Kessenich6090df02016-06-30 21:18:02 -06002463
2464 // modify just this child's view of the qualifier
2465 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2466 InheritQualifiers(memberQualifier, qualifier);
2467
2468 // using -1 above to indicate a hidden member
2469 if (member >= 0) {
2470 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2471 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2472 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2473 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002474 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2475 type.getQualifier().storage == glslang::EvqVaryingOut) {
2476 if (type.getBasicType() == glslang::EbtBlock ||
2477 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002478 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2479 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2480 }
2481 }
2482 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2483
2484 if (qualifier.storage == glslang::EvqBuffer) {
2485 std::vector<spv::Decoration> memory;
2486 TranslateMemoryDecoration(memberQualifier, memory);
2487 for (unsigned int i = 0; i < memory.size(); ++i)
2488 addMemberDecoration(spvType, member, memory[i]);
2489 }
2490
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002491 // Location assignment was already completed correctly by the front end,
2492 // just track whether a member needs to be decorated.
John Kessenich2f47bc92016-06-30 21:47:35 -06002493 // Ignore member locations if the container is an array, as that's
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002494 // ill-specified and decisions have been made to not allow this.
2495 if (! type.isArray() && memberQualifier.hasLocation())
2496 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06002497
John Kessenich2f47bc92016-06-30 21:47:35 -06002498 if (qualifier.hasLocation()) // track for upcoming inheritance
2499 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2500
John Kessenich6090df02016-06-30 21:18:02 -06002501 // component, XFB, others
2502 if (glslangMember.getQualifier().hasComponent())
2503 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2504 if (glslangMember.getQualifier().hasXfbOffset())
2505 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2506 else if (explicitLayout != glslang::ElpNone) {
2507 // figure out what to do with offset, which is accumulating
2508 int nextOffset;
2509 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2510 if (offset >= 0)
2511 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2512 offset = nextOffset;
2513 }
2514
2515 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2516 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2517
2518 // built-in variable decorations
2519 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002520 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002521 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002522
2523#ifdef NV_EXTENSIONS
2524 if (builtIn == spv::BuiltInLayer) {
2525 // SPV_NV_viewport_array2 extension
2526 if (glslangMember.getQualifier().layoutViewportRelative){
2527 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2528 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2529 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2530 }
2531 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2532 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2533 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2534 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2535 }
2536 }
chaocdf3956c2017-02-14 14:52:34 -08002537 if (glslangMember.getQualifier().layoutPassthrough) {
2538 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2539 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2540 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2541 }
chaoc771d89f2017-01-13 01:10:53 -08002542#endif
John Kessenich6090df02016-06-30 21:18:02 -06002543 }
2544 }
2545
2546 // Decorate the structure
2547 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich67027182017-04-19 18:34:49 -06002548 addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002549 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2550 builder.addCapability(spv::CapabilityGeometryStreams);
2551 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2552 }
2553 if (glslangIntermediate->getXfbMode()) {
2554 builder.addCapability(spv::CapabilityTransformFeedback);
2555 if (type.getQualifier().hasXfbStride())
2556 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2557 if (type.getQualifier().hasXfbBuffer())
2558 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2559 }
2560}
2561
John Kessenich6c292d32016-02-15 20:58:50 -07002562// Turn the expression forming the array size into an id.
2563// This is not quite trivial, because of specialization constants.
2564// Sometimes, a raw constant is turned into an Id, and sometimes
2565// a specialization constant expression is.
2566spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2567{
2568 // First, see if this is sized with a node, meaning a specialization constant:
2569 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2570 if (specNode != nullptr) {
2571 builder.clearAccessChain();
2572 specNode->traverse(this);
2573 return accessChainLoad(specNode->getAsTyped()->getType());
2574 }
qining25262b32016-05-06 17:25:16 -04002575
John Kessenich6c292d32016-02-15 20:58:50 -07002576 // Otherwise, need a compile-time (front end) size, get it:
2577 int size = arraySizes.getDimSize(dim);
2578 assert(size > 0);
2579 return builder.makeUintConstant(size);
2580}
2581
John Kessenich103bef92016-02-08 21:38:15 -07002582// Wrap the builder's accessChainLoad to:
2583// - localize handling of RelaxedPrecision
2584// - use the SPIR-V inferred type instead of another conversion of the glslang type
2585// (avoids unnecessary work and possible type punning for structures)
2586// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002587spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2588{
John Kessenich103bef92016-02-08 21:38:15 -07002589 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2590 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2591
2592 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002593 if (type.getBasicType() == glslang::EbtBool) {
2594 if (builder.isScalarType(nominalTypeId)) {
2595 // Conversion for bool
2596 spv::Id boolType = builder.makeBoolType();
2597 if (nominalTypeId != boolType)
2598 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2599 } else if (builder.isVectorType(nominalTypeId)) {
2600 // Conversion for bvec
2601 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2602 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2603 if (nominalTypeId != bvecType)
2604 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2605 }
2606 }
John Kessenich103bef92016-02-08 21:38:15 -07002607
2608 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002609}
2610
Rex Xu27253232016-02-23 17:51:09 +08002611// Wrap the builder's accessChainStore to:
2612// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002613//
2614// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002615void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2616{
2617 // Need to convert to abstract types when necessary
2618 if (type.getBasicType() == glslang::EbtBool) {
2619 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2620
2621 if (builder.isScalarType(nominalTypeId)) {
2622 // Conversion for bool
2623 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06002624 if (nominalTypeId != boolType) {
2625 // keep these outside arguments, for determinant order-of-evaluation
2626 spv::Id one = builder.makeUintConstant(1);
2627 spv::Id zero = builder.makeUintConstant(0);
2628 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2629 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06002630 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08002631 } else if (builder.isVectorType(nominalTypeId)) {
2632 // Conversion for bvec
2633 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2634 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06002635 if (nominalTypeId != bvecType) {
2636 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06002637 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2638 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2639 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06002640 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06002641 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
2642 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08002643 }
2644 }
2645
2646 builder.accessChainStore(rvalue);
2647}
2648
John Kessenich4bf71552016-09-02 11:20:21 -06002649// For storing when types match at the glslang level, but not might match at the
2650// SPIR-V level.
2651//
2652// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002653// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002654// as in a member-decorated way.
2655//
2656// NOTE: This function can handle any store request; if it's not special it
2657// simplifies to a simple OpStore.
2658//
2659// Implicitly uses the existing builder.accessChain as the storage target.
2660void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2661{
John Kessenichb3e24e42016-09-11 12:33:43 -06002662 // we only do the complex path here if it's an aggregate
2663 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002664 accessChainStore(type, rValue);
2665 return;
2666 }
2667
John Kessenichb3e24e42016-09-11 12:33:43 -06002668 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002669 spv::Id rType = builder.getTypeId(rValue);
2670 spv::Id lValue = builder.accessChainGetLValue();
2671 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2672 if (lType == rType) {
2673 accessChainStore(type, rValue);
2674 return;
2675 }
2676
John Kessenichb3e24e42016-09-11 12:33:43 -06002677 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002678 // where the two types were the same type in GLSL. This requires member
2679 // by member copy, recursively.
2680
John Kessenichb3e24e42016-09-11 12:33:43 -06002681 // If an array, copy element by element.
2682 if (type.isArray()) {
2683 glslang::TType glslangElementType(type, 0);
2684 spv::Id elementRType = builder.getContainedTypeId(rType);
2685 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2686 // get the source member
2687 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002688
John Kessenichb3e24e42016-09-11 12:33:43 -06002689 // set up the target storage
2690 builder.clearAccessChain();
2691 builder.setAccessChainLValue(lValue);
2692 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002693
John Kessenichb3e24e42016-09-11 12:33:43 -06002694 // store the member
2695 multiTypeStore(glslangElementType, elementRValue);
2696 }
2697 } else {
2698 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002699
John Kessenichb3e24e42016-09-11 12:33:43 -06002700 // loop over structure members
2701 const glslang::TTypeList& members = *type.getStruct();
2702 for (int m = 0; m < (int)members.size(); ++m) {
2703 const glslang::TType& glslangMemberType = *members[m].type;
2704
2705 // get the source member
2706 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2707 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2708
2709 // set up the target storage
2710 builder.clearAccessChain();
2711 builder.setAccessChainLValue(lValue);
2712 builder.accessChainPush(builder.makeIntConstant(m));
2713
2714 // store the member
2715 multiTypeStore(glslangMemberType, memberRValue);
2716 }
John Kessenich4bf71552016-09-02 11:20:21 -06002717 }
2718}
2719
John Kessenichf85e8062015-12-19 13:57:10 -07002720// Decide whether or not this type should be
2721// decorated with offsets and strides, and if so
2722// whether std140 or std430 rules should be applied.
2723glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002724{
John Kessenichf85e8062015-12-19 13:57:10 -07002725 // has to be a block
2726 if (type.getBasicType() != glslang::EbtBlock)
2727 return glslang::ElpNone;
2728
2729 // has to be a uniform or buffer block
2730 if (type.getQualifier().storage != glslang::EvqUniform &&
2731 type.getQualifier().storage != glslang::EvqBuffer)
2732 return glslang::ElpNone;
2733
2734 // return the layout to use
2735 switch (type.getQualifier().layoutPacking) {
2736 case glslang::ElpStd140:
2737 case glslang::ElpStd430:
2738 return type.getQualifier().layoutPacking;
2739 default:
2740 return glslang::ElpNone;
2741 }
John Kessenich31ed4832015-09-09 17:51:38 -06002742}
2743
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002744// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002745int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002746{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002747 int size;
John Kessenich49987892015-12-29 17:11:44 -07002748 int stride;
2749 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002750
2751 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002752}
2753
John Kessenich49987892015-12-29 17:11:44 -07002754// 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 -07002755// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002756int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002757{
John Kessenich49987892015-12-29 17:11:44 -07002758 glslang::TType elementType;
2759 elementType.shallowCopy(matrixType);
2760 elementType.clearArraySizes();
2761
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002762 int size;
John Kessenich49987892015-12-29 17:11:44 -07002763 int stride;
2764 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2765
2766 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002767}
2768
John Kessenich5e4b1242015-08-06 22:53:06 -06002769// Given a member type of a struct, realign the current offset for it, and compute
2770// the next (not yet aligned) offset for the next member, which will get aligned
2771// on the next call.
2772// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2773// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2774// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002775void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002776 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002777{
2778 // this will get a positive value when deemed necessary
2779 nextOffset = -1;
2780
John Kessenich5e4b1242015-08-06 22:53:06 -06002781 // override anything in currentOffset with user-set offset
2782 if (memberType.getQualifier().hasOffset())
2783 currentOffset = memberType.getQualifier().layoutOffset;
2784
2785 // It could be that current linker usage in glslang updated all the layoutOffset,
2786 // in which case the following code does not matter. But, that's not quite right
2787 // once cross-compilation unit GLSL validation is done, as the original user
2788 // settings are needed in layoutOffset, and then the following will come into play.
2789
John Kessenichf85e8062015-12-19 13:57:10 -07002790 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002791 if (! memberType.getQualifier().hasOffset())
2792 currentOffset = -1;
2793
2794 return;
2795 }
2796
John Kessenichf85e8062015-12-19 13:57:10 -07002797 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002798 if (currentOffset < 0)
2799 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002800
John Kessenich5e4b1242015-08-06 22:53:06 -06002801 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2802 // but possibly not yet correctly aligned.
2803
2804 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002805 int dummyStride;
2806 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06002807
2808 // Adjust alignment for HLSL rules
2809 if (glslangIntermediate->usingHlslOFfsets() &&
2810 ! memberType.isArray() && memberType.isVector()) {
2811 int dummySize;
2812 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
2813 if (componentAlignment <= 4)
2814 memberAlignment = componentAlignment;
2815 }
2816
2817 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06002818 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06002819
2820 // Bump up to vec4 if there is a bad straddle
2821 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
2822 glslang::RoundToPow2(currentOffset, 16);
2823
John Kessenich5e4b1242015-08-06 22:53:06 -06002824 nextOffset = currentOffset + memberSize;
2825}
2826
David Netoa901ffe2016-06-08 14:11:40 +01002827void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002828{
David Netoa901ffe2016-06-08 14:11:40 +01002829 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2830 switch (glslangBuiltIn)
2831 {
2832 case glslang::EbvClipDistance:
2833 case glslang::EbvCullDistance:
2834 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08002835#ifdef NV_EXTENSIONS
2836 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +08002837 case glslang::EbvViewportIndex:
chaoc771d89f2017-01-13 01:10:53 -08002838 case glslang::EbvViewportMaskNV:
2839 case glslang::EbvSecondaryPositionNV:
2840 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08002841 case glslang::EbvPositionPerViewNV:
2842 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08002843#endif
David Netoa901ffe2016-06-08 14:11:40 +01002844 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2845 // Alternately, we could just call this for any glslang built-in, since the
2846 // capability already guards against duplicates.
2847 TranslateBuiltInDecoration(glslangBuiltIn, false);
2848 break;
2849 default:
2850 // Capabilities were already generated when the struct was declared.
2851 break;
2852 }
John Kessenichebb50532016-05-16 19:22:05 -06002853}
2854
John Kessenich6fccb3c2016-09-19 16:01:41 -06002855bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002856{
John Kessenicheee9d532016-09-19 18:09:30 -06002857 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002858}
2859
2860// Make all the functions, skeletally, without actually visiting their bodies.
2861void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2862{
2863 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2864 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002865 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002866 continue;
2867
2868 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002869 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002870 //
qining25262b32016-05-06 17:25:16 -04002871 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002872 // function. What it is an address of varies:
2873 //
John Kessenich4bf71552016-09-02 11:20:21 -06002874 // - "in" parameters not marked as "const" can be written to without modifying the calling
2875 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002876 //
2877 // - "const in" parameters can just be the r-value, as no writes need occur.
2878 //
John Kessenich4bf71552016-09-02 11:20:21 -06002879 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2880 // 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 -06002881
2882 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002883 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002884 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2885
John Kessenich37789792017-03-21 23:56:40 -06002886 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() == glslangIntermediate->implicitThisName;
2887
John Kessenich140f3df2015-06-26 16:58:36 -06002888 for (int p = 0; p < (int)parameters.size(); ++p) {
2889 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2890 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenich37789792017-03-21 23:56:40 -06002891 // can we pass by reference?
2892 if (paramType.containsOpaque() || // sampler, etc.
John Kessenich4960baa2017-03-19 18:09:59 -06002893 (paramType.getBasicType() == glslang::EbtBlock &&
John Kessenich37789792017-03-21 23:56:40 -06002894 paramType.getQualifier().storage == glslang::EvqBuffer) || // SSBO
John Kessenichaa3c64c2017-03-28 09:52:38 -06002895 (p == 0 && implicitThis)) // implicit 'this'
John Kessenicha5c5fb62017-05-05 05:09:58 -06002896 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002897 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002898 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2899 else
John Kessenich4bf71552016-09-02 11:20:21 -06002900 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002901 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002902 paramTypes.push_back(typeId);
2903 }
2904
2905 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002906 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2907 convertGlslangToSpvType(glslFunction->getType()),
2908 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06002909 if (implicitThis)
2910 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06002911
2912 // Track function to emit/call later
2913 functionMap[glslFunction->getName().c_str()] = function;
2914
2915 // Set the parameter id's
2916 for (int p = 0; p < (int)parameters.size(); ++p) {
2917 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2918 // give a name too
2919 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2920 }
2921 }
2922}
2923
2924// Process all the initializers, while skipping the functions and link objects
2925void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2926{
2927 builder.setBuildPoint(shaderEntry->getLastBlock());
2928 for (int i = 0; i < (int)initializers.size(); ++i) {
2929 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2930 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2931
2932 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06002933 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06002934 initializer->traverse(this);
2935 }
2936 }
2937}
2938
2939// Process all the functions, while skipping initializers.
2940void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2941{
2942 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2943 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07002944 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06002945 node->traverse(this);
2946 }
2947}
2948
2949void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2950{
qining25262b32016-05-06 17:25:16 -04002951 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002952 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06002953 currentFunction = functionMap[node->getName().c_str()];
2954 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06002955 builder.setBuildPoint(functionBlock);
2956}
2957
Rex Xu04db3f52015-09-16 11:44:02 +08002958void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002959{
Rex Xufc618912015-09-09 16:42:49 +08002960 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002961
2962 glslang::TSampler sampler = {};
2963 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002964 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002965 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2966 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2967 }
2968
John Kessenich140f3df2015-06-26 16:58:36 -06002969 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2970 builder.clearAccessChain();
2971 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002972
2973 // Special case l-value operands
2974 bool lvalue = false;
2975 switch (node.getOp()) {
2976 case glslang::EOpImageAtomicAdd:
2977 case glslang::EOpImageAtomicMin:
2978 case glslang::EOpImageAtomicMax:
2979 case glslang::EOpImageAtomicAnd:
2980 case glslang::EOpImageAtomicOr:
2981 case glslang::EOpImageAtomicXor:
2982 case glslang::EOpImageAtomicExchange:
2983 case glslang::EOpImageAtomicCompSwap:
2984 if (i == 0)
2985 lvalue = true;
2986 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002987 case glslang::EOpSparseImageLoad:
2988 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2989 lvalue = true;
2990 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002991 case glslang::EOpSparseTexture:
2992 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2993 lvalue = true;
2994 break;
2995 case glslang::EOpSparseTextureClamp:
2996 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2997 lvalue = true;
2998 break;
2999 case glslang::EOpSparseTextureLod:
3000 case glslang::EOpSparseTextureOffset:
3001 if (i == 3)
3002 lvalue = true;
3003 break;
3004 case glslang::EOpSparseTextureFetch:
3005 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3006 lvalue = true;
3007 break;
3008 case glslang::EOpSparseTextureFetchOffset:
3009 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3010 lvalue = true;
3011 break;
3012 case glslang::EOpSparseTextureLodOffset:
3013 case glslang::EOpSparseTextureGrad:
3014 case glslang::EOpSparseTextureOffsetClamp:
3015 if (i == 4)
3016 lvalue = true;
3017 break;
3018 case glslang::EOpSparseTextureGradOffset:
3019 case glslang::EOpSparseTextureGradClamp:
3020 if (i == 5)
3021 lvalue = true;
3022 break;
3023 case glslang::EOpSparseTextureGradOffsetClamp:
3024 if (i == 6)
3025 lvalue = true;
3026 break;
3027 case glslang::EOpSparseTextureGather:
3028 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3029 lvalue = true;
3030 break;
3031 case glslang::EOpSparseTextureGatherOffset:
3032 case glslang::EOpSparseTextureGatherOffsets:
3033 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3034 lvalue = true;
3035 break;
Rex Xufc618912015-09-09 16:42:49 +08003036 default:
3037 break;
3038 }
3039
Rex Xu6b86d492015-09-16 17:48:22 +08003040 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003041 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003042 else
John Kessenich32cfd492016-02-02 12:37:46 -07003043 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003044 }
3045}
3046
John Kessenichfc51d282015-08-19 13:34:18 -06003047void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003048{
John Kessenichfc51d282015-08-19 13:34:18 -06003049 builder.clearAccessChain();
3050 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003051 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003052}
John Kessenich140f3df2015-06-26 16:58:36 -06003053
John Kessenichfc51d282015-08-19 13:34:18 -06003054spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3055{
John Kesseniche485c7a2017-05-31 18:50:53 -06003056 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003057 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003058
3059 builder.setLine(node->getLoc().line);
3060
John Kessenich8c8505c2016-07-26 12:50:38 -06003061 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06003062
John Kessenichfc51d282015-08-19 13:34:18 -06003063 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003064 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3065 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
3066 std::vector<spv::Id> arguments;
3067 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003068 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003069 else
3070 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003071 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003072
3073 spv::Builder::TextureParameters params = { };
3074 params.sampler = arguments[0];
3075
Rex Xu04db3f52015-09-16 11:44:02 +08003076 glslang::TCrackedTextureOp cracked;
3077 node->crackTexture(sampler, cracked);
3078
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003079 const bool isUnsignedResult =
3080 node->getType().getBasicType() == glslang::EbtUint64 ||
3081 node->getType().getBasicType() == glslang::EbtUint;
3082
John Kessenichfc51d282015-08-19 13:34:18 -06003083 // Check for queries
3084 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003085 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3086 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003087 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003088
John Kessenichfc51d282015-08-19 13:34:18 -06003089 switch (node->getOp()) {
3090 case glslang::EOpImageQuerySize:
3091 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003092 if (arguments.size() > 1) {
3093 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003094 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003095 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003096 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003097 case glslang::EOpImageQuerySamples:
3098 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003099 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003100 case glslang::EOpTextureQueryLod:
3101 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003102 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003103 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003104 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003105 case glslang::EOpSparseTexelsResident:
3106 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003107 default:
3108 assert(0);
3109 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003110 }
John Kessenich140f3df2015-06-26 16:58:36 -06003111 }
3112
Rex Xufc618912015-09-09 16:42:49 +08003113 // Check for image functions other than queries
3114 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003115 std::vector<spv::Id> operands;
3116 auto opIt = arguments.begin();
3117 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003118
3119 // Handle subpass operations
3120 // TODO: GLSL should change to have the "MS" only on the type rather than the
3121 // built-in function.
3122 if (cracked.subpass) {
3123 // add on the (0,0) coordinate
3124 spv::Id zero = builder.makeIntConstant(0);
3125 std::vector<spv::Id> comps;
3126 comps.push_back(zero);
3127 comps.push_back(zero);
3128 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3129 if (sampler.ms) {
3130 operands.push_back(spv::ImageOperandsSampleMask);
3131 operands.push_back(*(opIt++));
3132 }
John Kessenich8c8505c2016-07-26 12:50:38 -06003133 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07003134 }
3135
John Kessenich56bab042015-09-16 10:54:31 -06003136 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06003137 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07003138 if (sampler.ms) {
3139 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003140 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07003141 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003142 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3143 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06003144 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06003145 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08003146 if (sampler.ms) {
3147 operands.push_back(*(opIt + 1));
3148 operands.push_back(spv::ImageOperandsSampleMask);
3149 operands.push_back(*opIt);
3150 } else
3151 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003152 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003153 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3154 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003155 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08003156 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
3157 builder.addCapability(spv::CapabilitySparseResidency);
3158 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3159 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3160
3161 if (sampler.ms) {
3162 operands.push_back(spv::ImageOperandsSampleMask);
3163 operands.push_back(*opIt++);
3164 }
3165
3166 // Create the return type that was a special structure
3167 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003168 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003169 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3170 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3171
3172 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3173
3174 // Decode the return type
3175 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3176 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003177 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003178 // Process image atomic operations
3179
3180 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3181 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003182 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003183
John Kessenich8c8505c2016-07-26 12:50:38 -06003184 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003185 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003186
3187 std::vector<spv::Id> operands;
3188 operands.push_back(pointer);
3189 for (; opIt != arguments.end(); ++opIt)
3190 operands.push_back(*opIt);
3191
John Kessenich8c8505c2016-07-26 12:50:38 -06003192 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003193 }
3194 }
3195
3196 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003197 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003198 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3199
John Kessenichfc51d282015-08-19 13:34:18 -06003200 // check for bias argument
3201 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08003202 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003203 int nonBiasArgCount = 2;
3204 if (cracked.offset)
3205 ++nonBiasArgCount;
3206 if (cracked.grad)
3207 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003208 if (cracked.lodClamp)
3209 ++nonBiasArgCount;
3210 if (sparse)
3211 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003212
3213 if ((int)arguments.size() > nonBiasArgCount)
3214 bias = true;
3215 }
3216
John Kessenicha5c33d62016-06-02 23:45:21 -06003217 // See if the sampler param should really be just the SPV image part
3218 if (cracked.fetch) {
3219 // a fetch needs to have the image extracted first
3220 if (builder.isSampledImage(params.sampler))
3221 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3222 }
3223
John Kessenichfc51d282015-08-19 13:34:18 -06003224 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003225
John Kessenichfc51d282015-08-19 13:34:18 -06003226 params.coords = arguments[1];
3227 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003228 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003229
3230 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003231 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003232 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003233 ++extraArgs;
3234 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003235 params.Dref = arguments[2];
3236 ++extraArgs;
3237 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003238 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003239 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003240 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003241 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003242 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003243 dRefComp = builder.getNumComponents(params.coords) - 1;
3244 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003245 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3246 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003247
3248 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003249 if (cracked.lod) {
3250 params.lod = arguments[2];
3251 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003252 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3253 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3254 noImplicitLod = true;
3255 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003256
3257 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003258 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08003259 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003260 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003261 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003262
3263 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003264 if (cracked.grad) {
3265 params.gradX = arguments[2 + extraArgs];
3266 params.gradY = arguments[3 + extraArgs];
3267 extraArgs += 2;
3268 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003269
3270 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003271 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003272 params.offset = arguments[2 + extraArgs];
3273 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003274 } else if (cracked.offsets) {
3275 params.offsets = arguments[2 + extraArgs];
3276 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003277 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003278
3279 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003280 if (cracked.lodClamp) {
3281 params.lodClamp = arguments[2 + extraArgs];
3282 ++extraArgs;
3283 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003284
3285 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003286 if (sparse) {
3287 params.texelOut = arguments[2 + extraArgs];
3288 ++extraArgs;
3289 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003290
3291 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06003292 if (bias) {
3293 params.bias = arguments[2 + extraArgs];
3294 ++extraArgs;
3295 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003296
3297 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003298 if (cracked.gather && ! sampler.shadow) {
3299 // default component is 0, if missing, otherwise an argument
3300 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003301 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003302 ++extraArgs;
3303 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003304 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07003305 }
3306 }
John Kessenichfc51d282015-08-19 13:34:18 -06003307
John Kessenich65336482016-06-16 14:06:26 -06003308 // projective component (might not to move)
3309 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3310 // are divided by the last component of P."
3311 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3312 // unused components will appear after all used components."
3313 if (cracked.proj) {
3314 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3315 int projTargetComp;
3316 switch (sampler.dim) {
3317 case glslang::Esd1D: projTargetComp = 1; break;
3318 case glslang::Esd2D: projTargetComp = 2; break;
3319 case glslang::EsdRect: projTargetComp = 2; break;
3320 default: projTargetComp = projSourceComp; break;
3321 }
3322 // copy the projective coordinate if we have to
3323 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003324 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003325 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3326 projSourceComp);
3327 params.coords = builder.createCompositeInsert(projComp, params.coords,
3328 builder.getTypeId(params.coords), projTargetComp);
3329 }
3330 }
3331
John Kessenich8c8505c2016-07-26 12:50:38 -06003332 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003333}
3334
3335spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3336{
3337 // Grab the function's pointer from the previously created function
3338 spv::Function* function = functionMap[node->getName().c_str()];
3339 if (! function)
3340 return 0;
3341
3342 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3343 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3344
3345 // See comments in makeFunctions() for details about the semantics for parameter passing.
3346 //
3347 // These imply we need a four step process:
3348 // 1. Evaluate the arguments
3349 // 2. Allocate and make copies of in, out, and inout arguments
3350 // 3. Make the call
3351 // 4. Copy back the results
3352
3353 // 1. Evaluate the arguments
3354 std::vector<spv::Builder::AccessChain> lValues;
3355 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003356 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003357 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003358 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003359 // build l-value
3360 builder.clearAccessChain();
3361 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003362 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06003363 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
John Kessenich4a57dce2017-02-24 19:15:46 -07003364 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.containsOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06003365 // save l-value
3366 lValues.push_back(builder.getAccessChain());
3367 } else {
3368 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003369 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003370 }
3371 }
3372
3373 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3374 // copy the original into that space.
3375 //
3376 // Also, build up the list of actual arguments to pass in for the call
3377 int lValueCount = 0;
3378 int rValueCount = 0;
3379 std::vector<spv::Id> spvArgs;
3380 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003381 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003382 spv::Id arg;
steve-lunargdd8287a2017-02-23 18:04:12 -07003383 if (paramType.containsOpaque() ||
John Kessenich37789792017-03-21 23:56:40 -06003384 (paramType.getBasicType() == glslang::EbtBlock && qualifiers[a] == glslang::EvqBuffer) ||
3385 (a == 0 && function->hasImplicitThis())) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003386 builder.setAccessChain(lValues[lValueCount]);
3387 arg = builder.accessChainGetLValue();
3388 ++lValueCount;
3389 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06003390 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003391 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3392 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3393 // need to copy the input into output space
3394 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003395 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003396 builder.clearAccessChain();
3397 builder.setAccessChainLValue(arg);
3398 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003399 }
3400 ++lValueCount;
3401 } else {
3402 arg = rValues[rValueCount];
3403 ++rValueCount;
3404 }
3405 spvArgs.push_back(arg);
3406 }
3407
3408 // 3. Make the call.
3409 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003410 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003411
3412 // 4. Copy back out an "out" arguments.
3413 lValueCount = 0;
3414 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003415 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003416 if (qualifiers[a] != glslang::EvqConstReadOnly) {
3417 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3418 spv::Id copy = builder.createLoad(spvArgs[a]);
3419 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003420 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003421 }
3422 ++lValueCount;
3423 }
3424 }
3425
3426 return result;
3427}
3428
3429// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003430spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3431 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003432 spv::Id typeId, spv::Id left, spv::Id right,
3433 glslang::TBasicType typeProxy, bool reduceComparison)
3434{
Rex Xu8ff43de2016-04-22 16:51:45 +08003435 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003436#ifdef AMD_EXTENSIONS
3437 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3438#else
John Kessenich140f3df2015-06-26 16:58:36 -06003439 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003440#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003441 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003442
3443 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003444 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003445 bool comparison = false;
3446
3447 switch (op) {
3448 case glslang::EOpAdd:
3449 case glslang::EOpAddAssign:
3450 if (isFloat)
3451 binOp = spv::OpFAdd;
3452 else
3453 binOp = spv::OpIAdd;
3454 break;
3455 case glslang::EOpSub:
3456 case glslang::EOpSubAssign:
3457 if (isFloat)
3458 binOp = spv::OpFSub;
3459 else
3460 binOp = spv::OpISub;
3461 break;
3462 case glslang::EOpMul:
3463 case glslang::EOpMulAssign:
3464 if (isFloat)
3465 binOp = spv::OpFMul;
3466 else
3467 binOp = spv::OpIMul;
3468 break;
3469 case glslang::EOpVectorTimesScalar:
3470 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003471 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003472 if (builder.isVector(right))
3473 std::swap(left, right);
3474 assert(builder.isScalar(right));
3475 needMatchingVectors = false;
3476 binOp = spv::OpVectorTimesScalar;
3477 } else
3478 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003479 break;
3480 case glslang::EOpVectorTimesMatrix:
3481 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003482 binOp = spv::OpVectorTimesMatrix;
3483 break;
3484 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003485 binOp = spv::OpMatrixTimesVector;
3486 break;
3487 case glslang::EOpMatrixTimesScalar:
3488 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003489 binOp = spv::OpMatrixTimesScalar;
3490 break;
3491 case glslang::EOpMatrixTimesMatrix:
3492 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003493 binOp = spv::OpMatrixTimesMatrix;
3494 break;
3495 case glslang::EOpOuterProduct:
3496 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003497 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003498 break;
3499
3500 case glslang::EOpDiv:
3501 case glslang::EOpDivAssign:
3502 if (isFloat)
3503 binOp = spv::OpFDiv;
3504 else if (isUnsigned)
3505 binOp = spv::OpUDiv;
3506 else
3507 binOp = spv::OpSDiv;
3508 break;
3509 case glslang::EOpMod:
3510 case glslang::EOpModAssign:
3511 if (isFloat)
3512 binOp = spv::OpFMod;
3513 else if (isUnsigned)
3514 binOp = spv::OpUMod;
3515 else
3516 binOp = spv::OpSMod;
3517 break;
3518 case glslang::EOpRightShift:
3519 case glslang::EOpRightShiftAssign:
3520 if (isUnsigned)
3521 binOp = spv::OpShiftRightLogical;
3522 else
3523 binOp = spv::OpShiftRightArithmetic;
3524 break;
3525 case glslang::EOpLeftShift:
3526 case glslang::EOpLeftShiftAssign:
3527 binOp = spv::OpShiftLeftLogical;
3528 break;
3529 case glslang::EOpAnd:
3530 case glslang::EOpAndAssign:
3531 binOp = spv::OpBitwiseAnd;
3532 break;
3533 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003534 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003535 binOp = spv::OpLogicalAnd;
3536 break;
3537 case glslang::EOpInclusiveOr:
3538 case glslang::EOpInclusiveOrAssign:
3539 binOp = spv::OpBitwiseOr;
3540 break;
3541 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003542 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003543 binOp = spv::OpLogicalOr;
3544 break;
3545 case glslang::EOpExclusiveOr:
3546 case glslang::EOpExclusiveOrAssign:
3547 binOp = spv::OpBitwiseXor;
3548 break;
3549 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003550 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003551 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003552 break;
3553
3554 case glslang::EOpLessThan:
3555 case glslang::EOpGreaterThan:
3556 case glslang::EOpLessThanEqual:
3557 case glslang::EOpGreaterThanEqual:
3558 case glslang::EOpEqual:
3559 case glslang::EOpNotEqual:
3560 case glslang::EOpVectorEqual:
3561 case glslang::EOpVectorNotEqual:
3562 comparison = true;
3563 break;
3564 default:
3565 break;
3566 }
3567
John Kessenich7c1aa102015-10-15 13:29:11 -06003568 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003569 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003570 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003571 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003572 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003573
3574 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003575 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003576 builder.promoteScalar(precision, left, right);
3577
qining25262b32016-05-06 17:25:16 -04003578 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3579 addDecoration(result, noContraction);
3580 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003581 }
3582
3583 if (! comparison)
3584 return 0;
3585
John Kessenich7c1aa102015-10-15 13:29:11 -06003586 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003587
John Kessenich4583b612016-08-07 19:14:22 -06003588 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3589 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003590 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003591
3592 switch (op) {
3593 case glslang::EOpLessThan:
3594 if (isFloat)
3595 binOp = spv::OpFOrdLessThan;
3596 else if (isUnsigned)
3597 binOp = spv::OpULessThan;
3598 else
3599 binOp = spv::OpSLessThan;
3600 break;
3601 case glslang::EOpGreaterThan:
3602 if (isFloat)
3603 binOp = spv::OpFOrdGreaterThan;
3604 else if (isUnsigned)
3605 binOp = spv::OpUGreaterThan;
3606 else
3607 binOp = spv::OpSGreaterThan;
3608 break;
3609 case glslang::EOpLessThanEqual:
3610 if (isFloat)
3611 binOp = spv::OpFOrdLessThanEqual;
3612 else if (isUnsigned)
3613 binOp = spv::OpULessThanEqual;
3614 else
3615 binOp = spv::OpSLessThanEqual;
3616 break;
3617 case glslang::EOpGreaterThanEqual:
3618 if (isFloat)
3619 binOp = spv::OpFOrdGreaterThanEqual;
3620 else if (isUnsigned)
3621 binOp = spv::OpUGreaterThanEqual;
3622 else
3623 binOp = spv::OpSGreaterThanEqual;
3624 break;
3625 case glslang::EOpEqual:
3626 case glslang::EOpVectorEqual:
3627 if (isFloat)
3628 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003629 else if (isBool)
3630 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003631 else
3632 binOp = spv::OpIEqual;
3633 break;
3634 case glslang::EOpNotEqual:
3635 case glslang::EOpVectorNotEqual:
3636 if (isFloat)
3637 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003638 else if (isBool)
3639 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003640 else
3641 binOp = spv::OpINotEqual;
3642 break;
3643 default:
3644 break;
3645 }
3646
qining25262b32016-05-06 17:25:16 -04003647 if (binOp != spv::OpNop) {
3648 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3649 addDecoration(result, noContraction);
3650 return builder.setPrecision(result, precision);
3651 }
John Kessenich140f3df2015-06-26 16:58:36 -06003652
3653 return 0;
3654}
3655
John Kessenich04bb8a02015-12-12 12:28:14 -07003656//
3657// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3658// These can be any of:
3659//
3660// matrix * scalar
3661// scalar * matrix
3662// matrix * matrix linear algebraic
3663// matrix * vector
3664// vector * matrix
3665// matrix * matrix componentwise
3666// matrix op matrix op in {+, -, /}
3667// matrix op scalar op in {+, -, /}
3668// scalar op matrix op in {+, -, /}
3669//
qining25262b32016-05-06 17:25:16 -04003670spv::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 -07003671{
3672 bool firstClass = true;
3673
3674 // First, handle first-class matrix operations (* and matrix/scalar)
3675 switch (op) {
3676 case spv::OpFDiv:
3677 if (builder.isMatrix(left) && builder.isScalar(right)) {
3678 // turn matrix / scalar into a multiply...
3679 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3680 op = spv::OpMatrixTimesScalar;
3681 } else
3682 firstClass = false;
3683 break;
3684 case spv::OpMatrixTimesScalar:
3685 if (builder.isMatrix(right))
3686 std::swap(left, right);
3687 assert(builder.isScalar(right));
3688 break;
3689 case spv::OpVectorTimesMatrix:
3690 assert(builder.isVector(left));
3691 assert(builder.isMatrix(right));
3692 break;
3693 case spv::OpMatrixTimesVector:
3694 assert(builder.isMatrix(left));
3695 assert(builder.isVector(right));
3696 break;
3697 case spv::OpMatrixTimesMatrix:
3698 assert(builder.isMatrix(left));
3699 assert(builder.isMatrix(right));
3700 break;
3701 default:
3702 firstClass = false;
3703 break;
3704 }
3705
qining25262b32016-05-06 17:25:16 -04003706 if (firstClass) {
3707 spv::Id result = builder.createBinOp(op, typeId, left, right);
3708 addDecoration(result, noContraction);
3709 return builder.setPrecision(result, precision);
3710 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003711
LoopDawg592860c2016-06-09 08:57:35 -06003712 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003713 // The result type of all of them is the same type as the (a) matrix operand.
3714 // The algorithm is to:
3715 // - break the matrix(es) into vectors
3716 // - smear any scalar to a vector
3717 // - do vector operations
3718 // - make a matrix out the vector results
3719 switch (op) {
3720 case spv::OpFAdd:
3721 case spv::OpFSub:
3722 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003723 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003724 case spv::OpFMul:
3725 {
3726 // one time set up...
3727 bool leftMat = builder.isMatrix(left);
3728 bool rightMat = builder.isMatrix(right);
3729 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3730 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3731 spv::Id scalarType = builder.getScalarTypeId(typeId);
3732 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3733 std::vector<spv::Id> results;
3734 spv::Id smearVec = spv::NoResult;
3735 if (builder.isScalar(left))
3736 smearVec = builder.smearScalar(precision, left, vecType);
3737 else if (builder.isScalar(right))
3738 smearVec = builder.smearScalar(precision, right, vecType);
3739
3740 // do each vector op
3741 for (unsigned int c = 0; c < numCols; ++c) {
3742 std::vector<unsigned int> indexes;
3743 indexes.push_back(c);
3744 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3745 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003746 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3747 addDecoration(result, noContraction);
3748 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003749 }
3750
3751 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003752 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003753 }
3754 default:
3755 assert(0);
3756 return spv::NoResult;
3757 }
3758}
3759
qining25262b32016-05-06 17:25:16 -04003760spv::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 -06003761{
3762 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003763 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003764 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003765 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003766#ifdef AMD_EXTENSIONS
3767 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3768#else
Rex Xu04db3f52015-09-16 11:44:02 +08003769 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003770#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003771
3772 switch (op) {
3773 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003774 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003775 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003776 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003777 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003778 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003779 unaryOp = spv::OpSNegate;
3780 break;
3781
3782 case glslang::EOpLogicalNot:
3783 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003784 unaryOp = spv::OpLogicalNot;
3785 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003786 case glslang::EOpBitwiseNot:
3787 unaryOp = spv::OpNot;
3788 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003789
John Kessenich140f3df2015-06-26 16:58:36 -06003790 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003791 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003792 break;
3793 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003794 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003795 break;
3796 case glslang::EOpTranspose:
3797 unaryOp = spv::OpTranspose;
3798 break;
3799
3800 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003801 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003802 break;
3803 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003804 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003805 break;
3806 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003807 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003808 break;
3809 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003810 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003811 break;
3812 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003813 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003814 break;
3815 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003816 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003817 break;
3818 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003819 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003820 break;
3821 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003822 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003823 break;
3824
3825 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003826 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003827 break;
3828 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003829 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003830 break;
3831 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003832 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003833 break;
3834 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003835 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003836 break;
3837 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003838 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003839 break;
3840 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003841 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003842 break;
3843
3844 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003845 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003846 break;
3847 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003848 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003849 break;
3850
3851 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003852 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003853 break;
3854 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003855 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003856 break;
3857 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003858 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003859 break;
3860 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003861 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003862 break;
3863 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003864 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003865 break;
3866 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003867 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003868 break;
3869
3870 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003871 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003872 break;
3873 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003874 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003875 break;
3876 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003877 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003878 break;
3879 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003880 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003881 break;
3882 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003883 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003884 break;
3885 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003886 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003887 break;
3888
3889 case glslang::EOpIsNan:
3890 unaryOp = spv::OpIsNan;
3891 break;
3892 case glslang::EOpIsInf:
3893 unaryOp = spv::OpIsInf;
3894 break;
LoopDawg592860c2016-06-09 08:57:35 -06003895 case glslang::EOpIsFinite:
3896 unaryOp = spv::OpIsFinite;
3897 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003898
Rex Xucbc426e2015-12-15 16:03:10 +08003899 case glslang::EOpFloatBitsToInt:
3900 case glslang::EOpFloatBitsToUint:
3901 case glslang::EOpIntBitsToFloat:
3902 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003903 case glslang::EOpDoubleBitsToInt64:
3904 case glslang::EOpDoubleBitsToUint64:
3905 case glslang::EOpInt64BitsToDouble:
3906 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003907 unaryOp = spv::OpBitcast;
3908 break;
3909
John Kessenich140f3df2015-06-26 16:58:36 -06003910 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003911 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003912 break;
3913 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003914 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003915 break;
3916 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003917 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003918 break;
3919 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003920 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003921 break;
3922 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003923 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003924 break;
3925 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003926 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003927 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003928 case glslang::EOpPackSnorm4x8:
3929 libCall = spv::GLSLstd450PackSnorm4x8;
3930 break;
3931 case glslang::EOpUnpackSnorm4x8:
3932 libCall = spv::GLSLstd450UnpackSnorm4x8;
3933 break;
3934 case glslang::EOpPackUnorm4x8:
3935 libCall = spv::GLSLstd450PackUnorm4x8;
3936 break;
3937 case glslang::EOpUnpackUnorm4x8:
3938 libCall = spv::GLSLstd450UnpackUnorm4x8;
3939 break;
3940 case glslang::EOpPackDouble2x32:
3941 libCall = spv::GLSLstd450PackDouble2x32;
3942 break;
3943 case glslang::EOpUnpackDouble2x32:
3944 libCall = spv::GLSLstd450UnpackDouble2x32;
3945 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003946
Rex Xu8ff43de2016-04-22 16:51:45 +08003947 case glslang::EOpPackInt2x32:
3948 case glslang::EOpUnpackInt2x32:
3949 case glslang::EOpPackUint2x32:
3950 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08003951 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08003952 break;
3953
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003954#ifdef AMD_EXTENSIONS
3955 case glslang::EOpPackFloat2x16:
3956 case glslang::EOpUnpackFloat2x16:
3957 unaryOp = spv::OpBitcast;
3958 break;
3959#endif
3960
John Kessenich140f3df2015-06-26 16:58:36 -06003961 case glslang::EOpDPdx:
3962 unaryOp = spv::OpDPdx;
3963 break;
3964 case glslang::EOpDPdy:
3965 unaryOp = spv::OpDPdy;
3966 break;
3967 case glslang::EOpFwidth:
3968 unaryOp = spv::OpFwidth;
3969 break;
3970 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003971 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003972 unaryOp = spv::OpDPdxFine;
3973 break;
3974 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003975 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003976 unaryOp = spv::OpDPdyFine;
3977 break;
3978 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003979 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003980 unaryOp = spv::OpFwidthFine;
3981 break;
3982 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003983 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003984 unaryOp = spv::OpDPdxCoarse;
3985 break;
3986 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003987 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003988 unaryOp = spv::OpDPdyCoarse;
3989 break;
3990 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003991 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003992 unaryOp = spv::OpFwidthCoarse;
3993 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003994 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003995 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003996 libCall = spv::GLSLstd450InterpolateAtCentroid;
3997 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003998 case glslang::EOpAny:
3999 unaryOp = spv::OpAny;
4000 break;
4001 case glslang::EOpAll:
4002 unaryOp = spv::OpAll;
4003 break;
4004
4005 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004006 if (isFloat)
4007 libCall = spv::GLSLstd450FAbs;
4008 else
4009 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004010 break;
4011 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004012 if (isFloat)
4013 libCall = spv::GLSLstd450FSign;
4014 else
4015 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004016 break;
4017
John Kessenichfc51d282015-08-19 13:34:18 -06004018 case glslang::EOpAtomicCounterIncrement:
4019 case glslang::EOpAtomicCounterDecrement:
4020 case glslang::EOpAtomicCounter:
4021 {
4022 // Handle all of the atomics in one place, in createAtomicOperation()
4023 std::vector<spv::Id> operands;
4024 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08004025 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004026 }
4027
John Kessenichfc51d282015-08-19 13:34:18 -06004028 case glslang::EOpBitFieldReverse:
4029 unaryOp = spv::OpBitReverse;
4030 break;
4031 case glslang::EOpBitCount:
4032 unaryOp = spv::OpBitCount;
4033 break;
4034 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004035 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004036 break;
4037 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004038 if (isUnsigned)
4039 libCall = spv::GLSLstd450FindUMsb;
4040 else
4041 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004042 break;
4043
Rex Xu574ab042016-04-14 16:53:07 +08004044 case glslang::EOpBallot:
4045 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004046 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004047 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004048 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004049#ifdef AMD_EXTENSIONS
4050 case glslang::EOpMinInvocations:
4051 case glslang::EOpMaxInvocations:
4052 case glslang::EOpAddInvocations:
4053 case glslang::EOpMinInvocationsNonUniform:
4054 case glslang::EOpMaxInvocationsNonUniform:
4055 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004056 case glslang::EOpMinInvocationsInclusiveScan:
4057 case glslang::EOpMaxInvocationsInclusiveScan:
4058 case glslang::EOpAddInvocationsInclusiveScan:
4059 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4060 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4061 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4062 case glslang::EOpMinInvocationsExclusiveScan:
4063 case glslang::EOpMaxInvocationsExclusiveScan:
4064 case glslang::EOpAddInvocationsExclusiveScan:
4065 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4066 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4067 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004068#endif
Rex Xu51596642016-09-21 18:56:12 +08004069 {
4070 std::vector<spv::Id> operands;
4071 operands.push_back(operand);
4072 return createInvocationsOperation(op, typeId, operands, typeProxy);
4073 }
Rex Xu9d93a232016-05-05 12:30:44 +08004074
4075#ifdef AMD_EXTENSIONS
4076 case glslang::EOpMbcnt:
4077 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4078 libCall = spv::MbcntAMD;
4079 break;
4080
4081 case glslang::EOpCubeFaceIndex:
4082 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4083 libCall = spv::CubeFaceIndexAMD;
4084 break;
4085
4086 case glslang::EOpCubeFaceCoord:
4087 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4088 libCall = spv::CubeFaceCoordAMD;
4089 break;
4090#endif
Rex Xu338b1852016-05-05 20:38:33 +08004091
John Kessenich140f3df2015-06-26 16:58:36 -06004092 default:
4093 return 0;
4094 }
4095
4096 spv::Id id;
4097 if (libCall >= 0) {
4098 std::vector<spv::Id> args;
4099 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004100 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004101 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004102 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004103 }
John Kessenich140f3df2015-06-26 16:58:36 -06004104
qining25262b32016-05-06 17:25:16 -04004105 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07004106 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004107}
4108
John Kessenich7a53f762016-01-20 11:19:27 -07004109// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04004110spv::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 -07004111{
4112 // Handle unary operations vector by vector.
4113 // The result type is the same type as the original type.
4114 // The algorithm is to:
4115 // - break the matrix into vectors
4116 // - apply the operation to each vector
4117 // - make a matrix out the vector results
4118
4119 // get the types sorted out
4120 int numCols = builder.getNumColumns(operand);
4121 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004122 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4123 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004124 std::vector<spv::Id> results;
4125
4126 // do each vector op
4127 for (int c = 0; c < numCols; ++c) {
4128 std::vector<unsigned int> indexes;
4129 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004130 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4131 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
4132 addDecoration(destVec, noContraction);
4133 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004134 }
4135
4136 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004137 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07004138}
4139
Rex Xu73e3ce72016-04-27 18:48:17 +08004140spv::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 -06004141{
4142 spv::Op convOp = spv::OpNop;
4143 spv::Id zero = 0;
4144 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08004145 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004146
4147 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4148
4149 switch (op) {
4150 case glslang::EOpConvIntToBool:
4151 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08004152 case glslang::EOpConvInt64ToBool:
4153 case glslang::EOpConvUint64ToBool:
4154 zero = (op == glslang::EOpConvInt64ToBool ||
4155 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004156 zero = makeSmearedConstant(zero, vectorSize);
4157 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4158
4159 case glslang::EOpConvFloatToBool:
4160 zero = builder.makeFloatConstant(0.0F);
4161 zero = makeSmearedConstant(zero, vectorSize);
4162 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4163
4164 case glslang::EOpConvDoubleToBool:
4165 zero = builder.makeDoubleConstant(0.0);
4166 zero = makeSmearedConstant(zero, vectorSize);
4167 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4168
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004169#ifdef AMD_EXTENSIONS
4170 case glslang::EOpConvFloat16ToBool:
4171 zero = builder.makeFloat16Constant(0.0F);
4172 zero = makeSmearedConstant(zero, vectorSize);
4173 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4174#endif
4175
John Kessenich140f3df2015-06-26 16:58:36 -06004176 case glslang::EOpConvBoolToFloat:
4177 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004178 zero = builder.makeFloatConstant(0.0F);
4179 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004180 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004181
John Kessenich140f3df2015-06-26 16:58:36 -06004182 case glslang::EOpConvBoolToDouble:
4183 convOp = spv::OpSelect;
4184 zero = builder.makeDoubleConstant(0.0);
4185 one = builder.makeDoubleConstant(1.0);
4186 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004187
4188#ifdef AMD_EXTENSIONS
4189 case glslang::EOpConvBoolToFloat16:
4190 convOp = spv::OpSelect;
4191 zero = builder.makeFloat16Constant(0.0F);
4192 one = builder.makeFloat16Constant(1.0F);
4193 break;
4194#endif
4195
John Kessenich140f3df2015-06-26 16:58:36 -06004196 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004197 case glslang::EOpConvBoolToInt64:
4198 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
4199 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06004200 convOp = spv::OpSelect;
4201 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004202
John Kessenich140f3df2015-06-26 16:58:36 -06004203 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004204 case glslang::EOpConvBoolToUint64:
4205 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4206 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06004207 convOp = spv::OpSelect;
4208 break;
4209
4210 case glslang::EOpConvIntToFloat:
4211 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004212 case glslang::EOpConvInt64ToFloat:
4213 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004214#ifdef AMD_EXTENSIONS
4215 case glslang::EOpConvIntToFloat16:
4216 case glslang::EOpConvInt64ToFloat16:
4217#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004218 convOp = spv::OpConvertSToF;
4219 break;
4220
4221 case glslang::EOpConvUintToFloat:
4222 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004223 case glslang::EOpConvUint64ToFloat:
4224 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004225#ifdef AMD_EXTENSIONS
4226 case glslang::EOpConvUintToFloat16:
4227 case glslang::EOpConvUint64ToFloat16:
4228#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004229 convOp = spv::OpConvertUToF;
4230 break;
4231
4232 case glslang::EOpConvDoubleToFloat:
4233 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004234#ifdef AMD_EXTENSIONS
4235 case glslang::EOpConvDoubleToFloat16:
4236 case glslang::EOpConvFloat16ToDouble:
4237 case glslang::EOpConvFloatToFloat16:
4238 case glslang::EOpConvFloat16ToFloat:
4239#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004240 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004241 if (builder.isMatrixType(destType))
4242 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004243 break;
4244
4245 case glslang::EOpConvFloatToInt:
4246 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004247 case glslang::EOpConvFloatToInt64:
4248 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004249#ifdef AMD_EXTENSIONS
4250 case glslang::EOpConvFloat16ToInt:
4251 case glslang::EOpConvFloat16ToInt64:
4252#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004253 convOp = spv::OpConvertFToS;
4254 break;
4255
4256 case glslang::EOpConvUintToInt:
4257 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004258 case glslang::EOpConvUint64ToInt64:
4259 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04004260 if (builder.isInSpecConstCodeGenMode()) {
4261 // Build zero scalar or vector for OpIAdd.
Rex Xu64bcfdb2016-09-05 16:10:14 +08004262 zero = (op == glslang::EOpConvUint64ToInt64 ||
4263 op == glslang::EOpConvInt64ToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04004264 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004265 // Use OpIAdd, instead of OpBitcast to do the conversion when
4266 // generating for OpSpecConstantOp instruction.
4267 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4268 }
4269 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004270 convOp = spv::OpBitcast;
4271 break;
4272
4273 case glslang::EOpConvFloatToUint:
4274 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004275 case glslang::EOpConvFloatToUint64:
4276 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004277#ifdef AMD_EXTENSIONS
4278 case glslang::EOpConvFloat16ToUint:
4279 case glslang::EOpConvFloat16ToUint64:
4280#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004281 convOp = spv::OpConvertFToU;
4282 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004283
4284 case glslang::EOpConvIntToInt64:
4285 case glslang::EOpConvInt64ToInt:
4286 convOp = spv::OpSConvert;
4287 break;
4288
4289 case glslang::EOpConvUintToUint64:
4290 case glslang::EOpConvUint64ToUint:
4291 convOp = spv::OpUConvert;
4292 break;
4293
4294 case glslang::EOpConvIntToUint64:
4295 case glslang::EOpConvInt64ToUint:
4296 case glslang::EOpConvUint64ToInt:
4297 case glslang::EOpConvUintToInt64:
4298 // OpSConvert/OpUConvert + OpBitCast
4299 switch (op) {
4300 case glslang::EOpConvIntToUint64:
4301 convOp = spv::OpSConvert;
4302 type = builder.makeIntType(64);
4303 break;
4304 case glslang::EOpConvInt64ToUint:
4305 convOp = spv::OpSConvert;
4306 type = builder.makeIntType(32);
4307 break;
4308 case glslang::EOpConvUint64ToInt:
4309 convOp = spv::OpUConvert;
4310 type = builder.makeUintType(32);
4311 break;
4312 case glslang::EOpConvUintToInt64:
4313 convOp = spv::OpUConvert;
4314 type = builder.makeUintType(64);
4315 break;
4316 default:
4317 assert(0);
4318 break;
4319 }
4320
4321 if (vectorSize > 0)
4322 type = builder.makeVectorType(type, vectorSize);
4323
4324 operand = builder.createUnaryOp(convOp, type, operand);
4325
4326 if (builder.isInSpecConstCodeGenMode()) {
4327 // Build zero scalar or vector for OpIAdd.
4328 zero = (op == glslang::EOpConvIntToUint64 ||
4329 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4330 zero = makeSmearedConstant(zero, vectorSize);
4331 // Use OpIAdd, instead of OpBitcast to do the conversion when
4332 // generating for OpSpecConstantOp instruction.
4333 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4334 }
4335 // For normal run-time conversion instruction, use OpBitcast.
4336 convOp = spv::OpBitcast;
4337 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004338 default:
4339 break;
4340 }
4341
4342 spv::Id result = 0;
4343 if (convOp == spv::OpNop)
4344 return result;
4345
4346 if (convOp == spv::OpSelect) {
4347 zero = makeSmearedConstant(zero, vectorSize);
4348 one = makeSmearedConstant(one, vectorSize);
4349 result = builder.createTriOp(convOp, destType, operand, one, zero);
4350 } else
4351 result = builder.createUnaryOp(convOp, destType, operand);
4352
John Kessenich32cfd492016-02-02 12:37:46 -07004353 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004354}
4355
4356spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4357{
4358 if (vectorSize == 0)
4359 return constant;
4360
4361 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4362 std::vector<spv::Id> components;
4363 for (int c = 0; c < vectorSize; ++c)
4364 components.push_back(constant);
4365 return builder.makeCompositeConstant(vectorTypeId, components);
4366}
4367
John Kessenich426394d2015-07-23 10:22:48 -06004368// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004369spv::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 -06004370{
4371 spv::Op opCode = spv::OpNop;
4372
4373 switch (op) {
4374 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004375 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004376 opCode = spv::OpAtomicIAdd;
4377 break;
4378 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004379 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08004380 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004381 break;
4382 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004383 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08004384 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004385 break;
4386 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004387 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004388 opCode = spv::OpAtomicAnd;
4389 break;
4390 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004391 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06004392 opCode = spv::OpAtomicOr;
4393 break;
4394 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004395 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06004396 opCode = spv::OpAtomicXor;
4397 break;
4398 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004399 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004400 opCode = spv::OpAtomicExchange;
4401 break;
4402 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004403 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004404 opCode = spv::OpAtomicCompareExchange;
4405 break;
4406 case glslang::EOpAtomicCounterIncrement:
4407 opCode = spv::OpAtomicIIncrement;
4408 break;
4409 case glslang::EOpAtomicCounterDecrement:
4410 opCode = spv::OpAtomicIDecrement;
4411 break;
4412 case glslang::EOpAtomicCounter:
4413 opCode = spv::OpAtomicLoad;
4414 break;
4415 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004416 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004417 break;
4418 }
4419
4420 // Sort out the operands
4421 // - mapping from glslang -> SPV
4422 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004423 // - compare-exchange swaps the value and comparator
4424 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004425 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4426 auto opIt = operands.begin(); // walk the glslang operands
4427 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004428 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4429 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4430 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004431 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4432 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004433 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004434 spvAtomicOperands.push_back(*(opIt + 1));
4435 spvAtomicOperands.push_back(*opIt);
4436 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004437 }
John Kessenich426394d2015-07-23 10:22:48 -06004438
John Kessenich3e60a6f2015-09-14 22:45:16 -06004439 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004440 for (; opIt != operands.end(); ++opIt)
4441 spvAtomicOperands.push_back(*opIt);
4442
4443 return builder.createOp(opCode, typeId, spvAtomicOperands);
4444}
4445
John Kessenich91cef522016-05-05 16:45:40 -06004446// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004447spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004448{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004449#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004450 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004451 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004452#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004453
Rex Xu51596642016-09-21 18:56:12 +08004454 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004455 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004456 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4457
chaocf200da82016-12-20 12:44:35 -08004458 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4459 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004460 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4461 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004462 } else if (op == glslang::EOpAnyInvocation ||
4463 op == glslang::EOpAllInvocations ||
4464 op == glslang::EOpAllInvocationsEqual) {
4465 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4466 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004467 } else {
4468 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004469#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004470 if (op == glslang::EOpMinInvocationsNonUniform ||
4471 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004472 op == glslang::EOpAddInvocationsNonUniform ||
4473 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4474 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4475 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4476 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4477 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4478 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004479 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004480#endif
Rex Xu51596642016-09-21 18:56:12 +08004481
4482 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004483#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004484 switch (op) {
4485 case glslang::EOpMinInvocations:
4486 case glslang::EOpMaxInvocations:
4487 case glslang::EOpAddInvocations:
4488 case glslang::EOpMinInvocationsNonUniform:
4489 case glslang::EOpMaxInvocationsNonUniform:
4490 case glslang::EOpAddInvocationsNonUniform:
4491 groupOperation = spv::GroupOperationReduce;
4492 spvGroupOperands.push_back(groupOperation);
4493 break;
4494 case glslang::EOpMinInvocationsInclusiveScan:
4495 case glslang::EOpMaxInvocationsInclusiveScan:
4496 case glslang::EOpAddInvocationsInclusiveScan:
4497 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4498 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4499 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4500 groupOperation = spv::GroupOperationInclusiveScan;
4501 spvGroupOperands.push_back(groupOperation);
4502 break;
4503 case glslang::EOpMinInvocationsExclusiveScan:
4504 case glslang::EOpMaxInvocationsExclusiveScan:
4505 case glslang::EOpAddInvocationsExclusiveScan:
4506 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4507 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4508 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4509 groupOperation = spv::GroupOperationExclusiveScan;
4510 spvGroupOperands.push_back(groupOperation);
4511 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004512 default:
4513 break;
Rex Xu430ef402016-10-14 17:22:23 +08004514 }
Rex Xu9d93a232016-05-05 12:30:44 +08004515#endif
Rex Xu51596642016-09-21 18:56:12 +08004516 }
4517
4518 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4519 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004520
4521 switch (op) {
4522 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004523 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004524 break;
John Kessenich91cef522016-05-05 16:45:40 -06004525 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004526 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004527 break;
John Kessenich91cef522016-05-05 16:45:40 -06004528 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004529 opCode = spv::OpSubgroupAllEqualKHR;
4530 break;
Rex Xu51596642016-09-21 18:56:12 +08004531 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004532 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004533 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004534 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004535 break;
4536 case glslang::EOpReadFirstInvocation:
4537 opCode = spv::OpSubgroupFirstInvocationKHR;
4538 break;
4539 case glslang::EOpBallot:
4540 {
4541 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4542 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4543 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4544 //
4545 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4546 //
4547 spv::Id uintType = builder.makeUintType(32);
4548 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4549 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4550
4551 std::vector<spv::Id> components;
4552 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4553 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4554
4555 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4556 return builder.createUnaryOp(spv::OpBitcast, typeId,
4557 builder.createCompositeConstruct(uvec2Type, components));
4558 }
4559
Rex Xu9d93a232016-05-05 12:30:44 +08004560#ifdef AMD_EXTENSIONS
4561 case glslang::EOpMinInvocations:
4562 case glslang::EOpMaxInvocations:
4563 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08004564 case glslang::EOpMinInvocationsInclusiveScan:
4565 case glslang::EOpMaxInvocationsInclusiveScan:
4566 case glslang::EOpAddInvocationsInclusiveScan:
4567 case glslang::EOpMinInvocationsExclusiveScan:
4568 case glslang::EOpMaxInvocationsExclusiveScan:
4569 case glslang::EOpAddInvocationsExclusiveScan:
4570 if (op == glslang::EOpMinInvocations ||
4571 op == glslang::EOpMinInvocationsInclusiveScan ||
4572 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004573 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004574 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004575 else {
4576 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004577 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004578 else
Rex Xu51596642016-09-21 18:56:12 +08004579 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004580 }
Rex Xu430ef402016-10-14 17:22:23 +08004581 } else if (op == glslang::EOpMaxInvocations ||
4582 op == glslang::EOpMaxInvocationsInclusiveScan ||
4583 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004584 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004585 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004586 else {
4587 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004588 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004589 else
Rex Xu51596642016-09-21 18:56:12 +08004590 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004591 }
4592 } else {
4593 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004594 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004595 else
Rex Xu51596642016-09-21 18:56:12 +08004596 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004597 }
4598
Rex Xu2bbbe062016-08-23 15:41:05 +08004599 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004600 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004601
4602 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004603 case glslang::EOpMinInvocationsNonUniform:
4604 case glslang::EOpMaxInvocationsNonUniform:
4605 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004606 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4607 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4608 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4609 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4610 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4611 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4612 if (op == glslang::EOpMinInvocationsNonUniform ||
4613 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4614 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004615 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004616 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004617 else {
4618 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004619 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004620 else
Rex Xu51596642016-09-21 18:56:12 +08004621 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004622 }
4623 }
Rex Xu430ef402016-10-14 17:22:23 +08004624 else if (op == glslang::EOpMaxInvocationsNonUniform ||
4625 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4626 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004627 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004628 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004629 else {
4630 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004631 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004632 else
Rex Xu51596642016-09-21 18:56:12 +08004633 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004634 }
4635 }
4636 else {
4637 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004638 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004639 else
Rex Xu51596642016-09-21 18:56:12 +08004640 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004641 }
4642
Rex Xu2bbbe062016-08-23 15:41:05 +08004643 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004644 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004645
4646 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004647#endif
John Kessenich91cef522016-05-05 16:45:40 -06004648 default:
4649 logger->missingFunctionality("invocation operation");
4650 return spv::NoResult;
4651 }
Rex Xu51596642016-09-21 18:56:12 +08004652
4653 assert(opCode != spv::OpNop);
4654 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004655}
4656
Rex Xu2bbbe062016-08-23 15:41:05 +08004657// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08004658spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08004659{
Rex Xub7072052016-09-26 15:53:40 +08004660#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08004661 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4662 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08004663 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08004664 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08004665 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
4666 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
4667 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08004668#else
4669 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4670 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08004671 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
4672 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08004673#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08004674
4675 // Handle group invocation operations scalar by scalar.
4676 // The result type is the same type as the original type.
4677 // The algorithm is to:
4678 // - break the vector into scalars
4679 // - apply the operation to each scalar
4680 // - make a vector out the scalar results
4681
4682 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08004683 int numComponents = builder.getNumComponents(operands[0]);
4684 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08004685 std::vector<spv::Id> results;
4686
4687 // do each scalar op
4688 for (int comp = 0; comp < numComponents; ++comp) {
4689 std::vector<unsigned int> indexes;
4690 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08004691 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08004692 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08004693 if (op == spv::OpSubgroupReadInvocationKHR) {
4694 spvGroupOperands.push_back(scalar);
4695 spvGroupOperands.push_back(operands[1]);
4696 } else if (op == spv::OpGroupBroadcast) {
4697 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08004698 spvGroupOperands.push_back(scalar);
4699 spvGroupOperands.push_back(operands[1]);
4700 } else {
chaocf200da82016-12-20 12:44:35 -08004701 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08004702 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08004703 spvGroupOperands.push_back(scalar);
4704 }
Rex Xu2bbbe062016-08-23 15:41:05 +08004705
Rex Xub7072052016-09-26 15:53:40 +08004706 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08004707 }
4708
4709 // put the pieces together
4710 return builder.createCompositeConstruct(typeId, results);
4711}
Rex Xu2bbbe062016-08-23 15:41:05 +08004712
John Kessenich5e4b1242015-08-06 22:53:06 -06004713spv::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 -06004714{
Rex Xu8ff43de2016-04-22 16:51:45 +08004715 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004716#ifdef AMD_EXTENSIONS
4717 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4718#else
John Kessenich5e4b1242015-08-06 22:53:06 -06004719 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004720#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06004721
John Kessenich140f3df2015-06-26 16:58:36 -06004722 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004723 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004724 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05004725 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07004726 spv::Id typeId0 = 0;
4727 if (consumedOperands > 0)
4728 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08004729 spv::Id typeId1 = 0;
4730 if (consumedOperands > 1)
4731 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07004732 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004733
4734 switch (op) {
4735 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004736 if (isFloat)
4737 libCall = spv::GLSLstd450FMin;
4738 else if (isUnsigned)
4739 libCall = spv::GLSLstd450UMin;
4740 else
4741 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004742 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004743 break;
4744 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004745 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004746 break;
4747 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004748 if (isFloat)
4749 libCall = spv::GLSLstd450FMax;
4750 else if (isUnsigned)
4751 libCall = spv::GLSLstd450UMax;
4752 else
4753 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004754 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004755 break;
4756 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004757 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004758 break;
4759 case glslang::EOpDot:
4760 opCode = spv::OpDot;
4761 break;
4762 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004763 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004764 break;
4765
4766 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004767 if (isFloat)
4768 libCall = spv::GLSLstd450FClamp;
4769 else if (isUnsigned)
4770 libCall = spv::GLSLstd450UClamp;
4771 else
4772 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004773 builder.promoteScalar(precision, operands.front(), operands[1]);
4774 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004775 break;
4776 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08004777 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
4778 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07004779 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08004780 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07004781 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08004782 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07004783 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07004784 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004785 break;
4786 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004787 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004788 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004789 break;
4790 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004791 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004792 builder.promoteScalar(precision, operands[0], operands[2]);
4793 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004794 break;
4795
4796 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06004797 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06004798 break;
4799 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06004800 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06004801 break;
4802 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06004803 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06004804 break;
4805 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06004806 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06004807 break;
4808 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004809 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06004810 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004811 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07004812 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004813 libCall = spv::GLSLstd450InterpolateAtSample;
4814 break;
4815 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07004816 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004817 libCall = spv::GLSLstd450InterpolateAtOffset;
4818 break;
John Kessenich55e7d112015-11-15 21:33:39 -07004819 case glslang::EOpAddCarry:
4820 opCode = spv::OpIAddCarry;
4821 typeId = builder.makeStructResultType(typeId0, typeId0);
4822 consumedOperands = 2;
4823 break;
4824 case glslang::EOpSubBorrow:
4825 opCode = spv::OpISubBorrow;
4826 typeId = builder.makeStructResultType(typeId0, typeId0);
4827 consumedOperands = 2;
4828 break;
4829 case glslang::EOpUMulExtended:
4830 opCode = spv::OpUMulExtended;
4831 typeId = builder.makeStructResultType(typeId0, typeId0);
4832 consumedOperands = 2;
4833 break;
4834 case glslang::EOpIMulExtended:
4835 opCode = spv::OpSMulExtended;
4836 typeId = builder.makeStructResultType(typeId0, typeId0);
4837 consumedOperands = 2;
4838 break;
4839 case glslang::EOpBitfieldExtract:
4840 if (isUnsigned)
4841 opCode = spv::OpBitFieldUExtract;
4842 else
4843 opCode = spv::OpBitFieldSExtract;
4844 break;
4845 case glslang::EOpBitfieldInsert:
4846 opCode = spv::OpBitFieldInsert;
4847 break;
4848
4849 case glslang::EOpFma:
4850 libCall = spv::GLSLstd450Fma;
4851 break;
4852 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08004853 {
4854 libCall = spv::GLSLstd450FrexpStruct;
4855 assert(builder.isPointerType(typeId1));
4856 typeId1 = builder.getContainedTypeId(typeId1);
4857#ifdef AMD_EXTENSIONS
4858 int width = builder.getScalarTypeWidth(typeId1);
4859#else
4860 int width = 32;
4861#endif
4862 if (builder.getNumComponents(operands[0]) == 1)
4863 frexpIntType = builder.makeIntegerType(width, true);
4864 else
4865 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
4866 typeId = builder.makeStructResultType(typeId0, frexpIntType);
4867 consumedOperands = 1;
4868 }
John Kessenich55e7d112015-11-15 21:33:39 -07004869 break;
4870 case glslang::EOpLdexp:
4871 libCall = spv::GLSLstd450Ldexp;
4872 break;
4873
Rex Xu574ab042016-04-14 16:53:07 +08004874 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004875 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08004876
Rex Xu9d93a232016-05-05 12:30:44 +08004877#ifdef AMD_EXTENSIONS
4878 case glslang::EOpSwizzleInvocations:
4879 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4880 libCall = spv::SwizzleInvocationsAMD;
4881 break;
4882 case glslang::EOpSwizzleInvocationsMasked:
4883 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4884 libCall = spv::SwizzleInvocationsMaskedAMD;
4885 break;
4886 case glslang::EOpWriteInvocation:
4887 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4888 libCall = spv::WriteInvocationAMD;
4889 break;
4890
4891 case glslang::EOpMin3:
4892 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4893 if (isFloat)
4894 libCall = spv::FMin3AMD;
4895 else {
4896 if (isUnsigned)
4897 libCall = spv::UMin3AMD;
4898 else
4899 libCall = spv::SMin3AMD;
4900 }
4901 break;
4902 case glslang::EOpMax3:
4903 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4904 if (isFloat)
4905 libCall = spv::FMax3AMD;
4906 else {
4907 if (isUnsigned)
4908 libCall = spv::UMax3AMD;
4909 else
4910 libCall = spv::SMax3AMD;
4911 }
4912 break;
4913 case glslang::EOpMid3:
4914 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4915 if (isFloat)
4916 libCall = spv::FMid3AMD;
4917 else {
4918 if (isUnsigned)
4919 libCall = spv::UMid3AMD;
4920 else
4921 libCall = spv::SMid3AMD;
4922 }
4923 break;
4924
4925 case glslang::EOpInterpolateAtVertex:
4926 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
4927 libCall = spv::InterpolateAtVertexAMD;
4928 break;
4929#endif
4930
John Kessenich140f3df2015-06-26 16:58:36 -06004931 default:
4932 return 0;
4933 }
4934
4935 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07004936 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05004937 // Use an extended instruction from the standard library.
4938 // Construct the call arguments, without modifying the original operands vector.
4939 // We might need the remaining arguments, e.g. in the EOpFrexp case.
4940 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08004941 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07004942 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07004943 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06004944 case 0:
4945 // should all be handled by visitAggregate and createNoArgOperation
4946 assert(0);
4947 return 0;
4948 case 1:
4949 // should all be handled by createUnaryOperation
4950 assert(0);
4951 return 0;
4952 case 2:
4953 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
4954 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004955 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004956 // anything 3 or over doesn't have l-value operands, so all should be consumed
4957 assert(consumedOperands == operands.size());
4958 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06004959 break;
4960 }
4961 }
4962
John Kessenich55e7d112015-11-15 21:33:39 -07004963 // Decode the return types that were structures
4964 switch (op) {
4965 case glslang::EOpAddCarry:
4966 case glslang::EOpSubBorrow:
4967 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4968 id = builder.createCompositeExtract(id, typeId0, 0);
4969 break;
4970 case glslang::EOpUMulExtended:
4971 case glslang::EOpIMulExtended:
4972 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
4973 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4974 break;
4975 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08004976 {
4977 assert(operands.size() == 2);
4978 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
4979 // "exp" is floating-point type (from HLSL intrinsic)
4980 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
4981 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
4982 builder.createStore(member1, operands[1]);
4983 } else
4984 // "exp" is integer type (from GLSL built-in function)
4985 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
4986 id = builder.createCompositeExtract(id, typeId0, 0);
4987 }
John Kessenich55e7d112015-11-15 21:33:39 -07004988 break;
4989 default:
4990 break;
4991 }
4992
John Kessenich32cfd492016-02-02 12:37:46 -07004993 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004994}
4995
Rex Xu9d93a232016-05-05 12:30:44 +08004996// Intrinsics with no arguments (or no return value, and no precision).
4997spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06004998{
4999 // TODO: get the barrier operands correct
5000
5001 switch (op) {
5002 case glslang::EOpEmitVertex:
5003 builder.createNoResultOp(spv::OpEmitVertex);
5004 return 0;
5005 case glslang::EOpEndPrimitive:
5006 builder.createNoResultOp(spv::OpEndPrimitive);
5007 return 0;
5008 case glslang::EOpBarrier:
chrgau01@arm.comc3f1cdf2016-11-14 10:10:05 +01005009 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06005010 return 0;
5011 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06005012 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06005013 return 0;
5014 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06005015 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005016 return 0;
5017 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06005018 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005019 return 0;
5020 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06005021 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005022 return 0;
5023 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07005024 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005025 return 0;
5026 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07005027 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005028 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06005029 case glslang::EOpAllMemoryBarrierWithGroupSync:
5030 // Control barrier with non-"None" semantic is also a memory barrier.
5031 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
5032 return 0;
5033 case glslang::EOpGroupMemoryBarrierWithGroupSync:
5034 // Control barrier with non-"None" semantic is also a memory barrier.
5035 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
5036 return 0;
5037 case glslang::EOpWorkgroupMemoryBarrier:
5038 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5039 return 0;
5040 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
5041 // Control barrier with non-"None" semantic is also a memory barrier.
5042 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5043 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08005044#ifdef AMD_EXTENSIONS
5045 case glslang::EOpTime:
5046 {
5047 std::vector<spv::Id> args; // Dummy arguments
5048 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
5049 return builder.setPrecision(id, precision);
5050 }
5051#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005052 default:
Lei Zhang17535f72016-05-04 15:55:59 -04005053 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06005054 return 0;
5055 }
5056}
5057
5058spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
5059{
John Kessenich2f273362015-07-18 22:34:27 -06005060 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06005061 spv::Id id;
5062 if (symbolValues.end() != iter) {
5063 id = iter->second;
5064 return id;
5065 }
5066
5067 // it was not found, create it
5068 id = createSpvVariable(symbol);
5069 symbolValues[symbol->getId()] = id;
5070
Rex Xuc884b4a2016-06-29 15:03:44 +08005071 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06005072 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07005073 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08005074 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07005075 if (symbol->getType().getQualifier().hasSpecConstantId())
5076 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06005077 if (symbol->getQualifier().hasIndex())
5078 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
5079 if (symbol->getQualifier().hasComponent())
5080 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
5081 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005082 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005083 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005084 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005085 if (symbol->getQualifier().hasXfbBuffer())
5086 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5087 if (symbol->getQualifier().hasXfbOffset())
5088 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
5089 }
John Kessenich91e4aa52016-07-07 17:46:42 -06005090 // atomic counters use this:
5091 if (symbol->getQualifier().hasOffset())
5092 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005093 }
5094
scygan2c864272016-05-18 18:09:17 +02005095 if (symbol->getQualifier().hasLocation())
5096 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07005097 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07005098 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07005099 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06005100 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07005101 }
John Kessenich140f3df2015-06-26 16:58:36 -06005102 if (symbol->getQualifier().hasSet())
5103 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07005104 else if (IsDescriptorResource(symbol->getType())) {
5105 // default to 0
5106 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
5107 }
John Kessenich140f3df2015-06-26 16:58:36 -06005108 if (symbol->getQualifier().hasBinding())
5109 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07005110 if (symbol->getQualifier().hasAttachment())
5111 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06005112 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005113 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005114 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005115 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005116 if (symbol->getQualifier().hasXfbBuffer())
5117 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5118 }
5119
Rex Xu1da878f2016-02-21 20:59:01 +08005120 if (symbol->getType().isImage()) {
5121 std::vector<spv::Decoration> memory;
5122 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
5123 for (unsigned int i = 0; i < memory.size(); ++i)
5124 addDecoration(id, memory[i]);
5125 }
5126
John Kessenich140f3df2015-06-26 16:58:36 -06005127 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06005128 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06005129 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07005130 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06005131
John Kessenichecba76f2017-01-06 00:34:48 -07005132#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08005133 if (builtIn == spv::BuiltInSampleMask) {
5134 spv::Decoration decoration;
5135 // GL_NV_sample_mask_override_coverage extension
5136 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08005137 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08005138 else
5139 decoration = (spv::Decoration)spv::DecorationMax;
5140 addDecoration(id, decoration);
5141 if (decoration != spv::DecorationMax) {
5142 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
5143 }
5144 }
chaoc771d89f2017-01-13 01:10:53 -08005145 else if (builtIn == spv::BuiltInLayer) {
5146 // SPV_NV_viewport_array2 extension
5147 if (symbol->getQualifier().layoutViewportRelative)
5148 {
5149 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
5150 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
5151 builder.addExtension(spv::E_SPV_NV_viewport_array2);
5152 }
5153 if(symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048)
5154 {
5155 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
5156 builder.addCapability(spv::CapabilityShaderStereoViewNV);
5157 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
5158 }
5159 }
5160
chaoc6e5acae2016-12-20 13:28:52 -08005161 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08005162 addDecoration(id, spv::DecorationPassthroughNV);
5163 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08005164 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
5165 }
chaoc0ad6a4e2016-12-19 16:29:34 -08005166#endif
5167
John Kessenich140f3df2015-06-26 16:58:36 -06005168 return id;
5169}
5170
John Kessenich55e7d112015-11-15 21:33:39 -07005171// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06005172void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
5173{
John Kessenich4016e382016-07-15 11:53:56 -06005174 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005175 builder.addDecoration(id, dec);
5176}
5177
John Kessenich55e7d112015-11-15 21:33:39 -07005178// If 'dec' is valid, add a one-operand decoration to an object
5179void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
5180{
John Kessenich4016e382016-07-15 11:53:56 -06005181 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07005182 builder.addDecoration(id, dec, value);
5183}
5184
5185// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005186void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5187{
John Kessenich4016e382016-07-15 11:53:56 -06005188 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005189 builder.addMemberDecoration(id, (unsigned)member, dec);
5190}
5191
John Kessenich92187592016-02-01 13:45:25 -07005192// If 'dec' is valid, add a one-operand decoration to a struct member
5193void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5194{
John Kessenich4016e382016-07-15 11:53:56 -06005195 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005196 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5197}
5198
John Kessenich55e7d112015-11-15 21:33:39 -07005199// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005200// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005201//
5202// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5203//
5204// Recursively walk the nodes. The nodes form a tree whose leaves are
5205// regular constants, which themselves are trees that createSpvConstant()
5206// recursively walks. So, this function walks the "top" of the tree:
5207// - emit specialization constant-building instructions for specConstant
5208// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005209spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005210{
John Kessenich7cc0e282016-03-20 00:46:02 -06005211 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005212
qining4f4bb812016-04-03 23:55:17 -04005213 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005214 if (! node.getQualifier().specConstant) {
5215 // hand off to the non-spec-constant path
5216 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5217 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005218 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005219 nextConst, false);
5220 }
5221
5222 // We now know we have a specialization constant to build
5223
John Kessenichd94c0032016-05-30 19:29:40 -06005224 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005225 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5226 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5227 std::vector<spv::Id> dimConstId;
5228 for (int dim = 0; dim < 3; ++dim) {
5229 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5230 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5231 if (specConst)
5232 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5233 }
5234 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5235 }
5236
5237 // An AST node labelled as specialization constant should be a symbol node.
5238 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5239 if (auto* sn = node.getAsSymbolNode()) {
5240 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005241 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5242 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5243 // will set the builder into spec constant op instruction generating mode.
5244 sub_tree->traverse(this);
5245 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005246 } else if (auto* const_union_array = &sn->getConstArray()){
5247 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005248 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5249 builder.addName(id, sn->getName().c_str());
5250 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005251 }
5252 }
qining4f4bb812016-04-03 23:55:17 -04005253
5254 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5255 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005256 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005257 exit(1);
5258 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005259}
5260
John Kessenich140f3df2015-06-26 16:58:36 -06005261// Use 'consts' as the flattened glslang source of scalar constants to recursively
5262// build the aggregate SPIR-V constant.
5263//
5264// If there are not enough elements present in 'consts', 0 will be substituted;
5265// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5266//
qining08408382016-03-21 09:51:37 -04005267spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005268{
5269 // vector of constants for SPIR-V
5270 std::vector<spv::Id> spvConsts;
5271
5272 // Type is used for struct and array constants
5273 spv::Id typeId = convertGlslangToSpvType(glslangType);
5274
5275 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005276 glslang::TType elementType(glslangType, 0);
5277 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005278 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005279 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005280 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005281 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005282 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005283 } else if (glslangType.getStruct()) {
5284 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5285 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005286 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005287 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005288 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5289 bool zero = nextConst >= consts.size();
5290 switch (glslangType.getBasicType()) {
5291 case glslang::EbtInt:
5292 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5293 break;
5294 case glslang::EbtUint:
5295 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5296 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005297 case glslang::EbtInt64:
5298 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5299 break;
5300 case glslang::EbtUint64:
5301 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5302 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005303 case glslang::EbtFloat:
5304 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5305 break;
5306 case glslang::EbtDouble:
5307 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5308 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005309#ifdef AMD_EXTENSIONS
5310 case glslang::EbtFloat16:
5311 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5312 break;
5313#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005314 case glslang::EbtBool:
5315 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5316 break;
5317 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005318 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005319 break;
5320 }
5321 ++nextConst;
5322 }
5323 } else {
5324 // we have a non-aggregate (scalar) constant
5325 bool zero = nextConst >= consts.size();
5326 spv::Id scalar = 0;
5327 switch (glslangType.getBasicType()) {
5328 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005329 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005330 break;
5331 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005332 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005333 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005334 case glslang::EbtInt64:
5335 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5336 break;
5337 case glslang::EbtUint64:
5338 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5339 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005340 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005341 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005342 break;
5343 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005344 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005345 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005346#ifdef AMD_EXTENSIONS
5347 case glslang::EbtFloat16:
5348 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5349 break;
5350#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005351 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005352 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005353 break;
5354 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005355 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005356 break;
5357 }
5358 ++nextConst;
5359 return scalar;
5360 }
5361
5362 return builder.makeCompositeConstant(typeId, spvConsts);
5363}
5364
John Kessenich7c1aa102015-10-15 13:29:11 -06005365// Return true if the node is a constant or symbol whose reading has no
5366// non-trivial observable cost or effect.
5367bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5368{
5369 // don't know what this is
5370 if (node == nullptr)
5371 return false;
5372
5373 // a constant is safe
5374 if (node->getAsConstantUnion() != nullptr)
5375 return true;
5376
5377 // not a symbol means non-trivial
5378 if (node->getAsSymbolNode() == nullptr)
5379 return false;
5380
5381 // a symbol, depends on what's being read
5382 switch (node->getType().getQualifier().storage) {
5383 case glslang::EvqTemporary:
5384 case glslang::EvqGlobal:
5385 case glslang::EvqIn:
5386 case glslang::EvqInOut:
5387 case glslang::EvqConst:
5388 case glslang::EvqConstReadOnly:
5389 case glslang::EvqUniform:
5390 return true;
5391 default:
5392 return false;
5393 }
qining25262b32016-05-06 17:25:16 -04005394}
John Kessenich7c1aa102015-10-15 13:29:11 -06005395
5396// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06005397// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06005398// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06005399// Return true if trivial.
5400bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5401{
5402 if (node == nullptr)
5403 return false;
5404
John Kessenich84cc15f2017-05-24 16:44:47 -06005405 // count non scalars as trivial, as well as anything coming from HLSL
5406 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06005407 return true;
5408
John Kessenich7c1aa102015-10-15 13:29:11 -06005409 // symbols and constants are trivial
5410 if (isTrivialLeaf(node))
5411 return true;
5412
5413 // otherwise, it needs to be a simple operation or one or two leaf nodes
5414
5415 // not a simple operation
5416 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5417 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5418 if (binaryNode == nullptr && unaryNode == nullptr)
5419 return false;
5420
5421 // not on leaf nodes
5422 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5423 return false;
5424
5425 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5426 return false;
5427 }
5428
5429 switch (node->getAsOperator()->getOp()) {
5430 case glslang::EOpLogicalNot:
5431 case glslang::EOpConvIntToBool:
5432 case glslang::EOpConvUintToBool:
5433 case glslang::EOpConvFloatToBool:
5434 case glslang::EOpConvDoubleToBool:
5435 case glslang::EOpEqual:
5436 case glslang::EOpNotEqual:
5437 case glslang::EOpLessThan:
5438 case glslang::EOpGreaterThan:
5439 case glslang::EOpLessThanEqual:
5440 case glslang::EOpGreaterThanEqual:
5441 case glslang::EOpIndexDirect:
5442 case glslang::EOpIndexDirectStruct:
5443 case glslang::EOpLogicalXor:
5444 case glslang::EOpAny:
5445 case glslang::EOpAll:
5446 return true;
5447 default:
5448 return false;
5449 }
5450}
5451
5452// Emit short-circuiting code, where 'right' is never evaluated unless
5453// the left side is true (for &&) or false (for ||).
5454spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5455{
5456 spv::Id boolTypeId = builder.makeBoolType();
5457
5458 // emit left operand
5459 builder.clearAccessChain();
5460 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005461 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005462
5463 // Operands to accumulate OpPhi operands
5464 std::vector<spv::Id> phiOperands;
5465 // accumulate left operand's phi information
5466 phiOperands.push_back(leftId);
5467 phiOperands.push_back(builder.getBuildPoint()->getId());
5468
5469 // Make the two kinds of operation symmetric with a "!"
5470 // || => emit "if (! left) result = right"
5471 // && => emit "if ( left) result = right"
5472 //
5473 // TODO: this runtime "not" for || could be avoided by adding functionality
5474 // to 'builder' to have an "else" without an "then"
5475 if (op == glslang::EOpLogicalOr)
5476 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5477
5478 // make an "if" based on the left value
5479 spv::Builder::If ifBuilder(leftId, builder);
5480
5481 // emit right operand as the "then" part of the "if"
5482 builder.clearAccessChain();
5483 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005484 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005485
5486 // accumulate left operand's phi information
5487 phiOperands.push_back(rightId);
5488 phiOperands.push_back(builder.getBuildPoint()->getId());
5489
5490 // finish the "if"
5491 ifBuilder.makeEndIf();
5492
5493 // phi together the two results
5494 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5495}
5496
Rex Xu9d93a232016-05-05 12:30:44 +08005497// Return type Id of the imported set of extended instructions corresponds to the name.
5498// Import this set if it has not been imported yet.
5499spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5500{
5501 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5502 return extBuiltinMap[name];
5503 else {
Rex Xu51596642016-09-21 18:56:12 +08005504 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005505 spv::Id extBuiltins = builder.import(name);
5506 extBuiltinMap[name] = extBuiltins;
5507 return extBuiltins;
5508 }
5509}
5510
John Kessenich140f3df2015-06-26 16:58:36 -06005511}; // end anonymous namespace
5512
5513namespace glslang {
5514
John Kessenich68d78fd2015-07-12 19:28:10 -06005515void GetSpirvVersion(std::string& version)
5516{
John Kessenich9e55f632015-07-15 10:03:39 -06005517 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005518 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005519 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005520 version = buf;
5521}
5522
John Kessenich140f3df2015-06-26 16:58:36 -06005523// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005524void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005525{
5526 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005527 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005528 if (out.fail())
5529 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06005530 for (int i = 0; i < (int)spirv.size(); ++i) {
5531 unsigned int word = spirv[i];
5532 out.write((const char*)&word, 4);
5533 }
5534 out.close();
5535}
5536
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005537// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08005538void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005539{
5540 std::ofstream out;
5541 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005542 if (out.fail())
5543 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005544 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08005545 if (varName != nullptr) {
5546 out << "\t #pragma once" << std::endl;
5547 out << "const uint32_t " << varName << "[] = {" << std::endl;
5548 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005549 const int WORDS_PER_LINE = 8;
5550 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5551 out << "\t";
5552 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5553 const unsigned int word = spirv[i + j];
5554 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5555 if (i + j + 1 < (int)spirv.size()) {
5556 out << ",";
5557 }
5558 }
5559 out << std::endl;
5560 }
Flavio15017db2017-02-15 14:29:33 -08005561 if (varName != nullptr) {
5562 out << "};";
5563 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005564 out.close();
5565}
5566
John Kessenich140f3df2015-06-26 16:58:36 -06005567//
5568// Set up the glslang traversal
5569//
John Kessenich121853f2017-05-31 17:11:16 -06005570void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06005571{
Lei Zhang17535f72016-05-04 15:55:59 -04005572 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06005573 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04005574}
5575
John Kessenich121853f2017-05-31 17:11:16 -06005576void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv,
5577 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04005578{
John Kessenich140f3df2015-06-26 16:58:36 -06005579 TIntermNode* root = intermediate.getTreeRoot();
5580
5581 if (root == 0)
5582 return;
5583
John Kessenich121853f2017-05-31 17:11:16 -06005584 glslang::SpvOptions defaultOptions;
5585 if (options == nullptr)
5586 options = &defaultOptions;
5587
John Kessenich140f3df2015-06-26 16:58:36 -06005588 glslang::GetThreadPoolAllocator().push();
5589
John Kessenich121853f2017-05-31 17:11:16 -06005590 TGlslangToSpvTraverser it(&intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06005591 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07005592 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06005593 it.dumpSpv(spirv);
5594
5595 glslang::GetThreadPoolAllocator().pop();
5596}
5597
5598}; // end namespace glslang