• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*-------------------------------------------------------------------------
2  * Vulkan CTS Framework
3  * --------------------
4  *
5  * Copyright (c) 2015 Google Inc.
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  *//*!
20  * \file
21  * \brief Shading language (GLSL/HLSL) to SPIR-V.
22  *//*--------------------------------------------------------------------*/
23 
24 #include "vkShaderToSpirV.hpp"
25 #include "deArrayUtil.hpp"
26 #include "deSingleton.h"
27 #include "deMemory.h"
28 #include "deClock.h"
29 #include "qpDebugOut.h"
30 
31 #include "SPIRV/GlslangToSpv.h"
32 #include "SPIRV/disassemble.h"
33 #include "SPIRV/SPVRemapper.h"
34 #include "SPIRV/doc.h"
35 #include "glslang/Include/InfoSink.h"
36 #include "glslang/Include/ShHandle.h"
37 #include "glslang/MachineIndependent/localintermediate.h"
38 #include "glslang/Public/ShaderLang.h"
39 
40 namespace vk
41 {
42 
43 using std::string;
44 using std::vector;
45 
46 namespace
47 {
48 
getGlslangStage(glu::ShaderType type)49 EShLanguage getGlslangStage (glu::ShaderType type)
50 {
51 	static const EShLanguage stageMap[] =
52 	{
53 		EShLangVertex,
54 		EShLangFragment,
55 		EShLangGeometry,
56 		EShLangTessControl,
57 		EShLangTessEvaluation,
58 		EShLangCompute,
59 		EShLangRayGen,
60 		EShLangAnyHit,
61 		EShLangClosestHit,
62 		EShLangMiss,
63 		EShLangIntersect,
64 		EShLangCallable,
65 	};
66 	return de::getSizedArrayElement<glu::SHADERTYPE_LAST>(stageMap, type);
67 }
68 
69 static volatile deSingletonState	s_glslangInitState	= DE_SINGLETON_STATE_NOT_INITIALIZED;
70 
initGlslang(void *)71 void initGlslang (void*)
72 {
73 	// Main compiler
74 	glslang::InitializeProcess();
75 
76 	// SPIR-V disassembly
77 	spv::Parameterize();
78 }
79 
prepareGlslang(void)80 void prepareGlslang (void)
81 {
82 	deInitSingleton(&s_glslangInitState, initGlslang, DE_NULL);
83 }
84 
85 // \todo [2015-06-19 pyry] Specialize these per GLSL version
86 
87 // Fail compilation if more members are added to TLimits or TBuiltInResource
88 struct LimitsSizeHelper_s			{ bool m0, m1, m2, m3, m4, m5, m6, m7, m8; };
89 struct BuiltInResourceSizeHelper_s	{ int m[93]; LimitsSizeHelper_s l; };
90 
91 DE_STATIC_ASSERT(sizeof(TLimits)			== sizeof(LimitsSizeHelper_s));
92 DE_STATIC_ASSERT(sizeof(TBuiltInResource)	== sizeof(BuiltInResourceSizeHelper_s));
93 
getDefaultLimits(TLimits * limits)94 void getDefaultLimits (TLimits* limits)
95 {
96 	limits->nonInductiveForLoops					= true;
97 	limits->whileLoops								= true;
98 	limits->doWhileLoops							= true;
99 	limits->generalUniformIndexing					= true;
100 	limits->generalAttributeMatrixVectorIndexing	= true;
101 	limits->generalVaryingIndexing					= true;
102 	limits->generalSamplerIndexing					= true;
103 	limits->generalVariableIndexing					= true;
104 	limits->generalConstantMatrixVectorIndexing		= true;
105 }
106 
getDefaultBuiltInResources(TBuiltInResource * builtin)107 void getDefaultBuiltInResources (TBuiltInResource* builtin)
108 {
109 	getDefaultLimits(&builtin->limits);
110 
111 	builtin->maxLights									= 32;
112 	builtin->maxClipPlanes								= 6;
113 	builtin->maxTextureUnits							= 32;
114 	builtin->maxTextureCoords							= 32;
115 	builtin->maxVertexAttribs							= 64;
116 	builtin->maxVertexUniformComponents					= 4096;
117 	builtin->maxVaryingFloats							= 64;
118 	builtin->maxVertexTextureImageUnits					= 32;
119 	builtin->maxCombinedTextureImageUnits				= 80;
120 	builtin->maxTextureImageUnits						= 32;
121 	builtin->maxFragmentUniformComponents				= 4096;
122 	builtin->maxDrawBuffers								= 32;
123 	builtin->maxVertexUniformVectors					= 128;
124 	builtin->maxVaryingVectors							= 8;
125 	builtin->maxFragmentUniformVectors					= 16;
126 	builtin->maxVertexOutputVectors						= 16;
127 	builtin->maxFragmentInputVectors					= 15;
128 	builtin->minProgramTexelOffset						= -8;
129 	builtin->maxProgramTexelOffset						= 7;
130 	builtin->maxClipDistances							= 8;
131 	builtin->maxComputeWorkGroupCountX					= 65535;
132 	builtin->maxComputeWorkGroupCountY					= 65535;
133 	builtin->maxComputeWorkGroupCountZ					= 65535;
134 	builtin->maxComputeWorkGroupSizeX					= 1024;
135 	builtin->maxComputeWorkGroupSizeY					= 1024;
136 	builtin->maxComputeWorkGroupSizeZ					= 64;
137 	builtin->maxComputeUniformComponents				= 1024;
138 	builtin->maxComputeTextureImageUnits				= 16;
139 	builtin->maxComputeImageUniforms					= 8;
140 	builtin->maxComputeAtomicCounters					= 8;
141 	builtin->maxComputeAtomicCounterBuffers				= 1;
142 	builtin->maxVaryingComponents						= 60;
143 	builtin->maxVertexOutputComponents					= 64;
144 	builtin->maxGeometryInputComponents					= 64;
145 	builtin->maxGeometryOutputComponents				= 128;
146 	builtin->maxFragmentInputComponents					= 128;
147 	builtin->maxImageUnits								= 8;
148 	builtin->maxCombinedImageUnitsAndFragmentOutputs	= 8;
149 	builtin->maxCombinedShaderOutputResources			= 8;
150 	builtin->maxImageSamples							= 0;
151 	builtin->maxVertexImageUniforms						= 0;
152 	builtin->maxTessControlImageUniforms				= 0;
153 	builtin->maxTessEvaluationImageUniforms				= 0;
154 	builtin->maxGeometryImageUniforms					= 0;
155 	builtin->maxFragmentImageUniforms					= 8;
156 	builtin->maxCombinedImageUniforms					= 8;
157 	builtin->maxGeometryTextureImageUnits				= 16;
158 	builtin->maxGeometryOutputVertices					= 256;
159 	builtin->maxGeometryTotalOutputComponents			= 1024;
160 	builtin->maxGeometryUniformComponents				= 1024;
161 	builtin->maxGeometryVaryingComponents				= 64;
162 	builtin->maxTessControlInputComponents				= 128;
163 	builtin->maxTessControlOutputComponents				= 128;
164 	builtin->maxTessControlTextureImageUnits			= 16;
165 	builtin->maxTessControlUniformComponents			= 1024;
166 	builtin->maxTessControlTotalOutputComponents		= 4096;
167 	builtin->maxTessEvaluationInputComponents			= 128;
168 	builtin->maxTessEvaluationOutputComponents			= 128;
169 	builtin->maxTessEvaluationTextureImageUnits			= 16;
170 	builtin->maxTessEvaluationUniformComponents			= 1024;
171 	builtin->maxTessPatchComponents						= 120;
172 	builtin->maxPatchVertices							= 32;
173 	builtin->maxTessGenLevel							= 64;
174 	builtin->maxViewports								= 16;
175 	builtin->maxVertexAtomicCounters					= 0;
176 	builtin->maxTessControlAtomicCounters				= 0;
177 	builtin->maxTessEvaluationAtomicCounters			= 0;
178 	builtin->maxGeometryAtomicCounters					= 0;
179 	builtin->maxFragmentAtomicCounters					= 8;
180 	builtin->maxCombinedAtomicCounters					= 8;
181 	builtin->maxAtomicCounterBindings					= 1;
182 	builtin->maxVertexAtomicCounterBuffers				= 0;
183 	builtin->maxTessControlAtomicCounterBuffers			= 0;
184 	builtin->maxTessEvaluationAtomicCounterBuffers		= 0;
185 	builtin->maxGeometryAtomicCounterBuffers			= 0;
186 	builtin->maxFragmentAtomicCounterBuffers			= 1;
187 	builtin->maxCombinedAtomicCounterBuffers			= 1;
188 	builtin->maxAtomicCounterBufferSize					= 16384;
189 	builtin->maxTransformFeedbackBuffers				= 8;
190 	builtin->maxTransformFeedbackInterleavedComponents	= 16382;
191 	builtin->maxCullDistances							= 8;
192 	builtin->maxCombinedClipAndCullDistances			= 8;
193 	builtin->maxSamples									= 4;
194 	builtin->maxMeshOutputVerticesNV					= 256;
195 	builtin->maxMeshOutputPrimitivesNV					= 256;
196 	builtin->maxMeshWorkGroupSizeX_NV					= 32;
197 	builtin->maxMeshWorkGroupSizeY_NV					= 1;
198 	builtin->maxMeshWorkGroupSizeZ_NV					= 1;
199 	builtin->maxTaskWorkGroupSizeX_NV					= 32;
200 	builtin->maxTaskWorkGroupSizeY_NV					= 1;
201 	builtin->maxTaskWorkGroupSizeZ_NV					= 1;
202 	builtin->maxMeshViewCountNV							= 4;
203 	builtin->maxDualSourceDrawBuffersEXT				= 1;
204 };
205 
getNumShaderStages(const std::vector<std::string> * sources)206 int getNumShaderStages (const std::vector<std::string>* sources)
207 {
208 	int numShaderStages = 0;
209 
210 	for (int shaderType = 0; shaderType < glu::SHADERTYPE_LAST; ++shaderType)
211 	{
212 		if (!sources[shaderType].empty())
213 			numShaderStages += 1;
214 	}
215 
216 	return numShaderStages;
217 }
218 
getShaderStageSource(const std::vector<std::string> * sources,const ShaderBuildOptions buildOptions,glu::ShaderType shaderType)219 std::string getShaderStageSource (const std::vector<std::string>* sources, const ShaderBuildOptions buildOptions, glu::ShaderType shaderType)
220 {
221 	if (sources[shaderType].size() != 1)
222 		TCU_THROW(InternalError, "Linking multiple compilation units is not supported");
223 
224 	if ((buildOptions.flags & ShaderBuildOptions::FLAG_USE_STORAGE_BUFFER_STORAGE_CLASS) != 0)
225 	{
226 		// Hack to inject #pragma right after first #version statement
227 		std::string src			= sources[shaderType][0];
228 		size_t		injectPos	= 0;
229 
230 		if (de::beginsWith(src, "#version"))
231 			injectPos = src.find('\n') + 1;
232 
233 		src.insert(injectPos, "#pragma use_storage_buffer\n");
234 
235 		return src;
236 	}
237 	else
238 		return sources[shaderType][0];
239 }
240 
getCompileFlags(const ShaderBuildOptions & buildOpts,const ShaderLanguage shaderLanguage)241 EShMessages getCompileFlags (const ShaderBuildOptions& buildOpts, const ShaderLanguage shaderLanguage)
242 {
243 	EShMessages		flags	= (EShMessages)(EShMsgSpvRules | EShMsgVulkanRules);
244 
245 	if ((buildOpts.flags & ShaderBuildOptions::FLAG_ALLOW_RELAXED_OFFSETS) != 0)
246 		flags = (EShMessages)(flags | EShMsgHlslOffsets);
247 
248 	if (shaderLanguage == SHADER_LANGUAGE_HLSL)
249 		flags = (EShMessages)(flags | EShMsgReadHlsl);
250 
251 	return flags;
252 }
253 
254 } // anonymous
255 
compileShaderToSpirV(const std::vector<std::string> * sources,const ShaderBuildOptions & buildOptions,const ShaderLanguage shaderLanguage,std::vector<deUint32> * dst,glu::ShaderProgramInfo * buildInfo)256 bool compileShaderToSpirV (const std::vector<std::string>* sources, const ShaderBuildOptions& buildOptions, const ShaderLanguage shaderLanguage, std::vector<deUint32>* dst, glu::ShaderProgramInfo* buildInfo)
257 {
258 	TBuiltInResource	builtinRes = {};
259 	const EShMessages	compileFlags	= getCompileFlags(buildOptions, shaderLanguage);
260 
261 	if (buildOptions.targetVersion >= SPIRV_VERSION_LAST)
262 		TCU_THROW(InternalError, "Unsupported SPIR-V target version");
263 
264 	if (getNumShaderStages(sources) > 1)
265 		TCU_THROW(InternalError, "Linking multiple shader stages into a single SPIR-V binary is not supported");
266 
267 	prepareGlslang();
268 	getDefaultBuiltInResources(&builtinRes);
269 
270 	// \note Compiles only first found shader
271 	for (int shaderType = 0; shaderType < glu::SHADERTYPE_LAST; shaderType++)
272 	{
273 		if (!sources[shaderType].empty())
274 		{
275 			const std::string&		srcText				= getShaderStageSource(sources, buildOptions, (glu::ShaderType)shaderType);
276 			const char*				srcPtrs[]			= { srcText.c_str() };
277 			const EShLanguage		shaderStage			= getGlslangStage(glu::ShaderType(shaderType));
278 			glslang::TShader		shader				(shaderStage);
279 			glslang::TProgram		glslangProgram;
280 
281 			shader.setStrings(srcPtrs, DE_LENGTH_OF_ARRAY(srcPtrs));
282 
283 			switch ( buildOptions.targetVersion )
284 			{
285 			case SPIRV_VERSION_1_0:
286 				shader.setEnvTarget(glslang::EshTargetSpv, (glslang::EShTargetLanguageVersion)0x10000);
287 				break;
288 			case SPIRV_VERSION_1_1:
289 				shader.setEnvTarget(glslang::EshTargetSpv, (glslang::EShTargetLanguageVersion)0x10100);
290 				break;
291 			case SPIRV_VERSION_1_2:
292 				shader.setEnvTarget(glslang::EshTargetSpv, (glslang::EShTargetLanguageVersion)0x10200);
293 				break;
294 			case SPIRV_VERSION_1_3:
295 				shader.setEnvTarget(glslang::EshTargetSpv, (glslang::EShTargetLanguageVersion)0x10300);
296 				break;
297 			case SPIRV_VERSION_1_4:
298 				shader.setEnvTarget(glslang::EshTargetSpv, (glslang::EShTargetLanguageVersion)0x10400);
299 				break;
300 			case SPIRV_VERSION_1_5:
301 				shader.setEnvTarget(glslang::EshTargetSpv, (glslang::EShTargetLanguageVersion)0x10500);
302 				break;
303 			default:
304 				TCU_THROW(InternalError, "Unsupported SPIR-V target version");
305 			}
306 
307 			glslangProgram.addShader(&shader);
308 
309 			if (shaderLanguage == SHADER_LANGUAGE_HLSL)
310 			{
311 				// Entry point assumed to be named main.
312 				shader.setEntryPoint("main");
313 			}
314 
315 			{
316 				const deUint64	compileStartTime	= deGetMicroseconds();
317 				const int		compileRes			= shader.parse(&builtinRes, 110, false, compileFlags);
318 				glu::ShaderInfo	shaderBuildInfo;
319 
320 				shaderBuildInfo.type			= (glu::ShaderType)shaderType;
321 				shaderBuildInfo.source			= srcText;
322 				shaderBuildInfo.infoLog			= shader.getInfoLog(); // \todo [2015-07-13 pyry] Include debug log?
323 				shaderBuildInfo.compileTimeUs	= deGetMicroseconds()-compileStartTime;
324 				shaderBuildInfo.compileOk		= (compileRes != 0);
325 
326 				buildInfo->shaders.push_back(shaderBuildInfo);
327 			}
328 
329 			DE_ASSERT(buildInfo->shaders.size() == 1);
330 			if (buildInfo->shaders[0].compileOk)
331 			{
332 				const deUint64	linkStartTime	= deGetMicroseconds();
333 				const int		linkRes			= glslangProgram.link(compileFlags);
334 
335 				buildInfo->program.infoLog		= glslangProgram.getInfoLog(); // \todo [2015-11-05 scygan] Include debug log?
336 				buildInfo->program.linkOk		= (linkRes != 0);
337 				buildInfo->program.linkTimeUs	= deGetMicroseconds()-linkStartTime;
338 			}
339 
340 			if (buildInfo->program.linkOk)
341 			{
342 				const glslang::TIntermediate* const	intermediate	= glslangProgram.getIntermediate(shaderStage);
343 				glslang::GlslangToSpv(*intermediate, *dst);
344 			}
345 
346 			return buildInfo->program.linkOk;
347 		}
348 	}
349 
350 	TCU_THROW(InternalError, "Can't compile empty program");
351 }
352 
compileGlslToSpirV(const GlslSource & program,std::vector<deUint32> * dst,glu::ShaderProgramInfo * buildInfo)353 bool compileGlslToSpirV (const GlslSource& program, std::vector<deUint32>* dst, glu::ShaderProgramInfo* buildInfo)
354 {
355 	return compileShaderToSpirV(program.sources, program.buildOptions, program.shaderLanguage, dst, buildInfo);
356 }
357 
compileHlslToSpirV(const HlslSource & program,std::vector<deUint32> * dst,glu::ShaderProgramInfo * buildInfo)358 bool compileHlslToSpirV (const HlslSource& program, std::vector<deUint32>* dst, glu::ShaderProgramInfo* buildInfo)
359 {
360 	return compileShaderToSpirV(program.sources, program.buildOptions, program.shaderLanguage, dst, buildInfo);
361 }
362 
stripSpirVDebugInfo(const size_t numSrcInstrs,const deUint32 * srcInstrs,std::vector<deUint32> * dst)363 void stripSpirVDebugInfo (const size_t numSrcInstrs, const deUint32* srcInstrs, std::vector<deUint32>* dst)
364 {
365 	spv::spirvbin_t remapper;
366 
367 	// glslang operates in-place
368 	dst->resize(numSrcInstrs);
369 	std::copy(srcInstrs, srcInstrs+numSrcInstrs, dst->begin());
370 	remapper.remap(*dst, spv::spirvbin_base_t::STRIP);
371 }
372 
373 } // vk
374