blob: 8a08b7cce89fa04a0d11d1fa7d5c71f694bfddec [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"
Olli Etuaho3d932d82016-04-12 11:10:30 +030016#include "compiler/translator/DeferGlobalInitializers.h"
Zhenyao Mo4e94fea2016-08-09 14:31:37 -070017#include "compiler/translator/EmulateGLFragColorBroadcast.h"
Jamie Madilld5696192016-10-06 11:09:24 -040018#include "compiler/translator/EmulatePrecision.h"
Geoff Lang17732822013-08-29 13:46:49 -040019#include "compiler/translator/Initialize.h"
Zhenyao Mo4a667fe2014-02-11 12:35:01 -080020#include "compiler/translator/InitializeVariables.h"
Olli Etuaho9733cee2017-05-11 19:14:35 +030021#include "compiler/translator/IntermNodePatternMatcher.h"
Jamie Madill6b9cb252013-10-17 10:45:47 -040022#include "compiler/translator/ParseContext.h"
Olli Etuahoc6833112015-04-22 15:15:54 +030023#include "compiler/translator/PruneEmptyDeclarations.h"
Zhenyao Moe740add2014-07-18 17:01:01 -070024#include "compiler/translator/RegenerateStructNames.h"
Qiankun Miao705a9192016-08-29 10:05:27 +080025#include "compiler/translator/RemoveInvariantDeclaration.h"
Olli Etuaho5c407bb2015-06-01 12:20:39 +030026#include "compiler/translator/RemovePow.h"
Corentin Wallezd4b50542015-09-28 12:19:26 -070027#include "compiler/translator/RewriteDoWhile.h"
Zhenyao Mocd68fe72014-07-11 10:45:44 -070028#include "compiler/translator/ScalarizeVecAndMatConstructorArgs.h"
Olli Etuaho9733cee2017-05-11 19:14:35 +030029#include "compiler/translator/SeparateDeclarations.h"
30#include "compiler/translator/SimplifyLoopConditions.h"
Zhenyao Mo7cab38b2013-10-15 12:59:30 -070031#include "compiler/translator/UnfoldShortCircuitAST.h"
Qin Jiajia7835b522016-10-08 11:20:17 +080032#include "compiler/translator/UseInterfaceBlockFields.h"
Geoff Lang17732822013-08-29 13:46:49 -040033#include "compiler/translator/ValidateLimitations.h"
Olli Etuaho19d1dc92016-03-08 17:18:46 +020034#include "compiler/translator/ValidateMaxParameters.h"
Olli Etuaho09b04a22016-12-15 13:30:26 +000035#include "compiler/translator/ValidateMultiviewWebGL.h"
Geoff Lang17732822013-08-29 13:46:49 -040036#include "compiler/translator/ValidateOutputs.h"
37#include "compiler/translator/VariablePacker.h"
shannon.woods@transgaming.comda1ed362013-01-25 21:54:57 +000038#include "third_party/compiler/ArrayBoundsClamper.h"
Corentin Wallez28b65282016-06-16 07:24:50 -070039
Jamie Madillacb4b812016-11-07 13:50:29 -050040namespace sh
41{
42
Corentin Wallez28b65282016-06-16 07:24:50 -070043namespace
44{
45
46#if defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
47void DumpFuzzerCase(char const *const *shaderStrings,
48 size_t numStrings,
49 uint32_t type,
50 uint32_t spec,
51 uint32_t output,
52 uint64_t options)
53{
54 static int fileIndex = 0;
55
56 std::ostringstream o;
57 o << "corpus/" << fileIndex++ << ".sample";
58 std::string s = o.str();
59
60 // Must match the input format of the fuzzer
61 FILE *f = fopen(s.c_str(), "w");
62 fwrite(&type, sizeof(type), 1, f);
63 fwrite(&spec, sizeof(spec), 1, f);
64 fwrite(&output, sizeof(output), 1, f);
65 fwrite(&options, sizeof(options), 1, f);
66
67 char zero[128 - 20] = {0};
68 fwrite(&zero, 128 - 20, 1, f);
69
70 for (size_t i = 0; i < numStrings; i++)
71 {
72 fwrite(shaderStrings[i], sizeof(char), strlen(shaderStrings[i]), f);
73 }
74 fwrite(&zero, 1, 1, f);
75
76 fclose(f);
77}
78#endif // defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
79} // anonymous namespace
80
Jamie Madill5508f392014-02-20 13:31:36 -050081bool IsWebGLBasedSpec(ShShaderSpec spec)
maxvujovic@gmail.com430f5e02012-06-08 17:47:59 +000082{
Qiankun Miaoc2c5fc42016-08-31 15:24:22 +080083 return (spec == SH_WEBGL_SPEC || spec == SH_WEBGL2_SPEC || spec == SH_WEBGL3_SPEC);
maxvujovic@gmail.com430f5e02012-06-08 17:47:59 +000084}
85
Qingqing Dengad0d0792015-04-08 14:25:06 -070086bool IsGLSL130OrNewer(ShShaderOutput output)
87{
Jamie Madillacb4b812016-11-07 13:50:29 -050088 return (output == SH_GLSL_130_OUTPUT || output == SH_GLSL_140_OUTPUT ||
89 output == SH_GLSL_150_CORE_OUTPUT || output == SH_GLSL_330_CORE_OUTPUT ||
90 output == SH_GLSL_400_CORE_OUTPUT || output == SH_GLSL_410_CORE_OUTPUT ||
91 output == SH_GLSL_420_CORE_OUTPUT || output == SH_GLSL_430_CORE_OUTPUT ||
92 output == SH_GLSL_440_CORE_OUTPUT || output == SH_GLSL_450_CORE_OUTPUT);
Qingqing Dengad0d0792015-04-08 14:25:06 -070093}
94
Qiankun Miao705a9192016-08-29 10:05:27 +080095bool IsGLSL420OrNewer(ShShaderOutput output)
96{
Jamie Madillacb4b812016-11-07 13:50:29 -050097 return (output == SH_GLSL_420_CORE_OUTPUT || output == SH_GLSL_430_CORE_OUTPUT ||
98 output == SH_GLSL_440_CORE_OUTPUT || output == SH_GLSL_450_CORE_OUTPUT);
Qiankun Miao705a9192016-08-29 10:05:27 +080099}
100
Zhenyao Mob7bf7422016-11-08 14:44:05 -0800101bool IsGLSL410OrOlder(ShShaderOutput output)
102{
103 return (output == SH_GLSL_130_OUTPUT || output == SH_GLSL_140_OUTPUT ||
104 output == SH_GLSL_150_CORE_OUTPUT || output == SH_GLSL_330_CORE_OUTPUT ||
105 output == SH_GLSL_400_CORE_OUTPUT || output == SH_GLSL_410_CORE_OUTPUT);
106}
107
Qiankun Miao89dd8f32016-11-09 12:59:30 +0000108bool RemoveInvariant(sh::GLenum shaderType,
109 int shaderVersion,
110 ShShaderOutput outputType,
111 ShCompileOptions compileOptions)
112{
113 if ((compileOptions & SH_DONT_REMOVE_INVARIANT_FOR_FRAGMENT_INPUT) == 0 &&
114 shaderType == GL_FRAGMENT_SHADER && IsGLSL420OrNewer(outputType))
115 return true;
116
117 if ((compileOptions & SH_REMOVE_INVARIANT_AND_CENTROID_FOR_ESSL3) != 0 &&
Qiankun Miao41f9f672016-11-16 17:04:36 +0800118 shaderVersion >= 300 && shaderType == GL_VERTEX_SHADER)
Qiankun Miao89dd8f32016-11-09 12:59:30 +0000119 return true;
120
121 return false;
122}
123
Zhenyao Mo7faf1a12014-04-25 18:03:56 -0700124size_t GetGlobalMaxTokenSize(ShShaderSpec spec)
Jamie Madill88f6e942014-02-19 10:27:53 -0500125{
He Yunchao29ab9ff2015-08-06 16:58:30 +0800126 // WebGL defines a max token length of 256, while ES2 leaves max token
Jamie Madill88f6e942014-02-19 10:27:53 -0500127 // size undefined. ES3 defines a max size of 1024 characters.
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700128 switch (spec)
Jamie Madill88f6e942014-02-19 10:27:53 -0500129 {
Jamie Madillacb4b812016-11-07 13:50:29 -0500130 case SH_WEBGL_SPEC:
131 return 256;
132 default:
133 return 1024;
Jamie Madill88f6e942014-02-19 10:27:53 -0500134 }
135}
136
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500137namespace
138{
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700139
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800140class TScopedPoolAllocator
141{
142 public:
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500143 TScopedPoolAllocator(TPoolAllocator *allocator) : mAllocator(allocator)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800144 {
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400145 mAllocator->push();
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000146 SetGlobalPoolAllocator(mAllocator);
147 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800148 ~TScopedPoolAllocator()
149 {
Yunchao Hef81ce4a2017-04-24 10:49:17 +0800150 SetGlobalPoolAllocator(nullptr);
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400151 mAllocator->pop();
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000152 }
153
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800154 private:
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500155 TPoolAllocator *mAllocator;
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400156};
157
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800158class TScopedSymbolTableLevel
159{
160 public:
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500161 TScopedSymbolTableLevel(TSymbolTable *table) : mTable(table)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800162 {
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400163 ASSERT(mTable->atBuiltInLevel());
164 mTable->push();
165 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800166 ~TScopedSymbolTableLevel()
167 {
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400168 while (!mTable->atBuiltInLevel())
169 mTable->pop();
170 }
171
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800172 private:
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500173 TSymbolTable *mTable;
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000174};
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700175
176int MapSpecToShaderVersion(ShShaderSpec spec)
177{
178 switch (spec)
179 {
Jamie Madillacb4b812016-11-07 13:50:29 -0500180 case SH_GLES2_SPEC:
181 case SH_WEBGL_SPEC:
182 return 100;
183 case SH_GLES3_SPEC:
184 case SH_WEBGL2_SPEC:
185 return 300;
186 case SH_GLES3_1_SPEC:
187 case SH_WEBGL3_SPEC:
188 return 310;
189 default:
190 UNREACHABLE();
191 return 0;
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700192 }
193}
194
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000195} // namespace
196
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800197TShHandleBase::TShHandleBase()
198{
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000199 allocator.push();
200 SetGlobalPoolAllocator(&allocator);
201}
202
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800203TShHandleBase::~TShHandleBase()
204{
Yunchao Hef81ce4a2017-04-24 10:49:17 +0800205 SetGlobalPoolAllocator(nullptr);
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000206 allocator.popAll();
207}
208
Jamie Madill183bde52014-07-02 15:31:19 -0400209TCompiler::TCompiler(sh::GLenum type, ShShaderSpec spec, ShShaderOutput output)
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700210 : variablesCollected(false),
211 shaderType(type),
zmo@google.comf420c422011-09-12 18:27:59 +0000212 shaderSpec(spec),
Jamie Madill68fe74a2014-05-27 12:56:01 -0400213 outputType(output),
Jamie Madilleb1a0102013-07-08 13:31:38 -0400214 maxUniformVectors(0),
215 maxExpressionComplexity(0),
216 maxCallStackDepth(0),
Olli Etuaho19d1dc92016-03-08 17:18:46 +0200217 maxFunctionParameters(0),
shannon.woods%transgaming.com@gtempaccount.comcbb6b6a2013-04-13 03:27:47 +0000218 fragmentPrecisionHigh(false),
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000219 clampingStrategy(SH_CLAMP_WITH_CLAMP_INTRINSIC),
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200220 builtInFunctionEmulator(),
Olli Etuaho77ba4082016-12-16 12:01:18 +0000221 mDiagnostics(infoSink.info),
Yunchao Hef81ce4a2017-04-24 10:49:17 +0800222 mSourcePath(nullptr),
Martin Radev802abe02016-08-04 17:48:32 +0300223 mComputeShaderLocalSizeDeclared(false),
Corentin Wallezd4b50542015-09-28 12:19:26 -0700224 mTemporaryIndex(0)
alokp@chromium.org4888ceb2010-10-01 21:13:12 +0000225{
Martin Radev802abe02016-08-04 17:48:32 +0300226 mComputeShaderLocalSize.fill(1);
alokp@chromium.org4888ceb2010-10-01 21:13:12 +0000227}
228
229TCompiler::~TCompiler()
230{
231}
232
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800233bool TCompiler::shouldRunLoopAndIndexingValidation(ShCompileOptions compileOptions) const
Olli Etuaho5d91dda2015-06-18 15:47:46 +0300234{
235 // If compiling an ESSL 1.00 shader for WebGL, or if its been requested through the API,
236 // validate loop and indexing as well (to verify that the shader only uses minimal functionality
237 // of ESSL 1.00 as in Appendix A of the spec).
238 return (IsWebGLBasedSpec(shaderSpec) && shaderVersion == 100) ||
239 (compileOptions & SH_VALIDATE_LOOP_INDEXING);
240}
241
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500242bool TCompiler::Init(const ShBuiltInResources &resources)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000243{
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500244 shaderVersion = 100;
245 maxUniformVectors = (shaderType == GL_VERTEX_SHADER) ? resources.MaxVertexUniformVectors
246 : resources.MaxFragmentUniformVectors;
Jamie Madilleb1a0102013-07-08 13:31:38 -0400247 maxExpressionComplexity = resources.MaxExpressionComplexity;
Olli Etuaho19d1dc92016-03-08 17:18:46 +0200248 maxCallStackDepth = resources.MaxCallStackDepth;
249 maxFunctionParameters = resources.MaxFunctionParameters;
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400250
251 SetGlobalPoolAllocator(&allocator);
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000252
alokp@chromium.org07620a52010-09-23 17:53:56 +0000253 // Generate built-in symbol table.
254 if (!InitBuiltInSymbolTable(resources))
255 return false;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000256 InitExtensionBehavior(resources, extensionBehavior);
shannon.woods%transgaming.com@gtempaccount.comcbb6b6a2013-04-13 03:27:47 +0000257 fragmentPrecisionHigh = resources.FragmentPrecisionHigh == 1;
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000258
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000259 arrayBoundsClamper.SetClampingStrategy(resources.ArrayIndexClampingStrategy);
260 clampingStrategy = resources.ArrayIndexClampingStrategy;
261
daniel@transgaming.comc23f4612012-11-28 19:42:57 +0000262 hashFunction = resources.HashFunction;
263
alokp@chromium.org07620a52010-09-23 17:53:56 +0000264 return true;
265}
266
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100267TIntermBlock *TCompiler::compileTreeForTesting(const char *const shaderStrings[],
268 size_t numStrings,
269 ShCompileOptions compileOptions)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000270{
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200271 return compileTreeImpl(shaderStrings, numStrings, compileOptions);
272}
273
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100274TIntermBlock *TCompiler::compileTreeImpl(const char *const shaderStrings[],
275 size_t numStrings,
276 const ShCompileOptions compileOptions)
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200277{
alokp@chromium.org07620a52010-09-23 17:53:56 +0000278 clearResults();
279
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200280 ASSERT(numStrings > 0);
281 ASSERT(GetGlobalPoolAllocator());
alokp@chromium.org07620a52010-09-23 17:53:56 +0000282
David Yen0fbd1282015-02-02 14:46:09 -0800283 // Reset the extension behavior for each compilation unit.
284 ResetExtensionBehavior(extensionBehavior);
285
apatrick@chromium.org0f4cefe2011-01-26 19:30:57 +0000286 // First string is path of source file if flag is set. The actual source follows.
shannon.woods@transgaming.comd64b3da2013-02-28 23:19:26 +0000287 size_t firstSource = 0;
apatrick@chromium.org0f4cefe2011-01-26 19:30:57 +0000288 if (compileOptions & SH_SOURCE_PATH)
289 {
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200290 mSourcePath = shaderStrings[0];
apatrick@chromium.org0f4cefe2011-01-26 19:30:57 +0000291 ++firstSource;
292 }
293
Olli Etuahof119a262016-08-19 15:54:22 +0300294 TParseContext parseContext(symbolTable, extensionBehavior, shaderType, shaderSpec,
Olli Etuaho77ba4082016-12-16 12:01:18 +0000295 compileOptions, true, &mDiagnostics, getResources());
Olli Etuaho853dc1a2014-11-06 17:25:48 +0200296
Olli Etuahoa6996682015-10-12 14:32:30 +0300297 parseContext.setFragmentPrecisionHighOnESSL1(fragmentPrecisionHigh);
alokp@chromium.org07620a52010-09-23 17:53:56 +0000298
299 // We preserve symbols at the built-in level from compile-to-compile.
300 // Start pushing the user-defined symbols at global level.
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400301 TScopedSymbolTableLevel scopedSymbolLevel(&symbolTable);
alokp@chromium.org07620a52010-09-23 17:53:56 +0000302
303 // Parse shader.
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500304 bool success = (PaParseStrings(numStrings - firstSource, &shaderStrings[firstSource], nullptr,
305 &parseContext) == 0) &&
306 (parseContext.getTreeRoot() != nullptr);
shannon.woods%transgaming.com@gtempaccount.com0bbed382013-04-13 03:38:07 +0000307
shannon.woods%transgaming.com@gtempaccount.com5524db02013-04-13 03:38:16 +0000308 shaderVersion = parseContext.getShaderVersion();
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700309 if (success && MapSpecToShaderVersion(shaderSpec) < shaderVersion)
310 {
Olli Etuaho77ba4082016-12-16 12:01:18 +0000311 mDiagnostics.globalError("unsupported shader version");
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700312 success = false;
313 }
shannon.woods%transgaming.com@gtempaccount.com0bbed382013-04-13 03:38:07 +0000314
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100315 TIntermBlock *root = nullptr;
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200316
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800317 if (success)
318 {
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700319 mPragma = parseContext.pragma();
Kenneth Russell8bad46d2016-07-01 19:52:52 -0700320 symbolTable.setGlobalInvariant(mPragma.stdgl.invariantAll);
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700321
Martin Radev802abe02016-08-04 17:48:32 +0300322 mComputeShaderLocalSizeDeclared = parseContext.isComputeShaderLocalSizeDeclared();
323 mComputeShaderLocalSize = parseContext.getComputeShaderLocalSize();
324
Olli Etuaho09b04a22016-12-15 13:30:26 +0000325 mNumViews = parseContext.getNumViews();
326
Jamie Madill6e06b1f2015-05-14 10:01:17 -0400327 root = parseContext.getTreeRoot();
alokp@chromium.orgb59a7782010-11-24 18:38:33 +0000328
Olli Etuahoa6996682015-10-12 14:32:30 +0300329 // Highp might have been auto-enabled based on shader version
330 fragmentPrecisionHigh = parseContext.getFragmentPrecisionHigh();
331
Olli Etuaho09b04a22016-12-15 13:30:26 +0000332 if (success && (IsWebGLBasedSpec(shaderSpec) &&
333 IsExtensionEnabled(extensionBehavior, "GL_OVR_multiview") &&
334 IsExtensionEnabled(extensionBehavior, "GL_OVR_multiview2")))
335 {
336 // Can't enable both extensions at the same time.
337 mDiagnostics.globalError("Can't enable both OVR_multiview and OVR_multiview2");
338 success = false;
339 }
340
Jamie Madill6654bc92014-03-26 14:01:57 -0400341 // Disallow expressions deemed too complex.
342 if (success && (compileOptions & SH_LIMIT_EXPRESSION_COMPLEXITY))
343 success = limitExpressionComplexity(root);
344
Corentin Wallez71d147f2015-02-11 11:15:24 -0800345 // Create the function DAG and check there is no recursion
zmo@google.comb1762df2011-07-30 02:04:23 +0000346 if (success)
Corentin Wallez71d147f2015-02-11 11:15:24 -0800347 success = initCallDag(root);
348
349 if (success && (compileOptions & SH_LIMIT_CALL_STACK_DEPTH))
350 success = checkCallDepth();
351
352 // Checks which functions are used and if "main" exists
353 if (success)
354 {
355 functionMetadata.clear();
356 functionMetadata.resize(mCallDag.size());
357 success = tagUsedFunctions();
358 }
zmo@google.comb1762df2011-07-30 02:04:23 +0000359
Corentin Walleza094a8a2015-04-07 11:53:06 -0700360 if (success && !(compileOptions & SH_DONT_PRUNE_UNUSED_FUNCTIONS))
361 success = pruneUnusedFunctions(root);
362
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500363 // Prune empty declarations to work around driver bugs and to keep declaration output
364 // simple.
Olli Etuahoc6833112015-04-22 15:15:54 +0300365 if (success)
366 PruneEmptyDeclarations(root);
367
Andrei Volykhin73fa4b82017-05-05 18:45:06 +0300368 if (success && shaderVersion >= 300 && shaderType == GL_FRAGMENT_SHADER)
Jamie Madill05a80ce2013-06-20 11:55:49 -0400369 success = validateOutputs(root);
370
Olli Etuaho5d91dda2015-06-18 15:47:46 +0300371 if (success && shouldRunLoopAndIndexingValidation(compileOptions))
Olli Etuaho9ec79392017-03-31 23:04:23 +0300372 success =
373 ValidateLimitations(root, shaderType, symbolTable, shaderVersion, &mDiagnostics);
alokp@chromium.org07620a52010-09-23 17:53:56 +0000374
Olli Etuaho09b04a22016-12-15 13:30:26 +0000375 bool multiview2 = IsExtensionEnabled(extensionBehavior, "GL_OVR_multiview2");
376 if (success && compileResources.OVR_multiview && IsWebGLBasedSpec(shaderSpec) &&
377 (IsExtensionEnabled(extensionBehavior, "GL_OVR_multiview") || multiview2))
Olli Etuaho01d0ad02017-01-22 14:51:23 -0800378 success = ValidateMultiviewWebGL(root, shaderType, symbolTable, shaderVersion,
379 multiview2, &mDiagnostics);
Olli Etuaho09b04a22016-12-15 13:30:26 +0000380
Jamie Madilld5696192016-10-06 11:09:24 -0400381 // Fail compilation if precision emulation not supported.
382 if (success && getResources().WEBGL_debug_shader_precision &&
383 getPragma().debugShaderPrecision)
384 {
385 if (!EmulatePrecision::SupportedInLanguage(outputType))
386 {
Olli Etuaho77ba4082016-12-16 12:01:18 +0000387 mDiagnostics.globalError("Precision emulation not supported for this output type.");
Jamie Madilld5696192016-10-06 11:09:24 -0400388 success = false;
389 }
390 }
391
zmo@google.com32e97312011-08-24 01:03:11 +0000392 // Built-in function emulation needs to happen after validateLimitations pass.
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200393 if (success)
394 {
Jamie Madill438dbcf2016-06-17 14:20:05 -0400395 // TODO(jmadill): Remove global pool allocator.
396 GetGlobalPoolAllocator()->lock();
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200397 initBuiltInFunctionEmulator(&builtInFunctionEmulator, compileOptions);
Jamie Madill438dbcf2016-06-17 14:20:05 -0400398 GetGlobalPoolAllocator()->unlock();
Olli Etuahodfa75e82017-01-23 09:43:06 -0800399 builtInFunctionEmulator.markBuiltInFunctionsForEmulation(root);
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200400 }
zmo@google.com32e97312011-08-24 01:03:11 +0000401
daniel@transgaming.com4167cc92013-01-11 04:11:53 +0000402 // Clamping uniform array bounds needs to happen after validateLimitations pass.
403 if (success && (compileOptions & SH_CLAMP_INDIRECT_ARRAY_BOUNDS))
404 arrayBoundsClamper.MarkIndirectArrayBoundsForClamping(root);
405
Ian Ewell924b7de2016-01-21 13:54:28 -0500406 // gl_Position is always written in compatibility output mode
407 if (success && shaderType == GL_VERTEX_SHADER &&
408 ((compileOptions & SH_INIT_GL_POSITION) ||
409 (outputType == SH_GLSL_COMPATIBILITY_OUTPUT)))
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800410 initializeGLPosition(root);
Zhenyao Moac44cd22013-09-23 14:57:09 -0400411
Corentin Wallezd4b50542015-09-28 12:19:26 -0700412 // This pass might emit short circuits so keep it before the short circuit unfolding
413 if (success && (compileOptions & SH_REWRITE_DO_WHILE_LOOPS))
414 RewriteDoWhile(root, getTemporaryIndex());
415
Qiankun Miao09cfac62016-09-06 17:25:16 +0800416 if (success && (compileOptions & SH_ADD_AND_TRUE_TO_LOOP_CONDITION))
417 sh::AddAndTrueToLoopCondition(root);
418
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800419 if (success && (compileOptions & SH_UNFOLD_SHORT_CIRCUIT))
420 {
Zhenyao Mo7cab38b2013-10-15 12:59:30 -0700421 UnfoldShortCircuitAST unfoldShortCircuit;
422 root->traverse(&unfoldShortCircuit);
423 unfoldShortCircuit.updateTree();
424 }
425
Olli Etuaho5c407bb2015-06-01 12:20:39 +0300426 if (success && (compileOptions & SH_REMOVE_POW_WITH_CONSTANT_EXPONENT))
427 {
428 RemovePow(root);
429 }
430
Olli Etuaho4dfe8092015-08-21 17:44:35 +0300431 if (success && shouldCollectVariables(compileOptions))
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800432 {
Zhenyao Mo74da9f22013-09-23 14:57:01 -0400433 collectVariables(root);
Qin Jiajia7835b522016-10-08 11:20:17 +0800434 if (compileOptions & SH_USE_UNUSED_STANDARD_SHARED_BLOCKS)
435 {
436 useAllMembersInUnusedStandardAndSharedBlocks(root);
437 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800438 if (compileOptions & SH_ENFORCE_PACKING_RESTRICTIONS)
439 {
gman@chromium.org8d804792012-10-17 21:33:48 +0000440 success = enforcePackingRestrictions();
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800441 if (!success)
442 {
Olli Etuaho77ba4082016-12-16 12:01:18 +0000443 mDiagnostics.globalError("too many uniforms");
gman@chromium.org8d804792012-10-17 21:33:48 +0000444 }
445 }
Zhenyao Mo72111912016-07-20 17:45:56 -0700446 if (success && (compileOptions & SH_INIT_OUTPUT_VARIABLES))
447 {
Olli Etuaho27776e32016-07-22 14:00:56 +0300448 initializeOutputVariables(root);
Zhenyao Mo72111912016-07-20 17:45:56 -0700449 }
gman@chromium.org8d804792012-10-17 21:33:48 +0000450 }
zmo@google.comfd747b82011-04-23 01:30:07 +0000451
Yuly Novikov817232e2017-02-22 18:36:10 -0500452 // Removing invariant declarations must be done after collecting variables.
453 // Otherwise, built-in invariant declarations don't apply.
454 if (success && RemoveInvariant(shaderType, shaderVersion, outputType, compileOptions))
455 sh::RemoveInvariantDeclaration(root);
456
Zhenyao Mocd68fe72014-07-11 10:45:44 -0700457 if (success && (compileOptions & SH_SCALARIZE_VEC_AND_MAT_CONSTRUCTOR_ARGS))
458 {
Olli Etuahob990b552016-10-27 12:29:17 +0100459 ScalarizeVecAndMatConstructorArgs(root, shaderType, fragmentPrecisionHigh,
460 &mTemporaryIndex);
Zhenyao Mocd68fe72014-07-11 10:45:44 -0700461 }
462
Zhenyao Moe740add2014-07-18 17:01:01 -0700463 if (success && (compileOptions & SH_REGENERATE_STRUCT_NAMES))
464 {
465 RegenerateStructNames gen(symbolTable, shaderVersion);
466 root->traverse(&gen);
467 }
Olli Etuaho3d932d82016-04-12 11:10:30 +0300468
Zhenyao Mo4e94fea2016-08-09 14:31:37 -0700469 if (success && shaderType == GL_FRAGMENT_SHADER && shaderVersion == 100 &&
470 compileResources.EXT_draw_buffers && compileResources.MaxDrawBuffers > 1 &&
471 IsExtensionEnabled(extensionBehavior, "GL_EXT_draw_buffers"))
472 {
473 EmulateGLFragColorBroadcast(root, compileResources.MaxDrawBuffers, &outputVariables);
474 }
475
Olli Etuaho3d932d82016-04-12 11:10:30 +0300476 if (success)
477 {
Olli Etuaho0ffc4412017-05-19 14:18:55 +0300478 DeferGlobalInitializers(root, needToInitializeGlobalsInAST());
Olli Etuaho3d932d82016-04-12 11:10:30 +0300479 }
Olli Etuaho9733cee2017-05-11 19:14:35 +0300480
481 if (success && (compileOptions & SH_INITIALIZE_UNINITIALIZED_LOCALS) && getOutputType())
482 {
483 // Initialize uninitialized local variables.
484 // In some cases initializing can generate extra statements in the parent block, such as
485 // when initializing nameless structs or initializing arrays in ESSL 1.00. In that case
486 // we need to first simplify loop conditions and separate declarations. If we don't
487 // follow the Appendix A limitations, loop init statements can declare arrays or
488 // nameless structs and have multiple declarations.
489
490 if (!shouldRunLoopAndIndexingValidation(compileOptions))
491 {
492 SimplifyLoopConditions(root,
493 IntermNodePatternMatcher::kMultiDeclaration |
494 IntermNodePatternMatcher::kArrayDeclaration |
495 IntermNodePatternMatcher::kNamelessStructDeclaration,
496 getTemporaryIndex(), getSymbolTable(), getShaderVersion());
497 }
498 // We only really need to separate array declarations and nameless struct declarations,
499 // but it's simpler to just use the regular SeparateDeclarations.
500 SeparateDeclarations(root);
501 InitializeUninitializedLocals(root, getShaderVersion());
502 }
alokp@chromium.org07620a52010-09-23 17:53:56 +0000503 }
504
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200505 if (success)
506 return root;
507
Yunchao Hef81ce4a2017-04-24 10:49:17 +0800508 return nullptr;
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200509}
510
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800511bool TCompiler::compile(const char *const shaderStrings[],
512 size_t numStrings,
513 ShCompileOptions compileOptionsIn)
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200514{
Corentin Wallez28b65282016-06-16 07:24:50 -0700515#if defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
516 DumpFuzzerCase(shaderStrings, numStrings, shaderType, shaderSpec, outputType, compileOptionsIn);
517#endif // defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
518
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200519 if (numStrings == 0)
520 return true;
521
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800522 ShCompileOptions compileOptions = compileOptionsIn;
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700523
524 // Apply key workarounds.
525 if (shouldFlattenPragmaStdglInvariantAll())
526 {
527 // This should be harmless to do in all cases, but for the moment, do it only conditionally.
528 compileOptions |= SH_FLATTEN_PRAGMA_STDGL_INVARIANT_ALL;
529 }
530
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200531 TScopedPoolAllocator scopedAlloc(&allocator);
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100532 TIntermBlock *root = compileTreeImpl(shaderStrings, numStrings, compileOptions);
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200533
534 if (root)
535 {
536 if (compileOptions & SH_INTERMEDIATE_TREE)
537 TIntermediate::outputTree(root, infoSink.info);
538
539 if (compileOptions & SH_OBJECT_CODE)
540 translate(root, compileOptions);
541
542 // The IntermNode tree doesn't need to be deleted here, since the
543 // memory will be freed in a big chunk by the PoolAllocator.
544 return true;
545 }
546 return false;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000547}
548
Nicolas Capens49a88872013-06-20 09:54:03 -0400549bool TCompiler::InitBuiltInSymbolTable(const ShBuiltInResources &resources)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000550{
Olli Etuaho28cb0362016-11-22 15:42:37 +0000551 if (resources.MaxDrawBuffers < 1)
552 {
553 return false;
554 }
555 if (resources.EXT_blend_func_extended && resources.MaxDualSourceDrawBuffers < 1)
556 {
557 return false;
558 }
559
shannon.woods%transgaming.com@gtempaccount.com18b4c4b2013-04-13 03:31:40 +0000560 compileResources = resources;
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400561 setResourceString();
shannonwoods@chromium.org2ac0be92013-05-30 00:02:27 +0000562
Nicolas Capens49a88872013-06-20 09:54:03 -0400563 assert(symbolTable.isEmpty());
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500564 symbolTable.push(); // COMMON_BUILTINS
565 symbolTable.push(); // ESSL1_BUILTINS
566 symbolTable.push(); // ESSL3_BUILTINS
567 symbolTable.push(); // ESSL3_1_BUILTINS
shannonwoods@chromium.org2ac0be92013-05-30 00:02:27 +0000568
Nicolas Capens49a88872013-06-20 09:54:03 -0400569 TPublicType integer;
Martin Radev2cc85b32016-08-05 16:22:53 +0300570 integer.initializeBasicType(EbtInt);
Nicolas Capens49a88872013-06-20 09:54:03 -0400571
572 TPublicType floatingPoint;
Martin Radev2cc85b32016-08-05 16:22:53 +0300573 floatingPoint.initializeBasicType(EbtFloat);
Nicolas Capens49a88872013-06-20 09:54:03 -0400574
Jamie Madillacb4b812016-11-07 13:50:29 -0500575 switch (shaderType)
Nicolas Capens49a88872013-06-20 09:54:03 -0400576 {
Jamie Madillacb4b812016-11-07 13:50:29 -0500577 case GL_FRAGMENT_SHADER:
578 symbolTable.setDefaultPrecision(integer, EbpMedium);
579 break;
580 case GL_VERTEX_SHADER:
581 symbolTable.setDefaultPrecision(integer, EbpHigh);
582 symbolTable.setDefaultPrecision(floatingPoint, EbpHigh);
583 break;
584 case GL_COMPUTE_SHADER:
585 symbolTable.setDefaultPrecision(integer, EbpHigh);
586 symbolTable.setDefaultPrecision(floatingPoint, EbpHigh);
587 break;
588 default:
589 assert(false && "Language not supported");
Nicolas Capens49a88872013-06-20 09:54:03 -0400590 }
Olli Etuaho183d7e22015-11-20 15:59:09 +0200591 // Set defaults for sampler types that have default precision, even those that are
Zhenyao Moa5a1dfc2013-09-23 14:57:03 -0400592 // only available if an extension exists.
Olli Etuaho183d7e22015-11-20 15:59:09 +0200593 // New sampler types in ESSL3 don't have default precision. ESSL1 types do.
594 initSamplerDefaultPrecision(EbtSampler2D);
595 initSamplerDefaultPrecision(EbtSamplerCube);
596 // SamplerExternalOES is specified in the extension to have default precision.
597 initSamplerDefaultPrecision(EbtSamplerExternalOES);
Andrei Volykhina5527072017-03-22 16:46:30 +0300598 // SamplerExternal2DY2YEXT is specified in the extension to have default precision.
599 initSamplerDefaultPrecision(EbtSamplerExternal2DY2YEXT);
Olli Etuaho183d7e22015-11-20 15:59:09 +0200600 // It isn't specified whether Sampler2DRect has default precision.
601 initSamplerDefaultPrecision(EbtSampler2DRect);
Nicolas Capens49a88872013-06-20 09:54:03 -0400602
Jamie Madill1b452142013-07-12 14:51:11 -0400603 InsertBuiltInFunctions(shaderType, shaderSpec, resources, symbolTable);
Nicolas Capens49a88872013-06-20 09:54:03 -0400604
605 IdentifyBuiltIns(shaderType, shaderSpec, resources, symbolTable);
606
607 return true;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000608}
609
Olli Etuaho183d7e22015-11-20 15:59:09 +0200610void TCompiler::initSamplerDefaultPrecision(TBasicType samplerType)
611{
612 ASSERT(samplerType > EbtGuardSamplerBegin && samplerType < EbtGuardSamplerEnd);
613 TPublicType sampler;
Martin Radev2cc85b32016-08-05 16:22:53 +0300614 sampler.initializeBasicType(samplerType);
Olli Etuaho183d7e22015-11-20 15:59:09 +0200615 symbolTable.setDefaultPrecision(sampler, EbpLow);
616}
617
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400618void TCompiler::setResourceString()
619{
620 std::ostringstream strstream;
Geoff Langb66a9092016-05-16 15:59:14 -0400621
622 // clang-format off
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400623 strstream << ":MaxVertexAttribs:" << compileResources.MaxVertexAttribs
Jamie Madillacb4b812016-11-07 13:50:29 -0500624 << ":MaxVertexUniformVectors:" << compileResources.MaxVertexUniformVectors
625 << ":MaxVaryingVectors:" << compileResources.MaxVaryingVectors
626 << ":MaxVertexTextureImageUnits:" << compileResources.MaxVertexTextureImageUnits
627 << ":MaxCombinedTextureImageUnits:" << compileResources.MaxCombinedTextureImageUnits
628 << ":MaxTextureImageUnits:" << compileResources.MaxTextureImageUnits
629 << ":MaxFragmentUniformVectors:" << compileResources.MaxFragmentUniformVectors
630 << ":MaxDrawBuffers:" << compileResources.MaxDrawBuffers
631 << ":OES_standard_derivatives:" << compileResources.OES_standard_derivatives
632 << ":OES_EGL_image_external:" << compileResources.OES_EGL_image_external
633 << ":OES_EGL_image_external_essl3:" << compileResources.OES_EGL_image_external_essl3
634 << ":NV_EGL_stream_consumer_external:" << compileResources.NV_EGL_stream_consumer_external
635 << ":ARB_texture_rectangle:" << compileResources.ARB_texture_rectangle
636 << ":EXT_draw_buffers:" << compileResources.EXT_draw_buffers
637 << ":FragmentPrecisionHigh:" << compileResources.FragmentPrecisionHigh
638 << ":MaxExpressionComplexity:" << compileResources.MaxExpressionComplexity
639 << ":MaxCallStackDepth:" << compileResources.MaxCallStackDepth
640 << ":MaxFunctionParameters:" << compileResources.MaxFunctionParameters
641 << ":EXT_blend_func_extended:" << compileResources.EXT_blend_func_extended
642 << ":EXT_frag_depth:" << compileResources.EXT_frag_depth
643 << ":EXT_shader_texture_lod:" << compileResources.EXT_shader_texture_lod
644 << ":EXT_shader_framebuffer_fetch:" << compileResources.EXT_shader_framebuffer_fetch
645 << ":NV_shader_framebuffer_fetch:" << compileResources.NV_shader_framebuffer_fetch
646 << ":ARM_shader_framebuffer_fetch:" << compileResources.ARM_shader_framebuffer_fetch
Andrei Volykhina5527072017-03-22 16:46:30 +0300647 << ":EXT_YUV_target:" << compileResources.EXT_YUV_target
Jamie Madillacb4b812016-11-07 13:50:29 -0500648 << ":MaxVertexOutputVectors:" << compileResources.MaxVertexOutputVectors
649 << ":MaxFragmentInputVectors:" << compileResources.MaxFragmentInputVectors
650 << ":MinProgramTexelOffset:" << compileResources.MinProgramTexelOffset
651 << ":MaxProgramTexelOffset:" << compileResources.MaxProgramTexelOffset
652 << ":MaxDualSourceDrawBuffers:" << compileResources.MaxDualSourceDrawBuffers
653 << ":NV_draw_buffers:" << compileResources.NV_draw_buffers
654 << ":WEBGL_debug_shader_precision:" << compileResources.WEBGL_debug_shader_precision
655 << ":MaxImageUnits:" << compileResources.MaxImageUnits
656 << ":MaxVertexImageUniforms:" << compileResources.MaxVertexImageUniforms
657 << ":MaxFragmentImageUniforms:" << compileResources.MaxFragmentImageUniforms
658 << ":MaxComputeImageUniforms:" << compileResources.MaxComputeImageUniforms
659 << ":MaxCombinedImageUniforms:" << compileResources.MaxCombinedImageUniforms
660 << ":MaxCombinedShaderOutputResources:" << compileResources.MaxCombinedShaderOutputResources
661 << ":MaxComputeWorkGroupCountX:" << compileResources.MaxComputeWorkGroupCount[0]
662 << ":MaxComputeWorkGroupCountY:" << compileResources.MaxComputeWorkGroupCount[1]
663 << ":MaxComputeWorkGroupCountZ:" << compileResources.MaxComputeWorkGroupCount[2]
664 << ":MaxComputeWorkGroupSizeX:" << compileResources.MaxComputeWorkGroupSize[0]
665 << ":MaxComputeWorkGroupSizeY:" << compileResources.MaxComputeWorkGroupSize[1]
666 << ":MaxComputeWorkGroupSizeZ:" << compileResources.MaxComputeWorkGroupSize[2]
667 << ":MaxComputeUniformComponents:" << compileResources.MaxComputeUniformComponents
668 << ":MaxComputeTextureImageUnits:" << compileResources.MaxComputeTextureImageUnits
669 << ":MaxComputeAtomicCounters:" << compileResources.MaxComputeAtomicCounters
670 << ":MaxComputeAtomicCounterBuffers:" << compileResources.MaxComputeAtomicCounterBuffers
671 << ":MaxVertexAtomicCounters:" << compileResources.MaxVertexAtomicCounters
672 << ":MaxFragmentAtomicCounters:" << compileResources.MaxFragmentAtomicCounters
673 << ":MaxCombinedAtomicCounters:" << compileResources.MaxCombinedAtomicCounters
674 << ":MaxAtomicCounterBindings:" << compileResources.MaxAtomicCounterBindings
675 << ":MaxVertexAtomicCounterBuffers:" << compileResources.MaxVertexAtomicCounterBuffers
676 << ":MaxFragmentAtomicCounterBuffers:" << compileResources.MaxFragmentAtomicCounterBuffers
677 << ":MaxCombinedAtomicCounterBuffers:" << compileResources.MaxCombinedAtomicCounterBuffers
678 << ":MaxAtomicCounterBufferSize:" << compileResources.MaxAtomicCounterBufferSize;
Geoff Langb66a9092016-05-16 15:59:14 -0400679 // clang-format on
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400680
681 builtInResourcesString = strstream.str();
682}
683
alokp@chromium.org07620a52010-09-23 17:53:56 +0000684void TCompiler::clearResults()
685{
daniel@transgaming.com4167cc92013-01-11 04:11:53 +0000686 arrayBoundsClamper.Cleanup();
alokp@chromium.org07620a52010-09-23 17:53:56 +0000687 infoSink.info.erase();
688 infoSink.obj.erase();
689 infoSink.debug.erase();
Olli Etuaho77ba4082016-12-16 12:01:18 +0000690 mDiagnostics.resetErrorCount();
alokp@chromium.org07620a52010-09-23 17:53:56 +0000691
Jamie Madilled27c722014-07-02 15:31:23 -0400692 attributes.clear();
693 outputVariables.clear();
alokp@chromium.org07620a52010-09-23 17:53:56 +0000694 uniforms.clear();
Jamie Madill23a8a432014-07-09 13:27:42 -0400695 expandedUniforms.clear();
Zhenyao Mod2d340b2013-09-23 14:57:05 -0400696 varyings.clear();
Jamie Madilled27c722014-07-02 15:31:23 -0400697 interfaceBlocks.clear();
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700698 variablesCollected = false;
zmo@google.coma3b4ab42011-09-16 00:53:26 +0000699
Olli Etuaho09b04a22016-12-15 13:30:26 +0000700 mNumViews = -1;
701
Olli Etuahodfa75e82017-01-23 09:43:06 -0800702 builtInFunctionEmulator.cleanup();
daniel@transgaming.com0aa3b5a2012-11-28 19:43:24 +0000703
704 nameMap.clear();
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200705
Yunchao Hed7297bf2017-04-19 15:27:10 +0800706 mSourcePath = nullptr;
Corentin Wallezd4b50542015-09-28 12:19:26 -0700707 mTemporaryIndex = 0;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000708}
709
Corentin Wallez71d147f2015-02-11 11:15:24 -0800710bool TCompiler::initCallDag(TIntermNode *root)
zmo@google.comb1762df2011-07-30 02:04:23 +0000711{
Corentin Wallez71d147f2015-02-11 11:15:24 -0800712 mCallDag.clear();
713
Olli Etuaho77ba4082016-12-16 12:01:18 +0000714 switch (mCallDag.init(root, &mDiagnostics))
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800715 {
Jamie Madillacb4b812016-11-07 13:50:29 -0500716 case CallDAG::INITDAG_SUCCESS:
717 return true;
718 case CallDAG::INITDAG_RECURSION:
Jamie Madillacb4b812016-11-07 13:50:29 -0500719 case CallDAG::INITDAG_UNDEFINED:
Olli Etuaho77ba4082016-12-16 12:01:18 +0000720 // Error message has already been written out.
721 ASSERT(mDiagnostics.numErrors() > 0);
Jamie Madillacb4b812016-11-07 13:50:29 -0500722 return false;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800723 }
724
725 UNREACHABLE();
726 return true;
727}
728
729bool TCompiler::checkCallDepth()
730{
731 std::vector<int> depths(mCallDag.size());
732
733 for (size_t i = 0; i < mCallDag.size(); i++)
734 {
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500735 int depth = 0;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800736 auto &record = mCallDag.getRecordFromIndex(i);
737
738 for (auto &calleeIndex : record.callees)
739 {
740 depth = std::max(depth, depths[calleeIndex] + 1);
741 }
742
743 depths[i] = depth;
744
745 if (depth >= maxCallStackDepth)
746 {
747 // Trace back the function chain to have a meaningful info log.
Olli Etuaho77ba4082016-12-16 12:01:18 +0000748 std::stringstream errorStream;
749 errorStream << "Call stack too deep (larger than " << maxCallStackDepth
750 << ") with the following call chain: " << record.name;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800751
Cooper Partin4d61f7e2015-08-12 10:56:50 -0700752 int currentFunction = static_cast<int>(i);
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500753 int currentDepth = depth;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800754
755 while (currentFunction != -1)
756 {
Olli Etuaho77ba4082016-12-16 12:01:18 +0000757 errorStream << " -> " << mCallDag.getRecordFromIndex(currentFunction).name;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800758
759 int nextFunction = -1;
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500760 for (auto &calleeIndex : mCallDag.getRecordFromIndex(currentFunction).callees)
Corentin Wallez71d147f2015-02-11 11:15:24 -0800761 {
762 if (depths[calleeIndex] == currentDepth - 1)
763 {
764 currentDepth--;
765 nextFunction = calleeIndex;
766 }
767 }
768
769 currentFunction = nextFunction;
770 }
771
Olli Etuaho77ba4082016-12-16 12:01:18 +0000772 std::string errorStr = errorStream.str();
773 mDiagnostics.globalError(errorStr.c_str());
774
Corentin Wallez71d147f2015-02-11 11:15:24 -0800775 return false;
776 }
777 }
778
779 return true;
780}
781
782bool TCompiler::tagUsedFunctions()
783{
784 // Search from main, starting from the end of the DAG as it usually is the root.
Cooper Partin4d61f7e2015-08-12 10:56:50 -0700785 for (size_t i = mCallDag.size(); i-- > 0;)
Corentin Wallez71d147f2015-02-11 11:15:24 -0800786 {
Olli Etuahoec9232b2017-03-27 17:01:37 +0300787 if (mCallDag.getRecordFromIndex(i).name == "main")
Corentin Wallez71d147f2015-02-11 11:15:24 -0800788 {
789 internalTagUsedFunction(i);
790 return true;
791 }
792 }
793
Olli Etuaho77ba4082016-12-16 12:01:18 +0000794 mDiagnostics.globalError("Missing main()");
Corentin Wallez71d147f2015-02-11 11:15:24 -0800795 return false;
796}
797
798void TCompiler::internalTagUsedFunction(size_t index)
799{
800 if (functionMetadata[index].used)
801 {
802 return;
803 }
804
805 functionMetadata[index].used = true;
806
807 for (int calleeIndex : mCallDag.getRecordFromIndex(index).callees)
808 {
809 internalTagUsedFunction(calleeIndex);
zmo@google.comb1762df2011-07-30 02:04:23 +0000810 }
811}
812
Corentin Walleza094a8a2015-04-07 11:53:06 -0700813// A predicate for the stl that returns if a top-level node is unused
814class TCompiler::UnusedPredicate
815{
816 public:
817 UnusedPredicate(const CallDAG *callDag, const std::vector<FunctionMetadata> *metadatas)
Jamie Madillacb4b812016-11-07 13:50:29 -0500818 : mCallDag(callDag), mMetadatas(metadatas)
Corentin Walleza094a8a2015-04-07 11:53:06 -0700819 {
820 }
821
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500822 bool operator()(TIntermNode *node)
Corentin Walleza094a8a2015-04-07 11:53:06 -0700823 {
Olli Etuaho16c745a2017-01-16 17:02:27 +0000824 const TIntermFunctionPrototype *asFunctionPrototype = node->getAsFunctionPrototypeNode();
825 const TIntermFunctionDefinition *asFunctionDefinition = node->getAsFunctionDefinition();
Corentin Walleza094a8a2015-04-07 11:53:06 -0700826
Olli Etuaho336b1472016-10-05 16:37:55 +0100827 const TFunctionSymbolInfo *functionInfo = nullptr;
828
Olli Etuaho16c745a2017-01-16 17:02:27 +0000829 if (asFunctionDefinition)
Olli Etuaho336b1472016-10-05 16:37:55 +0100830 {
Olli Etuaho16c745a2017-01-16 17:02:27 +0000831 functionInfo = asFunctionDefinition->getFunctionSymbolInfo();
Olli Etuaho336b1472016-10-05 16:37:55 +0100832 }
Olli Etuaho16c745a2017-01-16 17:02:27 +0000833 else if (asFunctionPrototype)
Olli Etuaho336b1472016-10-05 16:37:55 +0100834 {
Olli Etuaho16c745a2017-01-16 17:02:27 +0000835 functionInfo = asFunctionPrototype->getFunctionSymbolInfo();
Olli Etuaho336b1472016-10-05 16:37:55 +0100836 }
837 if (functionInfo == nullptr)
Corentin Walleza094a8a2015-04-07 11:53:06 -0700838 {
839 return false;
840 }
841
Olli Etuaho336b1472016-10-05 16:37:55 +0100842 size_t callDagIndex = mCallDag->findIndex(functionInfo);
Corentin Walleza094a8a2015-04-07 11:53:06 -0700843 if (callDagIndex == CallDAG::InvalidIndex)
844 {
845 // This happens only for unimplemented prototypes which are thus unused
Olli Etuaho16c745a2017-01-16 17:02:27 +0000846 ASSERT(asFunctionPrototype);
Corentin Walleza094a8a2015-04-07 11:53:06 -0700847 return true;
848 }
849
850 ASSERT(callDagIndex < mMetadatas->size());
851 return !(*mMetadatas)[callDagIndex].used;
852 }
853
854 private:
855 const CallDAG *mCallDag;
856 const std::vector<FunctionMetadata> *mMetadatas;
857};
858
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100859bool TCompiler::pruneUnusedFunctions(TIntermBlock *root)
Corentin Walleza094a8a2015-04-07 11:53:06 -0700860{
Corentin Walleza094a8a2015-04-07 11:53:06 -0700861 UnusedPredicate isUnused(&mCallDag, &functionMetadata);
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100862 TIntermSequence *sequence = root->getSequence();
Corentin Wallezb081e782015-07-20 05:40:04 -0700863
864 if (!sequence->empty())
865 {
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500866 sequence->erase(std::remove_if(sequence->begin(), sequence->end(), isUnused),
867 sequence->end());
Corentin Wallezb081e782015-07-20 05:40:04 -0700868 }
Corentin Walleza094a8a2015-04-07 11:53:06 -0700869
870 return true;
871}
872
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500873bool TCompiler::validateOutputs(TIntermNode *root)
Jamie Madill05a80ce2013-06-20 11:55:49 -0400874{
Kimmo Kinnunenb18609b2015-07-16 14:13:11 +0300875 ValidateOutputs validateOutputs(getExtensionBehavior(), compileResources.MaxDrawBuffers);
Jamie Madill05a80ce2013-06-20 11:55:49 -0400876 root->traverse(&validateOutputs);
Olli Etuaho77ba4082016-12-16 12:01:18 +0000877 validateOutputs.validate(&mDiagnostics);
878 return (mDiagnostics.numErrors() == 0);
Jamie Madill05a80ce2013-06-20 11:55:49 -0400879}
880
Olli Etuahob4279202017-05-18 15:08:24 +0300881bool TCompiler::limitExpressionComplexity(TIntermBlock *root)
Jamie Madilleb1a0102013-07-08 13:31:38 -0400882{
Jamie Madillacb4b812016-11-07 13:50:29 -0500883 TMaxDepthTraverser traverser(maxExpressionComplexity + 1);
Jamie Madilleb1a0102013-07-08 13:31:38 -0400884 root->traverse(&traverser);
Jamie Madill6654bc92014-03-26 14:01:57 -0400885
886 if (traverser.getMaxDepth() > maxExpressionComplexity)
887 {
Olli Etuaho77ba4082016-12-16 12:01:18 +0000888 mDiagnostics.globalError("Expression too complex.");
Jamie Madill6654bc92014-03-26 14:01:57 -0400889 return false;
890 }
891
Olli Etuahob4279202017-05-18 15:08:24 +0300892 if (!ValidateMaxParameters(root, maxFunctionParameters))
Olli Etuaho19d1dc92016-03-08 17:18:46 +0200893 {
Olli Etuaho77ba4082016-12-16 12:01:18 +0000894 mDiagnostics.globalError("Function has too many parameters.");
Olli Etuaho19d1dc92016-03-08 17:18:46 +0200895 return false;
896 }
897
Jamie Madilleb1a0102013-07-08 13:31:38 -0400898 return true;
899}
900
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500901void TCompiler::collectVariables(TIntermNode *root)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000902{
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700903 if (!variablesCollected)
904 {
905 sh::CollectVariables collect(&attributes, &outputVariables, &uniforms, &varyings,
Jamie Madillacb4b812016-11-07 13:50:29 -0500906 &interfaceBlocks, hashFunction, symbolTable,
907 extensionBehavior);
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700908 root->traverse(&collect);
Jamie Madill23a8a432014-07-09 13:27:42 -0400909
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700910 // This is for enforcePackingRestriction().
911 sh::ExpandUniforms(uniforms, &expandedUniforms);
912 variablesCollected = true;
913 }
alokp@chromium.org07620a52010-09-23 17:53:56 +0000914}
zmo@google.comfd747b82011-04-23 01:30:07 +0000915
Corentin Wallez1df16022016-10-27 08:16:56 -0400916bool TCompiler::shouldCollectVariables(ShCompileOptions compileOptions)
917{
918 return (compileOptions & SH_VARIABLES) != 0;
919}
920
921bool TCompiler::wereVariablesCollected() const
922{
923 return variablesCollected;
924}
925
gman@chromium.org8d804792012-10-17 21:33:48 +0000926bool TCompiler::enforcePackingRestrictions()
927{
928 VariablePacker packer;
Jamie Madill23a8a432014-07-09 13:27:42 -0400929 return packer.CheckVariablesWithinPackingLimits(maxUniformVectors, expandedUniforms);
gman@chromium.org8d804792012-10-17 21:33:48 +0000930}
931
Olli Etuaho9cbc07c2017-05-10 18:22:01 +0300932void TCompiler::initializeGLPosition(TIntermBlock *root)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800933{
Zhenyao Mo72111912016-07-20 17:45:56 -0700934 InitVariableList list;
935 sh::ShaderVariable var(GL_FLOAT_VEC4, 0);
936 var.name = "gl_Position";
937 list.push_back(var);
Zhenyao Mod7490962016-11-09 15:49:51 -0800938 InitializeVariables(root, list, symbolTable);
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800939}
940
Olli Etuaho9cbc07c2017-05-10 18:22:01 +0300941void TCompiler::useAllMembersInUnusedStandardAndSharedBlocks(TIntermBlock *root)
Qin Jiajia7835b522016-10-08 11:20:17 +0800942{
943 sh::InterfaceBlockList list;
944
945 for (auto block : interfaceBlocks)
946 {
947 if (!block.staticUse &&
948 (block.layout == sh::BLOCKLAYOUT_STANDARD || block.layout == sh::BLOCKLAYOUT_SHARED))
949 {
950 list.push_back(block);
951 }
952 }
953
Zhenyao Mod7490962016-11-09 15:49:51 -0800954 sh::UseInterfaceBlockFields(root, list, symbolTable);
Qin Jiajia7835b522016-10-08 11:20:17 +0800955}
956
Olli Etuaho9cbc07c2017-05-10 18:22:01 +0300957void TCompiler::initializeOutputVariables(TIntermBlock *root)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800958{
Zhenyao Mo72111912016-07-20 17:45:56 -0700959 InitVariableList list;
960 if (shaderType == GL_VERTEX_SHADER)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800961 {
Zhenyao Mo72111912016-07-20 17:45:56 -0700962 for (auto var : varyings)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800963 {
Zhenyao Mof9312682016-07-22 12:51:31 -0700964 list.push_back(var);
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800965 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800966 }
Zhenyao Mo72111912016-07-20 17:45:56 -0700967 else
968 {
969 ASSERT(shaderType == GL_FRAGMENT_SHADER);
970 for (auto var : outputVariables)
971 {
972 list.push_back(var);
973 }
974 }
Zhenyao Mod7490962016-11-09 15:49:51 -0800975 InitializeVariables(root, list, symbolTable);
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800976}
977
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500978const TExtensionBehavior &TCompiler::getExtensionBehavior() const
zmo@google.com5601ea02011-06-10 18:23:25 +0000979{
980 return extensionBehavior;
981}
zmo@google.com32e97312011-08-24 01:03:11 +0000982
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200983const char *TCompiler::getSourcePath() const
984{
985 return mSourcePath;
986}
987
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500988const ShBuiltInResources &TCompiler::getResources() const
shannon.woods%transgaming.com@gtempaccount.com18b4c4b2013-04-13 03:31:40 +0000989{
990 return compileResources;
991}
992
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500993const ArrayBoundsClamper &TCompiler::getArrayBoundsClamper() const
daniel@transgaming.com4167cc92013-01-11 04:11:53 +0000994{
995 return arrayBoundsClamper;
996}
997
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000998ShArrayIndexClampingStrategy TCompiler::getArrayIndexClampingStrategy() const
999{
1000 return clampingStrategy;
1001}
1002
Jamie Madilld7b1ab52016-12-12 14:42:19 -05001003const BuiltInFunctionEmulator &TCompiler::getBuiltInFunctionEmulator() const
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +00001004{
1005 return builtInFunctionEmulator;
1006}
Zhenyao Mo94ac7b72014-10-15 18:22:08 -07001007
Qiankun Miao7ebb97f2016-09-08 18:01:50 +08001008void TCompiler::writePragma(ShCompileOptions compileOptions)
Zhenyao Mo94ac7b72014-10-15 18:22:08 -07001009{
Kenneth Russellbccc65d2016-07-19 16:48:43 -07001010 if (!(compileOptions & SH_FLATTEN_PRAGMA_STDGL_INVARIANT_ALL))
1011 {
1012 TInfoSinkBase &sink = infoSink.obj;
1013 if (mPragma.stdgl.invariantAll)
1014 sink << "#pragma STDGL invariant(all)\n";
1015 }
1016}
1017
1018bool TCompiler::isVaryingDefined(const char *varyingName)
1019{
1020 ASSERT(variablesCollected);
1021 for (size_t ii = 0; ii < varyings.size(); ++ii)
1022 {
1023 if (varyings[ii].name == varyingName)
1024 {
1025 return true;
1026 }
1027 }
1028
1029 return false;
Zhenyao Mo94ac7b72014-10-15 18:22:08 -07001030}
Jamie Madillacb4b812016-11-07 13:50:29 -05001031
1032} // namespace sh