blob: 6e76fe1210bbadbe85b671264381dfbdfa650994 [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"
Qiankun Miao09cfac62016-09-06 17:25:16 +080013#include "compiler/translator/AddAndTrueToLoopCondition.h"
Dmitry Skiba01971112015-07-10 14:54:00 -040014#include "compiler/translator/Cache.h"
Corentin Wallez71d147f2015-02-11 11:15:24 -080015#include "compiler/translator/CallDAG.h"
Martin Radev69056a12017-05-18 11:14:50 +030016#include "compiler/translator/DeclareAndInitBuiltinsForInstancedMultiview.h"
Olli Etuaho3d932d82016-04-12 11:10:30 +030017#include "compiler/translator/DeferGlobalInitializers.h"
Zhenyao Mo4e94fea2016-08-09 14:31:37 -070018#include "compiler/translator/EmulateGLFragColorBroadcast.h"
Jamie Madilld5696192016-10-06 11:09:24 -040019#include "compiler/translator/EmulatePrecision.h"
Geoff Lang17732822013-08-29 13:46:49 -040020#include "compiler/translator/Initialize.h"
Zhenyao Mo4a667fe2014-02-11 12:35:01 -080021#include "compiler/translator/InitializeVariables.h"
Olli Etuaho9733cee2017-05-11 19:14:35 +030022#include "compiler/translator/IntermNodePatternMatcher.h"
Olli Etuahocccf2b02017-07-05 14:50:54 +030023#include "compiler/translator/IsASTDepthBelowLimit.h"
24#include "compiler/translator/OutputTree.h"
Jamie Madill6b9cb252013-10-17 10:45:47 -040025#include "compiler/translator/ParseContext.h"
Olli Etuahoc6833112015-04-22 15:15:54 +030026#include "compiler/translator/PruneEmptyDeclarations.h"
Zhenyao Moe740add2014-07-18 17:01:01 -070027#include "compiler/translator/RegenerateStructNames.h"
Qiankun Miao705a9192016-08-29 10:05:27 +080028#include "compiler/translator/RemoveInvariantDeclaration.h"
Olli Etuaho5c407bb2015-06-01 12:20:39 +030029#include "compiler/translator/RemovePow.h"
Corentin Wallezd4b50542015-09-28 12:19:26 -070030#include "compiler/translator/RewriteDoWhile.h"
Zhenyao Mocd68fe72014-07-11 10:45:44 -070031#include "compiler/translator/ScalarizeVecAndMatConstructorArgs.h"
Olli Etuaho9733cee2017-05-11 19:14:35 +030032#include "compiler/translator/SeparateDeclarations.h"
33#include "compiler/translator/SimplifyLoopConditions.h"
Zhenyao Mo7cab38b2013-10-15 12:59:30 -070034#include "compiler/translator/UnfoldShortCircuitAST.h"
Qin Jiajia7835b522016-10-08 11:20:17 +080035#include "compiler/translator/UseInterfaceBlockFields.h"
Geoff Lang17732822013-08-29 13:46:49 -040036#include "compiler/translator/ValidateLimitations.h"
Olli Etuaho19d1dc92016-03-08 17:18:46 +020037#include "compiler/translator/ValidateMaxParameters.h"
Olli Etuaho09b04a22016-12-15 13:30:26 +000038#include "compiler/translator/ValidateMultiviewWebGL.h"
Geoff Lang17732822013-08-29 13:46:49 -040039#include "compiler/translator/ValidateOutputs.h"
40#include "compiler/translator/VariablePacker.h"
shannon.woods@transgaming.comda1ed362013-01-25 21:54:57 +000041#include "third_party/compiler/ArrayBoundsClamper.h"
Corentin Wallez28b65282016-06-16 07:24:50 -070042
Jamie Madillacb4b812016-11-07 13:50:29 -050043namespace sh
44{
45
Corentin Wallez28b65282016-06-16 07:24:50 -070046namespace
47{
48
49#if defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
50void DumpFuzzerCase(char const *const *shaderStrings,
51 size_t numStrings,
52 uint32_t type,
53 uint32_t spec,
54 uint32_t output,
55 uint64_t options)
56{
57 static int fileIndex = 0;
58
59 std::ostringstream o;
60 o << "corpus/" << fileIndex++ << ".sample";
61 std::string s = o.str();
62
63 // Must match the input format of the fuzzer
64 FILE *f = fopen(s.c_str(), "w");
65 fwrite(&type, sizeof(type), 1, f);
66 fwrite(&spec, sizeof(spec), 1, f);
67 fwrite(&output, sizeof(output), 1, f);
68 fwrite(&options, sizeof(options), 1, f);
69
70 char zero[128 - 20] = {0};
71 fwrite(&zero, 128 - 20, 1, f);
72
73 for (size_t i = 0; i < numStrings; i++)
74 {
75 fwrite(shaderStrings[i], sizeof(char), strlen(shaderStrings[i]), f);
76 }
77 fwrite(&zero, 1, 1, f);
78
79 fclose(f);
80}
81#endif // defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
82} // anonymous namespace
83
Jamie Madill5508f392014-02-20 13:31:36 -050084bool IsWebGLBasedSpec(ShShaderSpec spec)
maxvujovic@gmail.com430f5e02012-06-08 17:47:59 +000085{
Qiankun Miaoc2c5fc42016-08-31 15:24:22 +080086 return (spec == SH_WEBGL_SPEC || spec == SH_WEBGL2_SPEC || spec == SH_WEBGL3_SPEC);
maxvujovic@gmail.com430f5e02012-06-08 17:47:59 +000087}
88
Qingqing Dengad0d0792015-04-08 14:25:06 -070089bool IsGLSL130OrNewer(ShShaderOutput output)
90{
Jamie Madillacb4b812016-11-07 13:50:29 -050091 return (output == SH_GLSL_130_OUTPUT || output == SH_GLSL_140_OUTPUT ||
92 output == SH_GLSL_150_CORE_OUTPUT || output == SH_GLSL_330_CORE_OUTPUT ||
93 output == SH_GLSL_400_CORE_OUTPUT || output == SH_GLSL_410_CORE_OUTPUT ||
94 output == SH_GLSL_420_CORE_OUTPUT || output == SH_GLSL_430_CORE_OUTPUT ||
95 output == SH_GLSL_440_CORE_OUTPUT || output == SH_GLSL_450_CORE_OUTPUT);
Qingqing Dengad0d0792015-04-08 14:25:06 -070096}
97
Qiankun Miao705a9192016-08-29 10:05:27 +080098bool IsGLSL420OrNewer(ShShaderOutput output)
99{
Jamie Madillacb4b812016-11-07 13:50:29 -0500100 return (output == SH_GLSL_420_CORE_OUTPUT || output == SH_GLSL_430_CORE_OUTPUT ||
101 output == SH_GLSL_440_CORE_OUTPUT || output == SH_GLSL_450_CORE_OUTPUT);
Qiankun Miao705a9192016-08-29 10:05:27 +0800102}
103
Zhenyao Mob7bf7422016-11-08 14:44:05 -0800104bool IsGLSL410OrOlder(ShShaderOutput output)
105{
106 return (output == SH_GLSL_130_OUTPUT || output == SH_GLSL_140_OUTPUT ||
107 output == SH_GLSL_150_CORE_OUTPUT || output == SH_GLSL_330_CORE_OUTPUT ||
108 output == SH_GLSL_400_CORE_OUTPUT || output == SH_GLSL_410_CORE_OUTPUT);
109}
110
Qiankun Miao89dd8f32016-11-09 12:59:30 +0000111bool RemoveInvariant(sh::GLenum shaderType,
112 int shaderVersion,
113 ShShaderOutput outputType,
114 ShCompileOptions compileOptions)
115{
116 if ((compileOptions & SH_DONT_REMOVE_INVARIANT_FOR_FRAGMENT_INPUT) == 0 &&
117 shaderType == GL_FRAGMENT_SHADER && IsGLSL420OrNewer(outputType))
118 return true;
119
120 if ((compileOptions & SH_REMOVE_INVARIANT_AND_CENTROID_FOR_ESSL3) != 0 &&
Qiankun Miao41f9f672016-11-16 17:04:36 +0800121 shaderVersion >= 300 && shaderType == GL_VERTEX_SHADER)
Qiankun Miao89dd8f32016-11-09 12:59:30 +0000122 return true;
123
124 return false;
125}
126
Zhenyao Mo7faf1a12014-04-25 18:03:56 -0700127size_t GetGlobalMaxTokenSize(ShShaderSpec spec)
Jamie Madill88f6e942014-02-19 10:27:53 -0500128{
He Yunchao29ab9ff2015-08-06 16:58:30 +0800129 // WebGL defines a max token length of 256, while ES2 leaves max token
Jamie Madill88f6e942014-02-19 10:27:53 -0500130 // size undefined. ES3 defines a max size of 1024 characters.
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700131 switch (spec)
Jamie Madill88f6e942014-02-19 10:27:53 -0500132 {
Jamie Madillacb4b812016-11-07 13:50:29 -0500133 case SH_WEBGL_SPEC:
134 return 256;
135 default:
136 return 1024;
Jamie Madill88f6e942014-02-19 10:27:53 -0500137 }
138}
139
Shao77891c02017-06-23 16:30:17 +0800140int GetMaxUniformVectorsForShaderType(GLenum shaderType, const ShBuiltInResources &resources)
141{
142 switch (shaderType)
143 {
144 case GL_VERTEX_SHADER:
145 return resources.MaxVertexUniformVectors;
146 case GL_FRAGMENT_SHADER:
147 return resources.MaxFragmentUniformVectors;
148 case GL_COMPUTE_SHADER:
149 // TODO (jiawei.shao@intel.com): check if we need finer-grained component counting
150 return resources.MaxComputeUniformComponents / 4;
151 default:
152 UNIMPLEMENTED();
153 return -1;
154 }
155}
156
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500157namespace
158{
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700159
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800160class TScopedPoolAllocator
161{
162 public:
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500163 TScopedPoolAllocator(TPoolAllocator *allocator) : mAllocator(allocator)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800164 {
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400165 mAllocator->push();
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000166 SetGlobalPoolAllocator(mAllocator);
167 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800168 ~TScopedPoolAllocator()
169 {
Yunchao Hef81ce4a2017-04-24 10:49:17 +0800170 SetGlobalPoolAllocator(nullptr);
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400171 mAllocator->pop();
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000172 }
173
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800174 private:
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500175 TPoolAllocator *mAllocator;
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400176};
177
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800178class TScopedSymbolTableLevel
179{
180 public:
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500181 TScopedSymbolTableLevel(TSymbolTable *table) : mTable(table)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800182 {
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400183 ASSERT(mTable->atBuiltInLevel());
184 mTable->push();
185 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800186 ~TScopedSymbolTableLevel()
187 {
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400188 while (!mTable->atBuiltInLevel())
189 mTable->pop();
190 }
191
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800192 private:
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500193 TSymbolTable *mTable;
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000194};
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700195
196int MapSpecToShaderVersion(ShShaderSpec spec)
197{
198 switch (spec)
199 {
Jamie Madillacb4b812016-11-07 13:50:29 -0500200 case SH_GLES2_SPEC:
201 case SH_WEBGL_SPEC:
202 return 100;
203 case SH_GLES3_SPEC:
204 case SH_WEBGL2_SPEC:
205 return 300;
206 case SH_GLES3_1_SPEC:
207 case SH_WEBGL3_SPEC:
208 return 310;
209 default:
210 UNREACHABLE();
211 return 0;
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700212 }
213}
214
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000215} // namespace
216
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800217TShHandleBase::TShHandleBase()
218{
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000219 allocator.push();
220 SetGlobalPoolAllocator(&allocator);
221}
222
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800223TShHandleBase::~TShHandleBase()
224{
Yunchao Hef81ce4a2017-04-24 10:49:17 +0800225 SetGlobalPoolAllocator(nullptr);
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000226 allocator.popAll();
227}
228
Jamie Madill183bde52014-07-02 15:31:19 -0400229TCompiler::TCompiler(sh::GLenum type, ShShaderSpec spec, ShShaderOutput output)
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700230 : variablesCollected(false),
Olli Etuahob12040c2017-06-27 14:20:45 +0300231 mGLPositionInitialized(false),
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700232 shaderType(type),
zmo@google.comf420c422011-09-12 18:27:59 +0000233 shaderSpec(spec),
Jamie Madill68fe74a2014-05-27 12:56:01 -0400234 outputType(output),
Jamie Madilleb1a0102013-07-08 13:31:38 -0400235 maxUniformVectors(0),
236 maxExpressionComplexity(0),
237 maxCallStackDepth(0),
Olli Etuaho19d1dc92016-03-08 17:18:46 +0200238 maxFunctionParameters(0),
shannon.woods%transgaming.com@gtempaccount.comcbb6b6a2013-04-13 03:27:47 +0000239 fragmentPrecisionHigh(false),
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000240 clampingStrategy(SH_CLAMP_WITH_CLAMP_INTRINSIC),
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200241 builtInFunctionEmulator(),
Olli Etuaho77ba4082016-12-16 12:01:18 +0000242 mDiagnostics(infoSink.info),
Yunchao Hef81ce4a2017-04-24 10:49:17 +0800243 mSourcePath(nullptr),
Martin Radev802abe02016-08-04 17:48:32 +0300244 mComputeShaderLocalSizeDeclared(false),
Olli Etuaho4dd06d52017-07-05 12:41:06 +0300245 mTemporaryId()
alokp@chromium.org4888ceb2010-10-01 21:13:12 +0000246{
Martin Radev802abe02016-08-04 17:48:32 +0300247 mComputeShaderLocalSize.fill(1);
alokp@chromium.org4888ceb2010-10-01 21:13:12 +0000248}
249
250TCompiler::~TCompiler()
251{
252}
253
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800254bool TCompiler::shouldRunLoopAndIndexingValidation(ShCompileOptions compileOptions) const
Olli Etuaho5d91dda2015-06-18 15:47:46 +0300255{
256 // If compiling an ESSL 1.00 shader for WebGL, or if its been requested through the API,
257 // validate loop and indexing as well (to verify that the shader only uses minimal functionality
258 // of ESSL 1.00 as in Appendix A of the spec).
259 return (IsWebGLBasedSpec(shaderSpec) && shaderVersion == 100) ||
260 (compileOptions & SH_VALIDATE_LOOP_INDEXING);
261}
262
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500263bool TCompiler::Init(const ShBuiltInResources &resources)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000264{
Shao77891c02017-06-23 16:30:17 +0800265 shaderVersion = 100;
266
267 maxUniformVectors = GetMaxUniformVectorsForShaderType(shaderType, resources);
268
Jamie Madilleb1a0102013-07-08 13:31:38 -0400269 maxExpressionComplexity = resources.MaxExpressionComplexity;
Olli Etuaho19d1dc92016-03-08 17:18:46 +0200270 maxCallStackDepth = resources.MaxCallStackDepth;
271 maxFunctionParameters = resources.MaxFunctionParameters;
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400272
273 SetGlobalPoolAllocator(&allocator);
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000274
alokp@chromium.org07620a52010-09-23 17:53:56 +0000275 // Generate built-in symbol table.
276 if (!InitBuiltInSymbolTable(resources))
277 return false;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000278 InitExtensionBehavior(resources, extensionBehavior);
shannon.woods%transgaming.com@gtempaccount.comcbb6b6a2013-04-13 03:27:47 +0000279 fragmentPrecisionHigh = resources.FragmentPrecisionHigh == 1;
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000280
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000281 arrayBoundsClamper.SetClampingStrategy(resources.ArrayIndexClampingStrategy);
282 clampingStrategy = resources.ArrayIndexClampingStrategy;
283
daniel@transgaming.comc23f4612012-11-28 19:42:57 +0000284 hashFunction = resources.HashFunction;
285
alokp@chromium.org07620a52010-09-23 17:53:56 +0000286 return true;
287}
288
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100289TIntermBlock *TCompiler::compileTreeForTesting(const char *const shaderStrings[],
290 size_t numStrings,
291 ShCompileOptions compileOptions)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000292{
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200293 return compileTreeImpl(shaderStrings, numStrings, compileOptions);
294}
295
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100296TIntermBlock *TCompiler::compileTreeImpl(const char *const shaderStrings[],
297 size_t numStrings,
298 const ShCompileOptions compileOptions)
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200299{
alokp@chromium.org07620a52010-09-23 17:53:56 +0000300 clearResults();
301
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200302 ASSERT(numStrings > 0);
303 ASSERT(GetGlobalPoolAllocator());
alokp@chromium.org07620a52010-09-23 17:53:56 +0000304
David Yen0fbd1282015-02-02 14:46:09 -0800305 // Reset the extension behavior for each compilation unit.
306 ResetExtensionBehavior(extensionBehavior);
307
apatrick@chromium.org0f4cefe2011-01-26 19:30:57 +0000308 // First string is path of source file if flag is set. The actual source follows.
shannon.woods@transgaming.comd64b3da2013-02-28 23:19:26 +0000309 size_t firstSource = 0;
apatrick@chromium.org0f4cefe2011-01-26 19:30:57 +0000310 if (compileOptions & SH_SOURCE_PATH)
311 {
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200312 mSourcePath = shaderStrings[0];
apatrick@chromium.org0f4cefe2011-01-26 19:30:57 +0000313 ++firstSource;
314 }
315
Olli Etuahof119a262016-08-19 15:54:22 +0300316 TParseContext parseContext(symbolTable, extensionBehavior, shaderType, shaderSpec,
Olli Etuaho77ba4082016-12-16 12:01:18 +0000317 compileOptions, true, &mDiagnostics, getResources());
Olli Etuaho853dc1a2014-11-06 17:25:48 +0200318
Olli Etuahoa6996682015-10-12 14:32:30 +0300319 parseContext.setFragmentPrecisionHighOnESSL1(fragmentPrecisionHigh);
alokp@chromium.org07620a52010-09-23 17:53:56 +0000320
321 // We preserve symbols at the built-in level from compile-to-compile.
322 // Start pushing the user-defined symbols at global level.
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400323 TScopedSymbolTableLevel scopedSymbolLevel(&symbolTable);
alokp@chromium.org07620a52010-09-23 17:53:56 +0000324
325 // Parse shader.
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500326 bool success = (PaParseStrings(numStrings - firstSource, &shaderStrings[firstSource], nullptr,
327 &parseContext) == 0) &&
328 (parseContext.getTreeRoot() != nullptr);
shannon.woods%transgaming.com@gtempaccount.com0bbed382013-04-13 03:38:07 +0000329
shannon.woods%transgaming.com@gtempaccount.com5524db02013-04-13 03:38:16 +0000330 shaderVersion = parseContext.getShaderVersion();
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700331 if (success && MapSpecToShaderVersion(shaderSpec) < shaderVersion)
332 {
Olli Etuaho77ba4082016-12-16 12:01:18 +0000333 mDiagnostics.globalError("unsupported shader version");
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700334 success = false;
335 }
shannon.woods%transgaming.com@gtempaccount.com0bbed382013-04-13 03:38:07 +0000336
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100337 TIntermBlock *root = nullptr;
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200338
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800339 if (success)
340 {
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700341 mPragma = parseContext.pragma();
Kenneth Russell8bad46d2016-07-01 19:52:52 -0700342 symbolTable.setGlobalInvariant(mPragma.stdgl.invariantAll);
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700343
Martin Radev802abe02016-08-04 17:48:32 +0300344 mComputeShaderLocalSizeDeclared = parseContext.isComputeShaderLocalSizeDeclared();
345 mComputeShaderLocalSize = parseContext.getComputeShaderLocalSize();
346
Olli Etuaho09b04a22016-12-15 13:30:26 +0000347 mNumViews = parseContext.getNumViews();
348
Jamie Madill6e06b1f2015-05-14 10:01:17 -0400349 root = parseContext.getTreeRoot();
alokp@chromium.orgb59a7782010-11-24 18:38:33 +0000350
Olli Etuahoa6996682015-10-12 14:32:30 +0300351 // Highp might have been auto-enabled based on shader version
352 fragmentPrecisionHigh = parseContext.getFragmentPrecisionHigh();
353
Olli Etuaho09b04a22016-12-15 13:30:26 +0000354 if (success && (IsWebGLBasedSpec(shaderSpec) &&
355 IsExtensionEnabled(extensionBehavior, "GL_OVR_multiview") &&
356 IsExtensionEnabled(extensionBehavior, "GL_OVR_multiview2")))
357 {
358 // Can't enable both extensions at the same time.
359 mDiagnostics.globalError("Can't enable both OVR_multiview and OVR_multiview2");
360 success = false;
361 }
362
Jamie Madill6654bc92014-03-26 14:01:57 -0400363 // Disallow expressions deemed too complex.
364 if (success && (compileOptions & SH_LIMIT_EXPRESSION_COMPLEXITY))
365 success = limitExpressionComplexity(root);
366
Corentin Wallez71d147f2015-02-11 11:15:24 -0800367 // Create the function DAG and check there is no recursion
zmo@google.comb1762df2011-07-30 02:04:23 +0000368 if (success)
Corentin Wallez71d147f2015-02-11 11:15:24 -0800369 success = initCallDag(root);
370
371 if (success && (compileOptions & SH_LIMIT_CALL_STACK_DEPTH))
372 success = checkCallDepth();
373
374 // Checks which functions are used and if "main" exists
375 if (success)
376 {
377 functionMetadata.clear();
378 functionMetadata.resize(mCallDag.size());
379 success = tagUsedFunctions();
380 }
zmo@google.comb1762df2011-07-30 02:04:23 +0000381
Corentin Walleza094a8a2015-04-07 11:53:06 -0700382 if (success && !(compileOptions & SH_DONT_PRUNE_UNUSED_FUNCTIONS))
383 success = pruneUnusedFunctions(root);
384
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500385 // Prune empty declarations to work around driver bugs and to keep declaration output
386 // simple.
Olli Etuahoc6833112015-04-22 15:15:54 +0300387 if (success)
388 PruneEmptyDeclarations(root);
389
Andrei Volykhin73fa4b82017-05-05 18:45:06 +0300390 if (success && shaderVersion >= 300 && shaderType == GL_FRAGMENT_SHADER)
Olli Etuaho12b0b392017-05-30 13:22:31 +0300391 {
392 success = ValidateOutputs(root, getExtensionBehavior(), compileResources.MaxDrawBuffers,
393 &mDiagnostics);
394 }
Jamie Madill05a80ce2013-06-20 11:55:49 -0400395
Olli Etuaho5d91dda2015-06-18 15:47:46 +0300396 if (success && shouldRunLoopAndIndexingValidation(compileOptions))
Olli Etuaho9ec79392017-03-31 23:04:23 +0300397 success =
398 ValidateLimitations(root, shaderType, symbolTable, shaderVersion, &mDiagnostics);
alokp@chromium.org07620a52010-09-23 17:53:56 +0000399
Olli Etuaho09b04a22016-12-15 13:30:26 +0000400 bool multiview2 = IsExtensionEnabled(extensionBehavior, "GL_OVR_multiview2");
401 if (success && compileResources.OVR_multiview && IsWebGLBasedSpec(shaderSpec) &&
402 (IsExtensionEnabled(extensionBehavior, "GL_OVR_multiview") || multiview2))
Olli Etuaho01d0ad02017-01-22 14:51:23 -0800403 success = ValidateMultiviewWebGL(root, shaderType, symbolTable, shaderVersion,
404 multiview2, &mDiagnostics);
Olli Etuaho09b04a22016-12-15 13:30:26 +0000405
Jamie Madilld5696192016-10-06 11:09:24 -0400406 // Fail compilation if precision emulation not supported.
407 if (success && getResources().WEBGL_debug_shader_precision &&
408 getPragma().debugShaderPrecision)
409 {
410 if (!EmulatePrecision::SupportedInLanguage(outputType))
411 {
Olli Etuaho77ba4082016-12-16 12:01:18 +0000412 mDiagnostics.globalError("Precision emulation not supported for this output type.");
Jamie Madilld5696192016-10-06 11:09:24 -0400413 success = false;
414 }
415 }
416
zmo@google.com32e97312011-08-24 01:03:11 +0000417 // Built-in function emulation needs to happen after validateLimitations pass.
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200418 if (success)
419 {
Jamie Madill438dbcf2016-06-17 14:20:05 -0400420 // TODO(jmadill): Remove global pool allocator.
421 GetGlobalPoolAllocator()->lock();
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200422 initBuiltInFunctionEmulator(&builtInFunctionEmulator, compileOptions);
Jamie Madill438dbcf2016-06-17 14:20:05 -0400423 GetGlobalPoolAllocator()->unlock();
Olli Etuahodfa75e82017-01-23 09:43:06 -0800424 builtInFunctionEmulator.markBuiltInFunctionsForEmulation(root);
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200425 }
zmo@google.com32e97312011-08-24 01:03:11 +0000426
daniel@transgaming.com4167cc92013-01-11 04:11:53 +0000427 // Clamping uniform array bounds needs to happen after validateLimitations pass.
428 if (success && (compileOptions & SH_CLAMP_INDIRECT_ARRAY_BOUNDS))
429 arrayBoundsClamper.MarkIndirectArrayBoundsForClamping(root);
430
Martin Radev69056a12017-05-18 11:14:50 +0300431 if (success && (compileOptions & SH_INITIALIZE_BUILTINS_FOR_INSTANCED_MULTIVIEW) &&
Martin Radev7ef89a42017-07-05 14:23:06 +0300432 parseContext.isMultiviewExtensionEnabled() && getShaderType() != GL_COMPUTE_SHADER)
Martin Radev69056a12017-05-18 11:14:50 +0300433 {
Martin Radev7ef89a42017-07-05 14:23:06 +0300434 DeclareAndInitBuiltinsForInstancedMultiview(root, getNumViews(), getShaderType());
Martin Radev69056a12017-05-18 11:14:50 +0300435 }
436
Corentin Wallezd4b50542015-09-28 12:19:26 -0700437 // This pass might emit short circuits so keep it before the short circuit unfolding
438 if (success && (compileOptions & SH_REWRITE_DO_WHILE_LOOPS))
Olli Etuaho4dd06d52017-07-05 12:41:06 +0300439 RewriteDoWhile(root, getTemporaryId());
Corentin Wallezd4b50542015-09-28 12:19:26 -0700440
Qiankun Miao09cfac62016-09-06 17:25:16 +0800441 if (success && (compileOptions & SH_ADD_AND_TRUE_TO_LOOP_CONDITION))
442 sh::AddAndTrueToLoopCondition(root);
443
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800444 if (success && (compileOptions & SH_UNFOLD_SHORT_CIRCUIT))
445 {
Zhenyao Mo7cab38b2013-10-15 12:59:30 -0700446 UnfoldShortCircuitAST unfoldShortCircuit;
447 root->traverse(&unfoldShortCircuit);
448 unfoldShortCircuit.updateTree();
449 }
450
Olli Etuaho5c407bb2015-06-01 12:20:39 +0300451 if (success && (compileOptions & SH_REMOVE_POW_WITH_CONSTANT_EXPONENT))
452 {
453 RemovePow(root);
454 }
455
Olli Etuaho4dfe8092015-08-21 17:44:35 +0300456 if (success && shouldCollectVariables(compileOptions))
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800457 {
Olli Etuaho19515012017-06-26 18:00:17 +0300458 ASSERT(!variablesCollected);
459 CollectVariables(root, &attributes, &outputVariables, &uniforms, &varyings,
460 &interfaceBlocks, hashFunction, symbolTable, shaderVersion,
461 extensionBehavior);
462 variablesCollected = true;
Qin Jiajia7835b522016-10-08 11:20:17 +0800463 if (compileOptions & SH_USE_UNUSED_STANDARD_SHARED_BLOCKS)
464 {
465 useAllMembersInUnusedStandardAndSharedBlocks(root);
466 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800467 if (compileOptions & SH_ENFORCE_PACKING_RESTRICTIONS)
468 {
Olli Etuaho19515012017-06-26 18:00:17 +0300469 std::vector<sh::ShaderVariable> expandedUniforms;
470 sh::ExpandUniforms(uniforms, &expandedUniforms);
471 VariablePacker packer;
472 // Returns true if, after applying the packing rules in the GLSL ES 1.00.17 spec
473 // Appendix A, section 7, the shader does not use too many uniforms.
474 success =
475 packer.CheckVariablesWithinPackingLimits(maxUniformVectors, expandedUniforms);
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800476 if (!success)
477 {
Olli Etuaho77ba4082016-12-16 12:01:18 +0000478 mDiagnostics.globalError("too many uniforms");
gman@chromium.org8d804792012-10-17 21:33:48 +0000479 }
480 }
Zhenyao Mo72111912016-07-20 17:45:56 -0700481 if (success && (compileOptions & SH_INIT_OUTPUT_VARIABLES))
482 {
Olli Etuaho27776e32016-07-22 14:00:56 +0300483 initializeOutputVariables(root);
Zhenyao Mo72111912016-07-20 17:45:56 -0700484 }
gman@chromium.org8d804792012-10-17 21:33:48 +0000485 }
zmo@google.comfd747b82011-04-23 01:30:07 +0000486
Olli Etuahob12040c2017-06-27 14:20:45 +0300487 // gl_Position is always written in compatibility output mode.
488 // It may have been already initialized among other output variables, in that case we don't
489 // need to initialize it twice.
490 if (success && shaderType == GL_VERTEX_SHADER && !mGLPositionInitialized &&
491 ((compileOptions & SH_INIT_GL_POSITION) ||
492 (outputType == SH_GLSL_COMPATIBILITY_OUTPUT)))
493 {
494 initializeGLPosition(root);
495 mGLPositionInitialized = true;
496 }
497
Yuly Novikov817232e2017-02-22 18:36:10 -0500498 // Removing invariant declarations must be done after collecting variables.
499 // Otherwise, built-in invariant declarations don't apply.
500 if (success && RemoveInvariant(shaderType, shaderVersion, outputType, compileOptions))
501 sh::RemoveInvariantDeclaration(root);
502
Zhenyao Mocd68fe72014-07-11 10:45:44 -0700503 if (success && (compileOptions & SH_SCALARIZE_VEC_AND_MAT_CONSTRUCTOR_ARGS))
504 {
Olli Etuahob990b552016-10-27 12:29:17 +0100505 ScalarizeVecAndMatConstructorArgs(root, shaderType, fragmentPrecisionHigh,
Olli Etuaho4dd06d52017-07-05 12:41:06 +0300506 getTemporaryId());
Zhenyao Mocd68fe72014-07-11 10:45:44 -0700507 }
508
Zhenyao Moe740add2014-07-18 17:01:01 -0700509 if (success && (compileOptions & SH_REGENERATE_STRUCT_NAMES))
510 {
511 RegenerateStructNames gen(symbolTable, shaderVersion);
512 root->traverse(&gen);
513 }
Olli Etuaho3d932d82016-04-12 11:10:30 +0300514
Zhenyao Mo4e94fea2016-08-09 14:31:37 -0700515 if (success && shaderType == GL_FRAGMENT_SHADER && shaderVersion == 100 &&
516 compileResources.EXT_draw_buffers && compileResources.MaxDrawBuffers > 1 &&
517 IsExtensionEnabled(extensionBehavior, "GL_EXT_draw_buffers"))
518 {
519 EmulateGLFragColorBroadcast(root, compileResources.MaxDrawBuffers, &outputVariables);
520 }
521
Olli Etuaho3d932d82016-04-12 11:10:30 +0300522 if (success)
523 {
Olli Etuaho0ffc4412017-05-19 14:18:55 +0300524 DeferGlobalInitializers(root, needToInitializeGlobalsInAST());
Olli Etuaho3d932d82016-04-12 11:10:30 +0300525 }
Olli Etuaho9733cee2017-05-11 19:14:35 +0300526
527 if (success && (compileOptions & SH_INITIALIZE_UNINITIALIZED_LOCALS) && getOutputType())
528 {
529 // Initialize uninitialized local variables.
530 // In some cases initializing can generate extra statements in the parent block, such as
531 // when initializing nameless structs or initializing arrays in ESSL 1.00. In that case
532 // we need to first simplify loop conditions and separate declarations. If we don't
533 // follow the Appendix A limitations, loop init statements can declare arrays or
534 // nameless structs and have multiple declarations.
535
536 if (!shouldRunLoopAndIndexingValidation(compileOptions))
537 {
538 SimplifyLoopConditions(root,
539 IntermNodePatternMatcher::kMultiDeclaration |
540 IntermNodePatternMatcher::kArrayDeclaration |
541 IntermNodePatternMatcher::kNamelessStructDeclaration,
Olli Etuaho4dd06d52017-07-05 12:41:06 +0300542 getTemporaryId(), getSymbolTable(), getShaderVersion());
Olli Etuaho9733cee2017-05-11 19:14:35 +0300543 }
544 // We only really need to separate array declarations and nameless struct declarations,
545 // but it's simpler to just use the regular SeparateDeclarations.
546 SeparateDeclarations(root);
547 InitializeUninitializedLocals(root, getShaderVersion());
548 }
alokp@chromium.org07620a52010-09-23 17:53:56 +0000549 }
550
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200551 if (success)
552 return root;
553
Yunchao Hef81ce4a2017-04-24 10:49:17 +0800554 return nullptr;
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200555}
556
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800557bool TCompiler::compile(const char *const shaderStrings[],
558 size_t numStrings,
559 ShCompileOptions compileOptionsIn)
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200560{
Corentin Wallez28b65282016-06-16 07:24:50 -0700561#if defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
562 DumpFuzzerCase(shaderStrings, numStrings, shaderType, shaderSpec, outputType, compileOptionsIn);
563#endif // defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
564
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200565 if (numStrings == 0)
566 return true;
567
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800568 ShCompileOptions compileOptions = compileOptionsIn;
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700569
570 // Apply key workarounds.
571 if (shouldFlattenPragmaStdglInvariantAll())
572 {
573 // This should be harmless to do in all cases, but for the moment, do it only conditionally.
574 compileOptions |= SH_FLATTEN_PRAGMA_STDGL_INVARIANT_ALL;
575 }
576
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200577 TScopedPoolAllocator scopedAlloc(&allocator);
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100578 TIntermBlock *root = compileTreeImpl(shaderStrings, numStrings, compileOptions);
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200579
580 if (root)
581 {
582 if (compileOptions & SH_INTERMEDIATE_TREE)
Olli Etuahocccf2b02017-07-05 14:50:54 +0300583 OutputTree(root, infoSink.info);
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200584
585 if (compileOptions & SH_OBJECT_CODE)
586 translate(root, compileOptions);
587
588 // The IntermNode tree doesn't need to be deleted here, since the
589 // memory will be freed in a big chunk by the PoolAllocator.
590 return true;
591 }
592 return false;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000593}
594
Nicolas Capens49a88872013-06-20 09:54:03 -0400595bool TCompiler::InitBuiltInSymbolTable(const ShBuiltInResources &resources)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000596{
Olli Etuaho28cb0362016-11-22 15:42:37 +0000597 if (resources.MaxDrawBuffers < 1)
598 {
599 return false;
600 }
601 if (resources.EXT_blend_func_extended && resources.MaxDualSourceDrawBuffers < 1)
602 {
603 return false;
604 }
605
shannon.woods%transgaming.com@gtempaccount.com18b4c4b2013-04-13 03:31:40 +0000606 compileResources = resources;
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400607 setResourceString();
shannonwoods@chromium.org2ac0be92013-05-30 00:02:27 +0000608
Nicolas Capens49a88872013-06-20 09:54:03 -0400609 assert(symbolTable.isEmpty());
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500610 symbolTable.push(); // COMMON_BUILTINS
611 symbolTable.push(); // ESSL1_BUILTINS
612 symbolTable.push(); // ESSL3_BUILTINS
613 symbolTable.push(); // ESSL3_1_BUILTINS
shannonwoods@chromium.org2ac0be92013-05-30 00:02:27 +0000614
Jamie Madillacb4b812016-11-07 13:50:29 -0500615 switch (shaderType)
Nicolas Capens49a88872013-06-20 09:54:03 -0400616 {
Jamie Madillacb4b812016-11-07 13:50:29 -0500617 case GL_FRAGMENT_SHADER:
Olli Etuahocce89652017-06-19 16:04:09 +0300618 symbolTable.setDefaultPrecision(EbtInt, EbpMedium);
Jamie Madillacb4b812016-11-07 13:50:29 -0500619 break;
620 case GL_VERTEX_SHADER:
Olli Etuahocce89652017-06-19 16:04:09 +0300621 symbolTable.setDefaultPrecision(EbtInt, EbpHigh);
622 symbolTable.setDefaultPrecision(EbtFloat, EbpHigh);
Jamie Madillacb4b812016-11-07 13:50:29 -0500623 break;
624 case GL_COMPUTE_SHADER:
Olli Etuahocce89652017-06-19 16:04:09 +0300625 symbolTable.setDefaultPrecision(EbtInt, EbpHigh);
626 symbolTable.setDefaultPrecision(EbtFloat, EbpHigh);
Jamie Madillacb4b812016-11-07 13:50:29 -0500627 break;
628 default:
629 assert(false && "Language not supported");
Nicolas Capens49a88872013-06-20 09:54:03 -0400630 }
Olli Etuaho183d7e22015-11-20 15:59:09 +0200631 // Set defaults for sampler types that have default precision, even those that are
Zhenyao Moa5a1dfc2013-09-23 14:57:03 -0400632 // only available if an extension exists.
Olli Etuaho183d7e22015-11-20 15:59:09 +0200633 // New sampler types in ESSL3 don't have default precision. ESSL1 types do.
634 initSamplerDefaultPrecision(EbtSampler2D);
635 initSamplerDefaultPrecision(EbtSamplerCube);
636 // SamplerExternalOES is specified in the extension to have default precision.
637 initSamplerDefaultPrecision(EbtSamplerExternalOES);
Andrei Volykhina5527072017-03-22 16:46:30 +0300638 // SamplerExternal2DY2YEXT is specified in the extension to have default precision.
639 initSamplerDefaultPrecision(EbtSamplerExternal2DY2YEXT);
Olli Etuaho183d7e22015-11-20 15:59:09 +0200640 // It isn't specified whether Sampler2DRect has default precision.
641 initSamplerDefaultPrecision(EbtSampler2DRect);
Nicolas Capens49a88872013-06-20 09:54:03 -0400642
Olli Etuahocce89652017-06-19 16:04:09 +0300643 symbolTable.setDefaultPrecision(EbtAtomicCounter, EbpHigh);
jchen104cdac9e2017-05-08 11:01:20 +0800644
Jamie Madill1b452142013-07-12 14:51:11 -0400645 InsertBuiltInFunctions(shaderType, shaderSpec, resources, symbolTable);
Nicolas Capens49a88872013-06-20 09:54:03 -0400646
647 IdentifyBuiltIns(shaderType, shaderSpec, resources, symbolTable);
648
649 return true;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000650}
651
Olli Etuaho183d7e22015-11-20 15:59:09 +0200652void TCompiler::initSamplerDefaultPrecision(TBasicType samplerType)
653{
654 ASSERT(samplerType > EbtGuardSamplerBegin && samplerType < EbtGuardSamplerEnd);
Olli Etuahocce89652017-06-19 16:04:09 +0300655 symbolTable.setDefaultPrecision(samplerType, EbpLow);
Olli Etuaho183d7e22015-11-20 15:59:09 +0200656}
657
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400658void TCompiler::setResourceString()
659{
660 std::ostringstream strstream;
Geoff Langb66a9092016-05-16 15:59:14 -0400661
662 // clang-format off
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400663 strstream << ":MaxVertexAttribs:" << compileResources.MaxVertexAttribs
Jamie Madillacb4b812016-11-07 13:50:29 -0500664 << ":MaxVertexUniformVectors:" << compileResources.MaxVertexUniformVectors
665 << ":MaxVaryingVectors:" << compileResources.MaxVaryingVectors
666 << ":MaxVertexTextureImageUnits:" << compileResources.MaxVertexTextureImageUnits
667 << ":MaxCombinedTextureImageUnits:" << compileResources.MaxCombinedTextureImageUnits
668 << ":MaxTextureImageUnits:" << compileResources.MaxTextureImageUnits
669 << ":MaxFragmentUniformVectors:" << compileResources.MaxFragmentUniformVectors
670 << ":MaxDrawBuffers:" << compileResources.MaxDrawBuffers
671 << ":OES_standard_derivatives:" << compileResources.OES_standard_derivatives
672 << ":OES_EGL_image_external:" << compileResources.OES_EGL_image_external
673 << ":OES_EGL_image_external_essl3:" << compileResources.OES_EGL_image_external_essl3
674 << ":NV_EGL_stream_consumer_external:" << compileResources.NV_EGL_stream_consumer_external
675 << ":ARB_texture_rectangle:" << compileResources.ARB_texture_rectangle
676 << ":EXT_draw_buffers:" << compileResources.EXT_draw_buffers
677 << ":FragmentPrecisionHigh:" << compileResources.FragmentPrecisionHigh
678 << ":MaxExpressionComplexity:" << compileResources.MaxExpressionComplexity
679 << ":MaxCallStackDepth:" << compileResources.MaxCallStackDepth
680 << ":MaxFunctionParameters:" << compileResources.MaxFunctionParameters
681 << ":EXT_blend_func_extended:" << compileResources.EXT_blend_func_extended
682 << ":EXT_frag_depth:" << compileResources.EXT_frag_depth
683 << ":EXT_shader_texture_lod:" << compileResources.EXT_shader_texture_lod
684 << ":EXT_shader_framebuffer_fetch:" << compileResources.EXT_shader_framebuffer_fetch
685 << ":NV_shader_framebuffer_fetch:" << compileResources.NV_shader_framebuffer_fetch
686 << ":ARM_shader_framebuffer_fetch:" << compileResources.ARM_shader_framebuffer_fetch
Andrei Volykhina5527072017-03-22 16:46:30 +0300687 << ":EXT_YUV_target:" << compileResources.EXT_YUV_target
Jamie Madillacb4b812016-11-07 13:50:29 -0500688 << ":MaxVertexOutputVectors:" << compileResources.MaxVertexOutputVectors
689 << ":MaxFragmentInputVectors:" << compileResources.MaxFragmentInputVectors
690 << ":MinProgramTexelOffset:" << compileResources.MinProgramTexelOffset
691 << ":MaxProgramTexelOffset:" << compileResources.MaxProgramTexelOffset
692 << ":MaxDualSourceDrawBuffers:" << compileResources.MaxDualSourceDrawBuffers
693 << ":NV_draw_buffers:" << compileResources.NV_draw_buffers
694 << ":WEBGL_debug_shader_precision:" << compileResources.WEBGL_debug_shader_precision
695 << ":MaxImageUnits:" << compileResources.MaxImageUnits
696 << ":MaxVertexImageUniforms:" << compileResources.MaxVertexImageUniforms
697 << ":MaxFragmentImageUniforms:" << compileResources.MaxFragmentImageUniforms
698 << ":MaxComputeImageUniforms:" << compileResources.MaxComputeImageUniforms
699 << ":MaxCombinedImageUniforms:" << compileResources.MaxCombinedImageUniforms
700 << ":MaxCombinedShaderOutputResources:" << compileResources.MaxCombinedShaderOutputResources
701 << ":MaxComputeWorkGroupCountX:" << compileResources.MaxComputeWorkGroupCount[0]
702 << ":MaxComputeWorkGroupCountY:" << compileResources.MaxComputeWorkGroupCount[1]
703 << ":MaxComputeWorkGroupCountZ:" << compileResources.MaxComputeWorkGroupCount[2]
704 << ":MaxComputeWorkGroupSizeX:" << compileResources.MaxComputeWorkGroupSize[0]
705 << ":MaxComputeWorkGroupSizeY:" << compileResources.MaxComputeWorkGroupSize[1]
706 << ":MaxComputeWorkGroupSizeZ:" << compileResources.MaxComputeWorkGroupSize[2]
707 << ":MaxComputeUniformComponents:" << compileResources.MaxComputeUniformComponents
708 << ":MaxComputeTextureImageUnits:" << compileResources.MaxComputeTextureImageUnits
709 << ":MaxComputeAtomicCounters:" << compileResources.MaxComputeAtomicCounters
710 << ":MaxComputeAtomicCounterBuffers:" << compileResources.MaxComputeAtomicCounterBuffers
711 << ":MaxVertexAtomicCounters:" << compileResources.MaxVertexAtomicCounters
712 << ":MaxFragmentAtomicCounters:" << compileResources.MaxFragmentAtomicCounters
713 << ":MaxCombinedAtomicCounters:" << compileResources.MaxCombinedAtomicCounters
714 << ":MaxAtomicCounterBindings:" << compileResources.MaxAtomicCounterBindings
715 << ":MaxVertexAtomicCounterBuffers:" << compileResources.MaxVertexAtomicCounterBuffers
716 << ":MaxFragmentAtomicCounterBuffers:" << compileResources.MaxFragmentAtomicCounterBuffers
717 << ":MaxCombinedAtomicCounterBuffers:" << compileResources.MaxCombinedAtomicCounterBuffers
718 << ":MaxAtomicCounterBufferSize:" << compileResources.MaxAtomicCounterBufferSize;
Geoff Langb66a9092016-05-16 15:59:14 -0400719 // clang-format on
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400720
721 builtInResourcesString = strstream.str();
722}
723
alokp@chromium.org07620a52010-09-23 17:53:56 +0000724void TCompiler::clearResults()
725{
daniel@transgaming.com4167cc92013-01-11 04:11:53 +0000726 arrayBoundsClamper.Cleanup();
alokp@chromium.org07620a52010-09-23 17:53:56 +0000727 infoSink.info.erase();
728 infoSink.obj.erase();
729 infoSink.debug.erase();
Olli Etuaho77ba4082016-12-16 12:01:18 +0000730 mDiagnostics.resetErrorCount();
alokp@chromium.org07620a52010-09-23 17:53:56 +0000731
Jamie Madilled27c722014-07-02 15:31:23 -0400732 attributes.clear();
733 outputVariables.clear();
alokp@chromium.org07620a52010-09-23 17:53:56 +0000734 uniforms.clear();
Zhenyao Mod2d340b2013-09-23 14:57:05 -0400735 varyings.clear();
Jamie Madilled27c722014-07-02 15:31:23 -0400736 interfaceBlocks.clear();
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700737 variablesCollected = false;
Olli Etuahob12040c2017-06-27 14:20:45 +0300738 mGLPositionInitialized = false;
zmo@google.coma3b4ab42011-09-16 00:53:26 +0000739
Olli Etuaho09b04a22016-12-15 13:30:26 +0000740 mNumViews = -1;
741
Olli Etuahodfa75e82017-01-23 09:43:06 -0800742 builtInFunctionEmulator.cleanup();
daniel@transgaming.com0aa3b5a2012-11-28 19:43:24 +0000743
744 nameMap.clear();
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200745
Yunchao Hed7297bf2017-04-19 15:27:10 +0800746 mSourcePath = nullptr;
Olli Etuaho4dd06d52017-07-05 12:41:06 +0300747 mTemporaryId = TSymbolUniqueId();
alokp@chromium.org07620a52010-09-23 17:53:56 +0000748}
749
Corentin Wallez71d147f2015-02-11 11:15:24 -0800750bool TCompiler::initCallDag(TIntermNode *root)
zmo@google.comb1762df2011-07-30 02:04:23 +0000751{
Corentin Wallez71d147f2015-02-11 11:15:24 -0800752 mCallDag.clear();
753
Olli Etuaho77ba4082016-12-16 12:01:18 +0000754 switch (mCallDag.init(root, &mDiagnostics))
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800755 {
Jamie Madillacb4b812016-11-07 13:50:29 -0500756 case CallDAG::INITDAG_SUCCESS:
757 return true;
758 case CallDAG::INITDAG_RECURSION:
Jamie Madillacb4b812016-11-07 13:50:29 -0500759 case CallDAG::INITDAG_UNDEFINED:
Olli Etuaho77ba4082016-12-16 12:01:18 +0000760 // Error message has already been written out.
761 ASSERT(mDiagnostics.numErrors() > 0);
Jamie Madillacb4b812016-11-07 13:50:29 -0500762 return false;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800763 }
764
765 UNREACHABLE();
766 return true;
767}
768
769bool TCompiler::checkCallDepth()
770{
771 std::vector<int> depths(mCallDag.size());
772
773 for (size_t i = 0; i < mCallDag.size(); i++)
774 {
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500775 int depth = 0;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800776 auto &record = mCallDag.getRecordFromIndex(i);
777
778 for (auto &calleeIndex : record.callees)
779 {
780 depth = std::max(depth, depths[calleeIndex] + 1);
781 }
782
783 depths[i] = depth;
784
785 if (depth >= maxCallStackDepth)
786 {
787 // Trace back the function chain to have a meaningful info log.
Olli Etuaho77ba4082016-12-16 12:01:18 +0000788 std::stringstream errorStream;
789 errorStream << "Call stack too deep (larger than " << maxCallStackDepth
790 << ") with the following call chain: " << record.name;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800791
Cooper Partin4d61f7e2015-08-12 10:56:50 -0700792 int currentFunction = static_cast<int>(i);
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500793 int currentDepth = depth;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800794
795 while (currentFunction != -1)
796 {
Olli Etuaho77ba4082016-12-16 12:01:18 +0000797 errorStream << " -> " << mCallDag.getRecordFromIndex(currentFunction).name;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800798
799 int nextFunction = -1;
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500800 for (auto &calleeIndex : mCallDag.getRecordFromIndex(currentFunction).callees)
Corentin Wallez71d147f2015-02-11 11:15:24 -0800801 {
802 if (depths[calleeIndex] == currentDepth - 1)
803 {
804 currentDepth--;
805 nextFunction = calleeIndex;
806 }
807 }
808
809 currentFunction = nextFunction;
810 }
811
Olli Etuaho77ba4082016-12-16 12:01:18 +0000812 std::string errorStr = errorStream.str();
813 mDiagnostics.globalError(errorStr.c_str());
814
Corentin Wallez71d147f2015-02-11 11:15:24 -0800815 return false;
816 }
817 }
818
819 return true;
820}
821
822bool TCompiler::tagUsedFunctions()
823{
824 // Search from main, starting from the end of the DAG as it usually is the root.
Cooper Partin4d61f7e2015-08-12 10:56:50 -0700825 for (size_t i = mCallDag.size(); i-- > 0;)
Corentin Wallez71d147f2015-02-11 11:15:24 -0800826 {
Olli Etuahoec9232b2017-03-27 17:01:37 +0300827 if (mCallDag.getRecordFromIndex(i).name == "main")
Corentin Wallez71d147f2015-02-11 11:15:24 -0800828 {
829 internalTagUsedFunction(i);
830 return true;
831 }
832 }
833
Olli Etuaho77ba4082016-12-16 12:01:18 +0000834 mDiagnostics.globalError("Missing main()");
Corentin Wallez71d147f2015-02-11 11:15:24 -0800835 return false;
836}
837
838void TCompiler::internalTagUsedFunction(size_t index)
839{
840 if (functionMetadata[index].used)
841 {
842 return;
843 }
844
845 functionMetadata[index].used = true;
846
847 for (int calleeIndex : mCallDag.getRecordFromIndex(index).callees)
848 {
849 internalTagUsedFunction(calleeIndex);
zmo@google.comb1762df2011-07-30 02:04:23 +0000850 }
851}
852
Corentin Walleza094a8a2015-04-07 11:53:06 -0700853// A predicate for the stl that returns if a top-level node is unused
854class TCompiler::UnusedPredicate
855{
856 public:
857 UnusedPredicate(const CallDAG *callDag, const std::vector<FunctionMetadata> *metadatas)
Jamie Madillacb4b812016-11-07 13:50:29 -0500858 : mCallDag(callDag), mMetadatas(metadatas)
Corentin Walleza094a8a2015-04-07 11:53:06 -0700859 {
860 }
861
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500862 bool operator()(TIntermNode *node)
Corentin Walleza094a8a2015-04-07 11:53:06 -0700863 {
Olli Etuaho16c745a2017-01-16 17:02:27 +0000864 const TIntermFunctionPrototype *asFunctionPrototype = node->getAsFunctionPrototypeNode();
865 const TIntermFunctionDefinition *asFunctionDefinition = node->getAsFunctionDefinition();
Corentin Walleza094a8a2015-04-07 11:53:06 -0700866
Olli Etuaho336b1472016-10-05 16:37:55 +0100867 const TFunctionSymbolInfo *functionInfo = nullptr;
868
Olli Etuaho16c745a2017-01-16 17:02:27 +0000869 if (asFunctionDefinition)
Olli Etuaho336b1472016-10-05 16:37:55 +0100870 {
Olli Etuaho16c745a2017-01-16 17:02:27 +0000871 functionInfo = asFunctionDefinition->getFunctionSymbolInfo();
Olli Etuaho336b1472016-10-05 16:37:55 +0100872 }
Olli Etuaho16c745a2017-01-16 17:02:27 +0000873 else if (asFunctionPrototype)
Olli Etuaho336b1472016-10-05 16:37:55 +0100874 {
Olli Etuaho16c745a2017-01-16 17:02:27 +0000875 functionInfo = asFunctionPrototype->getFunctionSymbolInfo();
Olli Etuaho336b1472016-10-05 16:37:55 +0100876 }
877 if (functionInfo == nullptr)
Corentin Walleza094a8a2015-04-07 11:53:06 -0700878 {
879 return false;
880 }
881
Olli Etuaho336b1472016-10-05 16:37:55 +0100882 size_t callDagIndex = mCallDag->findIndex(functionInfo);
Corentin Walleza094a8a2015-04-07 11:53:06 -0700883 if (callDagIndex == CallDAG::InvalidIndex)
884 {
885 // This happens only for unimplemented prototypes which are thus unused
Olli Etuaho16c745a2017-01-16 17:02:27 +0000886 ASSERT(asFunctionPrototype);
Corentin Walleza094a8a2015-04-07 11:53:06 -0700887 return true;
888 }
889
890 ASSERT(callDagIndex < mMetadatas->size());
891 return !(*mMetadatas)[callDagIndex].used;
892 }
893
894 private:
895 const CallDAG *mCallDag;
896 const std::vector<FunctionMetadata> *mMetadatas;
897};
898
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100899bool TCompiler::pruneUnusedFunctions(TIntermBlock *root)
Corentin Walleza094a8a2015-04-07 11:53:06 -0700900{
Corentin Walleza094a8a2015-04-07 11:53:06 -0700901 UnusedPredicate isUnused(&mCallDag, &functionMetadata);
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100902 TIntermSequence *sequence = root->getSequence();
Corentin Wallezb081e782015-07-20 05:40:04 -0700903
904 if (!sequence->empty())
905 {
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500906 sequence->erase(std::remove_if(sequence->begin(), sequence->end(), isUnused),
907 sequence->end());
Corentin Wallezb081e782015-07-20 05:40:04 -0700908 }
Corentin Walleza094a8a2015-04-07 11:53:06 -0700909
910 return true;
911}
912
Olli Etuahob4279202017-05-18 15:08:24 +0300913bool TCompiler::limitExpressionComplexity(TIntermBlock *root)
Jamie Madilleb1a0102013-07-08 13:31:38 -0400914{
Olli Etuahocccf2b02017-07-05 14:50:54 +0300915 if (!IsASTDepthBelowLimit(root, maxExpressionComplexity))
Jamie Madill6654bc92014-03-26 14:01:57 -0400916 {
Olli Etuaho77ba4082016-12-16 12:01:18 +0000917 mDiagnostics.globalError("Expression too complex.");
Jamie Madill6654bc92014-03-26 14:01:57 -0400918 return false;
919 }
920
Olli Etuahob4279202017-05-18 15:08:24 +0300921 if (!ValidateMaxParameters(root, maxFunctionParameters))
Olli Etuaho19d1dc92016-03-08 17:18:46 +0200922 {
Olli Etuaho77ba4082016-12-16 12:01:18 +0000923 mDiagnostics.globalError("Function has too many parameters.");
Olli Etuaho19d1dc92016-03-08 17:18:46 +0200924 return false;
925 }
926
Jamie Madilleb1a0102013-07-08 13:31:38 -0400927 return true;
928}
929
Corentin Wallez1df16022016-10-27 08:16:56 -0400930bool TCompiler::shouldCollectVariables(ShCompileOptions compileOptions)
931{
932 return (compileOptions & SH_VARIABLES) != 0;
933}
934
935bool TCompiler::wereVariablesCollected() const
936{
937 return variablesCollected;
938}
939
Olli Etuaho9cbc07c2017-05-10 18:22:01 +0300940void TCompiler::initializeGLPosition(TIntermBlock *root)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800941{
Zhenyao Mo72111912016-07-20 17:45:56 -0700942 InitVariableList list;
943 sh::ShaderVariable var(GL_FLOAT_VEC4, 0);
944 var.name = "gl_Position";
945 list.push_back(var);
Martin Radeve145def2017-06-22 12:49:12 +0300946 InitializeVariables(root, list, symbolTable, shaderVersion, shaderSpec, extensionBehavior);
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800947}
948
Olli Etuaho9cbc07c2017-05-10 18:22:01 +0300949void TCompiler::useAllMembersInUnusedStandardAndSharedBlocks(TIntermBlock *root)
Qin Jiajia7835b522016-10-08 11:20:17 +0800950{
951 sh::InterfaceBlockList list;
952
953 for (auto block : interfaceBlocks)
954 {
955 if (!block.staticUse &&
956 (block.layout == sh::BLOCKLAYOUT_STANDARD || block.layout == sh::BLOCKLAYOUT_SHARED))
957 {
958 list.push_back(block);
959 }
960 }
961
Zhenyao Mod7490962016-11-09 15:49:51 -0800962 sh::UseInterfaceBlockFields(root, list, symbolTable);
Qin Jiajia7835b522016-10-08 11:20:17 +0800963}
964
Olli Etuaho9cbc07c2017-05-10 18:22:01 +0300965void TCompiler::initializeOutputVariables(TIntermBlock *root)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800966{
Zhenyao Mo72111912016-07-20 17:45:56 -0700967 InitVariableList list;
968 if (shaderType == GL_VERTEX_SHADER)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800969 {
Zhenyao Mo72111912016-07-20 17:45:56 -0700970 for (auto var : varyings)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800971 {
Zhenyao Mof9312682016-07-22 12:51:31 -0700972 list.push_back(var);
Olli Etuahob12040c2017-06-27 14:20:45 +0300973 if (var.name == "gl_Position")
974 {
975 ASSERT(!mGLPositionInitialized);
976 mGLPositionInitialized = true;
977 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800978 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800979 }
Zhenyao Mo72111912016-07-20 17:45:56 -0700980 else
981 {
982 ASSERT(shaderType == GL_FRAGMENT_SHADER);
983 for (auto var : outputVariables)
984 {
985 list.push_back(var);
986 }
987 }
Martin Radeve145def2017-06-22 12:49:12 +0300988 InitializeVariables(root, list, symbolTable, shaderVersion, shaderSpec, extensionBehavior);
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800989}
990
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500991const TExtensionBehavior &TCompiler::getExtensionBehavior() const
zmo@google.com5601ea02011-06-10 18:23:25 +0000992{
993 return extensionBehavior;
994}
zmo@google.com32e97312011-08-24 01:03:11 +0000995
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200996const char *TCompiler::getSourcePath() const
997{
998 return mSourcePath;
999}
1000
Jamie Madilld7b1ab52016-12-12 14:42:19 -05001001const ShBuiltInResources &TCompiler::getResources() const
shannon.woods%transgaming.com@gtempaccount.com18b4c4b2013-04-13 03:31:40 +00001002{
1003 return compileResources;
1004}
1005
Jamie Madilld7b1ab52016-12-12 14:42:19 -05001006const ArrayBoundsClamper &TCompiler::getArrayBoundsClamper() const
daniel@transgaming.com4167cc92013-01-11 04:11:53 +00001007{
1008 return arrayBoundsClamper;
1009}
1010
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +00001011ShArrayIndexClampingStrategy TCompiler::getArrayIndexClampingStrategy() const
1012{
1013 return clampingStrategy;
1014}
1015
Jamie Madilld7b1ab52016-12-12 14:42:19 -05001016const BuiltInFunctionEmulator &TCompiler::getBuiltInFunctionEmulator() const
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +00001017{
1018 return builtInFunctionEmulator;
1019}
Zhenyao Mo94ac7b72014-10-15 18:22:08 -07001020
Qiankun Miao7ebb97f2016-09-08 18:01:50 +08001021void TCompiler::writePragma(ShCompileOptions compileOptions)
Zhenyao Mo94ac7b72014-10-15 18:22:08 -07001022{
Kenneth Russellbccc65d2016-07-19 16:48:43 -07001023 if (!(compileOptions & SH_FLATTEN_PRAGMA_STDGL_INVARIANT_ALL))
1024 {
1025 TInfoSinkBase &sink = infoSink.obj;
1026 if (mPragma.stdgl.invariantAll)
1027 sink << "#pragma STDGL invariant(all)\n";
1028 }
1029}
1030
1031bool TCompiler::isVaryingDefined(const char *varyingName)
1032{
1033 ASSERT(variablesCollected);
1034 for (size_t ii = 0; ii < varyings.size(); ++ii)
1035 {
1036 if (varyings[ii].name == varyingName)
1037 {
1038 return true;
1039 }
1040 }
1041
1042 return false;
Zhenyao Mo94ac7b72014-10-15 18:22:08 -07001043}
Jamie Madillacb4b812016-11-07 13:50:29 -05001044
1045} // namespace sh