blob: bdfb7f38f839d14e9e2241bb38fd99b7a3fef111 [file] [log] [blame]
alokp@chromium.org07620a52010-09-23 17:53:56 +00001//
Jamie Madill88f6e942014-02-19 10:27:53 -05002// Copyright (c) 2002-2014 The ANGLE Project Authors. All rights reserved.
alokp@chromium.org07620a52010-09-23 17:53:56 +00003// Use of this source code is governed by a BSD-style license that can be
4// found in the LICENSE file.
5//
6
Corentin Wallez8b28a8b2016-09-15 19:47:56 -04007#include "compiler/translator/Compiler.h"
8
9#include <sstream>
10
11#include "angle_gl.h"
12#include "common/utilities.h"
Corentin Wallez71d147f2015-02-11 11:15:24 -080013#include "compiler/translator/CallDAG.h"
Olli Etuaho78ed6cd2017-08-09 16:19:00 +030014#include "compiler/translator/CollectVariables.h"
Geoff Lang17732822013-08-29 13:46:49 -040015#include "compiler/translator/Initialize.h"
Olli Etuahocccf2b02017-07-05 14:50:54 +030016#include "compiler/translator/IsASTDepthBelowLimit.h"
17#include "compiler/translator/OutputTree.h"
Jamie Madill6b9cb252013-10-17 10:45:47 -040018#include "compiler/translator/ParseContext.h"
Geoff Lang17732822013-08-29 13:46:49 -040019#include "compiler/translator/ValidateLimitations.h"
Olli Etuaho19d1dc92016-03-08 17:18:46 +020020#include "compiler/translator/ValidateMaxParameters.h"
Geoff Lang17732822013-08-29 13:46:49 -040021#include "compiler/translator/ValidateOutputs.h"
Jiawei Shao4cc89e22017-08-31 14:25:54 +080022#include "compiler/translator/ValidateVaryingLocations.h"
Geoff Lang17732822013-08-29 13:46:49 -040023#include "compiler/translator/VariablePacker.h"
Olli Etuahoa07b4212018-03-22 16:13:13 +020024#include "compiler/translator/tree_ops/AddAndTrueToLoopCondition.h"
25#include "compiler/translator/tree_ops/ClampFragDepth.h"
26#include "compiler/translator/tree_ops/ClampPointSize.h"
27#include "compiler/translator/tree_ops/DeclareAndInitBuiltinsForInstancedMultiview.h"
28#include "compiler/translator/tree_ops/DeferGlobalInitializers.h"
Austin Eng7cf9cd22018-10-09 15:27:32 -070029#include "compiler/translator/tree_ops/EmulateGLDrawID.h"
Olli Etuahoa07b4212018-03-22 16:13:13 +020030#include "compiler/translator/tree_ops/EmulateGLFragColorBroadcast.h"
31#include "compiler/translator/tree_ops/EmulatePrecision.h"
32#include "compiler/translator/tree_ops/FoldExpressions.h"
33#include "compiler/translator/tree_ops/InitializeVariables.h"
34#include "compiler/translator/tree_ops/PruneEmptyCases.h"
35#include "compiler/translator/tree_ops/PruneNoOps.h"
Shahbaz Youssefi216f73d2019-04-12 13:32:30 -040036#include "compiler/translator/tree_ops/RedefineInterfaceBlockLayoutQualifiersWithStd.h"
Olli Etuahoa07b4212018-03-22 16:13:13 +020037#include "compiler/translator/tree_ops/RegenerateStructNames.h"
38#include "compiler/translator/tree_ops/RemoveArrayLengthMethod.h"
39#include "compiler/translator/tree_ops/RemoveInvariantDeclaration.h"
40#include "compiler/translator/tree_ops/RemovePow.h"
41#include "compiler/translator/tree_ops/RemoveUnreferencedVariables.h"
42#include "compiler/translator/tree_ops/RewriteDoWhile.h"
Olli Etuaho983460e2018-05-02 17:57:39 +030043#include "compiler/translator/tree_ops/RewriteRepeatedAssignToSwizzled.h"
Olli Etuahoa07b4212018-03-22 16:13:13 +020044#include "compiler/translator/tree_ops/ScalarizeVecAndMatConstructorArgs.h"
45#include "compiler/translator/tree_ops/SeparateDeclarations.h"
46#include "compiler/translator/tree_ops/SimplifyLoopConditions.h"
47#include "compiler/translator/tree_ops/SplitSequenceOperator.h"
48#include "compiler/translator/tree_ops/UnfoldShortCircuitAST.h"
49#include "compiler/translator/tree_ops/UseInterfaceBlockFields.h"
50#include "compiler/translator/tree_ops/VectorizeVectorScalarArithmetic.h"
Olli Etuaho59c5b892018-04-03 11:44:50 +030051#include "compiler/translator/tree_util/BuiltIn_autogen.h"
Olli Etuahoc26214d2018-03-16 10:43:11 +020052#include "compiler/translator/tree_util/IntermNodePatternMatcher.h"
Olli Etuahob5601eb2017-11-15 18:08:04 +020053#include "compiler/translator/util.h"
shannon.woods@transgaming.comda1ed362013-01-25 21:54:57 +000054#include "third_party/compiler/ArrayBoundsClamper.h"
Corentin Wallez28b65282016-06-16 07:24:50 -070055
Jamie Madillacb4b812016-11-07 13:50:29 -050056namespace sh
57{
58
Corentin Wallez28b65282016-06-16 07:24:50 -070059namespace
60{
61
62#if defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
63void DumpFuzzerCase(char const *const *shaderStrings,
64 size_t numStrings,
65 uint32_t type,
66 uint32_t spec,
67 uint32_t output,
68 uint64_t options)
69{
70 static int fileIndex = 0;
71
Jonah Ryan-Davisf563fdc2019-01-31 13:53:59 -050072 std::ostringstream o = sh::InitializeStream<std::ostringstream>();
Corentin Wallez28b65282016-06-16 07:24:50 -070073 o << "corpus/" << fileIndex++ << ".sample";
74 std::string s = o.str();
75
76 // Must match the input format of the fuzzer
77 FILE *f = fopen(s.c_str(), "w");
78 fwrite(&type, sizeof(type), 1, f);
79 fwrite(&spec, sizeof(spec), 1, f);
80 fwrite(&output, sizeof(output), 1, f);
81 fwrite(&options, sizeof(options), 1, f);
82
83 char zero[128 - 20] = {0};
84 fwrite(&zero, 128 - 20, 1, f);
85
86 for (size_t i = 0; i < numStrings; i++)
87 {
88 fwrite(shaderStrings[i], sizeof(char), strlen(shaderStrings[i]), f);
89 }
90 fwrite(&zero, 1, 1, f);
91
92 fclose(f);
93}
94#endif // defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
95} // anonymous namespace
96
Qingqing Dengad0d0792015-04-08 14:25:06 -070097bool IsGLSL130OrNewer(ShShaderOutput output)
98{
Jamie Madillacb4b812016-11-07 13:50:29 -050099 return (output == SH_GLSL_130_OUTPUT || output == SH_GLSL_140_OUTPUT ||
100 output == SH_GLSL_150_CORE_OUTPUT || output == SH_GLSL_330_CORE_OUTPUT ||
101 output == SH_GLSL_400_CORE_OUTPUT || output == SH_GLSL_410_CORE_OUTPUT ||
102 output == SH_GLSL_420_CORE_OUTPUT || output == SH_GLSL_430_CORE_OUTPUT ||
103 output == SH_GLSL_440_CORE_OUTPUT || output == SH_GLSL_450_CORE_OUTPUT);
Qingqing Dengad0d0792015-04-08 14:25:06 -0700104}
105
Qiankun Miao705a9192016-08-29 10:05:27 +0800106bool IsGLSL420OrNewer(ShShaderOutput output)
107{
Jamie Madillacb4b812016-11-07 13:50:29 -0500108 return (output == SH_GLSL_420_CORE_OUTPUT || output == SH_GLSL_430_CORE_OUTPUT ||
109 output == SH_GLSL_440_CORE_OUTPUT || output == SH_GLSL_450_CORE_OUTPUT);
Qiankun Miao705a9192016-08-29 10:05:27 +0800110}
111
Zhenyao Mob7bf7422016-11-08 14:44:05 -0800112bool IsGLSL410OrOlder(ShShaderOutput output)
113{
114 return (output == SH_GLSL_130_OUTPUT || output == SH_GLSL_140_OUTPUT ||
115 output == SH_GLSL_150_CORE_OUTPUT || output == SH_GLSL_330_CORE_OUTPUT ||
116 output == SH_GLSL_400_CORE_OUTPUT || output == SH_GLSL_410_CORE_OUTPUT);
117}
118
Qiankun Miao89dd8f32016-11-09 12:59:30 +0000119bool RemoveInvariant(sh::GLenum shaderType,
120 int shaderVersion,
121 ShShaderOutput outputType,
122 ShCompileOptions compileOptions)
123{
124 if ((compileOptions & SH_DONT_REMOVE_INVARIANT_FOR_FRAGMENT_INPUT) == 0 &&
125 shaderType == GL_FRAGMENT_SHADER && IsGLSL420OrNewer(outputType))
126 return true;
127
128 if ((compileOptions & SH_REMOVE_INVARIANT_AND_CENTROID_FOR_ESSL3) != 0 &&
Qiankun Miao41f9f672016-11-16 17:04:36 +0800129 shaderVersion >= 300 && shaderType == GL_VERTEX_SHADER)
Qiankun Miao89dd8f32016-11-09 12:59:30 +0000130 return true;
131
132 return false;
133}
134
Zhenyao Mo7faf1a12014-04-25 18:03:56 -0700135size_t GetGlobalMaxTokenSize(ShShaderSpec spec)
Jamie Madill88f6e942014-02-19 10:27:53 -0500136{
He Yunchao29ab9ff2015-08-06 16:58:30 +0800137 // WebGL defines a max token length of 256, while ES2 leaves max token
Jamie Madill88f6e942014-02-19 10:27:53 -0500138 // size undefined. ES3 defines a max size of 1024 characters.
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700139 switch (spec)
Jamie Madill88f6e942014-02-19 10:27:53 -0500140 {
Jamie Madillacb4b812016-11-07 13:50:29 -0500141 case SH_WEBGL_SPEC:
142 return 256;
143 default:
144 return 1024;
Jamie Madill88f6e942014-02-19 10:27:53 -0500145 }
146}
147
Shao77891c02017-06-23 16:30:17 +0800148int GetMaxUniformVectorsForShaderType(GLenum shaderType, const ShBuiltInResources &resources)
149{
150 switch (shaderType)
151 {
152 case GL_VERTEX_SHADER:
153 return resources.MaxVertexUniformVectors;
154 case GL_FRAGMENT_SHADER:
155 return resources.MaxFragmentUniformVectors;
Shaob5cc1192017-07-06 10:47:20 +0800156
157 // TODO (jiawei.shao@intel.com): check if we need finer-grained component counting
Shao77891c02017-06-23 16:30:17 +0800158 case GL_COMPUTE_SHADER:
Shao77891c02017-06-23 16:30:17 +0800159 return resources.MaxComputeUniformComponents / 4;
Jiawei Shaobd924af2017-11-16 15:28:04 +0800160 case GL_GEOMETRY_SHADER_EXT:
Shaob5cc1192017-07-06 10:47:20 +0800161 return resources.MaxGeometryUniformComponents / 4;
Shao77891c02017-06-23 16:30:17 +0800162 default:
Shaob5cc1192017-07-06 10:47:20 +0800163 UNREACHABLE();
Shao77891c02017-06-23 16:30:17 +0800164 return -1;
165 }
166}
167
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500168namespace
169{
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700170
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800171class TScopedPoolAllocator
172{
173 public:
Tobin Ehlis5546fb42019-01-17 12:25:54 -0500174 TScopedPoolAllocator(angle::PoolAllocator *allocator) : mAllocator(allocator)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800175 {
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400176 mAllocator->push();
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000177 SetGlobalPoolAllocator(mAllocator);
178 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800179 ~TScopedPoolAllocator()
180 {
Yunchao Hef81ce4a2017-04-24 10:49:17 +0800181 SetGlobalPoolAllocator(nullptr);
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400182 mAllocator->pop();
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000183 }
184
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800185 private:
Tobin Ehlis5546fb42019-01-17 12:25:54 -0500186 angle::PoolAllocator *mAllocator;
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400187};
188
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800189class TScopedSymbolTableLevel
190{
191 public:
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500192 TScopedSymbolTableLevel(TSymbolTable *table) : mTable(table)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800193 {
Olli Etuaho437664b2018-02-28 15:38:14 +0200194 ASSERT(mTable->isEmpty());
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400195 mTable->push();
196 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800197 ~TScopedSymbolTableLevel()
198 {
Olli Etuaho437664b2018-02-28 15:38:14 +0200199 while (!mTable->isEmpty())
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400200 mTable->pop();
201 }
202
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800203 private:
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500204 TSymbolTable *mTable;
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000205};
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700206
207int MapSpecToShaderVersion(ShShaderSpec spec)
208{
209 switch (spec)
210 {
Jamie Madillacb4b812016-11-07 13:50:29 -0500211 case SH_GLES2_SPEC:
212 case SH_WEBGL_SPEC:
213 return 100;
214 case SH_GLES3_SPEC:
215 case SH_WEBGL2_SPEC:
216 return 300;
217 case SH_GLES3_1_SPEC:
218 case SH_WEBGL3_SPEC:
219 return 310;
220 default:
221 UNREACHABLE();
222 return 0;
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700223 }
224}
225
Olli Etuaho59c5b892018-04-03 11:44:50 +0300226bool ValidateFragColorAndFragData(GLenum shaderType,
227 int shaderVersion,
228 const TSymbolTable &symbolTable,
229 TDiagnostics *diagnostics)
230{
231 if (shaderVersion > 100 || shaderType != GL_FRAGMENT_SHADER)
232 {
233 return true;
234 }
235
236 bool usesFragColor = false;
237 bool usesFragData = false;
238 // This validation is a bit stricter than the spec - it's only an error to write to
239 // both FragData and FragColor. But because it's better not to have reads from undefined
240 // variables, we always return an error if they are both referenced, rather than only if they
241 // are written.
242 if (symbolTable.isStaticallyUsed(*BuiltInVariable::gl_FragColor()) ||
243 symbolTable.isStaticallyUsed(*BuiltInVariable::gl_SecondaryFragColorEXT()))
244 {
245 usesFragColor = true;
246 }
247 // Extension variables may not always be initialized (saves some time at symbol table init).
248 bool secondaryFragDataUsed =
249 symbolTable.gl_SecondaryFragDataEXT() != nullptr &&
250 symbolTable.isStaticallyUsed(*symbolTable.gl_SecondaryFragDataEXT());
251 if (symbolTable.isStaticallyUsed(*symbolTable.gl_FragData()) || secondaryFragDataUsed)
252 {
253 usesFragData = true;
254 }
255 if (usesFragColor && usesFragData)
256 {
257 const char *errorMessage = "cannot use both gl_FragData and gl_FragColor";
258 if (symbolTable.isStaticallyUsed(*BuiltInVariable::gl_SecondaryFragColorEXT()) ||
259 secondaryFragDataUsed)
260 {
261 errorMessage =
262 "cannot use both output variable sets (gl_FragData, gl_SecondaryFragDataEXT)"
263 " and (gl_FragColor, gl_SecondaryFragColorEXT)";
264 }
265 diagnostics->globalError(errorMessage);
266 return false;
267 }
268 return true;
269}
270
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000271} // namespace
272
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800273TShHandleBase::TShHandleBase()
274{
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000275 allocator.push();
276 SetGlobalPoolAllocator(&allocator);
277}
278
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800279TShHandleBase::~TShHandleBase()
280{
Yunchao Hef81ce4a2017-04-24 10:49:17 +0800281 SetGlobalPoolAllocator(nullptr);
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000282 allocator.popAll();
283}
284
Jamie Madill183bde52014-07-02 15:31:19 -0400285TCompiler::TCompiler(sh::GLenum type, ShShaderSpec spec, ShShaderOutput output)
Olli Etuaho6f591c92018-09-21 11:20:47 +0300286 : mVariablesCollected(false),
Olli Etuahob12040c2017-06-27 14:20:45 +0300287 mGLPositionInitialized(false),
Olli Etuaho6f591c92018-09-21 11:20:47 +0300288 mShaderType(type),
289 mShaderSpec(spec),
290 mOutputType(output),
291 mBuiltInFunctionEmulator(),
292 mDiagnostics(mInfoSink.info),
Yunchao Hef81ce4a2017-04-24 10:49:17 +0800293 mSourcePath(nullptr),
Shaob5cc1192017-07-06 10:47:20 +0800294 mComputeShaderLocalSizeDeclared(false),
Jamie Madill2f294c92017-11-20 14:47:26 -0500295 mComputeShaderLocalSize(1),
Shaob5cc1192017-07-06 10:47:20 +0800296 mGeometryShaderMaxVertices(-1),
297 mGeometryShaderInvocations(0),
298 mGeometryShaderInputPrimitiveType(EptUndefined),
299 mGeometryShaderOutputPrimitiveType(EptUndefined)
Jamie Madillb980c562018-11-27 11:34:27 -0500300{}
alokp@chromium.org4888ceb2010-10-01 21:13:12 +0000301
Jamie Madillb980c562018-11-27 11:34:27 -0500302TCompiler::~TCompiler() {}
alokp@chromium.org4888ceb2010-10-01 21:13:12 +0000303
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800304bool TCompiler::shouldRunLoopAndIndexingValidation(ShCompileOptions compileOptions) const
Olli Etuaho5d91dda2015-06-18 15:47:46 +0300305{
306 // If compiling an ESSL 1.00 shader for WebGL, or if its been requested through the API,
307 // validate loop and indexing as well (to verify that the shader only uses minimal functionality
308 // of ESSL 1.00 as in Appendix A of the spec).
Olli Etuaho6f591c92018-09-21 11:20:47 +0300309 return (IsWebGLBasedSpec(mShaderSpec) && mShaderVersion == 100) ||
Olli Etuaho5d91dda2015-06-18 15:47:46 +0300310 (compileOptions & SH_VALIDATE_LOOP_INDEXING);
311}
312
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500313bool TCompiler::Init(const ShBuiltInResources &resources)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000314{
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400315 SetGlobalPoolAllocator(&allocator);
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000316
alokp@chromium.org07620a52010-09-23 17:53:56 +0000317 // Generate built-in symbol table.
Olli Etuaho6f591c92018-09-21 11:20:47 +0300318 if (!initBuiltInSymbolTable(resources))
alokp@chromium.org07620a52010-09-23 17:53:56 +0000319 return false;
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000320
Olli Etuaho6f591c92018-09-21 11:20:47 +0300321 mResources = resources;
322 setResourceString();
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000323
Olli Etuaho6f591c92018-09-21 11:20:47 +0300324 InitExtensionBehavior(resources, mExtensionBehavior);
325 mArrayBoundsClamper.SetClampingStrategy(resources.ArrayIndexClampingStrategy);
alokp@chromium.org07620a52010-09-23 17:53:56 +0000326 return true;
327}
328
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100329TIntermBlock *TCompiler::compileTreeForTesting(const char *const shaderStrings[],
330 size_t numStrings,
331 ShCompileOptions compileOptions)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000332{
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200333 return compileTreeImpl(shaderStrings, numStrings, compileOptions);
334}
335
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100336TIntermBlock *TCompiler::compileTreeImpl(const char *const shaderStrings[],
337 size_t numStrings,
338 const ShCompileOptions compileOptions)
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200339{
alokp@chromium.org07620a52010-09-23 17:53:56 +0000340 clearResults();
341
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200342 ASSERT(numStrings > 0);
343 ASSERT(GetGlobalPoolAllocator());
alokp@chromium.org07620a52010-09-23 17:53:56 +0000344
David Yen0fbd1282015-02-02 14:46:09 -0800345 // Reset the extension behavior for each compilation unit.
Olli Etuaho6f591c92018-09-21 11:20:47 +0300346 ResetExtensionBehavior(mExtensionBehavior);
David Yen0fbd1282015-02-02 14:46:09 -0800347
Austin Eng7cf9cd22018-10-09 15:27:32 -0700348 // If gl_DrawID is not supported, remove it from the available extensions
349 // Currently we only allow emulation of gl_DrawID
350 const bool glDrawIDSupported = (compileOptions & SH_EMULATE_GL_DRAW_ID) != 0u;
351 if (!glDrawIDSupported)
352 {
353 auto it = mExtensionBehavior.find(TExtension::ANGLE_multi_draw);
354 if (it != mExtensionBehavior.end())
355 {
356 mExtensionBehavior.erase(it);
357 }
358 }
359
apatrick@chromium.org0f4cefe2011-01-26 19:30:57 +0000360 // First string is path of source file if flag is set. The actual source follows.
shannon.woods@transgaming.comd64b3da2013-02-28 23:19:26 +0000361 size_t firstSource = 0;
apatrick@chromium.org0f4cefe2011-01-26 19:30:57 +0000362 if (compileOptions & SH_SOURCE_PATH)
363 {
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200364 mSourcePath = shaderStrings[0];
apatrick@chromium.org0f4cefe2011-01-26 19:30:57 +0000365 ++firstSource;
366 }
367
Olli Etuaho6f591c92018-09-21 11:20:47 +0300368 TParseContext parseContext(mSymbolTable, mExtensionBehavior, mShaderType, mShaderSpec,
Olli Etuaho77ba4082016-12-16 12:01:18 +0000369 compileOptions, true, &mDiagnostics, getResources());
Olli Etuaho853dc1a2014-11-06 17:25:48 +0200370
Olli Etuaho6f591c92018-09-21 11:20:47 +0300371 parseContext.setFragmentPrecisionHighOnESSL1(mResources.FragmentPrecisionHigh == 1);
alokp@chromium.org07620a52010-09-23 17:53:56 +0000372
373 // We preserve symbols at the built-in level from compile-to-compile.
374 // Start pushing the user-defined symbols at global level.
Olli Etuaho6f591c92018-09-21 11:20:47 +0300375 TScopedSymbolTableLevel globalLevel(&mSymbolTable);
376 ASSERT(mSymbolTable.atGlobalLevel());
alokp@chromium.org07620a52010-09-23 17:53:56 +0000377
378 // Parse shader.
Olli Etuahod10cf692017-11-02 11:06:14 +0200379 if (PaParseStrings(numStrings - firstSource, &shaderStrings[firstSource], nullptr,
380 &parseContext) != 0)
381 {
382 return nullptr;
383 }
shannon.woods%transgaming.com@gtempaccount.com0bbed382013-04-13 03:38:07 +0000384
Olli Etuahod10cf692017-11-02 11:06:14 +0200385 if (parseContext.getTreeRoot() == nullptr)
386 {
387 return nullptr;
388 }
389
390 setASTMetadata(parseContext);
391
Jiawei Shaoe41df652018-02-09 14:31:39 +0800392 if (!checkShaderVersion(&parseContext))
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700393 {
Olli Etuahod10cf692017-11-02 11:06:14 +0200394 return nullptr;
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700395 }
shannon.woods%transgaming.com@gtempaccount.com0bbed382013-04-13 03:38:07 +0000396
Olli Etuahod10cf692017-11-02 11:06:14 +0200397 TIntermBlock *root = parseContext.getTreeRoot();
398 if (!checkAndSimplifyAST(root, parseContext, compileOptions))
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800399 {
Olli Etuahod10cf692017-11-02 11:06:14 +0200400 return nullptr;
401 }
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700402
Olli Etuahod10cf692017-11-02 11:06:14 +0200403 return root;
404}
Martin Radev802abe02016-08-04 17:48:32 +0300405
Jiawei Shaoe41df652018-02-09 14:31:39 +0800406bool TCompiler::checkShaderVersion(TParseContext *parseContext)
407{
Olli Etuaho6f591c92018-09-21 11:20:47 +0300408 if (MapSpecToShaderVersion(mShaderSpec) < mShaderVersion)
Jiawei Shaoe41df652018-02-09 14:31:39 +0800409 {
410 mDiagnostics.globalError("unsupported shader version");
411 return false;
412 }
413
414 ASSERT(parseContext);
Olli Etuaho6f591c92018-09-21 11:20:47 +0300415 switch (mShaderType)
Jiawei Shaoe41df652018-02-09 14:31:39 +0800416 {
417 case GL_COMPUTE_SHADER:
Olli Etuaho6f591c92018-09-21 11:20:47 +0300418 if (mShaderVersion < 310)
Jiawei Shaoe41df652018-02-09 14:31:39 +0800419 {
420 mDiagnostics.globalError("Compute shader is not supported in this shader version.");
421 return false;
422 }
423 break;
424
425 case GL_GEOMETRY_SHADER_EXT:
Olli Etuaho6f591c92018-09-21 11:20:47 +0300426 if (mShaderVersion < 310)
Jiawei Shaoe41df652018-02-09 14:31:39 +0800427 {
428 mDiagnostics.globalError(
429 "Geometry shader is not supported in this shader version.");
430 return false;
431 }
432 else
433 {
Olli Etuaho6f591c92018-09-21 11:20:47 +0300434 ASSERT(mShaderVersion == 310);
Jiawei Shaoe41df652018-02-09 14:31:39 +0800435 if (!parseContext->checkCanUseExtension(sh::TSourceLoc(),
436 TExtension::EXT_geometry_shader))
437 {
438 return false;
439 }
440 }
441 break;
442
443 default:
444 break;
445 }
446
447 return true;
448}
449
Olli Etuahod10cf692017-11-02 11:06:14 +0200450void TCompiler::setASTMetadata(const TParseContext &parseContext)
451{
Olli Etuaho6f591c92018-09-21 11:20:47 +0300452 mShaderVersion = parseContext.getShaderVersion();
Olli Etuaho09b04a22016-12-15 13:30:26 +0000453
Olli Etuahod10cf692017-11-02 11:06:14 +0200454 mPragma = parseContext.pragma();
Olli Etuaho6f591c92018-09-21 11:20:47 +0300455 mSymbolTable.setGlobalInvariant(mPragma.stdgl.invariantAll);
alokp@chromium.orgb59a7782010-11-24 18:38:33 +0000456
Olli Etuahod10cf692017-11-02 11:06:14 +0200457 mComputeShaderLocalSizeDeclared = parseContext.isComputeShaderLocalSizeDeclared();
458 mComputeShaderLocalSize = parseContext.getComputeShaderLocalSize();
Olli Etuahoa6996682015-10-12 14:32:30 +0300459
Olli Etuahod10cf692017-11-02 11:06:14 +0200460 mNumViews = parseContext.getNumViews();
461
Olli Etuaho6f591c92018-09-21 11:20:47 +0300462 if (mShaderType == GL_GEOMETRY_SHADER_EXT)
Olli Etuahod10cf692017-11-02 11:06:14 +0200463 {
464 mGeometryShaderInputPrimitiveType = parseContext.getGeometryShaderInputPrimitiveType();
465 mGeometryShaderOutputPrimitiveType = parseContext.getGeometryShaderOutputPrimitiveType();
466 mGeometryShaderMaxVertices = parseContext.getGeometryShaderMaxVertices();
467 mGeometryShaderInvocations = parseContext.getGeometryShaderInvocations();
468 }
469}
470
471bool TCompiler::checkAndSimplifyAST(TIntermBlock *root,
472 const TParseContext &parseContext,
473 ShCompileOptions compileOptions)
474{
475 // Disallow expressions deemed too complex.
476 if ((compileOptions & SH_LIMIT_EXPRESSION_COMPLEXITY) && !limitExpressionComplexity(root))
477 {
478 return false;
479 }
480
Olli Etuaho765924f2018-01-04 12:48:36 +0200481 if (shouldRunLoopAndIndexingValidation(compileOptions) &&
Olli Etuaho6f591c92018-09-21 11:20:47 +0300482 !ValidateLimitations(root, mShaderType, &mSymbolTable, &mDiagnostics))
Olli Etuaho765924f2018-01-04 12:48:36 +0200483 {
484 return false;
485 }
486
Olli Etuaho6f591c92018-09-21 11:20:47 +0300487 if (!ValidateFragColorAndFragData(mShaderType, mShaderVersion, mSymbolTable, &mDiagnostics))
Olli Etuaho59c5b892018-04-03 11:44:50 +0300488 {
489 return false;
490 }
491
Olli Etuaho765924f2018-01-04 12:48:36 +0200492 // Fold expressions that could not be folded before validation that was done as a part of
493 // parsing.
494 FoldExpressions(root, &mDiagnostics);
495 // Folding should only be able to generate warnings.
496 ASSERT(mDiagnostics.numErrors() == 0);
Shahbaz Youssefi91d469a2018-08-27 10:47:25 -0400497 if (!ValidateAST(root, &mDiagnostics, mValidateASTOptions))
498 {
499 return false;
500 }
Olli Etuaho765924f2018-01-04 12:48:36 +0200501
Olli Etuahod10cf692017-11-02 11:06:14 +0200502 // We prune no-ops to work around driver bugs and to keep AST processing and output simple.
503 // The following kinds of no-ops are pruned:
504 // 1. Empty declarations "int;".
505 // 2. Literal statements: "1.0;". The ESSL output doesn't define a default precision
506 // for float, so float literal statements would end up with no precision which is
507 // invalid ESSL.
508 // After this empty declarations are not allowed in the AST.
Olli Etuaho6f591c92018-09-21 11:20:47 +0300509 PruneNoOps(root, &mSymbolTable);
Shahbaz Youssefi91d469a2018-08-27 10:47:25 -0400510 if (!ValidateAST(root, &mDiagnostics, mValidateASTOptions))
511 {
512 return false;
513 }
Olli Etuahod10cf692017-11-02 11:06:14 +0200514
Olli Etuahod10cf692017-11-02 11:06:14 +0200515 // Create the function DAG and check there is no recursion
516 if (!initCallDag(root))
517 {
518 return false;
519 }
520
521 if ((compileOptions & SH_LIMIT_CALL_STACK_DEPTH) && !checkCallDepth())
522 {
523 return false;
524 }
525
526 // Checks which functions are used and if "main" exists
Olli Etuaho6f591c92018-09-21 11:20:47 +0300527 mFunctionMetadata.clear();
528 mFunctionMetadata.resize(mCallDag.size());
Olli Etuahod10cf692017-11-02 11:06:14 +0200529 if (!tagUsedFunctions())
530 {
531 return false;
532 }
533
534 if (!(compileOptions & SH_DONT_PRUNE_UNUSED_FUNCTIONS))
535 {
536 pruneUnusedFunctions(root);
Shahbaz Youssefi91d469a2018-08-27 10:47:25 -0400537 if (!ValidateAST(root, &mDiagnostics, mValidateASTOptions))
538 {
539 return false;
540 }
Olli Etuahod10cf692017-11-02 11:06:14 +0200541 }
542
Olli Etuaho6f591c92018-09-21 11:20:47 +0300543 if (mShaderVersion >= 310 && !ValidateVaryingLocations(root, &mDiagnostics, mShaderType))
Olli Etuahod10cf692017-11-02 11:06:14 +0200544 {
545 return false;
546 }
547
Olli Etuaho6f591c92018-09-21 11:20:47 +0300548 if (mShaderVersion >= 300 && mShaderType == GL_FRAGMENT_SHADER &&
549 !ValidateOutputs(root, getExtensionBehavior(), mResources.MaxDrawBuffers, &mDiagnostics))
Olli Etuahod10cf692017-11-02 11:06:14 +0200550 {
551 return false;
552 }
553
Olli Etuahod10cf692017-11-02 11:06:14 +0200554 // Fail compilation if precision emulation not supported.
555 if (getResources().WEBGL_debug_shader_precision && getPragma().debugShaderPrecision &&
Olli Etuaho6f591c92018-09-21 11:20:47 +0300556 !EmulatePrecision::SupportedInLanguage(mOutputType))
Olli Etuahod10cf692017-11-02 11:06:14 +0200557 {
558 mDiagnostics.globalError("Precision emulation not supported for this output type.");
559 return false;
560 }
561
Olli Etuahod10cf692017-11-02 11:06:14 +0200562 // Clamping uniform array bounds needs to happen after validateLimitations pass.
563 if (compileOptions & SH_CLAMP_INDIRECT_ARRAY_BOUNDS)
564 {
Olli Etuaho6f591c92018-09-21 11:20:47 +0300565 mArrayBoundsClamper.MarkIndirectArrayBoundsForClamping(root);
Olli Etuahod10cf692017-11-02 11:06:14 +0200566 }
567
568 if ((compileOptions & SH_INITIALIZE_BUILTINS_FOR_INSTANCED_MULTIVIEW) &&
Mingyu Hu7d64c482019-03-12 14:27:40 -0700569 parseContext.isExtensionEnabled(TExtension::OVR_multiview2) &&
Olli Etuahod10cf692017-11-02 11:06:14 +0200570 getShaderType() != GL_COMPUTE_SHADER)
571 {
Olli Etuaho6f591c92018-09-21 11:20:47 +0300572 DeclareAndInitBuiltinsForInstancedMultiview(root, mNumViews, mShaderType, compileOptions,
573 mOutputType, &mSymbolTable);
Shahbaz Youssefi91d469a2018-08-27 10:47:25 -0400574 if (!ValidateAST(root, &mDiagnostics, mValidateASTOptions))
575 {
576 return false;
577 }
Olli Etuahod10cf692017-11-02 11:06:14 +0200578 }
579
580 // This pass might emit short circuits so keep it before the short circuit unfolding
581 if (compileOptions & SH_REWRITE_DO_WHILE_LOOPS)
Shahbaz Youssefi91d469a2018-08-27 10:47:25 -0400582 {
Olli Etuaho6f591c92018-09-21 11:20:47 +0300583 RewriteDoWhile(root, &mSymbolTable);
Shahbaz Youssefi91d469a2018-08-27 10:47:25 -0400584 if (!ValidateAST(root, &mDiagnostics, mValidateASTOptions))
585 {
586 return false;
587 }
588 }
Olli Etuahod10cf692017-11-02 11:06:14 +0200589
590 if (compileOptions & SH_ADD_AND_TRUE_TO_LOOP_CONDITION)
Shahbaz Youssefi91d469a2018-08-27 10:47:25 -0400591 {
Olli Etuaho1776fd02018-01-31 11:46:52 +0200592 AddAndTrueToLoopCondition(root);
Shahbaz Youssefi91d469a2018-08-27 10:47:25 -0400593 if (!ValidateAST(root, &mDiagnostics, mValidateASTOptions))
594 {
595 return false;
596 }
597 }
Olli Etuahod10cf692017-11-02 11:06:14 +0200598
599 if (compileOptions & SH_UNFOLD_SHORT_CIRCUIT)
600 {
Olli Etuaho1776fd02018-01-31 11:46:52 +0200601 UnfoldShortCircuitAST(root);
Shahbaz Youssefi91d469a2018-08-27 10:47:25 -0400602 if (!ValidateAST(root, &mDiagnostics, mValidateASTOptions))
603 {
604 return false;
605 }
Olli Etuahod10cf692017-11-02 11:06:14 +0200606 }
607
608 if (compileOptions & SH_REMOVE_POW_WITH_CONSTANT_EXPONENT)
609 {
Olli Etuaho6f591c92018-09-21 11:20:47 +0300610 RemovePow(root, &mSymbolTable);
Shahbaz Youssefi91d469a2018-08-27 10:47:25 -0400611 if (!ValidateAST(root, &mDiagnostics, mValidateASTOptions))
612 {
613 return false;
614 }
Olli Etuahod10cf692017-11-02 11:06:14 +0200615 }
616
Olli Etuahod10cf692017-11-02 11:06:14 +0200617 if (compileOptions & SH_REGENERATE_STRUCT_NAMES)
618 {
Olli Etuaho6f591c92018-09-21 11:20:47 +0300619 RegenerateStructNames gen(&mSymbolTable);
Olli Etuahod10cf692017-11-02 11:06:14 +0200620 root->traverse(&gen);
Shahbaz Youssefi91d469a2018-08-27 10:47:25 -0400621 if (!ValidateAST(root, &mDiagnostics, mValidateASTOptions))
622 {
623 return false;
624 }
Olli Etuahod10cf692017-11-02 11:06:14 +0200625 }
626
Austin Eng7cf9cd22018-10-09 15:27:32 -0700627 if (mShaderType == GL_VERTEX_SHADER &&
628 IsExtensionEnabled(mExtensionBehavior, TExtension::ANGLE_multi_draw))
629 {
630 if ((compileOptions & SH_EMULATE_GL_DRAW_ID) != 0)
631 {
632 EmulateGLDrawID(root, &mSymbolTable, &mUniforms,
633 shouldCollectVariables(compileOptions));
Shahbaz Youssefi91d469a2018-08-27 10:47:25 -0400634 if (!ValidateAST(root, &mDiagnostics, mValidateASTOptions))
635 {
636 return false;
637 }
Austin Eng7cf9cd22018-10-09 15:27:32 -0700638 }
639 }
640
Olli Etuaho6f591c92018-09-21 11:20:47 +0300641 if (mShaderType == GL_FRAGMENT_SHADER && mShaderVersion == 100 && mResources.EXT_draw_buffers &&
642 mResources.MaxDrawBuffers > 1 &&
643 IsExtensionEnabled(mExtensionBehavior, TExtension::EXT_draw_buffers))
Olli Etuahod10cf692017-11-02 11:06:14 +0200644 {
Olli Etuaho6f591c92018-09-21 11:20:47 +0300645 EmulateGLFragColorBroadcast(root, mResources.MaxDrawBuffers, &mOutputVariables,
646 &mSymbolTable, mShaderVersion);
Shahbaz Youssefi91d469a2018-08-27 10:47:25 -0400647 if (!ValidateAST(root, &mDiagnostics, mValidateASTOptions))
648 {
649 return false;
650 }
Olli Etuahod10cf692017-11-02 11:06:14 +0200651 }
652
Olli Etuahoae04e1e2017-11-27 16:00:39 +0200653 int simplifyScalarized = (compileOptions & SH_SCALARIZE_VEC_AND_MAT_CONSTRUCTOR_ARGS)
654 ? IntermNodePatternMatcher::kScalarizedVecOrMatConstructor
655 : 0;
656
Olli Etuahod10cf692017-11-02 11:06:14 +0200657 // Split multi declarations and remove calls to array length().
658 // Note that SimplifyLoopConditions needs to be run before any other AST transformations
659 // that may need to generate new statements from loop conditions or loop expressions.
Olli Etuahoae04e1e2017-11-27 16:00:39 +0200660 SimplifyLoopConditions(root,
661 IntermNodePatternMatcher::kMultiDeclaration |
662 IntermNodePatternMatcher::kArrayLengthMethod | simplifyScalarized,
Olli Etuaho68981eb2018-01-23 17:46:12 +0200663 &getSymbolTable());
Shahbaz Youssefi91d469a2018-08-27 10:47:25 -0400664 if (!ValidateAST(root, &mDiagnostics, mValidateASTOptions))
665 {
666 return false;
667 }
Olli Etuahod10cf692017-11-02 11:06:14 +0200668
669 // Note that separate declarations need to be run before other AST transformations that
670 // generate new statements from expressions.
671 SeparateDeclarations(root);
Shahbaz Youssefi91d469a2018-08-27 10:47:25 -0400672 mValidateASTOptions.validateMultiDeclarations = true;
673 if (!ValidateAST(root, &mDiagnostics, mValidateASTOptions))
674 {
675 return false;
676 }
Olli Etuahod10cf692017-11-02 11:06:14 +0200677
Olli Etuahoae04e1e2017-11-27 16:00:39 +0200678 SplitSequenceOperator(root, IntermNodePatternMatcher::kArrayLengthMethod | simplifyScalarized,
Olli Etuaho68981eb2018-01-23 17:46:12 +0200679 &getSymbolTable());
Shahbaz Youssefi91d469a2018-08-27 10:47:25 -0400680 if (!ValidateAST(root, &mDiagnostics, mValidateASTOptions))
681 {
682 return false;
683 }
Olli Etuahod10cf692017-11-02 11:06:14 +0200684
685 RemoveArrayLengthMethod(root);
Shahbaz Youssefi91d469a2018-08-27 10:47:25 -0400686 if (!ValidateAST(root, &mDiagnostics, mValidateASTOptions))
687 {
688 return false;
689 }
Olli Etuahod10cf692017-11-02 11:06:14 +0200690
Olli Etuaho6f591c92018-09-21 11:20:47 +0300691 RemoveUnreferencedVariables(root, &mSymbolTable);
Shahbaz Youssefi91d469a2018-08-27 10:47:25 -0400692 if (!ValidateAST(root, &mDiagnostics, mValidateASTOptions))
693 {
694 return false;
695 }
Olli Etuaho3d70ca92017-11-10 16:53:26 +0200696
Olli Etuaho41217992018-03-15 11:15:33 +0200697 // In case the last case inside a switch statement is a certain type of no-op, GLSL compilers in
698 // drivers may not accept it. In this case we clean up the dead code from the end of switch
699 // statements. This is also required because PruneNoOps or RemoveUnreferencedVariables may have
700 // left switch statements that only contained an empty declaration inside the final case in an
701 // invalid state. Relies on that PruneNoOps and RemoveUnreferencedVariables have already been
702 // run.
Olli Etuaho0b0dcbc2018-03-14 11:33:22 +0200703 PruneEmptyCases(root);
Shahbaz Youssefi91d469a2018-08-27 10:47:25 -0400704 if (!ValidateAST(root, &mDiagnostics, mValidateASTOptions))
705 {
706 return false;
707 }
Olli Etuaho0b0dcbc2018-03-14 11:33:22 +0200708
Olli Etuaho3d70ca92017-11-10 16:53:26 +0200709 // Built-in function emulation needs to happen after validateLimitations pass.
710 // TODO(jmadill): Remove global pool allocator.
711 GetGlobalPoolAllocator()->lock();
Olli Etuaho6f591c92018-09-21 11:20:47 +0300712 initBuiltInFunctionEmulator(&mBuiltInFunctionEmulator, compileOptions);
Olli Etuaho3d70ca92017-11-10 16:53:26 +0200713 GetGlobalPoolAllocator()->unlock();
Olli Etuaho6f591c92018-09-21 11:20:47 +0300714 mBuiltInFunctionEmulator.markBuiltInFunctionsForEmulation(root);
Olli Etuaho3d70ca92017-11-10 16:53:26 +0200715
Olli Etuaho6f591c92018-09-21 11:20:47 +0300716 bool highPrecisionSupported = mShaderVersion > 100 || mShaderType != GL_FRAGMENT_SHADER ||
717 mResources.FragmentPrecisionHigh == 1;
Olli Etuaho3d70ca92017-11-10 16:53:26 +0200718 if (compileOptions & SH_SCALARIZE_VEC_AND_MAT_CONSTRUCTOR_ARGS)
719 {
Olli Etuaho6f591c92018-09-21 11:20:47 +0300720 ScalarizeVecAndMatConstructorArgs(root, mShaderType, highPrecisionSupported, &mSymbolTable);
Shahbaz Youssefi91d469a2018-08-27 10:47:25 -0400721 if (!ValidateAST(root, &mDiagnostics, mValidateASTOptions))
722 {
723 return false;
724 }
Olli Etuaho3d70ca92017-11-10 16:53:26 +0200725 }
726
Shahbaz Youssefi216f73d2019-04-12 13:32:30 -0400727 if (compileOptions & SH_REDEFINE_INTERFACE_LAYOUT_QUALIFIERS_WITH_STD)
728 {
729 // Change the interface block layouts based on GL_KHR_vulkan_glsl. Only std140 and std430
730 // are allowed in Vulkan GLSL.
731 RedefineInterfaceBlockLayoutQualifiersWithStd(root, &mSymbolTable);
732 }
733
Olli Etuaho3d70ca92017-11-10 16:53:26 +0200734 if (shouldCollectVariables(compileOptions))
735 {
Olli Etuaho6f591c92018-09-21 11:20:47 +0300736 ASSERT(!mVariablesCollected);
737 CollectVariables(root, &mAttributes, &mOutputVariables, &mUniforms, &mInputVaryings,
738 &mOutputVaryings, &mUniformBlocks, &mShaderStorageBlocks, &mInBlocks,
739 mResources.HashFunction, &mSymbolTable, mShaderType, mExtensionBehavior);
Olli Etuaho3d70ca92017-11-10 16:53:26 +0200740 collectInterfaceBlocks();
Olli Etuaho6f591c92018-09-21 11:20:47 +0300741 mVariablesCollected = true;
Olli Etuaho3d70ca92017-11-10 16:53:26 +0200742 if (compileOptions & SH_USE_UNUSED_STANDARD_SHARED_BLOCKS)
743 {
744 useAllMembersInUnusedStandardAndSharedBlocks(root);
745 }
746 if (compileOptions & SH_ENFORCE_PACKING_RESTRICTIONS)
747 {
Olli Etuaho6f591c92018-09-21 11:20:47 +0300748 int maxUniformVectors = GetMaxUniformVectorsForShaderType(mShaderType, mResources);
Olli Etuaho3d70ca92017-11-10 16:53:26 +0200749 // Returns true if, after applying the packing rules in the GLSL ES 1.00.17 spec
750 // Appendix A, section 7, the shader does not use too many uniforms.
Olli Etuaho6f591c92018-09-21 11:20:47 +0300751 if (!CheckVariablesInPackingLimits(maxUniformVectors, mUniforms))
Olli Etuaho3d70ca92017-11-10 16:53:26 +0200752 {
753 mDiagnostics.globalError("too many uniforms");
754 return false;
755 }
756 }
Olli Etuaho6f591c92018-09-21 11:20:47 +0300757 if ((compileOptions & SH_INIT_OUTPUT_VARIABLES) && (mShaderType != GL_COMPUTE_SHADER))
Olli Etuaho3d70ca92017-11-10 16:53:26 +0200758 {
759 initializeOutputVariables(root);
Shahbaz Youssefi91d469a2018-08-27 10:47:25 -0400760 if (!ValidateAST(root, &mDiagnostics, mValidateASTOptions))
761 {
762 return false;
763 }
Olli Etuaho3d70ca92017-11-10 16:53:26 +0200764 }
765 }
766
767 // Removing invariant declarations must be done after collecting variables.
768 // Otherwise, built-in invariant declarations don't apply.
Olli Etuaho6f591c92018-09-21 11:20:47 +0300769 if (RemoveInvariant(mShaderType, mShaderVersion, mOutputType, compileOptions))
Olli Etuaho3d70ca92017-11-10 16:53:26 +0200770 {
771 RemoveInvariantDeclaration(root);
Shahbaz Youssefi91d469a2018-08-27 10:47:25 -0400772 if (!ValidateAST(root, &mDiagnostics, mValidateASTOptions))
773 {
774 return false;
775 }
Olli Etuaho3d70ca92017-11-10 16:53:26 +0200776 }
777
778 // gl_Position is always written in compatibility output mode.
779 // It may have been already initialized among other output variables, in that case we don't
780 // need to initialize it twice.
Olli Etuaho6f591c92018-09-21 11:20:47 +0300781 if (mShaderType == GL_VERTEX_SHADER && !mGLPositionInitialized &&
782 ((compileOptions & SH_INIT_GL_POSITION) || (mOutputType == SH_GLSL_COMPATIBILITY_OUTPUT)))
Olli Etuaho3d70ca92017-11-10 16:53:26 +0200783 {
784 initializeGLPosition(root);
785 mGLPositionInitialized = true;
Shahbaz Youssefi91d469a2018-08-27 10:47:25 -0400786 if (!ValidateAST(root, &mDiagnostics, mValidateASTOptions))
787 {
788 return false;
789 }
Olli Etuaho3d70ca92017-11-10 16:53:26 +0200790 }
791
Olli Etuahob5601eb2017-11-15 18:08:04 +0200792 // DeferGlobalInitializers needs to be run before other AST transformations that generate new
793 // statements from expressions. But it's fine to run DeferGlobalInitializers after the above
794 // SplitSequenceOperator and RemoveArrayLengthMethod since they only have an effect on the AST
795 // on ESSL >= 3.00, and the initializers that need to be deferred can only exist in ESSL < 3.00.
796 bool initializeLocalsAndGlobals =
797 (compileOptions & SH_INITIALIZE_UNINITIALIZED_LOCALS) && !IsOutputHLSL(getOutputType());
Olli Etuaho2c7f34c2017-10-09 17:18:02 +0300798 bool canUseLoopsToInitialize = !(compileOptions & SH_DONT_USE_LOOPS_TO_INITIALIZE_VARIABLES);
Olli Etuaho87cc90d2017-12-12 15:28:06 +0200799 DeferGlobalInitializers(root, initializeLocalsAndGlobals, canUseLoopsToInitialize,
Olli Etuaho6f591c92018-09-21 11:20:47 +0300800 highPrecisionSupported, &mSymbolTable);
Shahbaz Youssefi91d469a2018-08-27 10:47:25 -0400801 if (!ValidateAST(root, &mDiagnostics, mValidateASTOptions))
802 {
803 return false;
804 }
Olli Etuaho2c7f34c2017-10-09 17:18:02 +0300805
Olli Etuahob5601eb2017-11-15 18:08:04 +0200806 if (initializeLocalsAndGlobals)
Olli Etuahod10cf692017-11-02 11:06:14 +0200807 {
808 // Initialize uninitialized local variables.
809 // In some cases initializing can generate extra statements in the parent block, such as
810 // when initializing nameless structs or initializing arrays in ESSL 1.00. In that case
811 // we need to first simplify loop conditions. We've already separated declarations
812 // earlier, which is also required. If we don't follow the Appendix A limitations, loop
813 // init statements can declare arrays or nameless structs and have multiple
814 // declarations.
815
816 if (!shouldRunLoopAndIndexingValidation(compileOptions))
817 {
818 SimplifyLoopConditions(root,
819 IntermNodePatternMatcher::kArrayDeclaration |
820 IntermNodePatternMatcher::kNamelessStructDeclaration,
Olli Etuaho68981eb2018-01-23 17:46:12 +0200821 &getSymbolTable());
Shahbaz Youssefi91d469a2018-08-27 10:47:25 -0400822 if (!ValidateAST(root, &mDiagnostics, mValidateASTOptions))
823 {
824 return false;
825 }
Olli Etuahod10cf692017-11-02 11:06:14 +0200826 }
Olli Etuaho661fc482017-10-16 12:17:05 +0300827
Olli Etuaho2c7f34c2017-10-09 17:18:02 +0300828 InitializeUninitializedLocals(root, getShaderVersion(), canUseLoopsToInitialize,
Olli Etuaho87cc90d2017-12-12 15:28:06 +0200829 highPrecisionSupported, &getSymbolTable());
Shahbaz Youssefi91d469a2018-08-27 10:47:25 -0400830 if (!ValidateAST(root, &mDiagnostics, mValidateASTOptions))
831 {
832 return false;
833 }
Olli Etuahod10cf692017-11-02 11:06:14 +0200834 }
835
836 if (getShaderType() == GL_VERTEX_SHADER && (compileOptions & SH_CLAMP_POINT_SIZE))
837 {
Olli Etuaho6f591c92018-09-21 11:20:47 +0300838 ClampPointSize(root, mResources.MaxPointSize, &getSymbolTable());
Shahbaz Youssefi91d469a2018-08-27 10:47:25 -0400839 if (!ValidateAST(root, &mDiagnostics, mValidateASTOptions))
840 {
841 return false;
842 }
Olli Etuahod10cf692017-11-02 11:06:14 +0200843 }
844
Olli Etuaho0690e1a2017-12-21 20:51:38 +0200845 if (getShaderType() == GL_FRAGMENT_SHADER && (compileOptions & SH_CLAMP_FRAG_DEPTH))
846 {
847 ClampFragDepth(root, &getSymbolTable());
Shahbaz Youssefi91d469a2018-08-27 10:47:25 -0400848 if (!ValidateAST(root, &mDiagnostics, mValidateASTOptions))
849 {
850 return false;
851 }
Olli Etuaho0690e1a2017-12-21 20:51:38 +0200852 }
853
Olli Etuaho983460e2018-05-02 17:57:39 +0300854 if (compileOptions & SH_REWRITE_REPEATED_ASSIGN_TO_SWIZZLED)
855 {
856 sh::RewriteRepeatedAssignToSwizzled(root);
Shahbaz Youssefi91d469a2018-08-27 10:47:25 -0400857 if (!ValidateAST(root, &mDiagnostics, mValidateASTOptions))
858 {
859 return false;
860 }
Olli Etuaho983460e2018-05-02 17:57:39 +0300861 }
862
Olli Etuaho661fc482017-10-16 12:17:05 +0300863 if (compileOptions & SH_REWRITE_VECTOR_SCALAR_ARITHMETIC)
864 {
865 VectorizeVectorScalarArithmetic(root, &getSymbolTable());
Shahbaz Youssefi91d469a2018-08-27 10:47:25 -0400866 if (!ValidateAST(root, &mDiagnostics, mValidateASTOptions))
867 {
868 return false;
869 }
Olli Etuaho661fc482017-10-16 12:17:05 +0300870 }
871
Olli Etuahod10cf692017-11-02 11:06:14 +0200872 return true;
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200873}
874
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800875bool TCompiler::compile(const char *const shaderStrings[],
876 size_t numStrings,
877 ShCompileOptions compileOptionsIn)
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200878{
Corentin Wallez28b65282016-06-16 07:24:50 -0700879#if defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
Olli Etuaho6f591c92018-09-21 11:20:47 +0300880 DumpFuzzerCase(shaderStrings, numStrings, mShaderType, mShaderSpec, mOutputType,
881 compileOptionsIn);
Corentin Wallez28b65282016-06-16 07:24:50 -0700882#endif // defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
883
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200884 if (numStrings == 0)
885 return true;
886
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800887 ShCompileOptions compileOptions = compileOptionsIn;
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700888
889 // Apply key workarounds.
890 if (shouldFlattenPragmaStdglInvariantAll())
891 {
892 // This should be harmless to do in all cases, but for the moment, do it only conditionally.
893 compileOptions |= SH_FLATTEN_PRAGMA_STDGL_INVARIANT_ALL;
894 }
895
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200896 TScopedPoolAllocator scopedAlloc(&allocator);
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100897 TIntermBlock *root = compileTreeImpl(shaderStrings, numStrings, compileOptions);
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200898
899 if (root)
900 {
901 if (compileOptions & SH_INTERMEDIATE_TREE)
Olli Etuaho6f591c92018-09-21 11:20:47 +0300902 OutputTree(root, mInfoSink.info);
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200903
904 if (compileOptions & SH_OBJECT_CODE)
Olli Etuaho89a69a02017-10-23 12:20:45 +0300905 {
906 PerformanceDiagnostics perfDiagnostics(&mDiagnostics);
907 translate(root, compileOptions, &perfDiagnostics);
908 }
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200909
Austin Eng7cf9cd22018-10-09 15:27:32 -0700910 if (mShaderType == GL_VERTEX_SHADER &&
911 IsExtensionEnabled(mExtensionBehavior, TExtension::ANGLE_multi_draw))
912 {
913 if ((compileOptions & SH_EMULATE_GL_DRAW_ID) != 0)
914 {
Jamie Madillb980c562018-11-27 11:34:27 -0500915 for (auto &uniform : mUniforms)
Austin Eng7cf9cd22018-10-09 15:27:32 -0700916 {
917 if (uniform.name == "angle_DrawID" && uniform.mappedName == "angle_DrawID")
918 {
919 uniform.name = "gl_DrawID";
920 break;
921 }
922 }
923 }
924 }
925
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200926 // The IntermNode tree doesn't need to be deleted here, since the
927 // memory will be freed in a big chunk by the PoolAllocator.
928 return true;
929 }
930 return false;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000931}
932
Olli Etuaho6f591c92018-09-21 11:20:47 +0300933bool TCompiler::initBuiltInSymbolTable(const ShBuiltInResources &resources)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000934{
Olli Etuaho28cb0362016-11-22 15:42:37 +0000935 if (resources.MaxDrawBuffers < 1)
936 {
937 return false;
938 }
939 if (resources.EXT_blend_func_extended && resources.MaxDualSourceDrawBuffers < 1)
940 {
941 return false;
942 }
943
Olli Etuaho6f591c92018-09-21 11:20:47 +0300944 mSymbolTable.initializeBuiltIns(mShaderType, mShaderSpec, resources);
Olli Etuaho5d69db12017-11-24 16:51:15 +0200945
Nicolas Capens49a88872013-06-20 09:54:03 -0400946 return true;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000947}
948
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400949void TCompiler::setResourceString()
950{
Jonah Ryan-Davisf563fdc2019-01-31 13:53:59 -0500951 std::ostringstream strstream = sh::InitializeStream<std::ostringstream>();
Geoff Langb66a9092016-05-16 15:59:14 -0400952
953 // clang-format off
Olli Etuaho6f591c92018-09-21 11:20:47 +0300954 strstream << ":MaxVertexAttribs:" << mResources.MaxVertexAttribs
955 << ":MaxVertexUniformVectors:" << mResources.MaxVertexUniformVectors
956 << ":MaxVaryingVectors:" << mResources.MaxVaryingVectors
957 << ":MaxVertexTextureImageUnits:" << mResources.MaxVertexTextureImageUnits
958 << ":MaxCombinedTextureImageUnits:" << mResources.MaxCombinedTextureImageUnits
959 << ":MaxTextureImageUnits:" << mResources.MaxTextureImageUnits
960 << ":MaxFragmentUniformVectors:" << mResources.MaxFragmentUniformVectors
961 << ":MaxDrawBuffers:" << mResources.MaxDrawBuffers
962 << ":OES_standard_derivatives:" << mResources.OES_standard_derivatives
963 << ":OES_EGL_image_external:" << mResources.OES_EGL_image_external
964 << ":OES_EGL_image_external_essl3:" << mResources.OES_EGL_image_external_essl3
965 << ":NV_EGL_stream_consumer_external:" << mResources.NV_EGL_stream_consumer_external
966 << ":ARB_texture_rectangle:" << mResources.ARB_texture_rectangle
967 << ":EXT_draw_buffers:" << mResources.EXT_draw_buffers
968 << ":FragmentPrecisionHigh:" << mResources.FragmentPrecisionHigh
969 << ":MaxExpressionComplexity:" << mResources.MaxExpressionComplexity
970 << ":MaxCallStackDepth:" << mResources.MaxCallStackDepth
971 << ":MaxFunctionParameters:" << mResources.MaxFunctionParameters
972 << ":EXT_blend_func_extended:" << mResources.EXT_blend_func_extended
973 << ":EXT_frag_depth:" << mResources.EXT_frag_depth
974 << ":EXT_shader_texture_lod:" << mResources.EXT_shader_texture_lod
975 << ":EXT_shader_framebuffer_fetch:" << mResources.EXT_shader_framebuffer_fetch
976 << ":NV_shader_framebuffer_fetch:" << mResources.NV_shader_framebuffer_fetch
977 << ":ARM_shader_framebuffer_fetch:" << mResources.ARM_shader_framebuffer_fetch
Mingyu Hu7d64c482019-03-12 14:27:40 -0700978 << ":OVR_multiview2:" << mResources.OVR_multiview2
Olli Etuaho6f591c92018-09-21 11:20:47 +0300979 << ":EXT_YUV_target:" << mResources.EXT_YUV_target
980 << ":EXT_geometry_shader:" << mResources.EXT_geometry_shader
981 << ":MaxVertexOutputVectors:" << mResources.MaxVertexOutputVectors
982 << ":MaxFragmentInputVectors:" << mResources.MaxFragmentInputVectors
983 << ":MinProgramTexelOffset:" << mResources.MinProgramTexelOffset
984 << ":MaxProgramTexelOffset:" << mResources.MaxProgramTexelOffset
985 << ":MaxDualSourceDrawBuffers:" << mResources.MaxDualSourceDrawBuffers
986 << ":MaxViewsOVR:" << mResources.MaxViewsOVR
987 << ":NV_draw_buffers:" << mResources.NV_draw_buffers
988 << ":WEBGL_debug_shader_precision:" << mResources.WEBGL_debug_shader_precision
Austin Eng7cf9cd22018-10-09 15:27:32 -0700989 << ":ANGLE_multi_draw:" << mResources.ANGLE_multi_draw
Olli Etuaho6f591c92018-09-21 11:20:47 +0300990 << ":MinProgramTextureGatherOffset:" << mResources.MinProgramTextureGatherOffset
991 << ":MaxProgramTextureGatherOffset:" << mResources.MaxProgramTextureGatherOffset
992 << ":MaxImageUnits:" << mResources.MaxImageUnits
993 << ":MaxVertexImageUniforms:" << mResources.MaxVertexImageUniforms
994 << ":MaxFragmentImageUniforms:" << mResources.MaxFragmentImageUniforms
995 << ":MaxComputeImageUniforms:" << mResources.MaxComputeImageUniforms
996 << ":MaxCombinedImageUniforms:" << mResources.MaxCombinedImageUniforms
997 << ":MaxCombinedShaderOutputResources:" << mResources.MaxCombinedShaderOutputResources
998 << ":MaxComputeWorkGroupCountX:" << mResources.MaxComputeWorkGroupCount[0]
999 << ":MaxComputeWorkGroupCountY:" << mResources.MaxComputeWorkGroupCount[1]
1000 << ":MaxComputeWorkGroupCountZ:" << mResources.MaxComputeWorkGroupCount[2]
1001 << ":MaxComputeWorkGroupSizeX:" << mResources.MaxComputeWorkGroupSize[0]
1002 << ":MaxComputeWorkGroupSizeY:" << mResources.MaxComputeWorkGroupSize[1]
1003 << ":MaxComputeWorkGroupSizeZ:" << mResources.MaxComputeWorkGroupSize[2]
1004 << ":MaxComputeUniformComponents:" << mResources.MaxComputeUniformComponents
1005 << ":MaxComputeTextureImageUnits:" << mResources.MaxComputeTextureImageUnits
1006 << ":MaxComputeAtomicCounters:" << mResources.MaxComputeAtomicCounters
1007 << ":MaxComputeAtomicCounterBuffers:" << mResources.MaxComputeAtomicCounterBuffers
1008 << ":MaxVertexAtomicCounters:" << mResources.MaxVertexAtomicCounters
1009 << ":MaxFragmentAtomicCounters:" << mResources.MaxFragmentAtomicCounters
1010 << ":MaxCombinedAtomicCounters:" << mResources.MaxCombinedAtomicCounters
1011 << ":MaxAtomicCounterBindings:" << mResources.MaxAtomicCounterBindings
1012 << ":MaxVertexAtomicCounterBuffers:" << mResources.MaxVertexAtomicCounterBuffers
1013 << ":MaxFragmentAtomicCounterBuffers:" << mResources.MaxFragmentAtomicCounterBuffers
1014 << ":MaxCombinedAtomicCounterBuffers:" << mResources.MaxCombinedAtomicCounterBuffers
1015 << ":MaxAtomicCounterBufferSize:" << mResources.MaxAtomicCounterBufferSize
1016 << ":MaxGeometryUniformComponents:" << mResources.MaxGeometryUniformComponents
1017 << ":MaxGeometryUniformBlocks:" << mResources.MaxGeometryUniformBlocks
1018 << ":MaxGeometryInputComponents:" << mResources.MaxGeometryInputComponents
1019 << ":MaxGeometryOutputComponents:" << mResources.MaxGeometryOutputComponents
1020 << ":MaxGeometryOutputVertices:" << mResources.MaxGeometryOutputVertices
1021 << ":MaxGeometryTotalOutputComponents:" << mResources.MaxGeometryTotalOutputComponents
1022 << ":MaxGeometryTextureImageUnits:" << mResources.MaxGeometryTextureImageUnits
1023 << ":MaxGeometryAtomicCounterBuffers:" << mResources.MaxGeometryAtomicCounterBuffers
1024 << ":MaxGeometryAtomicCounters:" << mResources.MaxGeometryAtomicCounters
1025 << ":MaxGeometryShaderStorageBlocks:" << mResources.MaxGeometryShaderStorageBlocks
1026 << ":MaxGeometryShaderInvocations:" << mResources.MaxGeometryShaderInvocations
1027 << ":MaxGeometryImageUniforms:" << mResources.MaxGeometryImageUniforms;
Geoff Langb66a9092016-05-16 15:59:14 -04001028 // clang-format on
Shannon Woods2d76e5f2014-05-16 17:46:41 -04001029
Olli Etuaho6f591c92018-09-21 11:20:47 +03001030 mBuiltInResourcesString = strstream.str();
Shannon Woods2d76e5f2014-05-16 17:46:41 -04001031}
1032
Jiajia Qin9b11ea42017-07-11 16:50:08 +08001033void TCompiler::collectInterfaceBlocks()
1034{
Olli Etuaho6f591c92018-09-21 11:20:47 +03001035 ASSERT(mInterfaceBlocks.empty());
1036 mInterfaceBlocks.reserve(mUniformBlocks.size() + mShaderStorageBlocks.size() +
1037 mInBlocks.size());
1038 mInterfaceBlocks.insert(mInterfaceBlocks.end(), mUniformBlocks.begin(), mUniformBlocks.end());
1039 mInterfaceBlocks.insert(mInterfaceBlocks.end(), mShaderStorageBlocks.begin(),
1040 mShaderStorageBlocks.end());
1041 mInterfaceBlocks.insert(mInterfaceBlocks.end(), mInBlocks.begin(), mInBlocks.end());
Jiajia Qin9b11ea42017-07-11 16:50:08 +08001042}
1043
alokp@chromium.org07620a52010-09-23 17:53:56 +00001044void TCompiler::clearResults()
1045{
Olli Etuaho6f591c92018-09-21 11:20:47 +03001046 mArrayBoundsClamper.Cleanup();
1047 mInfoSink.info.erase();
1048 mInfoSink.obj.erase();
1049 mInfoSink.debug.erase();
Olli Etuaho77ba4082016-12-16 12:01:18 +00001050 mDiagnostics.resetErrorCount();
alokp@chromium.org07620a52010-09-23 17:53:56 +00001051
Olli Etuaho6f591c92018-09-21 11:20:47 +03001052 mAttributes.clear();
1053 mOutputVariables.clear();
1054 mUniforms.clear();
1055 mInputVaryings.clear();
1056 mOutputVaryings.clear();
1057 mInterfaceBlocks.clear();
1058 mUniformBlocks.clear();
1059 mShaderStorageBlocks.clear();
1060 mInBlocks.clear();
1061 mVariablesCollected = false;
Olli Etuahob12040c2017-06-27 14:20:45 +03001062 mGLPositionInitialized = false;
zmo@google.coma3b4ab42011-09-16 00:53:26 +00001063
Olli Etuaho09b04a22016-12-15 13:30:26 +00001064 mNumViews = -1;
1065
Shaob5cc1192017-07-06 10:47:20 +08001066 mGeometryShaderInputPrimitiveType = EptUndefined;
1067 mGeometryShaderOutputPrimitiveType = EptUndefined;
1068 mGeometryShaderInvocations = 0;
1069 mGeometryShaderMaxVertices = -1;
1070
Olli Etuaho6f591c92018-09-21 11:20:47 +03001071 mBuiltInFunctionEmulator.cleanup();
daniel@transgaming.com0aa3b5a2012-11-28 19:43:24 +00001072
Olli Etuaho6f591c92018-09-21 11:20:47 +03001073 mNameMap.clear();
Olli Etuahoa3a5cc62015-02-13 13:12:22 +02001074
Jamie Madillb980c562018-11-27 11:34:27 -05001075 mSourcePath = nullptr;
Olli Etuaho5d69db12017-11-24 16:51:15 +02001076
Olli Etuaho6f591c92018-09-21 11:20:47 +03001077 mSymbolTable.clearCompilationResults();
alokp@chromium.org07620a52010-09-23 17:53:56 +00001078}
1079
Corentin Wallez71d147f2015-02-11 11:15:24 -08001080bool TCompiler::initCallDag(TIntermNode *root)
zmo@google.comb1762df2011-07-30 02:04:23 +00001081{
Corentin Wallez71d147f2015-02-11 11:15:24 -08001082 mCallDag.clear();
1083
Olli Etuaho77ba4082016-12-16 12:01:18 +00001084 switch (mCallDag.init(root, &mDiagnostics))
Zhenyao Mo4a667fe2014-02-11 12:35:01 -08001085 {
Jamie Madillacb4b812016-11-07 13:50:29 -05001086 case CallDAG::INITDAG_SUCCESS:
1087 return true;
1088 case CallDAG::INITDAG_RECURSION:
Jamie Madillacb4b812016-11-07 13:50:29 -05001089 case CallDAG::INITDAG_UNDEFINED:
Olli Etuaho77ba4082016-12-16 12:01:18 +00001090 // Error message has already been written out.
1091 ASSERT(mDiagnostics.numErrors() > 0);
Jamie Madillacb4b812016-11-07 13:50:29 -05001092 return false;
Corentin Wallez71d147f2015-02-11 11:15:24 -08001093 }
1094
1095 UNREACHABLE();
1096 return true;
1097}
1098
1099bool TCompiler::checkCallDepth()
1100{
1101 std::vector<int> depths(mCallDag.size());
1102
1103 for (size_t i = 0; i < mCallDag.size(); i++)
1104 {
Jonah Ryan-Davisf563fdc2019-01-31 13:53:59 -05001105 int depth = 0;
Jonah Ryan-Davisd4c09dd2019-01-29 11:22:54 -05001106 const CallDAG::Record &record = mCallDag.getRecordFromIndex(i);
Corentin Wallez71d147f2015-02-11 11:15:24 -08001107
Jonah Ryan-Davisd4c09dd2019-01-29 11:22:54 -05001108 for (const int &calleeIndex : record.callees)
Corentin Wallez71d147f2015-02-11 11:15:24 -08001109 {
1110 depth = std::max(depth, depths[calleeIndex] + 1);
1111 }
1112
1113 depths[i] = depth;
1114
Olli Etuaho6f591c92018-09-21 11:20:47 +03001115 if (depth >= mResources.MaxCallStackDepth)
Corentin Wallez71d147f2015-02-11 11:15:24 -08001116 {
1117 // Trace back the function chain to have a meaningful info log.
Jonah Ryan-Davisf563fdc2019-01-31 13:53:59 -05001118 std::stringstream errorStream = sh::InitializeStream<std::stringstream>();
Olli Etuaho6f591c92018-09-21 11:20:47 +03001119 errorStream << "Call stack too deep (larger than " << mResources.MaxCallStackDepth
Olli Etuahoc33f1e82017-12-29 16:55:29 +02001120 << ") with the following call chain: "
1121 << record.node->getFunction()->name();
Corentin Wallez71d147f2015-02-11 11:15:24 -08001122
Cooper Partin4d61f7e2015-08-12 10:56:50 -07001123 int currentFunction = static_cast<int>(i);
Jamie Madilld7b1ab52016-12-12 14:42:19 -05001124 int currentDepth = depth;
Corentin Wallez71d147f2015-02-11 11:15:24 -08001125
1126 while (currentFunction != -1)
1127 {
Olli Etuahoc33f1e82017-12-29 16:55:29 +02001128 errorStream
1129 << " -> "
1130 << mCallDag.getRecordFromIndex(currentFunction).node->getFunction()->name();
Corentin Wallez71d147f2015-02-11 11:15:24 -08001131
1132 int nextFunction = -1;
Jonah Ryan-Davisd4c09dd2019-01-29 11:22:54 -05001133 for (const int &calleeIndex : mCallDag.getRecordFromIndex(currentFunction).callees)
Corentin Wallez71d147f2015-02-11 11:15:24 -08001134 {
1135 if (depths[calleeIndex] == currentDepth - 1)
1136 {
1137 currentDepth--;
1138 nextFunction = calleeIndex;
1139 }
1140 }
1141
1142 currentFunction = nextFunction;
1143 }
1144
Olli Etuaho77ba4082016-12-16 12:01:18 +00001145 std::string errorStr = errorStream.str();
1146 mDiagnostics.globalError(errorStr.c_str());
1147
Corentin Wallez71d147f2015-02-11 11:15:24 -08001148 return false;
1149 }
1150 }
1151
1152 return true;
1153}
1154
1155bool TCompiler::tagUsedFunctions()
1156{
1157 // Search from main, starting from the end of the DAG as it usually is the root.
Cooper Partin4d61f7e2015-08-12 10:56:50 -07001158 for (size_t i = mCallDag.size(); i-- > 0;)
Corentin Wallez71d147f2015-02-11 11:15:24 -08001159 {
Olli Etuahoc33f1e82017-12-29 16:55:29 +02001160 if (mCallDag.getRecordFromIndex(i).node->getFunction()->isMain())
Corentin Wallez71d147f2015-02-11 11:15:24 -08001161 {
1162 internalTagUsedFunction(i);
1163 return true;
1164 }
1165 }
1166
Olli Etuaho77ba4082016-12-16 12:01:18 +00001167 mDiagnostics.globalError("Missing main()");
Corentin Wallez71d147f2015-02-11 11:15:24 -08001168 return false;
1169}
1170
1171void TCompiler::internalTagUsedFunction(size_t index)
1172{
Olli Etuaho6f591c92018-09-21 11:20:47 +03001173 if (mFunctionMetadata[index].used)
Corentin Wallez71d147f2015-02-11 11:15:24 -08001174 {
1175 return;
1176 }
1177
Olli Etuaho6f591c92018-09-21 11:20:47 +03001178 mFunctionMetadata[index].used = true;
Corentin Wallez71d147f2015-02-11 11:15:24 -08001179
1180 for (int calleeIndex : mCallDag.getRecordFromIndex(index).callees)
1181 {
1182 internalTagUsedFunction(calleeIndex);
zmo@google.comb1762df2011-07-30 02:04:23 +00001183 }
1184}
1185
Corentin Walleza094a8a2015-04-07 11:53:06 -07001186// A predicate for the stl that returns if a top-level node is unused
1187class TCompiler::UnusedPredicate
1188{
1189 public:
1190 UnusedPredicate(const CallDAG *callDag, const std::vector<FunctionMetadata> *metadatas)
Jamie Madillacb4b812016-11-07 13:50:29 -05001191 : mCallDag(callDag), mMetadatas(metadatas)
Jamie Madillb980c562018-11-27 11:34:27 -05001192 {}
Corentin Walleza094a8a2015-04-07 11:53:06 -07001193
Jamie Madilld7b1ab52016-12-12 14:42:19 -05001194 bool operator()(TIntermNode *node)
Corentin Walleza094a8a2015-04-07 11:53:06 -07001195 {
Olli Etuaho16c745a2017-01-16 17:02:27 +00001196 const TIntermFunctionPrototype *asFunctionPrototype = node->getAsFunctionPrototypeNode();
1197 const TIntermFunctionDefinition *asFunctionDefinition = node->getAsFunctionDefinition();
Corentin Walleza094a8a2015-04-07 11:53:06 -07001198
Olli Etuahobeb6dc72017-12-14 16:03:03 +02001199 const TFunction *func = nullptr;
Olli Etuaho336b1472016-10-05 16:37:55 +01001200
Olli Etuaho16c745a2017-01-16 17:02:27 +00001201 if (asFunctionDefinition)
Olli Etuaho336b1472016-10-05 16:37:55 +01001202 {
Olli Etuahobeb6dc72017-12-14 16:03:03 +02001203 func = asFunctionDefinition->getFunction();
Olli Etuaho336b1472016-10-05 16:37:55 +01001204 }
Olli Etuaho16c745a2017-01-16 17:02:27 +00001205 else if (asFunctionPrototype)
Olli Etuaho336b1472016-10-05 16:37:55 +01001206 {
Olli Etuahobeb6dc72017-12-14 16:03:03 +02001207 func = asFunctionPrototype->getFunction();
Olli Etuaho336b1472016-10-05 16:37:55 +01001208 }
Olli Etuahobeb6dc72017-12-14 16:03:03 +02001209 if (func == nullptr)
Corentin Walleza094a8a2015-04-07 11:53:06 -07001210 {
1211 return false;
1212 }
1213
Olli Etuahobeb6dc72017-12-14 16:03:03 +02001214 size_t callDagIndex = mCallDag->findIndex(func->uniqueId());
Corentin Walleza094a8a2015-04-07 11:53:06 -07001215 if (callDagIndex == CallDAG::InvalidIndex)
1216 {
1217 // This happens only for unimplemented prototypes which are thus unused
Olli Etuaho16c745a2017-01-16 17:02:27 +00001218 ASSERT(asFunctionPrototype);
Corentin Walleza094a8a2015-04-07 11:53:06 -07001219 return true;
1220 }
1221
1222 ASSERT(callDagIndex < mMetadatas->size());
1223 return !(*mMetadatas)[callDagIndex].used;
1224 }
1225
1226 private:
1227 const CallDAG *mCallDag;
1228 const std::vector<FunctionMetadata> *mMetadatas;
1229};
1230
Olli Etuahod10cf692017-11-02 11:06:14 +02001231void TCompiler::pruneUnusedFunctions(TIntermBlock *root)
Corentin Walleza094a8a2015-04-07 11:53:06 -07001232{
Olli Etuaho6f591c92018-09-21 11:20:47 +03001233 UnusedPredicate isUnused(&mCallDag, &mFunctionMetadata);
Olli Etuaho6d40bbd2016-09-30 13:49:38 +01001234 TIntermSequence *sequence = root->getSequence();
Corentin Wallezb081e782015-07-20 05:40:04 -07001235
1236 if (!sequence->empty())
1237 {
Jamie Madilld7b1ab52016-12-12 14:42:19 -05001238 sequence->erase(std::remove_if(sequence->begin(), sequence->end(), isUnused),
1239 sequence->end());
Corentin Wallezb081e782015-07-20 05:40:04 -07001240 }
Corentin Walleza094a8a2015-04-07 11:53:06 -07001241}
1242
Olli Etuahob4279202017-05-18 15:08:24 +03001243bool TCompiler::limitExpressionComplexity(TIntermBlock *root)
Jamie Madilleb1a0102013-07-08 13:31:38 -04001244{
Olli Etuaho6f591c92018-09-21 11:20:47 +03001245 if (!IsASTDepthBelowLimit(root, mResources.MaxExpressionComplexity))
Jamie Madill6654bc92014-03-26 14:01:57 -04001246 {
Olli Etuaho77ba4082016-12-16 12:01:18 +00001247 mDiagnostics.globalError("Expression too complex.");
Jamie Madill6654bc92014-03-26 14:01:57 -04001248 return false;
1249 }
1250
Olli Etuaho6f591c92018-09-21 11:20:47 +03001251 if (!ValidateMaxParameters(root, mResources.MaxFunctionParameters))
Olli Etuaho19d1dc92016-03-08 17:18:46 +02001252 {
Olli Etuaho77ba4082016-12-16 12:01:18 +00001253 mDiagnostics.globalError("Function has too many parameters.");
Olli Etuaho19d1dc92016-03-08 17:18:46 +02001254 return false;
1255 }
1256
Jamie Madilleb1a0102013-07-08 13:31:38 -04001257 return true;
1258}
1259
Corentin Wallez1df16022016-10-27 08:16:56 -04001260bool TCompiler::shouldCollectVariables(ShCompileOptions compileOptions)
1261{
1262 return (compileOptions & SH_VARIABLES) != 0;
1263}
1264
1265bool TCompiler::wereVariablesCollected() const
1266{
Olli Etuaho6f591c92018-09-21 11:20:47 +03001267 return mVariablesCollected;
Corentin Wallez1df16022016-10-27 08:16:56 -04001268}
1269
Olli Etuaho9cbc07c2017-05-10 18:22:01 +03001270void TCompiler::initializeGLPosition(TIntermBlock *root)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -08001271{
Zhenyao Mo72111912016-07-20 17:45:56 -07001272 InitVariableList list;
Olli Etuahoe7c28572017-10-23 16:29:33 +03001273 sh::ShaderVariable var(GL_FLOAT_VEC4);
Zhenyao Mo72111912016-07-20 17:45:56 -07001274 var.name = "gl_Position";
1275 list.push_back(var);
Olli Etuaho6f591c92018-09-21 11:20:47 +03001276 InitializeVariables(root, list, &mSymbolTable, mShaderVersion, mExtensionBehavior, false,
1277 false);
Zhenyao Mo4a667fe2014-02-11 12:35:01 -08001278}
1279
Olli Etuaho9cbc07c2017-05-10 18:22:01 +03001280void TCompiler::useAllMembersInUnusedStandardAndSharedBlocks(TIntermBlock *root)
Qin Jiajia7835b522016-10-08 11:20:17 +08001281{
1282 sh::InterfaceBlockList list;
1283
Jonah Ryan-Davisd4c09dd2019-01-29 11:22:54 -05001284 for (const sh::InterfaceBlock &block : mUniformBlocks)
Qin Jiajia7835b522016-10-08 11:20:17 +08001285 {
1286 if (!block.staticUse &&
Qin Jiajiaca68d982017-09-18 16:41:56 +08001287 (block.layout == sh::BLOCKLAYOUT_STD140 || block.layout == sh::BLOCKLAYOUT_SHARED))
Qin Jiajia7835b522016-10-08 11:20:17 +08001288 {
1289 list.push_back(block);
1290 }
1291 }
1292
Olli Etuaho6f591c92018-09-21 11:20:47 +03001293 sh::UseInterfaceBlockFields(root, list, mSymbolTable);
Qin Jiajia7835b522016-10-08 11:20:17 +08001294}
1295
Olli Etuaho9cbc07c2017-05-10 18:22:01 +03001296void TCompiler::initializeOutputVariables(TIntermBlock *root)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -08001297{
Zhenyao Mo72111912016-07-20 17:45:56 -07001298 InitVariableList list;
Olli Etuaho6f591c92018-09-21 11:20:47 +03001299 if (mShaderType == GL_VERTEX_SHADER || mShaderType == GL_GEOMETRY_SHADER_EXT)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -08001300 {
Jonah Ryan-Davisd4c09dd2019-01-29 11:22:54 -05001301 for (const sh::Varying &var : mOutputVaryings)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -08001302 {
Zhenyao Mof9312682016-07-22 12:51:31 -07001303 list.push_back(var);
Olli Etuahob12040c2017-06-27 14:20:45 +03001304 if (var.name == "gl_Position")
1305 {
1306 ASSERT(!mGLPositionInitialized);
1307 mGLPositionInitialized = true;
1308 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -08001309 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -08001310 }
Zhenyao Mo72111912016-07-20 17:45:56 -07001311 else
1312 {
Olli Etuaho6f591c92018-09-21 11:20:47 +03001313 ASSERT(mShaderType == GL_FRAGMENT_SHADER);
Jonah Ryan-Davisd4c09dd2019-01-29 11:22:54 -05001314 for (const sh::OutputVariable &var : mOutputVariables)
Zhenyao Mo72111912016-07-20 17:45:56 -07001315 {
1316 list.push_back(var);
1317 }
1318 }
Olli Etuaho6f591c92018-09-21 11:20:47 +03001319 InitializeVariables(root, list, &mSymbolTable, mShaderVersion, mExtensionBehavior, false,
1320 false);
Zhenyao Mo4a667fe2014-02-11 12:35:01 -08001321}
1322
Jamie Madilld7b1ab52016-12-12 14:42:19 -05001323const TExtensionBehavior &TCompiler::getExtensionBehavior() const
zmo@google.com5601ea02011-06-10 18:23:25 +00001324{
Olli Etuaho6f591c92018-09-21 11:20:47 +03001325 return mExtensionBehavior;
zmo@google.com5601ea02011-06-10 18:23:25 +00001326}
zmo@google.com32e97312011-08-24 01:03:11 +00001327
Olli Etuahoa3a5cc62015-02-13 13:12:22 +02001328const char *TCompiler::getSourcePath() const
1329{
1330 return mSourcePath;
1331}
1332
Jamie Madilld7b1ab52016-12-12 14:42:19 -05001333const ShBuiltInResources &TCompiler::getResources() const
shannon.woods%transgaming.com@gtempaccount.com18b4c4b2013-04-13 03:31:40 +00001334{
Olli Etuaho6f591c92018-09-21 11:20:47 +03001335 return mResources;
shannon.woods%transgaming.com@gtempaccount.com18b4c4b2013-04-13 03:31:40 +00001336}
1337
Jamie Madilld7b1ab52016-12-12 14:42:19 -05001338const ArrayBoundsClamper &TCompiler::getArrayBoundsClamper() const
daniel@transgaming.com4167cc92013-01-11 04:11:53 +00001339{
Olli Etuaho6f591c92018-09-21 11:20:47 +03001340 return mArrayBoundsClamper;
daniel@transgaming.com4167cc92013-01-11 04:11:53 +00001341}
1342
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +00001343ShArrayIndexClampingStrategy TCompiler::getArrayIndexClampingStrategy() const
1344{
Olli Etuaho6f591c92018-09-21 11:20:47 +03001345 return mResources.ArrayIndexClampingStrategy;
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +00001346}
1347
Jamie Madilld7b1ab52016-12-12 14:42:19 -05001348const BuiltInFunctionEmulator &TCompiler::getBuiltInFunctionEmulator() const
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +00001349{
Olli Etuaho6f591c92018-09-21 11:20:47 +03001350 return mBuiltInFunctionEmulator;
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +00001351}
Zhenyao Mo94ac7b72014-10-15 18:22:08 -07001352
Qiankun Miao7ebb97f2016-09-08 18:01:50 +08001353void TCompiler::writePragma(ShCompileOptions compileOptions)
Zhenyao Mo94ac7b72014-10-15 18:22:08 -07001354{
Kenneth Russellbccc65d2016-07-19 16:48:43 -07001355 if (!(compileOptions & SH_FLATTEN_PRAGMA_STDGL_INVARIANT_ALL))
1356 {
Olli Etuaho6f591c92018-09-21 11:20:47 +03001357 TInfoSinkBase &sink = mInfoSink.obj;
Kenneth Russellbccc65d2016-07-19 16:48:43 -07001358 if (mPragma.stdgl.invariantAll)
1359 sink << "#pragma STDGL invariant(all)\n";
1360 }
1361}
1362
1363bool TCompiler::isVaryingDefined(const char *varyingName)
1364{
Olli Etuaho6f591c92018-09-21 11:20:47 +03001365 ASSERT(mVariablesCollected);
1366 for (size_t ii = 0; ii < mInputVaryings.size(); ++ii)
Kenneth Russellbccc65d2016-07-19 16:48:43 -07001367 {
Olli Etuaho6f591c92018-09-21 11:20:47 +03001368 if (mInputVaryings[ii].name == varyingName)
Jiawei-Shaodf7d7c92017-07-31 09:34:04 +08001369 {
1370 return true;
1371 }
1372 }
Olli Etuaho6f591c92018-09-21 11:20:47 +03001373 for (size_t ii = 0; ii < mOutputVaryings.size(); ++ii)
Jiawei-Shaodf7d7c92017-07-31 09:34:04 +08001374 {
Olli Etuaho6f591c92018-09-21 11:20:47 +03001375 if (mOutputVaryings[ii].name == varyingName)
Kenneth Russellbccc65d2016-07-19 16:48:43 -07001376 {
1377 return true;
1378 }
1379 }
1380
1381 return false;
Zhenyao Mo94ac7b72014-10-15 18:22:08 -07001382}
Jamie Madillacb4b812016-11-07 13:50:29 -05001383
1384} // namespace sh