blob: 11f63a950bc3eb5ba6e0bc0e8f0b442ec656de33 [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))
376 success = ValidateMultiviewWebGL(root, shaderType, multiview2, &mDiagnostics);
377
Jamie Madilld5696192016-10-06 11:09:24 -0400378 // Fail compilation if precision emulation not supported.
379 if (success && getResources().WEBGL_debug_shader_precision &&
380 getPragma().debugShaderPrecision)
381 {
382 if (!EmulatePrecision::SupportedInLanguage(outputType))
383 {
Olli Etuaho77ba4082016-12-16 12:01:18 +0000384 mDiagnostics.globalError("Precision emulation not supported for this output type.");
Jamie Madilld5696192016-10-06 11:09:24 -0400385 success = false;
386 }
387 }
388
zmo@google.com32e97312011-08-24 01:03:11 +0000389 // Built-in function emulation needs to happen after validateLimitations pass.
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200390 if (success)
391 {
Jamie Madill438dbcf2016-06-17 14:20:05 -0400392 // TODO(jmadill): Remove global pool allocator.
393 GetGlobalPoolAllocator()->lock();
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200394 initBuiltInFunctionEmulator(&builtInFunctionEmulator, compileOptions);
Jamie Madill438dbcf2016-06-17 14:20:05 -0400395 GetGlobalPoolAllocator()->unlock();
zmo@google.com32e97312011-08-24 01:03:11 +0000396 builtInFunctionEmulator.MarkBuiltInFunctionsForEmulation(root);
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200397 }
zmo@google.com32e97312011-08-24 01:03:11 +0000398
daniel@transgaming.com4167cc92013-01-11 04:11:53 +0000399 // Clamping uniform array bounds needs to happen after validateLimitations pass.
400 if (success && (compileOptions & SH_CLAMP_INDIRECT_ARRAY_BOUNDS))
401 arrayBoundsClamper.MarkIndirectArrayBoundsForClamping(root);
402
Ian Ewell924b7de2016-01-21 13:54:28 -0500403 // gl_Position is always written in compatibility output mode
404 if (success && shaderType == GL_VERTEX_SHADER &&
405 ((compileOptions & SH_INIT_GL_POSITION) ||
406 (outputType == SH_GLSL_COMPATIBILITY_OUTPUT)))
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800407 initializeGLPosition(root);
Zhenyao Moac44cd22013-09-23 14:57:09 -0400408
Qiankun Miao89dd8f32016-11-09 12:59:30 +0000409 if (success && RemoveInvariant(shaderType, shaderVersion, outputType, compileOptions))
Qiankun Miao705a9192016-08-29 10:05:27 +0800410 sh::RemoveInvariantDeclaration(root);
411
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
Zhenyao Mocd68fe72014-07-11 10:45:44 -0700452 if (success && (compileOptions & SH_SCALARIZE_VEC_AND_MAT_CONSTRUCTOR_ARGS))
453 {
Olli Etuahob990b552016-10-27 12:29:17 +0100454 ScalarizeVecAndMatConstructorArgs(root, shaderType, fragmentPrecisionHigh,
455 &mTemporaryIndex);
Zhenyao Mocd68fe72014-07-11 10:45:44 -0700456 }
457
Zhenyao Moe740add2014-07-18 17:01:01 -0700458 if (success && (compileOptions & SH_REGENERATE_STRUCT_NAMES))
459 {
460 RegenerateStructNames gen(symbolTable, shaderVersion);
461 root->traverse(&gen);
462 }
Olli Etuaho3d932d82016-04-12 11:10:30 +0300463
Zhenyao Mo4e94fea2016-08-09 14:31:37 -0700464 if (success && shaderType == GL_FRAGMENT_SHADER && shaderVersion == 100 &&
465 compileResources.EXT_draw_buffers && compileResources.MaxDrawBuffers > 1 &&
466 IsExtensionEnabled(extensionBehavior, "GL_EXT_draw_buffers"))
467 {
468 EmulateGLFragColorBroadcast(root, compileResources.MaxDrawBuffers, &outputVariables);
469 }
470
Olli Etuaho3d932d82016-04-12 11:10:30 +0300471 if (success)
472 {
473 DeferGlobalInitializers(root);
474 }
alokp@chromium.org07620a52010-09-23 17:53:56 +0000475 }
476
Zhenyao Mo7faf1a12014-04-25 18:03:56 -0700477 SetGlobalParseContext(NULL);
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200478 if (success)
479 return root;
480
481 return NULL;
482}
483
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800484bool TCompiler::compile(const char *const shaderStrings[],
485 size_t numStrings,
486 ShCompileOptions compileOptionsIn)
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200487{
Corentin Wallez28b65282016-06-16 07:24:50 -0700488#if defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
489 DumpFuzzerCase(shaderStrings, numStrings, shaderType, shaderSpec, outputType, compileOptionsIn);
490#endif // defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
491
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200492 if (numStrings == 0)
493 return true;
494
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800495 ShCompileOptions compileOptions = compileOptionsIn;
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700496
497 // Apply key workarounds.
498 if (shouldFlattenPragmaStdglInvariantAll())
499 {
500 // This should be harmless to do in all cases, but for the moment, do it only conditionally.
501 compileOptions |= SH_FLATTEN_PRAGMA_STDGL_INVARIANT_ALL;
502 }
503
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200504 TScopedPoolAllocator scopedAlloc(&allocator);
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100505 TIntermBlock *root = compileTreeImpl(shaderStrings, numStrings, compileOptions);
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200506
507 if (root)
508 {
509 if (compileOptions & SH_INTERMEDIATE_TREE)
510 TIntermediate::outputTree(root, infoSink.info);
511
512 if (compileOptions & SH_OBJECT_CODE)
513 translate(root, compileOptions);
514
515 // The IntermNode tree doesn't need to be deleted here, since the
516 // memory will be freed in a big chunk by the PoolAllocator.
517 return true;
518 }
519 return false;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000520}
521
Nicolas Capens49a88872013-06-20 09:54:03 -0400522bool TCompiler::InitBuiltInSymbolTable(const ShBuiltInResources &resources)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000523{
Olli Etuaho28cb0362016-11-22 15:42:37 +0000524 if (resources.MaxDrawBuffers < 1)
525 {
526 return false;
527 }
528 if (resources.EXT_blend_func_extended && resources.MaxDualSourceDrawBuffers < 1)
529 {
530 return false;
531 }
532
shannon.woods%transgaming.com@gtempaccount.com18b4c4b2013-04-13 03:31:40 +0000533 compileResources = resources;
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400534 setResourceString();
shannonwoods@chromium.org2ac0be92013-05-30 00:02:27 +0000535
Nicolas Capens49a88872013-06-20 09:54:03 -0400536 assert(symbolTable.isEmpty());
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500537 symbolTable.push(); // COMMON_BUILTINS
538 symbolTable.push(); // ESSL1_BUILTINS
539 symbolTable.push(); // ESSL3_BUILTINS
540 symbolTable.push(); // ESSL3_1_BUILTINS
shannonwoods@chromium.org2ac0be92013-05-30 00:02:27 +0000541
Nicolas Capens49a88872013-06-20 09:54:03 -0400542 TPublicType integer;
Martin Radev2cc85b32016-08-05 16:22:53 +0300543 integer.initializeBasicType(EbtInt);
Nicolas Capens49a88872013-06-20 09:54:03 -0400544
545 TPublicType floatingPoint;
Martin Radev2cc85b32016-08-05 16:22:53 +0300546 floatingPoint.initializeBasicType(EbtFloat);
Nicolas Capens49a88872013-06-20 09:54:03 -0400547
Jamie Madillacb4b812016-11-07 13:50:29 -0500548 switch (shaderType)
Nicolas Capens49a88872013-06-20 09:54:03 -0400549 {
Jamie Madillacb4b812016-11-07 13:50:29 -0500550 case GL_FRAGMENT_SHADER:
551 symbolTable.setDefaultPrecision(integer, EbpMedium);
552 break;
553 case GL_VERTEX_SHADER:
554 symbolTable.setDefaultPrecision(integer, EbpHigh);
555 symbolTable.setDefaultPrecision(floatingPoint, EbpHigh);
556 break;
557 case GL_COMPUTE_SHADER:
558 symbolTable.setDefaultPrecision(integer, EbpHigh);
559 symbolTable.setDefaultPrecision(floatingPoint, EbpHigh);
560 break;
561 default:
562 assert(false && "Language not supported");
Nicolas Capens49a88872013-06-20 09:54:03 -0400563 }
Olli Etuaho183d7e22015-11-20 15:59:09 +0200564 // Set defaults for sampler types that have default precision, even those that are
Zhenyao Moa5a1dfc2013-09-23 14:57:03 -0400565 // only available if an extension exists.
Olli Etuaho183d7e22015-11-20 15:59:09 +0200566 // New sampler types in ESSL3 don't have default precision. ESSL1 types do.
567 initSamplerDefaultPrecision(EbtSampler2D);
568 initSamplerDefaultPrecision(EbtSamplerCube);
569 // SamplerExternalOES is specified in the extension to have default precision.
570 initSamplerDefaultPrecision(EbtSamplerExternalOES);
571 // It isn't specified whether Sampler2DRect has default precision.
572 initSamplerDefaultPrecision(EbtSampler2DRect);
Nicolas Capens49a88872013-06-20 09:54:03 -0400573
Jamie Madill1b452142013-07-12 14:51:11 -0400574 InsertBuiltInFunctions(shaderType, shaderSpec, resources, symbolTable);
Nicolas Capens49a88872013-06-20 09:54:03 -0400575
576 IdentifyBuiltIns(shaderType, shaderSpec, resources, symbolTable);
577
578 return true;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000579}
580
Olli Etuaho183d7e22015-11-20 15:59:09 +0200581void TCompiler::initSamplerDefaultPrecision(TBasicType samplerType)
582{
583 ASSERT(samplerType > EbtGuardSamplerBegin && samplerType < EbtGuardSamplerEnd);
584 TPublicType sampler;
Martin Radev2cc85b32016-08-05 16:22:53 +0300585 sampler.initializeBasicType(samplerType);
Olli Etuaho183d7e22015-11-20 15:59:09 +0200586 symbolTable.setDefaultPrecision(sampler, EbpLow);
587}
588
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400589void TCompiler::setResourceString()
590{
591 std::ostringstream strstream;
Geoff Langb66a9092016-05-16 15:59:14 -0400592
593 // clang-format off
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400594 strstream << ":MaxVertexAttribs:" << compileResources.MaxVertexAttribs
Jamie Madillacb4b812016-11-07 13:50:29 -0500595 << ":MaxVertexUniformVectors:" << compileResources.MaxVertexUniformVectors
596 << ":MaxVaryingVectors:" << compileResources.MaxVaryingVectors
597 << ":MaxVertexTextureImageUnits:" << compileResources.MaxVertexTextureImageUnits
598 << ":MaxCombinedTextureImageUnits:" << compileResources.MaxCombinedTextureImageUnits
599 << ":MaxTextureImageUnits:" << compileResources.MaxTextureImageUnits
600 << ":MaxFragmentUniformVectors:" << compileResources.MaxFragmentUniformVectors
601 << ":MaxDrawBuffers:" << compileResources.MaxDrawBuffers
602 << ":OES_standard_derivatives:" << compileResources.OES_standard_derivatives
603 << ":OES_EGL_image_external:" << compileResources.OES_EGL_image_external
604 << ":OES_EGL_image_external_essl3:" << compileResources.OES_EGL_image_external_essl3
605 << ":NV_EGL_stream_consumer_external:" << compileResources.NV_EGL_stream_consumer_external
606 << ":ARB_texture_rectangle:" << compileResources.ARB_texture_rectangle
607 << ":EXT_draw_buffers:" << compileResources.EXT_draw_buffers
608 << ":FragmentPrecisionHigh:" << compileResources.FragmentPrecisionHigh
609 << ":MaxExpressionComplexity:" << compileResources.MaxExpressionComplexity
610 << ":MaxCallStackDepth:" << compileResources.MaxCallStackDepth
611 << ":MaxFunctionParameters:" << compileResources.MaxFunctionParameters
612 << ":EXT_blend_func_extended:" << compileResources.EXT_blend_func_extended
613 << ":EXT_frag_depth:" << compileResources.EXT_frag_depth
614 << ":EXT_shader_texture_lod:" << compileResources.EXT_shader_texture_lod
615 << ":EXT_shader_framebuffer_fetch:" << compileResources.EXT_shader_framebuffer_fetch
616 << ":NV_shader_framebuffer_fetch:" << compileResources.NV_shader_framebuffer_fetch
617 << ":ARM_shader_framebuffer_fetch:" << compileResources.ARM_shader_framebuffer_fetch
618 << ":MaxVertexOutputVectors:" << compileResources.MaxVertexOutputVectors
619 << ":MaxFragmentInputVectors:" << compileResources.MaxFragmentInputVectors
620 << ":MinProgramTexelOffset:" << compileResources.MinProgramTexelOffset
621 << ":MaxProgramTexelOffset:" << compileResources.MaxProgramTexelOffset
622 << ":MaxDualSourceDrawBuffers:" << compileResources.MaxDualSourceDrawBuffers
623 << ":NV_draw_buffers:" << compileResources.NV_draw_buffers
624 << ":WEBGL_debug_shader_precision:" << compileResources.WEBGL_debug_shader_precision
625 << ":MaxImageUnits:" << compileResources.MaxImageUnits
626 << ":MaxVertexImageUniforms:" << compileResources.MaxVertexImageUniforms
627 << ":MaxFragmentImageUniforms:" << compileResources.MaxFragmentImageUniforms
628 << ":MaxComputeImageUniforms:" << compileResources.MaxComputeImageUniforms
629 << ":MaxCombinedImageUniforms:" << compileResources.MaxCombinedImageUniforms
630 << ":MaxCombinedShaderOutputResources:" << compileResources.MaxCombinedShaderOutputResources
631 << ":MaxComputeWorkGroupCountX:" << compileResources.MaxComputeWorkGroupCount[0]
632 << ":MaxComputeWorkGroupCountY:" << compileResources.MaxComputeWorkGroupCount[1]
633 << ":MaxComputeWorkGroupCountZ:" << compileResources.MaxComputeWorkGroupCount[2]
634 << ":MaxComputeWorkGroupSizeX:" << compileResources.MaxComputeWorkGroupSize[0]
635 << ":MaxComputeWorkGroupSizeY:" << compileResources.MaxComputeWorkGroupSize[1]
636 << ":MaxComputeWorkGroupSizeZ:" << compileResources.MaxComputeWorkGroupSize[2]
637 << ":MaxComputeUniformComponents:" << compileResources.MaxComputeUniformComponents
638 << ":MaxComputeTextureImageUnits:" << compileResources.MaxComputeTextureImageUnits
639 << ":MaxComputeAtomicCounters:" << compileResources.MaxComputeAtomicCounters
640 << ":MaxComputeAtomicCounterBuffers:" << compileResources.MaxComputeAtomicCounterBuffers
641 << ":MaxVertexAtomicCounters:" << compileResources.MaxVertexAtomicCounters
642 << ":MaxFragmentAtomicCounters:" << compileResources.MaxFragmentAtomicCounters
643 << ":MaxCombinedAtomicCounters:" << compileResources.MaxCombinedAtomicCounters
644 << ":MaxAtomicCounterBindings:" << compileResources.MaxAtomicCounterBindings
645 << ":MaxVertexAtomicCounterBuffers:" << compileResources.MaxVertexAtomicCounterBuffers
646 << ":MaxFragmentAtomicCounterBuffers:" << compileResources.MaxFragmentAtomicCounterBuffers
647 << ":MaxCombinedAtomicCounterBuffers:" << compileResources.MaxCombinedAtomicCounterBuffers
648 << ":MaxAtomicCounterBufferSize:" << compileResources.MaxAtomicCounterBufferSize;
Geoff Langb66a9092016-05-16 15:59:14 -0400649 // clang-format on
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400650
651 builtInResourcesString = strstream.str();
652}
653
alokp@chromium.org07620a52010-09-23 17:53:56 +0000654void TCompiler::clearResults()
655{
daniel@transgaming.com4167cc92013-01-11 04:11:53 +0000656 arrayBoundsClamper.Cleanup();
alokp@chromium.org07620a52010-09-23 17:53:56 +0000657 infoSink.info.erase();
658 infoSink.obj.erase();
659 infoSink.debug.erase();
Olli Etuaho77ba4082016-12-16 12:01:18 +0000660 mDiagnostics.resetErrorCount();
alokp@chromium.org07620a52010-09-23 17:53:56 +0000661
Jamie Madilled27c722014-07-02 15:31:23 -0400662 attributes.clear();
663 outputVariables.clear();
alokp@chromium.org07620a52010-09-23 17:53:56 +0000664 uniforms.clear();
Jamie Madill23a8a432014-07-09 13:27:42 -0400665 expandedUniforms.clear();
Zhenyao Mod2d340b2013-09-23 14:57:05 -0400666 varyings.clear();
Jamie Madilled27c722014-07-02 15:31:23 -0400667 interfaceBlocks.clear();
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700668 variablesCollected = false;
zmo@google.coma3b4ab42011-09-16 00:53:26 +0000669
Olli Etuaho09b04a22016-12-15 13:30:26 +0000670 mNumViews = -1;
671
zmo@google.coma3b4ab42011-09-16 00:53:26 +0000672 builtInFunctionEmulator.Cleanup();
daniel@transgaming.com0aa3b5a2012-11-28 19:43:24 +0000673
674 nameMap.clear();
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200675
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500676 mSourcePath = NULL;
Corentin Wallezd4b50542015-09-28 12:19:26 -0700677 mTemporaryIndex = 0;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000678}
679
Corentin Wallez71d147f2015-02-11 11:15:24 -0800680bool TCompiler::initCallDag(TIntermNode *root)
zmo@google.comb1762df2011-07-30 02:04:23 +0000681{
Corentin Wallez71d147f2015-02-11 11:15:24 -0800682 mCallDag.clear();
683
Olli Etuaho77ba4082016-12-16 12:01:18 +0000684 switch (mCallDag.init(root, &mDiagnostics))
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800685 {
Jamie Madillacb4b812016-11-07 13:50:29 -0500686 case CallDAG::INITDAG_SUCCESS:
687 return true;
688 case CallDAG::INITDAG_RECURSION:
Jamie Madillacb4b812016-11-07 13:50:29 -0500689 case CallDAG::INITDAG_UNDEFINED:
Olli Etuaho77ba4082016-12-16 12:01:18 +0000690 // Error message has already been written out.
691 ASSERT(mDiagnostics.numErrors() > 0);
Jamie Madillacb4b812016-11-07 13:50:29 -0500692 return false;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800693 }
694
695 UNREACHABLE();
696 return true;
697}
698
699bool TCompiler::checkCallDepth()
700{
701 std::vector<int> depths(mCallDag.size());
702
703 for (size_t i = 0; i < mCallDag.size(); i++)
704 {
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500705 int depth = 0;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800706 auto &record = mCallDag.getRecordFromIndex(i);
707
708 for (auto &calleeIndex : record.callees)
709 {
710 depth = std::max(depth, depths[calleeIndex] + 1);
711 }
712
713 depths[i] = depth;
714
715 if (depth >= maxCallStackDepth)
716 {
717 // Trace back the function chain to have a meaningful info log.
Olli Etuaho77ba4082016-12-16 12:01:18 +0000718 std::stringstream errorStream;
719 errorStream << "Call stack too deep (larger than " << maxCallStackDepth
720 << ") with the following call chain: " << record.name;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800721
Cooper Partin4d61f7e2015-08-12 10:56:50 -0700722 int currentFunction = static_cast<int>(i);
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500723 int currentDepth = depth;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800724
725 while (currentFunction != -1)
726 {
Olli Etuaho77ba4082016-12-16 12:01:18 +0000727 errorStream << " -> " << mCallDag.getRecordFromIndex(currentFunction).name;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800728
729 int nextFunction = -1;
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500730 for (auto &calleeIndex : mCallDag.getRecordFromIndex(currentFunction).callees)
Corentin Wallez71d147f2015-02-11 11:15:24 -0800731 {
732 if (depths[calleeIndex] == currentDepth - 1)
733 {
734 currentDepth--;
735 nextFunction = calleeIndex;
736 }
737 }
738
739 currentFunction = nextFunction;
740 }
741
Olli Etuaho77ba4082016-12-16 12:01:18 +0000742 std::string errorStr = errorStream.str();
743 mDiagnostics.globalError(errorStr.c_str());
744
Corentin Wallez71d147f2015-02-11 11:15:24 -0800745 return false;
746 }
747 }
748
749 return true;
750}
751
752bool TCompiler::tagUsedFunctions()
753{
754 // Search from main, starting from the end of the DAG as it usually is the root.
Cooper Partin4d61f7e2015-08-12 10:56:50 -0700755 for (size_t i = mCallDag.size(); i-- > 0;)
Corentin Wallez71d147f2015-02-11 11:15:24 -0800756 {
757 if (mCallDag.getRecordFromIndex(i).name == "main(")
758 {
759 internalTagUsedFunction(i);
760 return true;
761 }
762 }
763
Olli Etuaho77ba4082016-12-16 12:01:18 +0000764 mDiagnostics.globalError("Missing main()");
Corentin Wallez71d147f2015-02-11 11:15:24 -0800765 return false;
766}
767
768void TCompiler::internalTagUsedFunction(size_t index)
769{
770 if (functionMetadata[index].used)
771 {
772 return;
773 }
774
775 functionMetadata[index].used = true;
776
777 for (int calleeIndex : mCallDag.getRecordFromIndex(index).callees)
778 {
779 internalTagUsedFunction(calleeIndex);
zmo@google.comb1762df2011-07-30 02:04:23 +0000780 }
781}
782
Corentin Walleza094a8a2015-04-07 11:53:06 -0700783// A predicate for the stl that returns if a top-level node is unused
784class TCompiler::UnusedPredicate
785{
786 public:
787 UnusedPredicate(const CallDAG *callDag, const std::vector<FunctionMetadata> *metadatas)
Jamie Madillacb4b812016-11-07 13:50:29 -0500788 : mCallDag(callDag), mMetadatas(metadatas)
Corentin Walleza094a8a2015-04-07 11:53:06 -0700789 {
790 }
791
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500792 bool operator()(TIntermNode *node)
Corentin Walleza094a8a2015-04-07 11:53:06 -0700793 {
Olli Etuaho16c745a2017-01-16 17:02:27 +0000794 const TIntermFunctionPrototype *asFunctionPrototype = node->getAsFunctionPrototypeNode();
795 const TIntermFunctionDefinition *asFunctionDefinition = node->getAsFunctionDefinition();
Corentin Walleza094a8a2015-04-07 11:53:06 -0700796
Olli Etuaho336b1472016-10-05 16:37:55 +0100797 const TFunctionSymbolInfo *functionInfo = nullptr;
798
Olli Etuaho16c745a2017-01-16 17:02:27 +0000799 if (asFunctionDefinition)
Olli Etuaho336b1472016-10-05 16:37:55 +0100800 {
Olli Etuaho16c745a2017-01-16 17:02:27 +0000801 functionInfo = asFunctionDefinition->getFunctionSymbolInfo();
Olli Etuaho336b1472016-10-05 16:37:55 +0100802 }
Olli Etuaho16c745a2017-01-16 17:02:27 +0000803 else if (asFunctionPrototype)
Olli Etuaho336b1472016-10-05 16:37:55 +0100804 {
Olli Etuaho16c745a2017-01-16 17:02:27 +0000805 functionInfo = asFunctionPrototype->getFunctionSymbolInfo();
Olli Etuaho336b1472016-10-05 16:37:55 +0100806 }
807 if (functionInfo == nullptr)
Corentin Walleza094a8a2015-04-07 11:53:06 -0700808 {
809 return false;
810 }
811
Olli Etuaho336b1472016-10-05 16:37:55 +0100812 size_t callDagIndex = mCallDag->findIndex(functionInfo);
Corentin Walleza094a8a2015-04-07 11:53:06 -0700813 if (callDagIndex == CallDAG::InvalidIndex)
814 {
815 // This happens only for unimplemented prototypes which are thus unused
Olli Etuaho16c745a2017-01-16 17:02:27 +0000816 ASSERT(asFunctionPrototype);
Corentin Walleza094a8a2015-04-07 11:53:06 -0700817 return true;
818 }
819
820 ASSERT(callDagIndex < mMetadatas->size());
821 return !(*mMetadatas)[callDagIndex].used;
822 }
823
824 private:
825 const CallDAG *mCallDag;
826 const std::vector<FunctionMetadata> *mMetadatas;
827};
828
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100829bool TCompiler::pruneUnusedFunctions(TIntermBlock *root)
Corentin Walleza094a8a2015-04-07 11:53:06 -0700830{
Corentin Walleza094a8a2015-04-07 11:53:06 -0700831 UnusedPredicate isUnused(&mCallDag, &functionMetadata);
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100832 TIntermSequence *sequence = root->getSequence();
Corentin Wallezb081e782015-07-20 05:40:04 -0700833
834 if (!sequence->empty())
835 {
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500836 sequence->erase(std::remove_if(sequence->begin(), sequence->end(), isUnused),
837 sequence->end());
Corentin Wallezb081e782015-07-20 05:40:04 -0700838 }
Corentin Walleza094a8a2015-04-07 11:53:06 -0700839
840 return true;
841}
842
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500843bool TCompiler::validateOutputs(TIntermNode *root)
Jamie Madill05a80ce2013-06-20 11:55:49 -0400844{
Kimmo Kinnunenb18609b2015-07-16 14:13:11 +0300845 ValidateOutputs validateOutputs(getExtensionBehavior(), compileResources.MaxDrawBuffers);
Jamie Madill05a80ce2013-06-20 11:55:49 -0400846 root->traverse(&validateOutputs);
Olli Etuaho77ba4082016-12-16 12:01:18 +0000847 validateOutputs.validate(&mDiagnostics);
848 return (mDiagnostics.numErrors() == 0);
Jamie Madill05a80ce2013-06-20 11:55:49 -0400849}
850
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500851bool TCompiler::validateLimitations(TIntermNode *root)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800852{
Olli Etuaho77ba4082016-12-16 12:01:18 +0000853 ValidateLimitations validate(shaderType, &mDiagnostics);
alokp@chromium.orgb59a7782010-11-24 18:38:33 +0000854 root->traverse(&validate);
Olli Etuaho77ba4082016-12-16 12:01:18 +0000855 return mDiagnostics.numErrors() == 0;
alokp@chromium.orgb59a7782010-11-24 18:38:33 +0000856}
857
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500858bool TCompiler::limitExpressionComplexity(TIntermNode *root)
Jamie Madilleb1a0102013-07-08 13:31:38 -0400859{
Jamie Madillacb4b812016-11-07 13:50:29 -0500860 TMaxDepthTraverser traverser(maxExpressionComplexity + 1);
Jamie Madilleb1a0102013-07-08 13:31:38 -0400861 root->traverse(&traverser);
Jamie Madill6654bc92014-03-26 14:01:57 -0400862
863 if (traverser.getMaxDepth() > maxExpressionComplexity)
864 {
Olli Etuaho77ba4082016-12-16 12:01:18 +0000865 mDiagnostics.globalError("Expression too complex.");
Jamie Madill6654bc92014-03-26 14:01:57 -0400866 return false;
867 }
868
Olli Etuaho19d1dc92016-03-08 17:18:46 +0200869 if (!ValidateMaxParameters::validate(root, maxFunctionParameters))
870 {
Olli Etuaho77ba4082016-12-16 12:01:18 +0000871 mDiagnostics.globalError("Function has too many parameters.");
Olli Etuaho19d1dc92016-03-08 17:18:46 +0200872 return false;
873 }
874
Jamie Madilleb1a0102013-07-08 13:31:38 -0400875 return true;
876}
877
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500878void TCompiler::collectVariables(TIntermNode *root)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000879{
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700880 if (!variablesCollected)
881 {
882 sh::CollectVariables collect(&attributes, &outputVariables, &uniforms, &varyings,
Jamie Madillacb4b812016-11-07 13:50:29 -0500883 &interfaceBlocks, hashFunction, symbolTable,
884 extensionBehavior);
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700885 root->traverse(&collect);
Jamie Madill23a8a432014-07-09 13:27:42 -0400886
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700887 // This is for enforcePackingRestriction().
888 sh::ExpandUniforms(uniforms, &expandedUniforms);
889 variablesCollected = true;
890 }
alokp@chromium.org07620a52010-09-23 17:53:56 +0000891}
zmo@google.comfd747b82011-04-23 01:30:07 +0000892
Corentin Wallez1df16022016-10-27 08:16:56 -0400893bool TCompiler::shouldCollectVariables(ShCompileOptions compileOptions)
894{
895 return (compileOptions & SH_VARIABLES) != 0;
896}
897
898bool TCompiler::wereVariablesCollected() const
899{
900 return variablesCollected;
901}
902
gman@chromium.org8d804792012-10-17 21:33:48 +0000903bool TCompiler::enforcePackingRestrictions()
904{
905 VariablePacker packer;
Jamie Madill23a8a432014-07-09 13:27:42 -0400906 return packer.CheckVariablesWithinPackingLimits(maxUniformVectors, expandedUniforms);
gman@chromium.org8d804792012-10-17 21:33:48 +0000907}
908
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500909void TCompiler::initializeGLPosition(TIntermNode *root)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800910{
Zhenyao Mo72111912016-07-20 17:45:56 -0700911 InitVariableList list;
912 sh::ShaderVariable var(GL_FLOAT_VEC4, 0);
913 var.name = "gl_Position";
914 list.push_back(var);
Zhenyao Mod7490962016-11-09 15:49:51 -0800915 InitializeVariables(root, list, symbolTable);
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800916}
917
Qin Jiajia7835b522016-10-08 11:20:17 +0800918void TCompiler::useAllMembersInUnusedStandardAndSharedBlocks(TIntermNode *root)
919{
920 sh::InterfaceBlockList list;
921
922 for (auto block : interfaceBlocks)
923 {
924 if (!block.staticUse &&
925 (block.layout == sh::BLOCKLAYOUT_STANDARD || block.layout == sh::BLOCKLAYOUT_SHARED))
926 {
927 list.push_back(block);
928 }
929 }
930
Zhenyao Mod7490962016-11-09 15:49:51 -0800931 sh::UseInterfaceBlockFields(root, list, symbolTable);
Qin Jiajia7835b522016-10-08 11:20:17 +0800932}
933
Olli Etuaho27776e32016-07-22 14:00:56 +0300934void TCompiler::initializeOutputVariables(TIntermNode *root)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800935{
Zhenyao Mo72111912016-07-20 17:45:56 -0700936 InitVariableList list;
937 if (shaderType == GL_VERTEX_SHADER)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800938 {
Zhenyao Mo72111912016-07-20 17:45:56 -0700939 for (auto var : varyings)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800940 {
Zhenyao Mof9312682016-07-22 12:51:31 -0700941 list.push_back(var);
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800942 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800943 }
Zhenyao Mo72111912016-07-20 17:45:56 -0700944 else
945 {
946 ASSERT(shaderType == GL_FRAGMENT_SHADER);
947 for (auto var : outputVariables)
948 {
949 list.push_back(var);
950 }
951 }
Zhenyao Mod7490962016-11-09 15:49:51 -0800952 InitializeVariables(root, list, symbolTable);
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800953}
954
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500955const TExtensionBehavior &TCompiler::getExtensionBehavior() const
zmo@google.com5601ea02011-06-10 18:23:25 +0000956{
957 return extensionBehavior;
958}
zmo@google.com32e97312011-08-24 01:03:11 +0000959
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200960const char *TCompiler::getSourcePath() const
961{
962 return mSourcePath;
963}
964
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500965const ShBuiltInResources &TCompiler::getResources() const
shannon.woods%transgaming.com@gtempaccount.com18b4c4b2013-04-13 03:31:40 +0000966{
967 return compileResources;
968}
969
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500970const ArrayBoundsClamper &TCompiler::getArrayBoundsClamper() const
daniel@transgaming.com4167cc92013-01-11 04:11:53 +0000971{
972 return arrayBoundsClamper;
973}
974
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000975ShArrayIndexClampingStrategy TCompiler::getArrayIndexClampingStrategy() const
976{
977 return clampingStrategy;
978}
979
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500980const BuiltInFunctionEmulator &TCompiler::getBuiltInFunctionEmulator() const
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000981{
982 return builtInFunctionEmulator;
983}
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700984
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800985void TCompiler::writePragma(ShCompileOptions compileOptions)
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700986{
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700987 if (!(compileOptions & SH_FLATTEN_PRAGMA_STDGL_INVARIANT_ALL))
988 {
989 TInfoSinkBase &sink = infoSink.obj;
990 if (mPragma.stdgl.invariantAll)
991 sink << "#pragma STDGL invariant(all)\n";
992 }
993}
994
995bool TCompiler::isVaryingDefined(const char *varyingName)
996{
997 ASSERT(variablesCollected);
998 for (size_t ii = 0; ii < varyings.size(); ++ii)
999 {
1000 if (varyings[ii].name == varyingName)
1001 {
1002 return true;
1003 }
1004 }
1005
1006 return false;
Zhenyao Mo94ac7b72014-10-15 18:22:08 -07001007}
Jamie Madillacb4b812016-11-07 13:50:29 -05001008
1009} // namespace sh