blob: 3c2a97548e389e0a297d5c2f2f7476d83827103c [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"
Geoff Lang17732822013-08-29 13:46:49 -040020#include "compiler/translator/InitializeParseContext.h"
Zhenyao Mo4a667fe2014-02-11 12:35:01 -080021#include "compiler/translator/InitializeVariables.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"
Zhenyao Mo7cab38b2013-10-15 12:59:30 -070029#include "compiler/translator/UnfoldShortCircuitAST.h"
Qin Jiajia7835b522016-10-08 11:20:17 +080030#include "compiler/translator/UseInterfaceBlockFields.h"
Geoff Lang17732822013-08-29 13:46:49 -040031#include "compiler/translator/ValidateLimitations.h"
Olli Etuaho19d1dc92016-03-08 17:18:46 +020032#include "compiler/translator/ValidateMaxParameters.h"
Olli Etuaho09b04a22016-12-15 13:30:26 +000033#include "compiler/translator/ValidateMultiviewWebGL.h"
Geoff Lang17732822013-08-29 13:46:49 -040034#include "compiler/translator/ValidateOutputs.h"
35#include "compiler/translator/VariablePacker.h"
shannon.woods@transgaming.comda1ed362013-01-25 21:54:57 +000036#include "third_party/compiler/ArrayBoundsClamper.h"
Corentin Wallez28b65282016-06-16 07:24:50 -070037
Jamie Madillacb4b812016-11-07 13:50:29 -050038namespace sh
39{
40
Corentin Wallez28b65282016-06-16 07:24:50 -070041namespace
42{
43
44#if defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
45void DumpFuzzerCase(char const *const *shaderStrings,
46 size_t numStrings,
47 uint32_t type,
48 uint32_t spec,
49 uint32_t output,
50 uint64_t options)
51{
52 static int fileIndex = 0;
53
54 std::ostringstream o;
55 o << "corpus/" << fileIndex++ << ".sample";
56 std::string s = o.str();
57
58 // Must match the input format of the fuzzer
59 FILE *f = fopen(s.c_str(), "w");
60 fwrite(&type, sizeof(type), 1, f);
61 fwrite(&spec, sizeof(spec), 1, f);
62 fwrite(&output, sizeof(output), 1, f);
63 fwrite(&options, sizeof(options), 1, f);
64
65 char zero[128 - 20] = {0};
66 fwrite(&zero, 128 - 20, 1, f);
67
68 for (size_t i = 0; i < numStrings; i++)
69 {
70 fwrite(shaderStrings[i], sizeof(char), strlen(shaderStrings[i]), f);
71 }
72 fwrite(&zero, 1, 1, f);
73
74 fclose(f);
75}
76#endif // defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
77} // anonymous namespace
78
Jamie Madill5508f392014-02-20 13:31:36 -050079bool IsWebGLBasedSpec(ShShaderSpec spec)
maxvujovic@gmail.com430f5e02012-06-08 17:47:59 +000080{
Qiankun Miaoc2c5fc42016-08-31 15:24:22 +080081 return (spec == SH_WEBGL_SPEC || spec == SH_WEBGL2_SPEC || spec == SH_WEBGL3_SPEC);
maxvujovic@gmail.com430f5e02012-06-08 17:47:59 +000082}
83
Qingqing Dengad0d0792015-04-08 14:25:06 -070084bool IsGLSL130OrNewer(ShShaderOutput output)
85{
Jamie Madillacb4b812016-11-07 13:50:29 -050086 return (output == SH_GLSL_130_OUTPUT || output == SH_GLSL_140_OUTPUT ||
87 output == SH_GLSL_150_CORE_OUTPUT || output == SH_GLSL_330_CORE_OUTPUT ||
88 output == SH_GLSL_400_CORE_OUTPUT || output == SH_GLSL_410_CORE_OUTPUT ||
89 output == SH_GLSL_420_CORE_OUTPUT || output == SH_GLSL_430_CORE_OUTPUT ||
90 output == SH_GLSL_440_CORE_OUTPUT || output == SH_GLSL_450_CORE_OUTPUT);
Qingqing Dengad0d0792015-04-08 14:25:06 -070091}
92
Qiankun Miao705a9192016-08-29 10:05:27 +080093bool IsGLSL420OrNewer(ShShaderOutput output)
94{
Jamie Madillacb4b812016-11-07 13:50:29 -050095 return (output == SH_GLSL_420_CORE_OUTPUT || output == SH_GLSL_430_CORE_OUTPUT ||
96 output == SH_GLSL_440_CORE_OUTPUT || output == SH_GLSL_450_CORE_OUTPUT);
Qiankun Miao705a9192016-08-29 10:05:27 +080097}
98
Zhenyao Mob7bf7422016-11-08 14:44:05 -080099bool IsGLSL410OrOlder(ShShaderOutput output)
100{
101 return (output == SH_GLSL_130_OUTPUT || output == SH_GLSL_140_OUTPUT ||
102 output == SH_GLSL_150_CORE_OUTPUT || output == SH_GLSL_330_CORE_OUTPUT ||
103 output == SH_GLSL_400_CORE_OUTPUT || output == SH_GLSL_410_CORE_OUTPUT);
104}
105
Qiankun Miao89dd8f32016-11-09 12:59:30 +0000106bool RemoveInvariant(sh::GLenum shaderType,
107 int shaderVersion,
108 ShShaderOutput outputType,
109 ShCompileOptions compileOptions)
110{
111 if ((compileOptions & SH_DONT_REMOVE_INVARIANT_FOR_FRAGMENT_INPUT) == 0 &&
112 shaderType == GL_FRAGMENT_SHADER && IsGLSL420OrNewer(outputType))
113 return true;
114
115 if ((compileOptions & SH_REMOVE_INVARIANT_AND_CENTROID_FOR_ESSL3) != 0 &&
Qiankun Miao41f9f672016-11-16 17:04:36 +0800116 shaderVersion >= 300 && shaderType == GL_VERTEX_SHADER)
Qiankun Miao89dd8f32016-11-09 12:59:30 +0000117 return true;
118
119 return false;
120}
121
Zhenyao Mo7faf1a12014-04-25 18:03:56 -0700122size_t GetGlobalMaxTokenSize(ShShaderSpec spec)
Jamie Madill88f6e942014-02-19 10:27:53 -0500123{
He Yunchao29ab9ff2015-08-06 16:58:30 +0800124 // WebGL defines a max token length of 256, while ES2 leaves max token
Jamie Madill88f6e942014-02-19 10:27:53 -0500125 // size undefined. ES3 defines a max size of 1024 characters.
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700126 switch (spec)
Jamie Madill88f6e942014-02-19 10:27:53 -0500127 {
Jamie Madillacb4b812016-11-07 13:50:29 -0500128 case SH_WEBGL_SPEC:
129 return 256;
130 default:
131 return 1024;
Jamie Madill88f6e942014-02-19 10:27:53 -0500132 }
133}
134
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500135namespace
136{
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700137
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800138class TScopedPoolAllocator
139{
140 public:
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500141 TScopedPoolAllocator(TPoolAllocator *allocator) : mAllocator(allocator)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800142 {
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400143 mAllocator->push();
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000144 SetGlobalPoolAllocator(mAllocator);
145 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800146 ~TScopedPoolAllocator()
147 {
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000148 SetGlobalPoolAllocator(NULL);
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400149 mAllocator->pop();
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000150 }
151
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800152 private:
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500153 TPoolAllocator *mAllocator;
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400154};
155
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800156class TScopedSymbolTableLevel
157{
158 public:
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500159 TScopedSymbolTableLevel(TSymbolTable *table) : mTable(table)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800160 {
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400161 ASSERT(mTable->atBuiltInLevel());
162 mTable->push();
163 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800164 ~TScopedSymbolTableLevel()
165 {
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400166 while (!mTable->atBuiltInLevel())
167 mTable->pop();
168 }
169
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800170 private:
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500171 TSymbolTable *mTable;
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000172};
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700173
174int MapSpecToShaderVersion(ShShaderSpec spec)
175{
176 switch (spec)
177 {
Jamie Madillacb4b812016-11-07 13:50:29 -0500178 case SH_GLES2_SPEC:
179 case SH_WEBGL_SPEC:
180 return 100;
181 case SH_GLES3_SPEC:
182 case SH_WEBGL2_SPEC:
183 return 300;
184 case SH_GLES3_1_SPEC:
185 case SH_WEBGL3_SPEC:
186 return 310;
187 default:
188 UNREACHABLE();
189 return 0;
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700190 }
191}
192
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000193} // namespace
194
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800195TShHandleBase::TShHandleBase()
196{
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000197 allocator.push();
198 SetGlobalPoolAllocator(&allocator);
199}
200
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800201TShHandleBase::~TShHandleBase()
202{
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000203 SetGlobalPoolAllocator(NULL);
204 allocator.popAll();
205}
206
Jamie Madill183bde52014-07-02 15:31:19 -0400207TCompiler::TCompiler(sh::GLenum type, ShShaderSpec spec, ShShaderOutput output)
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700208 : variablesCollected(false),
209 shaderType(type),
zmo@google.comf420c422011-09-12 18:27:59 +0000210 shaderSpec(spec),
Jamie Madill68fe74a2014-05-27 12:56:01 -0400211 outputType(output),
Jamie Madilleb1a0102013-07-08 13:31:38 -0400212 maxUniformVectors(0),
213 maxExpressionComplexity(0),
214 maxCallStackDepth(0),
Olli Etuaho19d1dc92016-03-08 17:18:46 +0200215 maxFunctionParameters(0),
shannon.woods%transgaming.com@gtempaccount.comcbb6b6a2013-04-13 03:27:47 +0000216 fragmentPrecisionHigh(false),
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000217 clampingStrategy(SH_CLAMP_WITH_CLAMP_INTRINSIC),
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200218 builtInFunctionEmulator(),
Olli Etuaho77ba4082016-12-16 12:01:18 +0000219 mDiagnostics(infoSink.info),
Corentin Wallezd4b50542015-09-28 12:19:26 -0700220 mSourcePath(NULL),
Martin Radev802abe02016-08-04 17:48:32 +0300221 mComputeShaderLocalSizeDeclared(false),
Corentin Wallezd4b50542015-09-28 12:19:26 -0700222 mTemporaryIndex(0)
alokp@chromium.org4888ceb2010-10-01 21:13:12 +0000223{
Martin Radev802abe02016-08-04 17:48:32 +0300224 mComputeShaderLocalSize.fill(1);
alokp@chromium.org4888ceb2010-10-01 21:13:12 +0000225}
226
227TCompiler::~TCompiler()
228{
229}
230
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800231bool TCompiler::shouldRunLoopAndIndexingValidation(ShCompileOptions compileOptions) const
Olli Etuaho5d91dda2015-06-18 15:47:46 +0300232{
233 // If compiling an ESSL 1.00 shader for WebGL, or if its been requested through the API,
234 // validate loop and indexing as well (to verify that the shader only uses minimal functionality
235 // of ESSL 1.00 as in Appendix A of the spec).
236 return (IsWebGLBasedSpec(shaderSpec) && shaderVersion == 100) ||
237 (compileOptions & SH_VALIDATE_LOOP_INDEXING);
238}
239
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500240bool TCompiler::Init(const ShBuiltInResources &resources)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000241{
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500242 shaderVersion = 100;
243 maxUniformVectors = (shaderType == GL_VERTEX_SHADER) ? resources.MaxVertexUniformVectors
244 : resources.MaxFragmentUniformVectors;
Jamie Madilleb1a0102013-07-08 13:31:38 -0400245 maxExpressionComplexity = resources.MaxExpressionComplexity;
Olli Etuaho19d1dc92016-03-08 17:18:46 +0200246 maxCallStackDepth = resources.MaxCallStackDepth;
247 maxFunctionParameters = resources.MaxFunctionParameters;
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400248
249 SetGlobalPoolAllocator(&allocator);
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000250
alokp@chromium.org07620a52010-09-23 17:53:56 +0000251 // Generate built-in symbol table.
252 if (!InitBuiltInSymbolTable(resources))
253 return false;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000254 InitExtensionBehavior(resources, extensionBehavior);
shannon.woods%transgaming.com@gtempaccount.comcbb6b6a2013-04-13 03:27:47 +0000255 fragmentPrecisionHigh = resources.FragmentPrecisionHigh == 1;
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000256
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000257 arrayBoundsClamper.SetClampingStrategy(resources.ArrayIndexClampingStrategy);
258 clampingStrategy = resources.ArrayIndexClampingStrategy;
259
daniel@transgaming.comc23f4612012-11-28 19:42:57 +0000260 hashFunction = resources.HashFunction;
261
alokp@chromium.org07620a52010-09-23 17:53:56 +0000262 return true;
263}
264
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100265TIntermBlock *TCompiler::compileTreeForTesting(const char *const shaderStrings[],
266 size_t numStrings,
267 ShCompileOptions compileOptions)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000268{
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200269 return compileTreeImpl(shaderStrings, numStrings, compileOptions);
270}
271
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100272TIntermBlock *TCompiler::compileTreeImpl(const char *const shaderStrings[],
273 size_t numStrings,
274 const ShCompileOptions compileOptions)
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200275{
alokp@chromium.org07620a52010-09-23 17:53:56 +0000276 clearResults();
277
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200278 ASSERT(numStrings > 0);
279 ASSERT(GetGlobalPoolAllocator());
alokp@chromium.org07620a52010-09-23 17:53:56 +0000280
David Yen0fbd1282015-02-02 14:46:09 -0800281 // Reset the extension behavior for each compilation unit.
282 ResetExtensionBehavior(extensionBehavior);
283
apatrick@chromium.org0f4cefe2011-01-26 19:30:57 +0000284 // First string is path of source file if flag is set. The actual source follows.
shannon.woods@transgaming.comd64b3da2013-02-28 23:19:26 +0000285 size_t firstSource = 0;
apatrick@chromium.org0f4cefe2011-01-26 19:30:57 +0000286 if (compileOptions & SH_SOURCE_PATH)
287 {
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200288 mSourcePath = shaderStrings[0];
apatrick@chromium.org0f4cefe2011-01-26 19:30:57 +0000289 ++firstSource;
290 }
291
Olli Etuahof119a262016-08-19 15:54:22 +0300292 TParseContext parseContext(symbolTable, extensionBehavior, shaderType, shaderSpec,
Olli Etuaho77ba4082016-12-16 12:01:18 +0000293 compileOptions, true, &mDiagnostics, getResources());
Olli Etuaho853dc1a2014-11-06 17:25:48 +0200294
Olli Etuahoa6996682015-10-12 14:32:30 +0300295 parseContext.setFragmentPrecisionHighOnESSL1(fragmentPrecisionHigh);
Alok Priyadarshi8156b6b2013-09-23 14:56:58 -0400296 SetGlobalParseContext(&parseContext);
alokp@chromium.org07620a52010-09-23 17:53:56 +0000297
298 // We preserve symbols at the built-in level from compile-to-compile.
299 // Start pushing the user-defined symbols at global level.
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400300 TScopedSymbolTableLevel scopedSymbolLevel(&symbolTable);
alokp@chromium.org07620a52010-09-23 17:53:56 +0000301
302 // Parse shader.
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500303 bool success = (PaParseStrings(numStrings - firstSource, &shaderStrings[firstSource], nullptr,
304 &parseContext) == 0) &&
305 (parseContext.getTreeRoot() != nullptr);
shannon.woods%transgaming.com@gtempaccount.com0bbed382013-04-13 03:38:07 +0000306
shannon.woods%transgaming.com@gtempaccount.com5524db02013-04-13 03:38:16 +0000307 shaderVersion = parseContext.getShaderVersion();
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700308 if (success && MapSpecToShaderVersion(shaderSpec) < shaderVersion)
309 {
Olli Etuaho77ba4082016-12-16 12:01:18 +0000310 mDiagnostics.globalError("unsupported shader version");
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700311 success = false;
312 }
shannon.woods%transgaming.com@gtempaccount.com0bbed382013-04-13 03:38:07 +0000313
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100314 TIntermBlock *root = nullptr;
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200315
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800316 if (success)
317 {
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700318 mPragma = parseContext.pragma();
Kenneth Russell8bad46d2016-07-01 19:52:52 -0700319 symbolTable.setGlobalInvariant(mPragma.stdgl.invariantAll);
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700320
Martin Radev802abe02016-08-04 17:48:32 +0300321 mComputeShaderLocalSizeDeclared = parseContext.isComputeShaderLocalSizeDeclared();
322 mComputeShaderLocalSize = parseContext.getComputeShaderLocalSize();
323
Olli Etuaho09b04a22016-12-15 13:30:26 +0000324 mNumViews = parseContext.getNumViews();
325
Jamie Madill6e06b1f2015-05-14 10:01:17 -0400326 root = parseContext.getTreeRoot();
alokp@chromium.orgb59a7782010-11-24 18:38:33 +0000327
Olli Etuahoa6996682015-10-12 14:32:30 +0300328 // Highp might have been auto-enabled based on shader version
329 fragmentPrecisionHigh = parseContext.getFragmentPrecisionHigh();
330
Olli Etuaho09b04a22016-12-15 13:30:26 +0000331 if (success && (IsWebGLBasedSpec(shaderSpec) &&
332 IsExtensionEnabled(extensionBehavior, "GL_OVR_multiview") &&
333 IsExtensionEnabled(extensionBehavior, "GL_OVR_multiview2")))
334 {
335 // Can't enable both extensions at the same time.
336 mDiagnostics.globalError("Can't enable both OVR_multiview and OVR_multiview2");
337 success = false;
338 }
339
Jamie Madill6654bc92014-03-26 14:01:57 -0400340 // Disallow expressions deemed too complex.
341 if (success && (compileOptions & SH_LIMIT_EXPRESSION_COMPLEXITY))
342 success = limitExpressionComplexity(root);
343
Corentin Wallez71d147f2015-02-11 11:15:24 -0800344 // Create the function DAG and check there is no recursion
zmo@google.comb1762df2011-07-30 02:04:23 +0000345 if (success)
Corentin Wallez71d147f2015-02-11 11:15:24 -0800346 success = initCallDag(root);
347
348 if (success && (compileOptions & SH_LIMIT_CALL_STACK_DEPTH))
349 success = checkCallDepth();
350
351 // Checks which functions are used and if "main" exists
352 if (success)
353 {
354 functionMetadata.clear();
355 functionMetadata.resize(mCallDag.size());
356 success = tagUsedFunctions();
357 }
zmo@google.comb1762df2011-07-30 02:04:23 +0000358
Corentin Walleza094a8a2015-04-07 11:53:06 -0700359 if (success && !(compileOptions & SH_DONT_PRUNE_UNUSED_FUNCTIONS))
360 success = pruneUnusedFunctions(root);
361
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500362 // Prune empty declarations to work around driver bugs and to keep declaration output
363 // simple.
Olli Etuahoc6833112015-04-22 15:15:54 +0300364 if (success)
365 PruneEmptyDeclarations(root);
366
Jamie Madill183bde52014-07-02 15:31:19 -0400367 if (success && shaderVersion == 300 && shaderType == GL_FRAGMENT_SHADER)
Jamie Madill05a80ce2013-06-20 11:55:49 -0400368 success = validateOutputs(root);
369
Olli Etuaho5d91dda2015-06-18 15:47:46 +0300370 if (success && shouldRunLoopAndIndexingValidation(compileOptions))
alokp@chromium.orgb59a7782010-11-24 18:38:33 +0000371 success = validateLimitations(root);
alokp@chromium.org07620a52010-09-23 17:53:56 +0000372
Olli Etuaho09b04a22016-12-15 13:30:26 +0000373 bool multiview2 = IsExtensionEnabled(extensionBehavior, "GL_OVR_multiview2");
374 if (success && compileResources.OVR_multiview && IsWebGLBasedSpec(shaderSpec) &&
375 (IsExtensionEnabled(extensionBehavior, "GL_OVR_multiview") || multiview2))
Olli Etuaho01d0ad02017-01-22 14:51:23 -0800376 success = ValidateMultiviewWebGL(root, shaderType, symbolTable, shaderVersion,
377 multiview2, &mDiagnostics);
Olli Etuaho09b04a22016-12-15 13:30:26 +0000378
Jamie Madilld5696192016-10-06 11:09:24 -0400379 // Fail compilation if precision emulation not supported.
380 if (success && getResources().WEBGL_debug_shader_precision &&
381 getPragma().debugShaderPrecision)
382 {
383 if (!EmulatePrecision::SupportedInLanguage(outputType))
384 {
Olli Etuaho77ba4082016-12-16 12:01:18 +0000385 mDiagnostics.globalError("Precision emulation not supported for this output type.");
Jamie Madilld5696192016-10-06 11:09:24 -0400386 success = false;
387 }
388 }
389
zmo@google.com32e97312011-08-24 01:03:11 +0000390 // Built-in function emulation needs to happen after validateLimitations pass.
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200391 if (success)
392 {
Jamie Madill438dbcf2016-06-17 14:20:05 -0400393 // TODO(jmadill): Remove global pool allocator.
394 GetGlobalPoolAllocator()->lock();
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200395 initBuiltInFunctionEmulator(&builtInFunctionEmulator, compileOptions);
Jamie Madill438dbcf2016-06-17 14:20:05 -0400396 GetGlobalPoolAllocator()->unlock();
Olli Etuahodfa75e82017-01-23 09:43:06 -0800397 builtInFunctionEmulator.markBuiltInFunctionsForEmulation(root);
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200398 }
zmo@google.com32e97312011-08-24 01:03:11 +0000399
daniel@transgaming.com4167cc92013-01-11 04:11:53 +0000400 // Clamping uniform array bounds needs to happen after validateLimitations pass.
401 if (success && (compileOptions & SH_CLAMP_INDIRECT_ARRAY_BOUNDS))
402 arrayBoundsClamper.MarkIndirectArrayBoundsForClamping(root);
403
Ian Ewell924b7de2016-01-21 13:54:28 -0500404 // gl_Position is always written in compatibility output mode
405 if (success && shaderType == GL_VERTEX_SHADER &&
406 ((compileOptions & SH_INIT_GL_POSITION) ||
407 (outputType == SH_GLSL_COMPATIBILITY_OUTPUT)))
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800408 initializeGLPosition(root);
Zhenyao Moac44cd22013-09-23 14:57:09 -0400409
Qiankun Miao89dd8f32016-11-09 12:59:30 +0000410 if (success && RemoveInvariant(shaderType, shaderVersion, outputType, compileOptions))
Qiankun Miao705a9192016-08-29 10:05:27 +0800411 sh::RemoveInvariantDeclaration(root);
412
Corentin Wallezd4b50542015-09-28 12:19:26 -0700413 // This pass might emit short circuits so keep it before the short circuit unfolding
414 if (success && (compileOptions & SH_REWRITE_DO_WHILE_LOOPS))
415 RewriteDoWhile(root, getTemporaryIndex());
416
Qiankun Miao09cfac62016-09-06 17:25:16 +0800417 if (success && (compileOptions & SH_ADD_AND_TRUE_TO_LOOP_CONDITION))
418 sh::AddAndTrueToLoopCondition(root);
419
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800420 if (success && (compileOptions & SH_UNFOLD_SHORT_CIRCUIT))
421 {
Zhenyao Mo7cab38b2013-10-15 12:59:30 -0700422 UnfoldShortCircuitAST unfoldShortCircuit;
423 root->traverse(&unfoldShortCircuit);
424 unfoldShortCircuit.updateTree();
425 }
426
Olli Etuaho5c407bb2015-06-01 12:20:39 +0300427 if (success && (compileOptions & SH_REMOVE_POW_WITH_CONSTANT_EXPONENT))
428 {
429 RemovePow(root);
430 }
431
Olli Etuaho4dfe8092015-08-21 17:44:35 +0300432 if (success && shouldCollectVariables(compileOptions))
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800433 {
Zhenyao Mo74da9f22013-09-23 14:57:01 -0400434 collectVariables(root);
Qin Jiajia7835b522016-10-08 11:20:17 +0800435 if (compileOptions & SH_USE_UNUSED_STANDARD_SHARED_BLOCKS)
436 {
437 useAllMembersInUnusedStandardAndSharedBlocks(root);
438 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800439 if (compileOptions & SH_ENFORCE_PACKING_RESTRICTIONS)
440 {
gman@chromium.org8d804792012-10-17 21:33:48 +0000441 success = enforcePackingRestrictions();
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800442 if (!success)
443 {
Olli Etuaho77ba4082016-12-16 12:01:18 +0000444 mDiagnostics.globalError("too many uniforms");
gman@chromium.org8d804792012-10-17 21:33:48 +0000445 }
446 }
Zhenyao Mo72111912016-07-20 17:45:56 -0700447 if (success && (compileOptions & SH_INIT_OUTPUT_VARIABLES))
448 {
Olli Etuaho27776e32016-07-22 14:00:56 +0300449 initializeOutputVariables(root);
Zhenyao Mo72111912016-07-20 17:45:56 -0700450 }
gman@chromium.org8d804792012-10-17 21:33:48 +0000451 }
zmo@google.comfd747b82011-04-23 01:30:07 +0000452
Zhenyao Mocd68fe72014-07-11 10:45:44 -0700453 if (success && (compileOptions & SH_SCALARIZE_VEC_AND_MAT_CONSTRUCTOR_ARGS))
454 {
Olli Etuahob990b552016-10-27 12:29:17 +0100455 ScalarizeVecAndMatConstructorArgs(root, shaderType, fragmentPrecisionHigh,
456 &mTemporaryIndex);
Zhenyao Mocd68fe72014-07-11 10:45:44 -0700457 }
458
Zhenyao Moe740add2014-07-18 17:01:01 -0700459 if (success && (compileOptions & SH_REGENERATE_STRUCT_NAMES))
460 {
461 RegenerateStructNames gen(symbolTable, shaderVersion);
462 root->traverse(&gen);
463 }
Olli Etuaho3d932d82016-04-12 11:10:30 +0300464
Zhenyao Mo4e94fea2016-08-09 14:31:37 -0700465 if (success && shaderType == GL_FRAGMENT_SHADER && shaderVersion == 100 &&
466 compileResources.EXT_draw_buffers && compileResources.MaxDrawBuffers > 1 &&
467 IsExtensionEnabled(extensionBehavior, "GL_EXT_draw_buffers"))
468 {
469 EmulateGLFragColorBroadcast(root, compileResources.MaxDrawBuffers, &outputVariables);
470 }
471
Olli Etuaho3d932d82016-04-12 11:10:30 +0300472 if (success)
473 {
474 DeferGlobalInitializers(root);
475 }
alokp@chromium.org07620a52010-09-23 17:53:56 +0000476 }
477
Zhenyao Mo7faf1a12014-04-25 18:03:56 -0700478 SetGlobalParseContext(NULL);
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200479 if (success)
480 return root;
481
482 return NULL;
483}
484
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800485bool TCompiler::compile(const char *const shaderStrings[],
486 size_t numStrings,
487 ShCompileOptions compileOptionsIn)
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200488{
Corentin Wallez28b65282016-06-16 07:24:50 -0700489#if defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
490 DumpFuzzerCase(shaderStrings, numStrings, shaderType, shaderSpec, outputType, compileOptionsIn);
491#endif // defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
492
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200493 if (numStrings == 0)
494 return true;
495
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800496 ShCompileOptions compileOptions = compileOptionsIn;
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700497
498 // Apply key workarounds.
499 if (shouldFlattenPragmaStdglInvariantAll())
500 {
501 // This should be harmless to do in all cases, but for the moment, do it only conditionally.
502 compileOptions |= SH_FLATTEN_PRAGMA_STDGL_INVARIANT_ALL;
503 }
504
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200505 TScopedPoolAllocator scopedAlloc(&allocator);
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100506 TIntermBlock *root = compileTreeImpl(shaderStrings, numStrings, compileOptions);
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200507
508 if (root)
509 {
510 if (compileOptions & SH_INTERMEDIATE_TREE)
511 TIntermediate::outputTree(root, infoSink.info);
512
513 if (compileOptions & SH_OBJECT_CODE)
514 translate(root, compileOptions);
515
516 // The IntermNode tree doesn't need to be deleted here, since the
517 // memory will be freed in a big chunk by the PoolAllocator.
518 return true;
519 }
520 return false;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000521}
522
Nicolas Capens49a88872013-06-20 09:54:03 -0400523bool TCompiler::InitBuiltInSymbolTable(const ShBuiltInResources &resources)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000524{
Olli Etuaho28cb0362016-11-22 15:42:37 +0000525 if (resources.MaxDrawBuffers < 1)
526 {
527 return false;
528 }
529 if (resources.EXT_blend_func_extended && resources.MaxDualSourceDrawBuffers < 1)
530 {
531 return false;
532 }
533
shannon.woods%transgaming.com@gtempaccount.com18b4c4b2013-04-13 03:31:40 +0000534 compileResources = resources;
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400535 setResourceString();
shannonwoods@chromium.org2ac0be92013-05-30 00:02:27 +0000536
Nicolas Capens49a88872013-06-20 09:54:03 -0400537 assert(symbolTable.isEmpty());
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500538 symbolTable.push(); // COMMON_BUILTINS
539 symbolTable.push(); // ESSL1_BUILTINS
540 symbolTable.push(); // ESSL3_BUILTINS
541 symbolTable.push(); // ESSL3_1_BUILTINS
shannonwoods@chromium.org2ac0be92013-05-30 00:02:27 +0000542
Nicolas Capens49a88872013-06-20 09:54:03 -0400543 TPublicType integer;
Martin Radev2cc85b32016-08-05 16:22:53 +0300544 integer.initializeBasicType(EbtInt);
Nicolas Capens49a88872013-06-20 09:54:03 -0400545
546 TPublicType floatingPoint;
Martin Radev2cc85b32016-08-05 16:22:53 +0300547 floatingPoint.initializeBasicType(EbtFloat);
Nicolas Capens49a88872013-06-20 09:54:03 -0400548
Jamie Madillacb4b812016-11-07 13:50:29 -0500549 switch (shaderType)
Nicolas Capens49a88872013-06-20 09:54:03 -0400550 {
Jamie Madillacb4b812016-11-07 13:50:29 -0500551 case GL_FRAGMENT_SHADER:
552 symbolTable.setDefaultPrecision(integer, EbpMedium);
553 break;
554 case GL_VERTEX_SHADER:
555 symbolTable.setDefaultPrecision(integer, EbpHigh);
556 symbolTable.setDefaultPrecision(floatingPoint, EbpHigh);
557 break;
558 case GL_COMPUTE_SHADER:
559 symbolTable.setDefaultPrecision(integer, EbpHigh);
560 symbolTable.setDefaultPrecision(floatingPoint, EbpHigh);
561 break;
562 default:
563 assert(false && "Language not supported");
Nicolas Capens49a88872013-06-20 09:54:03 -0400564 }
Olli Etuaho183d7e22015-11-20 15:59:09 +0200565 // Set defaults for sampler types that have default precision, even those that are
Zhenyao Moa5a1dfc2013-09-23 14:57:03 -0400566 // only available if an extension exists.
Olli Etuaho183d7e22015-11-20 15:59:09 +0200567 // New sampler types in ESSL3 don't have default precision. ESSL1 types do.
568 initSamplerDefaultPrecision(EbtSampler2D);
569 initSamplerDefaultPrecision(EbtSamplerCube);
570 // SamplerExternalOES is specified in the extension to have default precision.
571 initSamplerDefaultPrecision(EbtSamplerExternalOES);
572 // It isn't specified whether Sampler2DRect has default precision.
573 initSamplerDefaultPrecision(EbtSampler2DRect);
Nicolas Capens49a88872013-06-20 09:54:03 -0400574
Jamie Madill1b452142013-07-12 14:51:11 -0400575 InsertBuiltInFunctions(shaderType, shaderSpec, resources, symbolTable);
Nicolas Capens49a88872013-06-20 09:54:03 -0400576
577 IdentifyBuiltIns(shaderType, shaderSpec, resources, symbolTable);
578
579 return true;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000580}
581
Olli Etuaho183d7e22015-11-20 15:59:09 +0200582void TCompiler::initSamplerDefaultPrecision(TBasicType samplerType)
583{
584 ASSERT(samplerType > EbtGuardSamplerBegin && samplerType < EbtGuardSamplerEnd);
585 TPublicType sampler;
Martin Radev2cc85b32016-08-05 16:22:53 +0300586 sampler.initializeBasicType(samplerType);
Olli Etuaho183d7e22015-11-20 15:59:09 +0200587 symbolTable.setDefaultPrecision(sampler, EbpLow);
588}
589
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400590void TCompiler::setResourceString()
591{
592 std::ostringstream strstream;
Geoff Langb66a9092016-05-16 15:59:14 -0400593
594 // clang-format off
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400595 strstream << ":MaxVertexAttribs:" << compileResources.MaxVertexAttribs
Jamie Madillacb4b812016-11-07 13:50:29 -0500596 << ":MaxVertexUniformVectors:" << compileResources.MaxVertexUniformVectors
597 << ":MaxVaryingVectors:" << compileResources.MaxVaryingVectors
598 << ":MaxVertexTextureImageUnits:" << compileResources.MaxVertexTextureImageUnits
599 << ":MaxCombinedTextureImageUnits:" << compileResources.MaxCombinedTextureImageUnits
600 << ":MaxTextureImageUnits:" << compileResources.MaxTextureImageUnits
601 << ":MaxFragmentUniformVectors:" << compileResources.MaxFragmentUniformVectors
602 << ":MaxDrawBuffers:" << compileResources.MaxDrawBuffers
603 << ":OES_standard_derivatives:" << compileResources.OES_standard_derivatives
604 << ":OES_EGL_image_external:" << compileResources.OES_EGL_image_external
605 << ":OES_EGL_image_external_essl3:" << compileResources.OES_EGL_image_external_essl3
606 << ":NV_EGL_stream_consumer_external:" << compileResources.NV_EGL_stream_consumer_external
607 << ":ARB_texture_rectangle:" << compileResources.ARB_texture_rectangle
608 << ":EXT_draw_buffers:" << compileResources.EXT_draw_buffers
609 << ":FragmentPrecisionHigh:" << compileResources.FragmentPrecisionHigh
610 << ":MaxExpressionComplexity:" << compileResources.MaxExpressionComplexity
611 << ":MaxCallStackDepth:" << compileResources.MaxCallStackDepth
612 << ":MaxFunctionParameters:" << compileResources.MaxFunctionParameters
613 << ":EXT_blend_func_extended:" << compileResources.EXT_blend_func_extended
614 << ":EXT_frag_depth:" << compileResources.EXT_frag_depth
615 << ":EXT_shader_texture_lod:" << compileResources.EXT_shader_texture_lod
616 << ":EXT_shader_framebuffer_fetch:" << compileResources.EXT_shader_framebuffer_fetch
617 << ":NV_shader_framebuffer_fetch:" << compileResources.NV_shader_framebuffer_fetch
618 << ":ARM_shader_framebuffer_fetch:" << compileResources.ARM_shader_framebuffer_fetch
619 << ":MaxVertexOutputVectors:" << compileResources.MaxVertexOutputVectors
620 << ":MaxFragmentInputVectors:" << compileResources.MaxFragmentInputVectors
621 << ":MinProgramTexelOffset:" << compileResources.MinProgramTexelOffset
622 << ":MaxProgramTexelOffset:" << compileResources.MaxProgramTexelOffset
623 << ":MaxDualSourceDrawBuffers:" << compileResources.MaxDualSourceDrawBuffers
624 << ":NV_draw_buffers:" << compileResources.NV_draw_buffers
625 << ":WEBGL_debug_shader_precision:" << compileResources.WEBGL_debug_shader_precision
626 << ":MaxImageUnits:" << compileResources.MaxImageUnits
627 << ":MaxVertexImageUniforms:" << compileResources.MaxVertexImageUniforms
628 << ":MaxFragmentImageUniforms:" << compileResources.MaxFragmentImageUniforms
629 << ":MaxComputeImageUniforms:" << compileResources.MaxComputeImageUniforms
630 << ":MaxCombinedImageUniforms:" << compileResources.MaxCombinedImageUniforms
631 << ":MaxCombinedShaderOutputResources:" << compileResources.MaxCombinedShaderOutputResources
632 << ":MaxComputeWorkGroupCountX:" << compileResources.MaxComputeWorkGroupCount[0]
633 << ":MaxComputeWorkGroupCountY:" << compileResources.MaxComputeWorkGroupCount[1]
634 << ":MaxComputeWorkGroupCountZ:" << compileResources.MaxComputeWorkGroupCount[2]
635 << ":MaxComputeWorkGroupSizeX:" << compileResources.MaxComputeWorkGroupSize[0]
636 << ":MaxComputeWorkGroupSizeY:" << compileResources.MaxComputeWorkGroupSize[1]
637 << ":MaxComputeWorkGroupSizeZ:" << compileResources.MaxComputeWorkGroupSize[2]
638 << ":MaxComputeUniformComponents:" << compileResources.MaxComputeUniformComponents
639 << ":MaxComputeTextureImageUnits:" << compileResources.MaxComputeTextureImageUnits
640 << ":MaxComputeAtomicCounters:" << compileResources.MaxComputeAtomicCounters
641 << ":MaxComputeAtomicCounterBuffers:" << compileResources.MaxComputeAtomicCounterBuffers
642 << ":MaxVertexAtomicCounters:" << compileResources.MaxVertexAtomicCounters
643 << ":MaxFragmentAtomicCounters:" << compileResources.MaxFragmentAtomicCounters
644 << ":MaxCombinedAtomicCounters:" << compileResources.MaxCombinedAtomicCounters
645 << ":MaxAtomicCounterBindings:" << compileResources.MaxAtomicCounterBindings
646 << ":MaxVertexAtomicCounterBuffers:" << compileResources.MaxVertexAtomicCounterBuffers
647 << ":MaxFragmentAtomicCounterBuffers:" << compileResources.MaxFragmentAtomicCounterBuffers
648 << ":MaxCombinedAtomicCounterBuffers:" << compileResources.MaxCombinedAtomicCounterBuffers
649 << ":MaxAtomicCounterBufferSize:" << compileResources.MaxAtomicCounterBufferSize;
Geoff Langb66a9092016-05-16 15:59:14 -0400650 // clang-format on
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400651
652 builtInResourcesString = strstream.str();
653}
654
alokp@chromium.org07620a52010-09-23 17:53:56 +0000655void TCompiler::clearResults()
656{
daniel@transgaming.com4167cc92013-01-11 04:11:53 +0000657 arrayBoundsClamper.Cleanup();
alokp@chromium.org07620a52010-09-23 17:53:56 +0000658 infoSink.info.erase();
659 infoSink.obj.erase();
660 infoSink.debug.erase();
Olli Etuaho77ba4082016-12-16 12:01:18 +0000661 mDiagnostics.resetErrorCount();
alokp@chromium.org07620a52010-09-23 17:53:56 +0000662
Jamie Madilled27c722014-07-02 15:31:23 -0400663 attributes.clear();
664 outputVariables.clear();
alokp@chromium.org07620a52010-09-23 17:53:56 +0000665 uniforms.clear();
Jamie Madill23a8a432014-07-09 13:27:42 -0400666 expandedUniforms.clear();
Zhenyao Mod2d340b2013-09-23 14:57:05 -0400667 varyings.clear();
Jamie Madilled27c722014-07-02 15:31:23 -0400668 interfaceBlocks.clear();
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700669 variablesCollected = false;
zmo@google.coma3b4ab42011-09-16 00:53:26 +0000670
Olli Etuaho09b04a22016-12-15 13:30:26 +0000671 mNumViews = -1;
672
Olli Etuahodfa75e82017-01-23 09:43:06 -0800673 builtInFunctionEmulator.cleanup();
daniel@transgaming.com0aa3b5a2012-11-28 19:43:24 +0000674
675 nameMap.clear();
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200676
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500677 mSourcePath = NULL;
Corentin Wallezd4b50542015-09-28 12:19:26 -0700678 mTemporaryIndex = 0;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000679}
680
Corentin Wallez71d147f2015-02-11 11:15:24 -0800681bool TCompiler::initCallDag(TIntermNode *root)
zmo@google.comb1762df2011-07-30 02:04:23 +0000682{
Corentin Wallez71d147f2015-02-11 11:15:24 -0800683 mCallDag.clear();
684
Olli Etuaho77ba4082016-12-16 12:01:18 +0000685 switch (mCallDag.init(root, &mDiagnostics))
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800686 {
Jamie Madillacb4b812016-11-07 13:50:29 -0500687 case CallDAG::INITDAG_SUCCESS:
688 return true;
689 case CallDAG::INITDAG_RECURSION:
Jamie Madillacb4b812016-11-07 13:50:29 -0500690 case CallDAG::INITDAG_UNDEFINED:
Olli Etuaho77ba4082016-12-16 12:01:18 +0000691 // Error message has already been written out.
692 ASSERT(mDiagnostics.numErrors() > 0);
Jamie Madillacb4b812016-11-07 13:50:29 -0500693 return false;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800694 }
695
696 UNREACHABLE();
697 return true;
698}
699
700bool TCompiler::checkCallDepth()
701{
702 std::vector<int> depths(mCallDag.size());
703
704 for (size_t i = 0; i < mCallDag.size(); i++)
705 {
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500706 int depth = 0;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800707 auto &record = mCallDag.getRecordFromIndex(i);
708
709 for (auto &calleeIndex : record.callees)
710 {
711 depth = std::max(depth, depths[calleeIndex] + 1);
712 }
713
714 depths[i] = depth;
715
716 if (depth >= maxCallStackDepth)
717 {
718 // Trace back the function chain to have a meaningful info log.
Olli Etuaho77ba4082016-12-16 12:01:18 +0000719 std::stringstream errorStream;
720 errorStream << "Call stack too deep (larger than " << maxCallStackDepth
721 << ") with the following call chain: " << record.name;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800722
Cooper Partin4d61f7e2015-08-12 10:56:50 -0700723 int currentFunction = static_cast<int>(i);
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500724 int currentDepth = depth;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800725
726 while (currentFunction != -1)
727 {
Olli Etuaho77ba4082016-12-16 12:01:18 +0000728 errorStream << " -> " << mCallDag.getRecordFromIndex(currentFunction).name;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800729
730 int nextFunction = -1;
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500731 for (auto &calleeIndex : mCallDag.getRecordFromIndex(currentFunction).callees)
Corentin Wallez71d147f2015-02-11 11:15:24 -0800732 {
733 if (depths[calleeIndex] == currentDepth - 1)
734 {
735 currentDepth--;
736 nextFunction = calleeIndex;
737 }
738 }
739
740 currentFunction = nextFunction;
741 }
742
Olli Etuaho77ba4082016-12-16 12:01:18 +0000743 std::string errorStr = errorStream.str();
744 mDiagnostics.globalError(errorStr.c_str());
745
Corentin Wallez71d147f2015-02-11 11:15:24 -0800746 return false;
747 }
748 }
749
750 return true;
751}
752
753bool TCompiler::tagUsedFunctions()
754{
755 // Search from main, starting from the end of the DAG as it usually is the root.
Cooper Partin4d61f7e2015-08-12 10:56:50 -0700756 for (size_t i = mCallDag.size(); i-- > 0;)
Corentin Wallez71d147f2015-02-11 11:15:24 -0800757 {
758 if (mCallDag.getRecordFromIndex(i).name == "main(")
759 {
760 internalTagUsedFunction(i);
761 return true;
762 }
763 }
764
Olli Etuaho77ba4082016-12-16 12:01:18 +0000765 mDiagnostics.globalError("Missing main()");
Corentin Wallez71d147f2015-02-11 11:15:24 -0800766 return false;
767}
768
769void TCompiler::internalTagUsedFunction(size_t index)
770{
771 if (functionMetadata[index].used)
772 {
773 return;
774 }
775
776 functionMetadata[index].used = true;
777
778 for (int calleeIndex : mCallDag.getRecordFromIndex(index).callees)
779 {
780 internalTagUsedFunction(calleeIndex);
zmo@google.comb1762df2011-07-30 02:04:23 +0000781 }
782}
783
Corentin Walleza094a8a2015-04-07 11:53:06 -0700784// A predicate for the stl that returns if a top-level node is unused
785class TCompiler::UnusedPredicate
786{
787 public:
788 UnusedPredicate(const CallDAG *callDag, const std::vector<FunctionMetadata> *metadatas)
Jamie Madillacb4b812016-11-07 13:50:29 -0500789 : mCallDag(callDag), mMetadatas(metadatas)
Corentin Walleza094a8a2015-04-07 11:53:06 -0700790 {
791 }
792
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500793 bool operator()(TIntermNode *node)
Corentin Walleza094a8a2015-04-07 11:53:06 -0700794 {
Olli Etuaho16c745a2017-01-16 17:02:27 +0000795 const TIntermFunctionPrototype *asFunctionPrototype = node->getAsFunctionPrototypeNode();
796 const TIntermFunctionDefinition *asFunctionDefinition = node->getAsFunctionDefinition();
Corentin Walleza094a8a2015-04-07 11:53:06 -0700797
Olli Etuaho336b1472016-10-05 16:37:55 +0100798 const TFunctionSymbolInfo *functionInfo = nullptr;
799
Olli Etuaho16c745a2017-01-16 17:02:27 +0000800 if (asFunctionDefinition)
Olli Etuaho336b1472016-10-05 16:37:55 +0100801 {
Olli Etuaho16c745a2017-01-16 17:02:27 +0000802 functionInfo = asFunctionDefinition->getFunctionSymbolInfo();
Olli Etuaho336b1472016-10-05 16:37:55 +0100803 }
Olli Etuaho16c745a2017-01-16 17:02:27 +0000804 else if (asFunctionPrototype)
Olli Etuaho336b1472016-10-05 16:37:55 +0100805 {
Olli Etuaho16c745a2017-01-16 17:02:27 +0000806 functionInfo = asFunctionPrototype->getFunctionSymbolInfo();
Olli Etuaho336b1472016-10-05 16:37:55 +0100807 }
808 if (functionInfo == nullptr)
Corentin Walleza094a8a2015-04-07 11:53:06 -0700809 {
810 return false;
811 }
812
Olli Etuaho336b1472016-10-05 16:37:55 +0100813 size_t callDagIndex = mCallDag->findIndex(functionInfo);
Corentin Walleza094a8a2015-04-07 11:53:06 -0700814 if (callDagIndex == CallDAG::InvalidIndex)
815 {
816 // This happens only for unimplemented prototypes which are thus unused
Olli Etuaho16c745a2017-01-16 17:02:27 +0000817 ASSERT(asFunctionPrototype);
Corentin Walleza094a8a2015-04-07 11:53:06 -0700818 return true;
819 }
820
821 ASSERT(callDagIndex < mMetadatas->size());
822 return !(*mMetadatas)[callDagIndex].used;
823 }
824
825 private:
826 const CallDAG *mCallDag;
827 const std::vector<FunctionMetadata> *mMetadatas;
828};
829
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100830bool TCompiler::pruneUnusedFunctions(TIntermBlock *root)
Corentin Walleza094a8a2015-04-07 11:53:06 -0700831{
Corentin Walleza094a8a2015-04-07 11:53:06 -0700832 UnusedPredicate isUnused(&mCallDag, &functionMetadata);
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100833 TIntermSequence *sequence = root->getSequence();
Corentin Wallezb081e782015-07-20 05:40:04 -0700834
835 if (!sequence->empty())
836 {
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500837 sequence->erase(std::remove_if(sequence->begin(), sequence->end(), isUnused),
838 sequence->end());
Corentin Wallezb081e782015-07-20 05:40:04 -0700839 }
Corentin Walleza094a8a2015-04-07 11:53:06 -0700840
841 return true;
842}
843
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500844bool TCompiler::validateOutputs(TIntermNode *root)
Jamie Madill05a80ce2013-06-20 11:55:49 -0400845{
Kimmo Kinnunenb18609b2015-07-16 14:13:11 +0300846 ValidateOutputs validateOutputs(getExtensionBehavior(), compileResources.MaxDrawBuffers);
Jamie Madill05a80ce2013-06-20 11:55:49 -0400847 root->traverse(&validateOutputs);
Olli Etuaho77ba4082016-12-16 12:01:18 +0000848 validateOutputs.validate(&mDiagnostics);
849 return (mDiagnostics.numErrors() == 0);
Jamie Madill05a80ce2013-06-20 11:55:49 -0400850}
851
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500852bool TCompiler::validateLimitations(TIntermNode *root)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800853{
Olli Etuaho77ba4082016-12-16 12:01:18 +0000854 ValidateLimitations validate(shaderType, &mDiagnostics);
alokp@chromium.orgb59a7782010-11-24 18:38:33 +0000855 root->traverse(&validate);
Olli Etuaho77ba4082016-12-16 12:01:18 +0000856 return mDiagnostics.numErrors() == 0;
alokp@chromium.orgb59a7782010-11-24 18:38:33 +0000857}
858
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500859bool TCompiler::limitExpressionComplexity(TIntermNode *root)
Jamie Madilleb1a0102013-07-08 13:31:38 -0400860{
Jamie Madillacb4b812016-11-07 13:50:29 -0500861 TMaxDepthTraverser traverser(maxExpressionComplexity + 1);
Jamie Madilleb1a0102013-07-08 13:31:38 -0400862 root->traverse(&traverser);
Jamie Madill6654bc92014-03-26 14:01:57 -0400863
864 if (traverser.getMaxDepth() > maxExpressionComplexity)
865 {
Olli Etuaho77ba4082016-12-16 12:01:18 +0000866 mDiagnostics.globalError("Expression too complex.");
Jamie Madill6654bc92014-03-26 14:01:57 -0400867 return false;
868 }
869
Olli Etuaho19d1dc92016-03-08 17:18:46 +0200870 if (!ValidateMaxParameters::validate(root, maxFunctionParameters))
871 {
Olli Etuaho77ba4082016-12-16 12:01:18 +0000872 mDiagnostics.globalError("Function has too many parameters.");
Olli Etuaho19d1dc92016-03-08 17:18:46 +0200873 return false;
874 }
875
Jamie Madilleb1a0102013-07-08 13:31:38 -0400876 return true;
877}
878
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500879void TCompiler::collectVariables(TIntermNode *root)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000880{
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700881 if (!variablesCollected)
882 {
883 sh::CollectVariables collect(&attributes, &outputVariables, &uniforms, &varyings,
Jamie Madillacb4b812016-11-07 13:50:29 -0500884 &interfaceBlocks, hashFunction, symbolTable,
885 extensionBehavior);
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700886 root->traverse(&collect);
Jamie Madill23a8a432014-07-09 13:27:42 -0400887
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700888 // This is for enforcePackingRestriction().
889 sh::ExpandUniforms(uniforms, &expandedUniforms);
890 variablesCollected = true;
891 }
alokp@chromium.org07620a52010-09-23 17:53:56 +0000892}
zmo@google.comfd747b82011-04-23 01:30:07 +0000893
Corentin Wallez1df16022016-10-27 08:16:56 -0400894bool TCompiler::shouldCollectVariables(ShCompileOptions compileOptions)
895{
896 return (compileOptions & SH_VARIABLES) != 0;
897}
898
899bool TCompiler::wereVariablesCollected() const
900{
901 return variablesCollected;
902}
903
gman@chromium.org8d804792012-10-17 21:33:48 +0000904bool TCompiler::enforcePackingRestrictions()
905{
906 VariablePacker packer;
Jamie Madill23a8a432014-07-09 13:27:42 -0400907 return packer.CheckVariablesWithinPackingLimits(maxUniformVectors, expandedUniforms);
gman@chromium.org8d804792012-10-17 21:33:48 +0000908}
909
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500910void TCompiler::initializeGLPosition(TIntermNode *root)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800911{
Zhenyao Mo72111912016-07-20 17:45:56 -0700912 InitVariableList list;
913 sh::ShaderVariable var(GL_FLOAT_VEC4, 0);
914 var.name = "gl_Position";
915 list.push_back(var);
Zhenyao Mod7490962016-11-09 15:49:51 -0800916 InitializeVariables(root, list, symbolTable);
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800917}
918
Qin Jiajia7835b522016-10-08 11:20:17 +0800919void TCompiler::useAllMembersInUnusedStandardAndSharedBlocks(TIntermNode *root)
920{
921 sh::InterfaceBlockList list;
922
923 for (auto block : interfaceBlocks)
924 {
925 if (!block.staticUse &&
926 (block.layout == sh::BLOCKLAYOUT_STANDARD || block.layout == sh::BLOCKLAYOUT_SHARED))
927 {
928 list.push_back(block);
929 }
930 }
931
Zhenyao Mod7490962016-11-09 15:49:51 -0800932 sh::UseInterfaceBlockFields(root, list, symbolTable);
Qin Jiajia7835b522016-10-08 11:20:17 +0800933}
934
Olli Etuaho27776e32016-07-22 14:00:56 +0300935void TCompiler::initializeOutputVariables(TIntermNode *root)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800936{
Zhenyao Mo72111912016-07-20 17:45:56 -0700937 InitVariableList list;
938 if (shaderType == GL_VERTEX_SHADER)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800939 {
Zhenyao Mo72111912016-07-20 17:45:56 -0700940 for (auto var : varyings)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800941 {
Zhenyao Mof9312682016-07-22 12:51:31 -0700942 list.push_back(var);
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800943 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800944 }
Zhenyao Mo72111912016-07-20 17:45:56 -0700945 else
946 {
947 ASSERT(shaderType == GL_FRAGMENT_SHADER);
948 for (auto var : outputVariables)
949 {
950 list.push_back(var);
951 }
952 }
Zhenyao Mod7490962016-11-09 15:49:51 -0800953 InitializeVariables(root, list, symbolTable);
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800954}
955
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500956const TExtensionBehavior &TCompiler::getExtensionBehavior() const
zmo@google.com5601ea02011-06-10 18:23:25 +0000957{
958 return extensionBehavior;
959}
zmo@google.com32e97312011-08-24 01:03:11 +0000960
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200961const char *TCompiler::getSourcePath() const
962{
963 return mSourcePath;
964}
965
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500966const ShBuiltInResources &TCompiler::getResources() const
shannon.woods%transgaming.com@gtempaccount.com18b4c4b2013-04-13 03:31:40 +0000967{
968 return compileResources;
969}
970
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500971const ArrayBoundsClamper &TCompiler::getArrayBoundsClamper() const
daniel@transgaming.com4167cc92013-01-11 04:11:53 +0000972{
973 return arrayBoundsClamper;
974}
975
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000976ShArrayIndexClampingStrategy TCompiler::getArrayIndexClampingStrategy() const
977{
978 return clampingStrategy;
979}
980
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500981const BuiltInFunctionEmulator &TCompiler::getBuiltInFunctionEmulator() const
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000982{
983 return builtInFunctionEmulator;
984}
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700985
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800986void TCompiler::writePragma(ShCompileOptions compileOptions)
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700987{
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700988 if (!(compileOptions & SH_FLATTEN_PRAGMA_STDGL_INVARIANT_ALL))
989 {
990 TInfoSinkBase &sink = infoSink.obj;
991 if (mPragma.stdgl.invariantAll)
992 sink << "#pragma STDGL invariant(all)\n";
993 }
994}
995
996bool TCompiler::isVaryingDefined(const char *varyingName)
997{
998 ASSERT(variablesCollected);
999 for (size_t ii = 0; ii < varyings.size(); ++ii)
1000 {
1001 if (varyings[ii].name == varyingName)
1002 {
1003 return true;
1004 }
1005 }
1006
1007 return false;
Zhenyao Mo94ac7b72014-10-15 18:22:08 -07001008}
Jamie Madillacb4b812016-11-07 13:50:29 -05001009
1010} // namespace sh