blob: c975038ea11cfba0f8733d17e71a580ccea93339 [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"
Jamie Madill6b9cb252013-10-17 10:45:47 -040023#include "compiler/translator/ParseContext.h"
Olli Etuahoc6833112015-04-22 15:15:54 +030024#include "compiler/translator/PruneEmptyDeclarations.h"
Zhenyao Moe740add2014-07-18 17:01:01 -070025#include "compiler/translator/RegenerateStructNames.h"
Qiankun Miao705a9192016-08-29 10:05:27 +080026#include "compiler/translator/RemoveInvariantDeclaration.h"
Olli Etuaho5c407bb2015-06-01 12:20:39 +030027#include "compiler/translator/RemovePow.h"
Corentin Wallezd4b50542015-09-28 12:19:26 -070028#include "compiler/translator/RewriteDoWhile.h"
Zhenyao Mocd68fe72014-07-11 10:45:44 -070029#include "compiler/translator/ScalarizeVecAndMatConstructorArgs.h"
Olli Etuaho9733cee2017-05-11 19:14:35 +030030#include "compiler/translator/SeparateDeclarations.h"
31#include "compiler/translator/SimplifyLoopConditions.h"
Zhenyao Mo7cab38b2013-10-15 12:59:30 -070032#include "compiler/translator/UnfoldShortCircuitAST.h"
Qin Jiajia7835b522016-10-08 11:20:17 +080033#include "compiler/translator/UseInterfaceBlockFields.h"
Geoff Lang17732822013-08-29 13:46:49 -040034#include "compiler/translator/ValidateLimitations.h"
Olli Etuaho19d1dc92016-03-08 17:18:46 +020035#include "compiler/translator/ValidateMaxParameters.h"
Olli Etuaho09b04a22016-12-15 13:30:26 +000036#include "compiler/translator/ValidateMultiviewWebGL.h"
Geoff Lang17732822013-08-29 13:46:49 -040037#include "compiler/translator/ValidateOutputs.h"
38#include "compiler/translator/VariablePacker.h"
shannon.woods@transgaming.comda1ed362013-01-25 21:54:57 +000039#include "third_party/compiler/ArrayBoundsClamper.h"
Corentin Wallez28b65282016-06-16 07:24:50 -070040
Jamie Madillacb4b812016-11-07 13:50:29 -050041namespace sh
42{
43
Corentin Wallez28b65282016-06-16 07:24:50 -070044namespace
45{
46
47#if defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
48void DumpFuzzerCase(char const *const *shaderStrings,
49 size_t numStrings,
50 uint32_t type,
51 uint32_t spec,
52 uint32_t output,
53 uint64_t options)
54{
55 static int fileIndex = 0;
56
57 std::ostringstream o;
58 o << "corpus/" << fileIndex++ << ".sample";
59 std::string s = o.str();
60
61 // Must match the input format of the fuzzer
62 FILE *f = fopen(s.c_str(), "w");
63 fwrite(&type, sizeof(type), 1, f);
64 fwrite(&spec, sizeof(spec), 1, f);
65 fwrite(&output, sizeof(output), 1, f);
66 fwrite(&options, sizeof(options), 1, f);
67
68 char zero[128 - 20] = {0};
69 fwrite(&zero, 128 - 20, 1, f);
70
71 for (size_t i = 0; i < numStrings; i++)
72 {
73 fwrite(shaderStrings[i], sizeof(char), strlen(shaderStrings[i]), f);
74 }
75 fwrite(&zero, 1, 1, f);
76
77 fclose(f);
78}
79#endif // defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
80} // anonymous namespace
81
Jamie Madill5508f392014-02-20 13:31:36 -050082bool IsWebGLBasedSpec(ShShaderSpec spec)
maxvujovic@gmail.com430f5e02012-06-08 17:47:59 +000083{
Qiankun Miaoc2c5fc42016-08-31 15:24:22 +080084 return (spec == SH_WEBGL_SPEC || spec == SH_WEBGL2_SPEC || spec == SH_WEBGL3_SPEC);
maxvujovic@gmail.com430f5e02012-06-08 17:47:59 +000085}
86
Qingqing Dengad0d0792015-04-08 14:25:06 -070087bool IsGLSL130OrNewer(ShShaderOutput output)
88{
Jamie Madillacb4b812016-11-07 13:50:29 -050089 return (output == SH_GLSL_130_OUTPUT || output == SH_GLSL_140_OUTPUT ||
90 output == SH_GLSL_150_CORE_OUTPUT || output == SH_GLSL_330_CORE_OUTPUT ||
91 output == SH_GLSL_400_CORE_OUTPUT || output == SH_GLSL_410_CORE_OUTPUT ||
92 output == SH_GLSL_420_CORE_OUTPUT || output == SH_GLSL_430_CORE_OUTPUT ||
93 output == SH_GLSL_440_CORE_OUTPUT || output == SH_GLSL_450_CORE_OUTPUT);
Qingqing Dengad0d0792015-04-08 14:25:06 -070094}
95
Qiankun Miao705a9192016-08-29 10:05:27 +080096bool IsGLSL420OrNewer(ShShaderOutput output)
97{
Jamie Madillacb4b812016-11-07 13:50:29 -050098 return (output == SH_GLSL_420_CORE_OUTPUT || output == SH_GLSL_430_CORE_OUTPUT ||
99 output == SH_GLSL_440_CORE_OUTPUT || output == SH_GLSL_450_CORE_OUTPUT);
Qiankun Miao705a9192016-08-29 10:05:27 +0800100}
101
Zhenyao Mob7bf7422016-11-08 14:44:05 -0800102bool IsGLSL410OrOlder(ShShaderOutput output)
103{
104 return (output == SH_GLSL_130_OUTPUT || output == SH_GLSL_140_OUTPUT ||
105 output == SH_GLSL_150_CORE_OUTPUT || output == SH_GLSL_330_CORE_OUTPUT ||
106 output == SH_GLSL_400_CORE_OUTPUT || output == SH_GLSL_410_CORE_OUTPUT);
107}
108
Qiankun Miao89dd8f32016-11-09 12:59:30 +0000109bool RemoveInvariant(sh::GLenum shaderType,
110 int shaderVersion,
111 ShShaderOutput outputType,
112 ShCompileOptions compileOptions)
113{
114 if ((compileOptions & SH_DONT_REMOVE_INVARIANT_FOR_FRAGMENT_INPUT) == 0 &&
115 shaderType == GL_FRAGMENT_SHADER && IsGLSL420OrNewer(outputType))
116 return true;
117
118 if ((compileOptions & SH_REMOVE_INVARIANT_AND_CENTROID_FOR_ESSL3) != 0 &&
Qiankun Miao41f9f672016-11-16 17:04:36 +0800119 shaderVersion >= 300 && shaderType == GL_VERTEX_SHADER)
Qiankun Miao89dd8f32016-11-09 12:59:30 +0000120 return true;
121
122 return false;
123}
124
Zhenyao Mo7faf1a12014-04-25 18:03:56 -0700125size_t GetGlobalMaxTokenSize(ShShaderSpec spec)
Jamie Madill88f6e942014-02-19 10:27:53 -0500126{
He Yunchao29ab9ff2015-08-06 16:58:30 +0800127 // WebGL defines a max token length of 256, while ES2 leaves max token
Jamie Madill88f6e942014-02-19 10:27:53 -0500128 // size undefined. ES3 defines a max size of 1024 characters.
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700129 switch (spec)
Jamie Madill88f6e942014-02-19 10:27:53 -0500130 {
Jamie Madillacb4b812016-11-07 13:50:29 -0500131 case SH_WEBGL_SPEC:
132 return 256;
133 default:
134 return 1024;
Jamie Madill88f6e942014-02-19 10:27:53 -0500135 }
136}
137
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500138namespace
139{
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700140
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800141class TScopedPoolAllocator
142{
143 public:
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500144 TScopedPoolAllocator(TPoolAllocator *allocator) : mAllocator(allocator)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800145 {
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400146 mAllocator->push();
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000147 SetGlobalPoolAllocator(mAllocator);
148 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800149 ~TScopedPoolAllocator()
150 {
Yunchao Hef81ce4a2017-04-24 10:49:17 +0800151 SetGlobalPoolAllocator(nullptr);
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400152 mAllocator->pop();
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000153 }
154
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800155 private:
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500156 TPoolAllocator *mAllocator;
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400157};
158
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800159class TScopedSymbolTableLevel
160{
161 public:
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500162 TScopedSymbolTableLevel(TSymbolTable *table) : mTable(table)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800163 {
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400164 ASSERT(mTable->atBuiltInLevel());
165 mTable->push();
166 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800167 ~TScopedSymbolTableLevel()
168 {
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400169 while (!mTable->atBuiltInLevel())
170 mTable->pop();
171 }
172
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800173 private:
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500174 TSymbolTable *mTable;
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000175};
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700176
177int MapSpecToShaderVersion(ShShaderSpec spec)
178{
179 switch (spec)
180 {
Jamie Madillacb4b812016-11-07 13:50:29 -0500181 case SH_GLES2_SPEC:
182 case SH_WEBGL_SPEC:
183 return 100;
184 case SH_GLES3_SPEC:
185 case SH_WEBGL2_SPEC:
186 return 300;
187 case SH_GLES3_1_SPEC:
188 case SH_WEBGL3_SPEC:
189 return 310;
190 default:
191 UNREACHABLE();
192 return 0;
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700193 }
194}
195
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000196} // namespace
197
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800198TShHandleBase::TShHandleBase()
199{
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000200 allocator.push();
201 SetGlobalPoolAllocator(&allocator);
202}
203
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800204TShHandleBase::~TShHandleBase()
205{
Yunchao Hef81ce4a2017-04-24 10:49:17 +0800206 SetGlobalPoolAllocator(nullptr);
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000207 allocator.popAll();
208}
209
Jamie Madill183bde52014-07-02 15:31:19 -0400210TCompiler::TCompiler(sh::GLenum type, ShShaderSpec spec, ShShaderOutput output)
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700211 : variablesCollected(false),
212 shaderType(type),
zmo@google.comf420c422011-09-12 18:27:59 +0000213 shaderSpec(spec),
Jamie Madill68fe74a2014-05-27 12:56:01 -0400214 outputType(output),
Jamie Madilleb1a0102013-07-08 13:31:38 -0400215 maxUniformVectors(0),
216 maxExpressionComplexity(0),
217 maxCallStackDepth(0),
Olli Etuaho19d1dc92016-03-08 17:18:46 +0200218 maxFunctionParameters(0),
shannon.woods%transgaming.com@gtempaccount.comcbb6b6a2013-04-13 03:27:47 +0000219 fragmentPrecisionHigh(false),
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000220 clampingStrategy(SH_CLAMP_WITH_CLAMP_INTRINSIC),
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200221 builtInFunctionEmulator(),
Olli Etuaho77ba4082016-12-16 12:01:18 +0000222 mDiagnostics(infoSink.info),
Yunchao Hef81ce4a2017-04-24 10:49:17 +0800223 mSourcePath(nullptr),
Martin Radev802abe02016-08-04 17:48:32 +0300224 mComputeShaderLocalSizeDeclared(false),
Corentin Wallezd4b50542015-09-28 12:19:26 -0700225 mTemporaryIndex(0)
alokp@chromium.org4888ceb2010-10-01 21:13:12 +0000226{
Martin Radev802abe02016-08-04 17:48:32 +0300227 mComputeShaderLocalSize.fill(1);
alokp@chromium.org4888ceb2010-10-01 21:13:12 +0000228}
229
230TCompiler::~TCompiler()
231{
232}
233
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800234bool TCompiler::shouldRunLoopAndIndexingValidation(ShCompileOptions compileOptions) const
Olli Etuaho5d91dda2015-06-18 15:47:46 +0300235{
236 // If compiling an ESSL 1.00 shader for WebGL, or if its been requested through the API,
237 // validate loop and indexing as well (to verify that the shader only uses minimal functionality
238 // of ESSL 1.00 as in Appendix A of the spec).
239 return (IsWebGLBasedSpec(shaderSpec) && shaderVersion == 100) ||
240 (compileOptions & SH_VALIDATE_LOOP_INDEXING);
241}
242
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500243bool TCompiler::Init(const ShBuiltInResources &resources)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000244{
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500245 shaderVersion = 100;
246 maxUniformVectors = (shaderType == GL_VERTEX_SHADER) ? resources.MaxVertexUniformVectors
247 : resources.MaxFragmentUniformVectors;
Jamie Madilleb1a0102013-07-08 13:31:38 -0400248 maxExpressionComplexity = resources.MaxExpressionComplexity;
Olli Etuaho19d1dc92016-03-08 17:18:46 +0200249 maxCallStackDepth = resources.MaxCallStackDepth;
250 maxFunctionParameters = resources.MaxFunctionParameters;
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400251
252 SetGlobalPoolAllocator(&allocator);
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000253
alokp@chromium.org07620a52010-09-23 17:53:56 +0000254 // Generate built-in symbol table.
255 if (!InitBuiltInSymbolTable(resources))
256 return false;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000257 InitExtensionBehavior(resources, extensionBehavior);
shannon.woods%transgaming.com@gtempaccount.comcbb6b6a2013-04-13 03:27:47 +0000258 fragmentPrecisionHigh = resources.FragmentPrecisionHigh == 1;
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000259
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000260 arrayBoundsClamper.SetClampingStrategy(resources.ArrayIndexClampingStrategy);
261 clampingStrategy = resources.ArrayIndexClampingStrategy;
262
daniel@transgaming.comc23f4612012-11-28 19:42:57 +0000263 hashFunction = resources.HashFunction;
264
alokp@chromium.org07620a52010-09-23 17:53:56 +0000265 return true;
266}
267
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100268TIntermBlock *TCompiler::compileTreeForTesting(const char *const shaderStrings[],
269 size_t numStrings,
270 ShCompileOptions compileOptions)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000271{
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200272 return compileTreeImpl(shaderStrings, numStrings, compileOptions);
273}
274
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100275TIntermBlock *TCompiler::compileTreeImpl(const char *const shaderStrings[],
276 size_t numStrings,
277 const ShCompileOptions compileOptions)
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200278{
alokp@chromium.org07620a52010-09-23 17:53:56 +0000279 clearResults();
280
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200281 ASSERT(numStrings > 0);
282 ASSERT(GetGlobalPoolAllocator());
alokp@chromium.org07620a52010-09-23 17:53:56 +0000283
David Yen0fbd1282015-02-02 14:46:09 -0800284 // Reset the extension behavior for each compilation unit.
285 ResetExtensionBehavior(extensionBehavior);
286
apatrick@chromium.org0f4cefe2011-01-26 19:30:57 +0000287 // First string is path of source file if flag is set. The actual source follows.
shannon.woods@transgaming.comd64b3da2013-02-28 23:19:26 +0000288 size_t firstSource = 0;
apatrick@chromium.org0f4cefe2011-01-26 19:30:57 +0000289 if (compileOptions & SH_SOURCE_PATH)
290 {
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200291 mSourcePath = shaderStrings[0];
apatrick@chromium.org0f4cefe2011-01-26 19:30:57 +0000292 ++firstSource;
293 }
294
Olli Etuahof119a262016-08-19 15:54:22 +0300295 TParseContext parseContext(symbolTable, extensionBehavior, shaderType, shaderSpec,
Olli Etuaho77ba4082016-12-16 12:01:18 +0000296 compileOptions, true, &mDiagnostics, getResources());
Olli Etuaho853dc1a2014-11-06 17:25:48 +0200297
Olli Etuahoa6996682015-10-12 14:32:30 +0300298 parseContext.setFragmentPrecisionHighOnESSL1(fragmentPrecisionHigh);
alokp@chromium.org07620a52010-09-23 17:53:56 +0000299
300 // We preserve symbols at the built-in level from compile-to-compile.
301 // Start pushing the user-defined symbols at global level.
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400302 TScopedSymbolTableLevel scopedSymbolLevel(&symbolTable);
alokp@chromium.org07620a52010-09-23 17:53:56 +0000303
304 // Parse shader.
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500305 bool success = (PaParseStrings(numStrings - firstSource, &shaderStrings[firstSource], nullptr,
306 &parseContext) == 0) &&
307 (parseContext.getTreeRoot() != nullptr);
shannon.woods%transgaming.com@gtempaccount.com0bbed382013-04-13 03:38:07 +0000308
shannon.woods%transgaming.com@gtempaccount.com5524db02013-04-13 03:38:16 +0000309 shaderVersion = parseContext.getShaderVersion();
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700310 if (success && MapSpecToShaderVersion(shaderSpec) < shaderVersion)
311 {
Olli Etuaho77ba4082016-12-16 12:01:18 +0000312 mDiagnostics.globalError("unsupported shader version");
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700313 success = false;
314 }
shannon.woods%transgaming.com@gtempaccount.com0bbed382013-04-13 03:38:07 +0000315
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100316 TIntermBlock *root = nullptr;
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200317
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800318 if (success)
319 {
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700320 mPragma = parseContext.pragma();
Kenneth Russell8bad46d2016-07-01 19:52:52 -0700321 symbolTable.setGlobalInvariant(mPragma.stdgl.invariantAll);
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700322
Martin Radev802abe02016-08-04 17:48:32 +0300323 mComputeShaderLocalSizeDeclared = parseContext.isComputeShaderLocalSizeDeclared();
324 mComputeShaderLocalSize = parseContext.getComputeShaderLocalSize();
325
Olli Etuaho09b04a22016-12-15 13:30:26 +0000326 mNumViews = parseContext.getNumViews();
327
Jamie Madill6e06b1f2015-05-14 10:01:17 -0400328 root = parseContext.getTreeRoot();
alokp@chromium.orgb59a7782010-11-24 18:38:33 +0000329
Olli Etuahoa6996682015-10-12 14:32:30 +0300330 // Highp might have been auto-enabled based on shader version
331 fragmentPrecisionHigh = parseContext.getFragmentPrecisionHigh();
332
Olli Etuaho09b04a22016-12-15 13:30:26 +0000333 if (success && (IsWebGLBasedSpec(shaderSpec) &&
334 IsExtensionEnabled(extensionBehavior, "GL_OVR_multiview") &&
335 IsExtensionEnabled(extensionBehavior, "GL_OVR_multiview2")))
336 {
337 // Can't enable both extensions at the same time.
338 mDiagnostics.globalError("Can't enable both OVR_multiview and OVR_multiview2");
339 success = false;
340 }
341
Jamie Madill6654bc92014-03-26 14:01:57 -0400342 // Disallow expressions deemed too complex.
343 if (success && (compileOptions & SH_LIMIT_EXPRESSION_COMPLEXITY))
344 success = limitExpressionComplexity(root);
345
Corentin Wallez71d147f2015-02-11 11:15:24 -0800346 // Create the function DAG and check there is no recursion
zmo@google.comb1762df2011-07-30 02:04:23 +0000347 if (success)
Corentin Wallez71d147f2015-02-11 11:15:24 -0800348 success = initCallDag(root);
349
350 if (success && (compileOptions & SH_LIMIT_CALL_STACK_DEPTH))
351 success = checkCallDepth();
352
353 // Checks which functions are used and if "main" exists
354 if (success)
355 {
356 functionMetadata.clear();
357 functionMetadata.resize(mCallDag.size());
358 success = tagUsedFunctions();
359 }
zmo@google.comb1762df2011-07-30 02:04:23 +0000360
Corentin Walleza094a8a2015-04-07 11:53:06 -0700361 if (success && !(compileOptions & SH_DONT_PRUNE_UNUSED_FUNCTIONS))
362 success = pruneUnusedFunctions(root);
363
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500364 // Prune empty declarations to work around driver bugs and to keep declaration output
365 // simple.
Olli Etuahoc6833112015-04-22 15:15:54 +0300366 if (success)
367 PruneEmptyDeclarations(root);
368
Andrei Volykhin73fa4b82017-05-05 18:45:06 +0300369 if (success && shaderVersion >= 300 && shaderType == GL_FRAGMENT_SHADER)
Olli Etuaho12b0b392017-05-30 13:22:31 +0300370 {
371 success = ValidateOutputs(root, getExtensionBehavior(), compileResources.MaxDrawBuffers,
372 &mDiagnostics);
373 }
Jamie Madill05a80ce2013-06-20 11:55:49 -0400374
Olli Etuaho5d91dda2015-06-18 15:47:46 +0300375 if (success && shouldRunLoopAndIndexingValidation(compileOptions))
Olli Etuaho9ec79392017-03-31 23:04:23 +0300376 success =
377 ValidateLimitations(root, shaderType, symbolTable, shaderVersion, &mDiagnostics);
alokp@chromium.org07620a52010-09-23 17:53:56 +0000378
Olli Etuaho09b04a22016-12-15 13:30:26 +0000379 bool multiview2 = IsExtensionEnabled(extensionBehavior, "GL_OVR_multiview2");
380 if (success && compileResources.OVR_multiview && IsWebGLBasedSpec(shaderSpec) &&
381 (IsExtensionEnabled(extensionBehavior, "GL_OVR_multiview") || multiview2))
Olli Etuaho01d0ad02017-01-22 14:51:23 -0800382 success = ValidateMultiviewWebGL(root, shaderType, symbolTable, shaderVersion,
383 multiview2, &mDiagnostics);
Olli Etuaho09b04a22016-12-15 13:30:26 +0000384
Jamie Madilld5696192016-10-06 11:09:24 -0400385 // Fail compilation if precision emulation not supported.
386 if (success && getResources().WEBGL_debug_shader_precision &&
387 getPragma().debugShaderPrecision)
388 {
389 if (!EmulatePrecision::SupportedInLanguage(outputType))
390 {
Olli Etuaho77ba4082016-12-16 12:01:18 +0000391 mDiagnostics.globalError("Precision emulation not supported for this output type.");
Jamie Madilld5696192016-10-06 11:09:24 -0400392 success = false;
393 }
394 }
395
zmo@google.com32e97312011-08-24 01:03:11 +0000396 // Built-in function emulation needs to happen after validateLimitations pass.
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200397 if (success)
398 {
Jamie Madill438dbcf2016-06-17 14:20:05 -0400399 // TODO(jmadill): Remove global pool allocator.
400 GetGlobalPoolAllocator()->lock();
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200401 initBuiltInFunctionEmulator(&builtInFunctionEmulator, compileOptions);
Jamie Madill438dbcf2016-06-17 14:20:05 -0400402 GetGlobalPoolAllocator()->unlock();
Olli Etuahodfa75e82017-01-23 09:43:06 -0800403 builtInFunctionEmulator.markBuiltInFunctionsForEmulation(root);
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200404 }
zmo@google.com32e97312011-08-24 01:03:11 +0000405
daniel@transgaming.com4167cc92013-01-11 04:11:53 +0000406 // Clamping uniform array bounds needs to happen after validateLimitations pass.
407 if (success && (compileOptions & SH_CLAMP_INDIRECT_ARRAY_BOUNDS))
408 arrayBoundsClamper.MarkIndirectArrayBoundsForClamping(root);
409
Martin Radev69056a12017-05-18 11:14:50 +0300410 if (success && (compileOptions & SH_INITIALIZE_BUILTINS_FOR_INSTANCED_MULTIVIEW) &&
411 parseContext.isMultiviewExtensionEnabled() && getShaderType() == GL_VERTEX_SHADER)
412 {
413 DeclareAndInitBuiltinsForInstancedMultiview(root, getNumViews());
414 }
415
Ian Ewell924b7de2016-01-21 13:54:28 -0500416 // gl_Position is always written in compatibility output mode
417 if (success && shaderType == GL_VERTEX_SHADER &&
418 ((compileOptions & SH_INIT_GL_POSITION) ||
419 (outputType == SH_GLSL_COMPATIBILITY_OUTPUT)))
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800420 initializeGLPosition(root);
Zhenyao Moac44cd22013-09-23 14:57:09 -0400421
Corentin Wallezd4b50542015-09-28 12:19:26 -0700422 // This pass might emit short circuits so keep it before the short circuit unfolding
423 if (success && (compileOptions & SH_REWRITE_DO_WHILE_LOOPS))
424 RewriteDoWhile(root, getTemporaryIndex());
425
Qiankun Miao09cfac62016-09-06 17:25:16 +0800426 if (success && (compileOptions & SH_ADD_AND_TRUE_TO_LOOP_CONDITION))
427 sh::AddAndTrueToLoopCondition(root);
428
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800429 if (success && (compileOptions & SH_UNFOLD_SHORT_CIRCUIT))
430 {
Zhenyao Mo7cab38b2013-10-15 12:59:30 -0700431 UnfoldShortCircuitAST unfoldShortCircuit;
432 root->traverse(&unfoldShortCircuit);
433 unfoldShortCircuit.updateTree();
434 }
435
Olli Etuaho5c407bb2015-06-01 12:20:39 +0300436 if (success && (compileOptions & SH_REMOVE_POW_WITH_CONSTANT_EXPONENT))
437 {
438 RemovePow(root);
439 }
440
Olli Etuaho4dfe8092015-08-21 17:44:35 +0300441 if (success && shouldCollectVariables(compileOptions))
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800442 {
Olli Etuaho19515012017-06-26 18:00:17 +0300443 ASSERT(!variablesCollected);
444 CollectVariables(root, &attributes, &outputVariables, &uniforms, &varyings,
445 &interfaceBlocks, hashFunction, symbolTable, shaderVersion,
446 extensionBehavior);
447 variablesCollected = true;
Qin Jiajia7835b522016-10-08 11:20:17 +0800448 if (compileOptions & SH_USE_UNUSED_STANDARD_SHARED_BLOCKS)
449 {
450 useAllMembersInUnusedStandardAndSharedBlocks(root);
451 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800452 if (compileOptions & SH_ENFORCE_PACKING_RESTRICTIONS)
453 {
Olli Etuaho19515012017-06-26 18:00:17 +0300454 std::vector<sh::ShaderVariable> expandedUniforms;
455 sh::ExpandUniforms(uniforms, &expandedUniforms);
456 VariablePacker packer;
457 // Returns true if, after applying the packing rules in the GLSL ES 1.00.17 spec
458 // Appendix A, section 7, the shader does not use too many uniforms.
459 success =
460 packer.CheckVariablesWithinPackingLimits(maxUniformVectors, expandedUniforms);
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800461 if (!success)
462 {
Olli Etuaho77ba4082016-12-16 12:01:18 +0000463 mDiagnostics.globalError("too many uniforms");
gman@chromium.org8d804792012-10-17 21:33:48 +0000464 }
465 }
Zhenyao Mo72111912016-07-20 17:45:56 -0700466 if (success && (compileOptions & SH_INIT_OUTPUT_VARIABLES))
467 {
Olli Etuaho27776e32016-07-22 14:00:56 +0300468 initializeOutputVariables(root);
Zhenyao Mo72111912016-07-20 17:45:56 -0700469 }
gman@chromium.org8d804792012-10-17 21:33:48 +0000470 }
zmo@google.comfd747b82011-04-23 01:30:07 +0000471
Yuly Novikov817232e2017-02-22 18:36:10 -0500472 // Removing invariant declarations must be done after collecting variables.
473 // Otherwise, built-in invariant declarations don't apply.
474 if (success && RemoveInvariant(shaderType, shaderVersion, outputType, compileOptions))
475 sh::RemoveInvariantDeclaration(root);
476
Zhenyao Mocd68fe72014-07-11 10:45:44 -0700477 if (success && (compileOptions & SH_SCALARIZE_VEC_AND_MAT_CONSTRUCTOR_ARGS))
478 {
Olli Etuahob990b552016-10-27 12:29:17 +0100479 ScalarizeVecAndMatConstructorArgs(root, shaderType, fragmentPrecisionHigh,
480 &mTemporaryIndex);
Zhenyao Mocd68fe72014-07-11 10:45:44 -0700481 }
482
Zhenyao Moe740add2014-07-18 17:01:01 -0700483 if (success && (compileOptions & SH_REGENERATE_STRUCT_NAMES))
484 {
485 RegenerateStructNames gen(symbolTable, shaderVersion);
486 root->traverse(&gen);
487 }
Olli Etuaho3d932d82016-04-12 11:10:30 +0300488
Zhenyao Mo4e94fea2016-08-09 14:31:37 -0700489 if (success && shaderType == GL_FRAGMENT_SHADER && shaderVersion == 100 &&
490 compileResources.EXT_draw_buffers && compileResources.MaxDrawBuffers > 1 &&
491 IsExtensionEnabled(extensionBehavior, "GL_EXT_draw_buffers"))
492 {
493 EmulateGLFragColorBroadcast(root, compileResources.MaxDrawBuffers, &outputVariables);
494 }
495
Olli Etuaho3d932d82016-04-12 11:10:30 +0300496 if (success)
497 {
Olli Etuaho0ffc4412017-05-19 14:18:55 +0300498 DeferGlobalInitializers(root, needToInitializeGlobalsInAST());
Olli Etuaho3d932d82016-04-12 11:10:30 +0300499 }
Olli Etuaho9733cee2017-05-11 19:14:35 +0300500
501 if (success && (compileOptions & SH_INITIALIZE_UNINITIALIZED_LOCALS) && getOutputType())
502 {
503 // Initialize uninitialized local variables.
504 // In some cases initializing can generate extra statements in the parent block, such as
505 // when initializing nameless structs or initializing arrays in ESSL 1.00. In that case
506 // we need to first simplify loop conditions and separate declarations. If we don't
507 // follow the Appendix A limitations, loop init statements can declare arrays or
508 // nameless structs and have multiple declarations.
509
510 if (!shouldRunLoopAndIndexingValidation(compileOptions))
511 {
512 SimplifyLoopConditions(root,
513 IntermNodePatternMatcher::kMultiDeclaration |
514 IntermNodePatternMatcher::kArrayDeclaration |
515 IntermNodePatternMatcher::kNamelessStructDeclaration,
516 getTemporaryIndex(), getSymbolTable(), getShaderVersion());
517 }
518 // We only really need to separate array declarations and nameless struct declarations,
519 // but it's simpler to just use the regular SeparateDeclarations.
520 SeparateDeclarations(root);
521 InitializeUninitializedLocals(root, getShaderVersion());
522 }
alokp@chromium.org07620a52010-09-23 17:53:56 +0000523 }
524
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200525 if (success)
526 return root;
527
Yunchao Hef81ce4a2017-04-24 10:49:17 +0800528 return nullptr;
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200529}
530
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800531bool TCompiler::compile(const char *const shaderStrings[],
532 size_t numStrings,
533 ShCompileOptions compileOptionsIn)
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200534{
Corentin Wallez28b65282016-06-16 07:24:50 -0700535#if defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
536 DumpFuzzerCase(shaderStrings, numStrings, shaderType, shaderSpec, outputType, compileOptionsIn);
537#endif // defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
538
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200539 if (numStrings == 0)
540 return true;
541
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800542 ShCompileOptions compileOptions = compileOptionsIn;
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700543
544 // Apply key workarounds.
545 if (shouldFlattenPragmaStdglInvariantAll())
546 {
547 // This should be harmless to do in all cases, but for the moment, do it only conditionally.
548 compileOptions |= SH_FLATTEN_PRAGMA_STDGL_INVARIANT_ALL;
549 }
550
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200551 TScopedPoolAllocator scopedAlloc(&allocator);
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100552 TIntermBlock *root = compileTreeImpl(shaderStrings, numStrings, compileOptions);
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200553
554 if (root)
555 {
556 if (compileOptions & SH_INTERMEDIATE_TREE)
557 TIntermediate::outputTree(root, infoSink.info);
558
559 if (compileOptions & SH_OBJECT_CODE)
560 translate(root, compileOptions);
561
562 // The IntermNode tree doesn't need to be deleted here, since the
563 // memory will be freed in a big chunk by the PoolAllocator.
564 return true;
565 }
566 return false;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000567}
568
Nicolas Capens49a88872013-06-20 09:54:03 -0400569bool TCompiler::InitBuiltInSymbolTable(const ShBuiltInResources &resources)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000570{
Olli Etuaho28cb0362016-11-22 15:42:37 +0000571 if (resources.MaxDrawBuffers < 1)
572 {
573 return false;
574 }
575 if (resources.EXT_blend_func_extended && resources.MaxDualSourceDrawBuffers < 1)
576 {
577 return false;
578 }
579
shannon.woods%transgaming.com@gtempaccount.com18b4c4b2013-04-13 03:31:40 +0000580 compileResources = resources;
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400581 setResourceString();
shannonwoods@chromium.org2ac0be92013-05-30 00:02:27 +0000582
Nicolas Capens49a88872013-06-20 09:54:03 -0400583 assert(symbolTable.isEmpty());
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500584 symbolTable.push(); // COMMON_BUILTINS
585 symbolTable.push(); // ESSL1_BUILTINS
586 symbolTable.push(); // ESSL3_BUILTINS
587 symbolTable.push(); // ESSL3_1_BUILTINS
shannonwoods@chromium.org2ac0be92013-05-30 00:02:27 +0000588
Jamie Madillacb4b812016-11-07 13:50:29 -0500589 switch (shaderType)
Nicolas Capens49a88872013-06-20 09:54:03 -0400590 {
Jamie Madillacb4b812016-11-07 13:50:29 -0500591 case GL_FRAGMENT_SHADER:
Olli Etuahocce89652017-06-19 16:04:09 +0300592 symbolTable.setDefaultPrecision(EbtInt, EbpMedium);
Jamie Madillacb4b812016-11-07 13:50:29 -0500593 break;
594 case GL_VERTEX_SHADER:
Olli Etuahocce89652017-06-19 16:04:09 +0300595 symbolTable.setDefaultPrecision(EbtInt, EbpHigh);
596 symbolTable.setDefaultPrecision(EbtFloat, EbpHigh);
Jamie Madillacb4b812016-11-07 13:50:29 -0500597 break;
598 case GL_COMPUTE_SHADER:
Olli Etuahocce89652017-06-19 16:04:09 +0300599 symbolTable.setDefaultPrecision(EbtInt, EbpHigh);
600 symbolTable.setDefaultPrecision(EbtFloat, EbpHigh);
Jamie Madillacb4b812016-11-07 13:50:29 -0500601 break;
602 default:
603 assert(false && "Language not supported");
Nicolas Capens49a88872013-06-20 09:54:03 -0400604 }
Olli Etuaho183d7e22015-11-20 15:59:09 +0200605 // Set defaults for sampler types that have default precision, even those that are
Zhenyao Moa5a1dfc2013-09-23 14:57:03 -0400606 // only available if an extension exists.
Olli Etuaho183d7e22015-11-20 15:59:09 +0200607 // New sampler types in ESSL3 don't have default precision. ESSL1 types do.
608 initSamplerDefaultPrecision(EbtSampler2D);
609 initSamplerDefaultPrecision(EbtSamplerCube);
610 // SamplerExternalOES is specified in the extension to have default precision.
611 initSamplerDefaultPrecision(EbtSamplerExternalOES);
Andrei Volykhina5527072017-03-22 16:46:30 +0300612 // SamplerExternal2DY2YEXT is specified in the extension to have default precision.
613 initSamplerDefaultPrecision(EbtSamplerExternal2DY2YEXT);
Olli Etuaho183d7e22015-11-20 15:59:09 +0200614 // It isn't specified whether Sampler2DRect has default precision.
615 initSamplerDefaultPrecision(EbtSampler2DRect);
Nicolas Capens49a88872013-06-20 09:54:03 -0400616
Olli Etuahocce89652017-06-19 16:04:09 +0300617 symbolTable.setDefaultPrecision(EbtAtomicCounter, EbpHigh);
jchen104cdac9e2017-05-08 11:01:20 +0800618
Jamie Madill1b452142013-07-12 14:51:11 -0400619 InsertBuiltInFunctions(shaderType, shaderSpec, resources, symbolTable);
Nicolas Capens49a88872013-06-20 09:54:03 -0400620
621 IdentifyBuiltIns(shaderType, shaderSpec, resources, symbolTable);
622
623 return true;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000624}
625
Olli Etuaho183d7e22015-11-20 15:59:09 +0200626void TCompiler::initSamplerDefaultPrecision(TBasicType samplerType)
627{
628 ASSERT(samplerType > EbtGuardSamplerBegin && samplerType < EbtGuardSamplerEnd);
Olli Etuahocce89652017-06-19 16:04:09 +0300629 symbolTable.setDefaultPrecision(samplerType, EbpLow);
Olli Etuaho183d7e22015-11-20 15:59:09 +0200630}
631
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400632void TCompiler::setResourceString()
633{
634 std::ostringstream strstream;
Geoff Langb66a9092016-05-16 15:59:14 -0400635
636 // clang-format off
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400637 strstream << ":MaxVertexAttribs:" << compileResources.MaxVertexAttribs
Jamie Madillacb4b812016-11-07 13:50:29 -0500638 << ":MaxVertexUniformVectors:" << compileResources.MaxVertexUniformVectors
639 << ":MaxVaryingVectors:" << compileResources.MaxVaryingVectors
640 << ":MaxVertexTextureImageUnits:" << compileResources.MaxVertexTextureImageUnits
641 << ":MaxCombinedTextureImageUnits:" << compileResources.MaxCombinedTextureImageUnits
642 << ":MaxTextureImageUnits:" << compileResources.MaxTextureImageUnits
643 << ":MaxFragmentUniformVectors:" << compileResources.MaxFragmentUniformVectors
644 << ":MaxDrawBuffers:" << compileResources.MaxDrawBuffers
645 << ":OES_standard_derivatives:" << compileResources.OES_standard_derivatives
646 << ":OES_EGL_image_external:" << compileResources.OES_EGL_image_external
647 << ":OES_EGL_image_external_essl3:" << compileResources.OES_EGL_image_external_essl3
648 << ":NV_EGL_stream_consumer_external:" << compileResources.NV_EGL_stream_consumer_external
649 << ":ARB_texture_rectangle:" << compileResources.ARB_texture_rectangle
650 << ":EXT_draw_buffers:" << compileResources.EXT_draw_buffers
651 << ":FragmentPrecisionHigh:" << compileResources.FragmentPrecisionHigh
652 << ":MaxExpressionComplexity:" << compileResources.MaxExpressionComplexity
653 << ":MaxCallStackDepth:" << compileResources.MaxCallStackDepth
654 << ":MaxFunctionParameters:" << compileResources.MaxFunctionParameters
655 << ":EXT_blend_func_extended:" << compileResources.EXT_blend_func_extended
656 << ":EXT_frag_depth:" << compileResources.EXT_frag_depth
657 << ":EXT_shader_texture_lod:" << compileResources.EXT_shader_texture_lod
658 << ":EXT_shader_framebuffer_fetch:" << compileResources.EXT_shader_framebuffer_fetch
659 << ":NV_shader_framebuffer_fetch:" << compileResources.NV_shader_framebuffer_fetch
660 << ":ARM_shader_framebuffer_fetch:" << compileResources.ARM_shader_framebuffer_fetch
Andrei Volykhina5527072017-03-22 16:46:30 +0300661 << ":EXT_YUV_target:" << compileResources.EXT_YUV_target
Jamie Madillacb4b812016-11-07 13:50:29 -0500662 << ":MaxVertexOutputVectors:" << compileResources.MaxVertexOutputVectors
663 << ":MaxFragmentInputVectors:" << compileResources.MaxFragmentInputVectors
664 << ":MinProgramTexelOffset:" << compileResources.MinProgramTexelOffset
665 << ":MaxProgramTexelOffset:" << compileResources.MaxProgramTexelOffset
666 << ":MaxDualSourceDrawBuffers:" << compileResources.MaxDualSourceDrawBuffers
667 << ":NV_draw_buffers:" << compileResources.NV_draw_buffers
668 << ":WEBGL_debug_shader_precision:" << compileResources.WEBGL_debug_shader_precision
669 << ":MaxImageUnits:" << compileResources.MaxImageUnits
670 << ":MaxVertexImageUniforms:" << compileResources.MaxVertexImageUniforms
671 << ":MaxFragmentImageUniforms:" << compileResources.MaxFragmentImageUniforms
672 << ":MaxComputeImageUniforms:" << compileResources.MaxComputeImageUniforms
673 << ":MaxCombinedImageUniforms:" << compileResources.MaxCombinedImageUniforms
674 << ":MaxCombinedShaderOutputResources:" << compileResources.MaxCombinedShaderOutputResources
675 << ":MaxComputeWorkGroupCountX:" << compileResources.MaxComputeWorkGroupCount[0]
676 << ":MaxComputeWorkGroupCountY:" << compileResources.MaxComputeWorkGroupCount[1]
677 << ":MaxComputeWorkGroupCountZ:" << compileResources.MaxComputeWorkGroupCount[2]
678 << ":MaxComputeWorkGroupSizeX:" << compileResources.MaxComputeWorkGroupSize[0]
679 << ":MaxComputeWorkGroupSizeY:" << compileResources.MaxComputeWorkGroupSize[1]
680 << ":MaxComputeWorkGroupSizeZ:" << compileResources.MaxComputeWorkGroupSize[2]
681 << ":MaxComputeUniformComponents:" << compileResources.MaxComputeUniformComponents
682 << ":MaxComputeTextureImageUnits:" << compileResources.MaxComputeTextureImageUnits
683 << ":MaxComputeAtomicCounters:" << compileResources.MaxComputeAtomicCounters
684 << ":MaxComputeAtomicCounterBuffers:" << compileResources.MaxComputeAtomicCounterBuffers
685 << ":MaxVertexAtomicCounters:" << compileResources.MaxVertexAtomicCounters
686 << ":MaxFragmentAtomicCounters:" << compileResources.MaxFragmentAtomicCounters
687 << ":MaxCombinedAtomicCounters:" << compileResources.MaxCombinedAtomicCounters
688 << ":MaxAtomicCounterBindings:" << compileResources.MaxAtomicCounterBindings
689 << ":MaxVertexAtomicCounterBuffers:" << compileResources.MaxVertexAtomicCounterBuffers
690 << ":MaxFragmentAtomicCounterBuffers:" << compileResources.MaxFragmentAtomicCounterBuffers
691 << ":MaxCombinedAtomicCounterBuffers:" << compileResources.MaxCombinedAtomicCounterBuffers
692 << ":MaxAtomicCounterBufferSize:" << compileResources.MaxAtomicCounterBufferSize;
Geoff Langb66a9092016-05-16 15:59:14 -0400693 // clang-format on
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400694
695 builtInResourcesString = strstream.str();
696}
697
alokp@chromium.org07620a52010-09-23 17:53:56 +0000698void TCompiler::clearResults()
699{
daniel@transgaming.com4167cc92013-01-11 04:11:53 +0000700 arrayBoundsClamper.Cleanup();
alokp@chromium.org07620a52010-09-23 17:53:56 +0000701 infoSink.info.erase();
702 infoSink.obj.erase();
703 infoSink.debug.erase();
Olli Etuaho77ba4082016-12-16 12:01:18 +0000704 mDiagnostics.resetErrorCount();
alokp@chromium.org07620a52010-09-23 17:53:56 +0000705
Jamie Madilled27c722014-07-02 15:31:23 -0400706 attributes.clear();
707 outputVariables.clear();
alokp@chromium.org07620a52010-09-23 17:53:56 +0000708 uniforms.clear();
Zhenyao Mod2d340b2013-09-23 14:57:05 -0400709 varyings.clear();
Jamie Madilled27c722014-07-02 15:31:23 -0400710 interfaceBlocks.clear();
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700711 variablesCollected = false;
zmo@google.coma3b4ab42011-09-16 00:53:26 +0000712
Olli Etuaho09b04a22016-12-15 13:30:26 +0000713 mNumViews = -1;
714
Olli Etuahodfa75e82017-01-23 09:43:06 -0800715 builtInFunctionEmulator.cleanup();
daniel@transgaming.com0aa3b5a2012-11-28 19:43:24 +0000716
717 nameMap.clear();
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200718
Yunchao Hed7297bf2017-04-19 15:27:10 +0800719 mSourcePath = nullptr;
Corentin Wallezd4b50542015-09-28 12:19:26 -0700720 mTemporaryIndex = 0;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000721}
722
Corentin Wallez71d147f2015-02-11 11:15:24 -0800723bool TCompiler::initCallDag(TIntermNode *root)
zmo@google.comb1762df2011-07-30 02:04:23 +0000724{
Corentin Wallez71d147f2015-02-11 11:15:24 -0800725 mCallDag.clear();
726
Olli Etuaho77ba4082016-12-16 12:01:18 +0000727 switch (mCallDag.init(root, &mDiagnostics))
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800728 {
Jamie Madillacb4b812016-11-07 13:50:29 -0500729 case CallDAG::INITDAG_SUCCESS:
730 return true;
731 case CallDAG::INITDAG_RECURSION:
Jamie Madillacb4b812016-11-07 13:50:29 -0500732 case CallDAG::INITDAG_UNDEFINED:
Olli Etuaho77ba4082016-12-16 12:01:18 +0000733 // Error message has already been written out.
734 ASSERT(mDiagnostics.numErrors() > 0);
Jamie Madillacb4b812016-11-07 13:50:29 -0500735 return false;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800736 }
737
738 UNREACHABLE();
739 return true;
740}
741
742bool TCompiler::checkCallDepth()
743{
744 std::vector<int> depths(mCallDag.size());
745
746 for (size_t i = 0; i < mCallDag.size(); i++)
747 {
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500748 int depth = 0;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800749 auto &record = mCallDag.getRecordFromIndex(i);
750
751 for (auto &calleeIndex : record.callees)
752 {
753 depth = std::max(depth, depths[calleeIndex] + 1);
754 }
755
756 depths[i] = depth;
757
758 if (depth >= maxCallStackDepth)
759 {
760 // Trace back the function chain to have a meaningful info log.
Olli Etuaho77ba4082016-12-16 12:01:18 +0000761 std::stringstream errorStream;
762 errorStream << "Call stack too deep (larger than " << maxCallStackDepth
763 << ") with the following call chain: " << record.name;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800764
Cooper Partin4d61f7e2015-08-12 10:56:50 -0700765 int currentFunction = static_cast<int>(i);
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500766 int currentDepth = depth;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800767
768 while (currentFunction != -1)
769 {
Olli Etuaho77ba4082016-12-16 12:01:18 +0000770 errorStream << " -> " << mCallDag.getRecordFromIndex(currentFunction).name;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800771
772 int nextFunction = -1;
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500773 for (auto &calleeIndex : mCallDag.getRecordFromIndex(currentFunction).callees)
Corentin Wallez71d147f2015-02-11 11:15:24 -0800774 {
775 if (depths[calleeIndex] == currentDepth - 1)
776 {
777 currentDepth--;
778 nextFunction = calleeIndex;
779 }
780 }
781
782 currentFunction = nextFunction;
783 }
784
Olli Etuaho77ba4082016-12-16 12:01:18 +0000785 std::string errorStr = errorStream.str();
786 mDiagnostics.globalError(errorStr.c_str());
787
Corentin Wallez71d147f2015-02-11 11:15:24 -0800788 return false;
789 }
790 }
791
792 return true;
793}
794
795bool TCompiler::tagUsedFunctions()
796{
797 // Search from main, starting from the end of the DAG as it usually is the root.
Cooper Partin4d61f7e2015-08-12 10:56:50 -0700798 for (size_t i = mCallDag.size(); i-- > 0;)
Corentin Wallez71d147f2015-02-11 11:15:24 -0800799 {
Olli Etuahoec9232b2017-03-27 17:01:37 +0300800 if (mCallDag.getRecordFromIndex(i).name == "main")
Corentin Wallez71d147f2015-02-11 11:15:24 -0800801 {
802 internalTagUsedFunction(i);
803 return true;
804 }
805 }
806
Olli Etuaho77ba4082016-12-16 12:01:18 +0000807 mDiagnostics.globalError("Missing main()");
Corentin Wallez71d147f2015-02-11 11:15:24 -0800808 return false;
809}
810
811void TCompiler::internalTagUsedFunction(size_t index)
812{
813 if (functionMetadata[index].used)
814 {
815 return;
816 }
817
818 functionMetadata[index].used = true;
819
820 for (int calleeIndex : mCallDag.getRecordFromIndex(index).callees)
821 {
822 internalTagUsedFunction(calleeIndex);
zmo@google.comb1762df2011-07-30 02:04:23 +0000823 }
824}
825
Corentin Walleza094a8a2015-04-07 11:53:06 -0700826// A predicate for the stl that returns if a top-level node is unused
827class TCompiler::UnusedPredicate
828{
829 public:
830 UnusedPredicate(const CallDAG *callDag, const std::vector<FunctionMetadata> *metadatas)
Jamie Madillacb4b812016-11-07 13:50:29 -0500831 : mCallDag(callDag), mMetadatas(metadatas)
Corentin Walleza094a8a2015-04-07 11:53:06 -0700832 {
833 }
834
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500835 bool operator()(TIntermNode *node)
Corentin Walleza094a8a2015-04-07 11:53:06 -0700836 {
Olli Etuaho16c745a2017-01-16 17:02:27 +0000837 const TIntermFunctionPrototype *asFunctionPrototype = node->getAsFunctionPrototypeNode();
838 const TIntermFunctionDefinition *asFunctionDefinition = node->getAsFunctionDefinition();
Corentin Walleza094a8a2015-04-07 11:53:06 -0700839
Olli Etuaho336b1472016-10-05 16:37:55 +0100840 const TFunctionSymbolInfo *functionInfo = nullptr;
841
Olli Etuaho16c745a2017-01-16 17:02:27 +0000842 if (asFunctionDefinition)
Olli Etuaho336b1472016-10-05 16:37:55 +0100843 {
Olli Etuaho16c745a2017-01-16 17:02:27 +0000844 functionInfo = asFunctionDefinition->getFunctionSymbolInfo();
Olli Etuaho336b1472016-10-05 16:37:55 +0100845 }
Olli Etuaho16c745a2017-01-16 17:02:27 +0000846 else if (asFunctionPrototype)
Olli Etuaho336b1472016-10-05 16:37:55 +0100847 {
Olli Etuaho16c745a2017-01-16 17:02:27 +0000848 functionInfo = asFunctionPrototype->getFunctionSymbolInfo();
Olli Etuaho336b1472016-10-05 16:37:55 +0100849 }
850 if (functionInfo == nullptr)
Corentin Walleza094a8a2015-04-07 11:53:06 -0700851 {
852 return false;
853 }
854
Olli Etuaho336b1472016-10-05 16:37:55 +0100855 size_t callDagIndex = mCallDag->findIndex(functionInfo);
Corentin Walleza094a8a2015-04-07 11:53:06 -0700856 if (callDagIndex == CallDAG::InvalidIndex)
857 {
858 // This happens only for unimplemented prototypes which are thus unused
Olli Etuaho16c745a2017-01-16 17:02:27 +0000859 ASSERT(asFunctionPrototype);
Corentin Walleza094a8a2015-04-07 11:53:06 -0700860 return true;
861 }
862
863 ASSERT(callDagIndex < mMetadatas->size());
864 return !(*mMetadatas)[callDagIndex].used;
865 }
866
867 private:
868 const CallDAG *mCallDag;
869 const std::vector<FunctionMetadata> *mMetadatas;
870};
871
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100872bool TCompiler::pruneUnusedFunctions(TIntermBlock *root)
Corentin Walleza094a8a2015-04-07 11:53:06 -0700873{
Corentin Walleza094a8a2015-04-07 11:53:06 -0700874 UnusedPredicate isUnused(&mCallDag, &functionMetadata);
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100875 TIntermSequence *sequence = root->getSequence();
Corentin Wallezb081e782015-07-20 05:40:04 -0700876
877 if (!sequence->empty())
878 {
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500879 sequence->erase(std::remove_if(sequence->begin(), sequence->end(), isUnused),
880 sequence->end());
Corentin Wallezb081e782015-07-20 05:40:04 -0700881 }
Corentin Walleza094a8a2015-04-07 11:53:06 -0700882
883 return true;
884}
885
Olli Etuahob4279202017-05-18 15:08:24 +0300886bool TCompiler::limitExpressionComplexity(TIntermBlock *root)
Jamie Madilleb1a0102013-07-08 13:31:38 -0400887{
Jamie Madillacb4b812016-11-07 13:50:29 -0500888 TMaxDepthTraverser traverser(maxExpressionComplexity + 1);
Jamie Madilleb1a0102013-07-08 13:31:38 -0400889 root->traverse(&traverser);
Jamie Madill6654bc92014-03-26 14:01:57 -0400890
891 if (traverser.getMaxDepth() > maxExpressionComplexity)
892 {
Olli Etuaho77ba4082016-12-16 12:01:18 +0000893 mDiagnostics.globalError("Expression too complex.");
Jamie Madill6654bc92014-03-26 14:01:57 -0400894 return false;
895 }
896
Olli Etuahob4279202017-05-18 15:08:24 +0300897 if (!ValidateMaxParameters(root, maxFunctionParameters))
Olli Etuaho19d1dc92016-03-08 17:18:46 +0200898 {
Olli Etuaho77ba4082016-12-16 12:01:18 +0000899 mDiagnostics.globalError("Function has too many parameters.");
Olli Etuaho19d1dc92016-03-08 17:18:46 +0200900 return false;
901 }
902
Jamie Madilleb1a0102013-07-08 13:31:38 -0400903 return true;
904}
905
Corentin Wallez1df16022016-10-27 08:16:56 -0400906bool TCompiler::shouldCollectVariables(ShCompileOptions compileOptions)
907{
908 return (compileOptions & SH_VARIABLES) != 0;
909}
910
911bool TCompiler::wereVariablesCollected() const
912{
913 return variablesCollected;
914}
915
Olli Etuaho9cbc07c2017-05-10 18:22:01 +0300916void TCompiler::initializeGLPosition(TIntermBlock *root)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800917{
Zhenyao Mo72111912016-07-20 17:45:56 -0700918 InitVariableList list;
919 sh::ShaderVariable var(GL_FLOAT_VEC4, 0);
920 var.name = "gl_Position";
921 list.push_back(var);
Zhenyao Mod7490962016-11-09 15:49:51 -0800922 InitializeVariables(root, list, symbolTable);
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800923}
924
Olli Etuaho9cbc07c2017-05-10 18:22:01 +0300925void TCompiler::useAllMembersInUnusedStandardAndSharedBlocks(TIntermBlock *root)
Qin Jiajia7835b522016-10-08 11:20:17 +0800926{
927 sh::InterfaceBlockList list;
928
929 for (auto block : interfaceBlocks)
930 {
931 if (!block.staticUse &&
932 (block.layout == sh::BLOCKLAYOUT_STANDARD || block.layout == sh::BLOCKLAYOUT_SHARED))
933 {
934 list.push_back(block);
935 }
936 }
937
Zhenyao Mod7490962016-11-09 15:49:51 -0800938 sh::UseInterfaceBlockFields(root, list, symbolTable);
Qin Jiajia7835b522016-10-08 11:20:17 +0800939}
940
Olli Etuaho9cbc07c2017-05-10 18:22:01 +0300941void TCompiler::initializeOutputVariables(TIntermBlock *root)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800942{
Zhenyao Mo72111912016-07-20 17:45:56 -0700943 InitVariableList list;
944 if (shaderType == GL_VERTEX_SHADER)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800945 {
Zhenyao Mo72111912016-07-20 17:45:56 -0700946 for (auto var : varyings)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800947 {
Zhenyao Mof9312682016-07-22 12:51:31 -0700948 list.push_back(var);
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800949 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800950 }
Zhenyao Mo72111912016-07-20 17:45:56 -0700951 else
952 {
953 ASSERT(shaderType == GL_FRAGMENT_SHADER);
954 for (auto var : outputVariables)
955 {
956 list.push_back(var);
957 }
958 }
Zhenyao Mod7490962016-11-09 15:49:51 -0800959 InitializeVariables(root, list, symbolTable);
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800960}
961
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500962const TExtensionBehavior &TCompiler::getExtensionBehavior() const
zmo@google.com5601ea02011-06-10 18:23:25 +0000963{
964 return extensionBehavior;
965}
zmo@google.com32e97312011-08-24 01:03:11 +0000966
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200967const char *TCompiler::getSourcePath() const
968{
969 return mSourcePath;
970}
971
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500972const ShBuiltInResources &TCompiler::getResources() const
shannon.woods%transgaming.com@gtempaccount.com18b4c4b2013-04-13 03:31:40 +0000973{
974 return compileResources;
975}
976
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500977const ArrayBoundsClamper &TCompiler::getArrayBoundsClamper() const
daniel@transgaming.com4167cc92013-01-11 04:11:53 +0000978{
979 return arrayBoundsClamper;
980}
981
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000982ShArrayIndexClampingStrategy TCompiler::getArrayIndexClampingStrategy() const
983{
984 return clampingStrategy;
985}
986
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500987const BuiltInFunctionEmulator &TCompiler::getBuiltInFunctionEmulator() const
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000988{
989 return builtInFunctionEmulator;
990}
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700991
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800992void TCompiler::writePragma(ShCompileOptions compileOptions)
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700993{
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700994 if (!(compileOptions & SH_FLATTEN_PRAGMA_STDGL_INVARIANT_ALL))
995 {
996 TInfoSinkBase &sink = infoSink.obj;
997 if (mPragma.stdgl.invariantAll)
998 sink << "#pragma STDGL invariant(all)\n";
999 }
1000}
1001
1002bool TCompiler::isVaryingDefined(const char *varyingName)
1003{
1004 ASSERT(variablesCollected);
1005 for (size_t ii = 0; ii < varyings.size(); ++ii)
1006 {
1007 if (varyings[ii].name == varyingName)
1008 {
1009 return true;
1010 }
1011 }
1012
1013 return false;
Zhenyao Mo94ac7b72014-10-15 18:22:08 -07001014}
Jamie Madillacb4b812016-11-07 13:50:29 -05001015
1016} // namespace sh