blob: de9d98f0d46cf66895729480afcfc8671fc4c019 [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/ForLoopUnroll.h"
20#include "compiler/translator/Initialize.h"
Geoff Lang17732822013-08-29 13:46:49 -040021#include "compiler/translator/InitializeParseContext.h"
Zhenyao Mo4a667fe2014-02-11 12:35:01 -080022#include "compiler/translator/InitializeVariables.h"
Jamie Madill6b9cb252013-10-17 10:45:47 -040023#include "compiler/translator/ParseContext.h"
Olli Etuahoc6833112015-04-22 15:15:54 +030024#include "compiler/translator/PruneEmptyDeclarations.h"
Zhenyao Moe740add2014-07-18 17:01:01 -070025#include "compiler/translator/RegenerateStructNames.h"
Qiankun Miao705a9192016-08-29 10:05:27 +080026#include "compiler/translator/RemoveInvariantDeclaration.h"
Olli Etuaho5c407bb2015-06-01 12:20:39 +030027#include "compiler/translator/RemovePow.h"
Corentin Wallezd4b50542015-09-28 12:19:26 -070028#include "compiler/translator/RewriteDoWhile.h"
Zhenyao Mocd68fe72014-07-11 10:45:44 -070029#include "compiler/translator/ScalarizeVecAndMatConstructorArgs.h"
Zhenyao Mo7cab38b2013-10-15 12:59:30 -070030#include "compiler/translator/UnfoldShortCircuitAST.h"
Qin Jiajia7835b522016-10-08 11:20:17 +080031#include "compiler/translator/UseInterfaceBlockFields.h"
Geoff Lang17732822013-08-29 13:46:49 -040032#include "compiler/translator/ValidateLimitations.h"
Olli Etuaho19d1dc92016-03-08 17:18:46 +020033#include "compiler/translator/ValidateMaxParameters.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{
Jamie Madill88f6e942014-02-19 10:27:53 -0500124 // WebGL defines a max token legnth of 256, while ES2 leaves max token
125 // 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
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000135namespace {
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700136
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800137class TScopedPoolAllocator
138{
139 public:
140 TScopedPoolAllocator(TPoolAllocator* allocator) : mAllocator(allocator)
141 {
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400142 mAllocator->push();
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000143 SetGlobalPoolAllocator(mAllocator);
144 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800145 ~TScopedPoolAllocator()
146 {
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000147 SetGlobalPoolAllocator(NULL);
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400148 mAllocator->pop();
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000149 }
150
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800151 private:
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000152 TPoolAllocator* mAllocator;
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400153};
154
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800155class TScopedSymbolTableLevel
156{
157 public:
158 TScopedSymbolTableLevel(TSymbolTable* table) : mTable(table)
159 {
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400160 ASSERT(mTable->atBuiltInLevel());
161 mTable->push();
162 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800163 ~TScopedSymbolTableLevel()
164 {
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400165 while (!mTable->atBuiltInLevel())
166 mTable->pop();
167 }
168
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800169 private:
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400170 TSymbolTable* mTable;
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000171};
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700172
173int MapSpecToShaderVersion(ShShaderSpec spec)
174{
175 switch (spec)
176 {
Jamie Madillacb4b812016-11-07 13:50:29 -0500177 case SH_GLES2_SPEC:
178 case SH_WEBGL_SPEC:
179 return 100;
180 case SH_GLES3_SPEC:
181 case SH_WEBGL2_SPEC:
182 return 300;
183 case SH_GLES3_1_SPEC:
184 case SH_WEBGL3_SPEC:
185 return 310;
186 default:
187 UNREACHABLE();
188 return 0;
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700189 }
190}
191
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000192} // namespace
193
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800194TShHandleBase::TShHandleBase()
195{
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000196 allocator.push();
197 SetGlobalPoolAllocator(&allocator);
198}
199
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800200TShHandleBase::~TShHandleBase()
201{
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000202 SetGlobalPoolAllocator(NULL);
203 allocator.popAll();
204}
205
Jamie Madill183bde52014-07-02 15:31:19 -0400206TCompiler::TCompiler(sh::GLenum type, ShShaderSpec spec, ShShaderOutput output)
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700207 : variablesCollected(false),
208 shaderType(type),
zmo@google.comf420c422011-09-12 18:27:59 +0000209 shaderSpec(spec),
Jamie Madill68fe74a2014-05-27 12:56:01 -0400210 outputType(output),
Jamie Madilleb1a0102013-07-08 13:31:38 -0400211 maxUniformVectors(0),
212 maxExpressionComplexity(0),
213 maxCallStackDepth(0),
Olli Etuaho19d1dc92016-03-08 17:18:46 +0200214 maxFunctionParameters(0),
shannon.woods%transgaming.com@gtempaccount.comcbb6b6a2013-04-13 03:27:47 +0000215 fragmentPrecisionHigh(false),
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000216 clampingStrategy(SH_CLAMP_WITH_CLAMP_INTRINSIC),
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200217 builtInFunctionEmulator(),
Corentin Wallezd4b50542015-09-28 12:19:26 -0700218 mSourcePath(NULL),
Martin Radev802abe02016-08-04 17:48:32 +0300219 mComputeShaderLocalSizeDeclared(false),
Corentin Wallezd4b50542015-09-28 12:19:26 -0700220 mTemporaryIndex(0)
alokp@chromium.org4888ceb2010-10-01 21:13:12 +0000221{
Martin Radev802abe02016-08-04 17:48:32 +0300222 mComputeShaderLocalSize.fill(1);
alokp@chromium.org4888ceb2010-10-01 21:13:12 +0000223}
224
225TCompiler::~TCompiler()
226{
227}
228
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800229bool TCompiler::shouldRunLoopAndIndexingValidation(ShCompileOptions compileOptions) const
Olli Etuaho5d91dda2015-06-18 15:47:46 +0300230{
231 // If compiling an ESSL 1.00 shader for WebGL, or if its been requested through the API,
232 // validate loop and indexing as well (to verify that the shader only uses minimal functionality
233 // of ESSL 1.00 as in Appendix A of the spec).
234 return (IsWebGLBasedSpec(shaderSpec) && shaderVersion == 100) ||
235 (compileOptions & SH_VALIDATE_LOOP_INDEXING);
236}
237
alokp@chromium.org4888ceb2010-10-01 21:13:12 +0000238bool TCompiler::Init(const ShBuiltInResources& resources)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000239{
shannon.woods%transgaming.com@gtempaccount.com0bbed382013-04-13 03:38:07 +0000240 shaderVersion = 100;
Jamie Madill183bde52014-07-02 15:31:19 -0400241 maxUniformVectors = (shaderType == GL_VERTEX_SHADER) ?
gman@chromium.org8d804792012-10-17 21:33:48 +0000242 resources.MaxVertexUniformVectors :
243 resources.MaxFragmentUniformVectors;
Jamie Madilleb1a0102013-07-08 13:31:38 -0400244 maxExpressionComplexity = resources.MaxExpressionComplexity;
Olli Etuaho19d1dc92016-03-08 17:18:46 +0200245 maxCallStackDepth = resources.MaxCallStackDepth;
246 maxFunctionParameters = resources.MaxFunctionParameters;
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400247
248 SetGlobalPoolAllocator(&allocator);
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000249
alokp@chromium.org07620a52010-09-23 17:53:56 +0000250 // Generate built-in symbol table.
251 if (!InitBuiltInSymbolTable(resources))
252 return false;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000253 InitExtensionBehavior(resources, extensionBehavior);
shannon.woods%transgaming.com@gtempaccount.comcbb6b6a2013-04-13 03:27:47 +0000254 fragmentPrecisionHigh = resources.FragmentPrecisionHigh == 1;
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000255
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000256 arrayBoundsClamper.SetClampingStrategy(resources.ArrayIndexClampingStrategy);
257 clampingStrategy = resources.ArrayIndexClampingStrategy;
258
daniel@transgaming.comc23f4612012-11-28 19:42:57 +0000259 hashFunction = resources.HashFunction;
260
alokp@chromium.org07620a52010-09-23 17:53:56 +0000261 return true;
262}
263
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100264TIntermBlock *TCompiler::compileTreeForTesting(const char *const shaderStrings[],
265 size_t numStrings,
266 ShCompileOptions compileOptions)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000267{
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200268 return compileTreeImpl(shaderStrings, numStrings, compileOptions);
269}
270
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100271TIntermBlock *TCompiler::compileTreeImpl(const char *const shaderStrings[],
272 size_t numStrings,
273 const ShCompileOptions compileOptions)
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200274{
alokp@chromium.org07620a52010-09-23 17:53:56 +0000275 clearResults();
276
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200277 ASSERT(numStrings > 0);
278 ASSERT(GetGlobalPoolAllocator());
alokp@chromium.org07620a52010-09-23 17:53:56 +0000279
David Yen0fbd1282015-02-02 14:46:09 -0800280 // Reset the extension behavior for each compilation unit.
281 ResetExtensionBehavior(extensionBehavior);
282
apatrick@chromium.org0f4cefe2011-01-26 19:30:57 +0000283 // First string is path of source file if flag is set. The actual source follows.
shannon.woods@transgaming.comd64b3da2013-02-28 23:19:26 +0000284 size_t firstSource = 0;
apatrick@chromium.org0f4cefe2011-01-26 19:30:57 +0000285 if (compileOptions & SH_SOURCE_PATH)
286 {
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200287 mSourcePath = shaderStrings[0];
apatrick@chromium.org0f4cefe2011-01-26 19:30:57 +0000288 ++firstSource;
289 }
290
Olli Etuahof119a262016-08-19 15:54:22 +0300291 TParseContext parseContext(symbolTable, extensionBehavior, shaderType, shaderSpec,
Olli Etuahoe1a94c62015-11-16 17:35:25 +0200292 compileOptions, true, infoSink, getResources());
Olli Etuaho853dc1a2014-11-06 17:25:48 +0200293
Olli Etuahoa6996682015-10-12 14:32:30 +0300294 parseContext.setFragmentPrecisionHighOnESSL1(fragmentPrecisionHigh);
Alok Priyadarshi8156b6b2013-09-23 14:56:58 -0400295 SetGlobalParseContext(&parseContext);
alokp@chromium.org07620a52010-09-23 17:53:56 +0000296
297 // We preserve symbols at the built-in level from compile-to-compile.
298 // Start pushing the user-defined symbols at global level.
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400299 TScopedSymbolTableLevel scopedSymbolLevel(&symbolTable);
alokp@chromium.org07620a52010-09-23 17:53:56 +0000300
301 // Parse shader.
302 bool success =
Jamie Madill6e06b1f2015-05-14 10:01:17 -0400303 (PaParseStrings(numStrings - firstSource, &shaderStrings[firstSource], nullptr, &parseContext) == 0) &&
304 (parseContext.getTreeRoot() != nullptr);
shannon.woods%transgaming.com@gtempaccount.com0bbed382013-04-13 03:38:07 +0000305
shannon.woods%transgaming.com@gtempaccount.com5524db02013-04-13 03:38:16 +0000306 shaderVersion = parseContext.getShaderVersion();
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700307 if (success && MapSpecToShaderVersion(shaderSpec) < shaderVersion)
308 {
309 infoSink.info.prefix(EPrefixError);
310 infoSink.info << "unsupported shader version";
311 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
Jamie Madill6e06b1f2015-05-14 10:01:17 -0400324 root = parseContext.getTreeRoot();
alokp@chromium.orgb59a7782010-11-24 18:38:33 +0000325
Olli Etuahoa6996682015-10-12 14:32:30 +0300326 // Highp might have been auto-enabled based on shader version
327 fragmentPrecisionHigh = parseContext.getFragmentPrecisionHigh();
328
Jamie Madill6654bc92014-03-26 14:01:57 -0400329 // Disallow expressions deemed too complex.
330 if (success && (compileOptions & SH_LIMIT_EXPRESSION_COMPLEXITY))
331 success = limitExpressionComplexity(root);
332
Corentin Wallez71d147f2015-02-11 11:15:24 -0800333 // Create the function DAG and check there is no recursion
zmo@google.comb1762df2011-07-30 02:04:23 +0000334 if (success)
Corentin Wallez71d147f2015-02-11 11:15:24 -0800335 success = initCallDag(root);
336
337 if (success && (compileOptions & SH_LIMIT_CALL_STACK_DEPTH))
338 success = checkCallDepth();
339
340 // Checks which functions are used and if "main" exists
341 if (success)
342 {
343 functionMetadata.clear();
344 functionMetadata.resize(mCallDag.size());
345 success = tagUsedFunctions();
346 }
zmo@google.comb1762df2011-07-30 02:04:23 +0000347
Corentin Walleza094a8a2015-04-07 11:53:06 -0700348 if (success && !(compileOptions & SH_DONT_PRUNE_UNUSED_FUNCTIONS))
349 success = pruneUnusedFunctions(root);
350
Olli Etuahoc6833112015-04-22 15:15:54 +0300351 // Prune empty declarations to work around driver bugs and to keep declaration output simple.
352 if (success)
353 PruneEmptyDeclarations(root);
354
Jamie Madill183bde52014-07-02 15:31:19 -0400355 if (success && shaderVersion == 300 && shaderType == GL_FRAGMENT_SHADER)
Jamie Madill05a80ce2013-06-20 11:55:49 -0400356 success = validateOutputs(root);
357
Olli Etuaho5d91dda2015-06-18 15:47:46 +0300358 if (success && shouldRunLoopAndIndexingValidation(compileOptions))
alokp@chromium.orgb59a7782010-11-24 18:38:33 +0000359 success = validateLimitations(root);
alokp@chromium.org07620a52010-09-23 17:53:56 +0000360
Jamie Madilld5696192016-10-06 11:09:24 -0400361 // Fail compilation if precision emulation not supported.
362 if (success && getResources().WEBGL_debug_shader_precision &&
363 getPragma().debugShaderPrecision)
364 {
365 if (!EmulatePrecision::SupportedInLanguage(outputType))
366 {
367 infoSink.info.prefix(EPrefixError);
368 infoSink.info << "Precision emulation not supported for this output type.";
369 success = false;
370 }
371 }
372
zmo@google.com0c6bb7a2011-08-17 19:39:58 +0000373 // Unroll for-loop markup needs to happen after validateLimitations pass.
374 if (success && (compileOptions & SH_UNROLL_FOR_LOOP_WITH_INTEGER_INDEX))
Zhenyao Mo3cdfcce2014-03-07 13:00:08 -0800375 {
Olli Etuaho8a76dcc2015-12-10 20:25:12 +0200376 ForLoopUnrollMarker marker(ForLoopUnrollMarker::kIntegerIndex,
377 shouldRunLoopAndIndexingValidation(compileOptions));
Zhenyao Mo550c6002014-02-26 15:40:48 -0800378 root->traverse(&marker);
379 }
380 if (success && (compileOptions & SH_UNROLL_FOR_LOOP_WITH_SAMPLER_ARRAY_INDEX))
Zhenyao Mo3cdfcce2014-03-07 13:00:08 -0800381 {
Olli Etuaho8a76dcc2015-12-10 20:25:12 +0200382 ForLoopUnrollMarker marker(ForLoopUnrollMarker::kSamplerArrayIndex,
383 shouldRunLoopAndIndexingValidation(compileOptions));
Zhenyao Mo550c6002014-02-26 15:40:48 -0800384 root->traverse(&marker);
385 if (marker.samplerArrayIndexIsFloatLoopIndex())
386 {
387 infoSink.info.prefix(EPrefixError);
388 infoSink.info << "sampler array index is float loop index";
389 success = false;
390 }
391 }
zmo@google.com0c6bb7a2011-08-17 19:39:58 +0000392
zmo@google.com32e97312011-08-24 01:03:11 +0000393 // Built-in function emulation needs to happen after validateLimitations pass.
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200394 if (success)
395 {
Jamie Madill438dbcf2016-06-17 14:20:05 -0400396 // TODO(jmadill): Remove global pool allocator.
397 GetGlobalPoolAllocator()->lock();
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200398 initBuiltInFunctionEmulator(&builtInFunctionEmulator, compileOptions);
Jamie Madill438dbcf2016-06-17 14:20:05 -0400399 GetGlobalPoolAllocator()->unlock();
zmo@google.com32e97312011-08-24 01:03:11 +0000400 builtInFunctionEmulator.MarkBuiltInFunctionsForEmulation(root);
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200401 }
zmo@google.com32e97312011-08-24 01:03:11 +0000402
daniel@transgaming.com4167cc92013-01-11 04:11:53 +0000403 // Clamping uniform array bounds needs to happen after validateLimitations pass.
404 if (success && (compileOptions & SH_CLAMP_INDIRECT_ARRAY_BOUNDS))
405 arrayBoundsClamper.MarkIndirectArrayBoundsForClamping(root);
406
Ian Ewell924b7de2016-01-21 13:54:28 -0500407 // gl_Position is always written in compatibility output mode
408 if (success && shaderType == GL_VERTEX_SHADER &&
409 ((compileOptions & SH_INIT_GL_POSITION) ||
410 (outputType == SH_GLSL_COMPATIBILITY_OUTPUT)))
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800411 initializeGLPosition(root);
Zhenyao Moac44cd22013-09-23 14:57:09 -0400412
Qiankun Miao89dd8f32016-11-09 12:59:30 +0000413 if (success && RemoveInvariant(shaderType, shaderVersion, outputType, compileOptions))
Qiankun Miao705a9192016-08-29 10:05:27 +0800414 sh::RemoveInvariantDeclaration(root);
415
Corentin Wallezd4b50542015-09-28 12:19:26 -0700416 // This pass might emit short circuits so keep it before the short circuit unfolding
417 if (success && (compileOptions & SH_REWRITE_DO_WHILE_LOOPS))
418 RewriteDoWhile(root, getTemporaryIndex());
419
Qiankun Miao09cfac62016-09-06 17:25:16 +0800420 if (success && (compileOptions & SH_ADD_AND_TRUE_TO_LOOP_CONDITION))
421 sh::AddAndTrueToLoopCondition(root);
422
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800423 if (success && (compileOptions & SH_UNFOLD_SHORT_CIRCUIT))
424 {
Zhenyao Mo7cab38b2013-10-15 12:59:30 -0700425 UnfoldShortCircuitAST unfoldShortCircuit;
426 root->traverse(&unfoldShortCircuit);
427 unfoldShortCircuit.updateTree();
428 }
429
Olli Etuaho5c407bb2015-06-01 12:20:39 +0300430 if (success && (compileOptions & SH_REMOVE_POW_WITH_CONSTANT_EXPONENT))
431 {
432 RemovePow(root);
433 }
434
Olli Etuaho4dfe8092015-08-21 17:44:35 +0300435 if (success && shouldCollectVariables(compileOptions))
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800436 {
Zhenyao Mo74da9f22013-09-23 14:57:01 -0400437 collectVariables(root);
Qin Jiajia7835b522016-10-08 11:20:17 +0800438 if (compileOptions & SH_USE_UNUSED_STANDARD_SHARED_BLOCKS)
439 {
440 useAllMembersInUnusedStandardAndSharedBlocks(root);
441 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800442 if (compileOptions & SH_ENFORCE_PACKING_RESTRICTIONS)
443 {
gman@chromium.org8d804792012-10-17 21:33:48 +0000444 success = enforcePackingRestrictions();
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800445 if (!success)
446 {
Jamie Madill075edd82013-07-08 13:30:19 -0400447 infoSink.info.prefix(EPrefixError);
448 infoSink.info << "too many uniforms";
gman@chromium.org8d804792012-10-17 21:33:48 +0000449 }
450 }
Zhenyao Mo72111912016-07-20 17:45:56 -0700451 if (success && (compileOptions & SH_INIT_OUTPUT_VARIABLES))
452 {
Olli Etuaho27776e32016-07-22 14:00:56 +0300453 initializeOutputVariables(root);
Zhenyao Mo72111912016-07-20 17:45:56 -0700454 }
gman@chromium.org8d804792012-10-17 21:33:48 +0000455 }
zmo@google.comfd747b82011-04-23 01:30:07 +0000456
Zhenyao Mocd68fe72014-07-11 10:45:44 -0700457 if (success && (compileOptions & SH_SCALARIZE_VEC_AND_MAT_CONSTRUCTOR_ARGS))
458 {
Olli Etuahob990b552016-10-27 12:29:17 +0100459 ScalarizeVecAndMatConstructorArgs(root, shaderType, fragmentPrecisionHigh,
460 &mTemporaryIndex);
Zhenyao Mocd68fe72014-07-11 10:45:44 -0700461 }
462
Zhenyao Moe740add2014-07-18 17:01:01 -0700463 if (success && (compileOptions & SH_REGENERATE_STRUCT_NAMES))
464 {
465 RegenerateStructNames gen(symbolTable, shaderVersion);
466 root->traverse(&gen);
467 }
Olli Etuaho3d932d82016-04-12 11:10:30 +0300468
Zhenyao Mo4e94fea2016-08-09 14:31:37 -0700469 if (success && shaderType == GL_FRAGMENT_SHADER && shaderVersion == 100 &&
470 compileResources.EXT_draw_buffers && compileResources.MaxDrawBuffers > 1 &&
471 IsExtensionEnabled(extensionBehavior, "GL_EXT_draw_buffers"))
472 {
473 EmulateGLFragColorBroadcast(root, compileResources.MaxDrawBuffers, &outputVariables);
474 }
475
Olli Etuaho3d932d82016-04-12 11:10:30 +0300476 if (success)
477 {
478 DeferGlobalInitializers(root);
479 }
alokp@chromium.org07620a52010-09-23 17:53:56 +0000480 }
481
Zhenyao Mo7faf1a12014-04-25 18:03:56 -0700482 SetGlobalParseContext(NULL);
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200483 if (success)
484 return root;
485
486 return NULL;
487}
488
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800489bool TCompiler::compile(const char *const shaderStrings[],
490 size_t numStrings,
491 ShCompileOptions compileOptionsIn)
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200492{
Corentin Wallez28b65282016-06-16 07:24:50 -0700493#if defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
494 DumpFuzzerCase(shaderStrings, numStrings, shaderType, shaderSpec, outputType, compileOptionsIn);
495#endif // defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
496
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200497 if (numStrings == 0)
498 return true;
499
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800500 ShCompileOptions compileOptions = compileOptionsIn;
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700501
502 // Apply key workarounds.
503 if (shouldFlattenPragmaStdglInvariantAll())
504 {
505 // This should be harmless to do in all cases, but for the moment, do it only conditionally.
506 compileOptions |= SH_FLATTEN_PRAGMA_STDGL_INVARIANT_ALL;
507 }
508
Corentin Wallezb2792db2016-10-07 11:21:09 -0400509 ShCompileOptions unrollFlags =
510 SH_UNROLL_FOR_LOOP_WITH_INTEGER_INDEX | SH_UNROLL_FOR_LOOP_WITH_SAMPLER_ARRAY_INDEX;
511 if ((compileOptions & SH_ADD_AND_TRUE_TO_LOOP_CONDITION) != 0 &&
512 (compileOptions & unrollFlags) != 0)
513 {
514 infoSink.info.prefix(EPrefixError);
515 infoSink.info
516 << "Unsupported compile flag combination: unroll & ADD_TRUE_TO_LOOP_CONDITION";
517 return false;
518 }
519
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200520 TScopedPoolAllocator scopedAlloc(&allocator);
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100521 TIntermBlock *root = compileTreeImpl(shaderStrings, numStrings, compileOptions);
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200522
523 if (root)
524 {
525 if (compileOptions & SH_INTERMEDIATE_TREE)
526 TIntermediate::outputTree(root, infoSink.info);
527
528 if (compileOptions & SH_OBJECT_CODE)
529 translate(root, compileOptions);
530
531 // The IntermNode tree doesn't need to be deleted here, since the
532 // memory will be freed in a big chunk by the PoolAllocator.
533 return true;
534 }
535 return false;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000536}
537
Nicolas Capens49a88872013-06-20 09:54:03 -0400538bool TCompiler::InitBuiltInSymbolTable(const ShBuiltInResources &resources)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000539{
shannon.woods%transgaming.com@gtempaccount.com18b4c4b2013-04-13 03:31:40 +0000540 compileResources = resources;
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400541 setResourceString();
shannonwoods@chromium.org2ac0be92013-05-30 00:02:27 +0000542
Nicolas Capens49a88872013-06-20 09:54:03 -0400543 assert(symbolTable.isEmpty());
544 symbolTable.push(); // COMMON_BUILTINS
545 symbolTable.push(); // ESSL1_BUILTINS
546 symbolTable.push(); // ESSL3_BUILTINS
Martin Radeve93d24e2016-07-28 12:06:05 +0300547 symbolTable.push(); // ESSL3_1_BUILTINS
shannonwoods@chromium.org2ac0be92013-05-30 00:02:27 +0000548
Nicolas Capens49a88872013-06-20 09:54:03 -0400549 TPublicType integer;
Martin Radev2cc85b32016-08-05 16:22:53 +0300550 integer.initializeBasicType(EbtInt);
Nicolas Capens49a88872013-06-20 09:54:03 -0400551
552 TPublicType floatingPoint;
Martin Radev2cc85b32016-08-05 16:22:53 +0300553 floatingPoint.initializeBasicType(EbtFloat);
Nicolas Capens49a88872013-06-20 09:54:03 -0400554
Jamie Madillacb4b812016-11-07 13:50:29 -0500555 switch (shaderType)
Nicolas Capens49a88872013-06-20 09:54:03 -0400556 {
Jamie Madillacb4b812016-11-07 13:50:29 -0500557 case GL_FRAGMENT_SHADER:
558 symbolTable.setDefaultPrecision(integer, EbpMedium);
559 break;
560 case GL_VERTEX_SHADER:
561 symbolTable.setDefaultPrecision(integer, EbpHigh);
562 symbolTable.setDefaultPrecision(floatingPoint, EbpHigh);
563 break;
564 case GL_COMPUTE_SHADER:
565 symbolTable.setDefaultPrecision(integer, EbpHigh);
566 symbolTable.setDefaultPrecision(floatingPoint, EbpHigh);
567 break;
568 default:
569 assert(false && "Language not supported");
Nicolas Capens49a88872013-06-20 09:54:03 -0400570 }
Olli Etuaho183d7e22015-11-20 15:59:09 +0200571 // Set defaults for sampler types that have default precision, even those that are
Zhenyao Moa5a1dfc2013-09-23 14:57:03 -0400572 // only available if an extension exists.
Olli Etuaho183d7e22015-11-20 15:59:09 +0200573 // New sampler types in ESSL3 don't have default precision. ESSL1 types do.
574 initSamplerDefaultPrecision(EbtSampler2D);
575 initSamplerDefaultPrecision(EbtSamplerCube);
576 // SamplerExternalOES is specified in the extension to have default precision.
577 initSamplerDefaultPrecision(EbtSamplerExternalOES);
578 // It isn't specified whether Sampler2DRect has default precision.
579 initSamplerDefaultPrecision(EbtSampler2DRect);
Nicolas Capens49a88872013-06-20 09:54:03 -0400580
Jamie Madill1b452142013-07-12 14:51:11 -0400581 InsertBuiltInFunctions(shaderType, shaderSpec, resources, symbolTable);
Nicolas Capens49a88872013-06-20 09:54:03 -0400582
583 IdentifyBuiltIns(shaderType, shaderSpec, resources, symbolTable);
584
585 return true;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000586}
587
Olli Etuaho183d7e22015-11-20 15:59:09 +0200588void TCompiler::initSamplerDefaultPrecision(TBasicType samplerType)
589{
590 ASSERT(samplerType > EbtGuardSamplerBegin && samplerType < EbtGuardSamplerEnd);
591 TPublicType sampler;
Martin Radev2cc85b32016-08-05 16:22:53 +0300592 sampler.initializeBasicType(samplerType);
Olli Etuaho183d7e22015-11-20 15:59:09 +0200593 symbolTable.setDefaultPrecision(sampler, EbpLow);
594}
595
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400596void TCompiler::setResourceString()
597{
598 std::ostringstream strstream;
Geoff Langb66a9092016-05-16 15:59:14 -0400599
600 // clang-format off
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400601 strstream << ":MaxVertexAttribs:" << compileResources.MaxVertexAttribs
Jamie Madillacb4b812016-11-07 13:50:29 -0500602 << ":MaxVertexUniformVectors:" << compileResources.MaxVertexUniformVectors
603 << ":MaxVaryingVectors:" << compileResources.MaxVaryingVectors
604 << ":MaxVertexTextureImageUnits:" << compileResources.MaxVertexTextureImageUnits
605 << ":MaxCombinedTextureImageUnits:" << compileResources.MaxCombinedTextureImageUnits
606 << ":MaxTextureImageUnits:" << compileResources.MaxTextureImageUnits
607 << ":MaxFragmentUniformVectors:" << compileResources.MaxFragmentUniformVectors
608 << ":MaxDrawBuffers:" << compileResources.MaxDrawBuffers
609 << ":OES_standard_derivatives:" << compileResources.OES_standard_derivatives
610 << ":OES_EGL_image_external:" << compileResources.OES_EGL_image_external
611 << ":OES_EGL_image_external_essl3:" << compileResources.OES_EGL_image_external_essl3
612 << ":NV_EGL_stream_consumer_external:" << compileResources.NV_EGL_stream_consumer_external
613 << ":ARB_texture_rectangle:" << compileResources.ARB_texture_rectangle
614 << ":EXT_draw_buffers:" << compileResources.EXT_draw_buffers
615 << ":FragmentPrecisionHigh:" << compileResources.FragmentPrecisionHigh
616 << ":MaxExpressionComplexity:" << compileResources.MaxExpressionComplexity
617 << ":MaxCallStackDepth:" << compileResources.MaxCallStackDepth
618 << ":MaxFunctionParameters:" << compileResources.MaxFunctionParameters
619 << ":EXT_blend_func_extended:" << compileResources.EXT_blend_func_extended
620 << ":EXT_frag_depth:" << compileResources.EXT_frag_depth
621 << ":EXT_shader_texture_lod:" << compileResources.EXT_shader_texture_lod
622 << ":EXT_shader_framebuffer_fetch:" << compileResources.EXT_shader_framebuffer_fetch
623 << ":NV_shader_framebuffer_fetch:" << compileResources.NV_shader_framebuffer_fetch
624 << ":ARM_shader_framebuffer_fetch:" << compileResources.ARM_shader_framebuffer_fetch
625 << ":MaxVertexOutputVectors:" << compileResources.MaxVertexOutputVectors
626 << ":MaxFragmentInputVectors:" << compileResources.MaxFragmentInputVectors
627 << ":MinProgramTexelOffset:" << compileResources.MinProgramTexelOffset
628 << ":MaxProgramTexelOffset:" << compileResources.MaxProgramTexelOffset
629 << ":MaxDualSourceDrawBuffers:" << compileResources.MaxDualSourceDrawBuffers
630 << ":NV_draw_buffers:" << compileResources.NV_draw_buffers
631 << ":WEBGL_debug_shader_precision:" << compileResources.WEBGL_debug_shader_precision
632 << ":MaxImageUnits:" << compileResources.MaxImageUnits
633 << ":MaxVertexImageUniforms:" << compileResources.MaxVertexImageUniforms
634 << ":MaxFragmentImageUniforms:" << compileResources.MaxFragmentImageUniforms
635 << ":MaxComputeImageUniforms:" << compileResources.MaxComputeImageUniforms
636 << ":MaxCombinedImageUniforms:" << compileResources.MaxCombinedImageUniforms
637 << ":MaxCombinedShaderOutputResources:" << compileResources.MaxCombinedShaderOutputResources
638 << ":MaxComputeWorkGroupCountX:" << compileResources.MaxComputeWorkGroupCount[0]
639 << ":MaxComputeWorkGroupCountY:" << compileResources.MaxComputeWorkGroupCount[1]
640 << ":MaxComputeWorkGroupCountZ:" << compileResources.MaxComputeWorkGroupCount[2]
641 << ":MaxComputeWorkGroupSizeX:" << compileResources.MaxComputeWorkGroupSize[0]
642 << ":MaxComputeWorkGroupSizeY:" << compileResources.MaxComputeWorkGroupSize[1]
643 << ":MaxComputeWorkGroupSizeZ:" << compileResources.MaxComputeWorkGroupSize[2]
644 << ":MaxComputeUniformComponents:" << compileResources.MaxComputeUniformComponents
645 << ":MaxComputeTextureImageUnits:" << compileResources.MaxComputeTextureImageUnits
646 << ":MaxComputeAtomicCounters:" << compileResources.MaxComputeAtomicCounters
647 << ":MaxComputeAtomicCounterBuffers:" << compileResources.MaxComputeAtomicCounterBuffers
648 << ":MaxVertexAtomicCounters:" << compileResources.MaxVertexAtomicCounters
649 << ":MaxFragmentAtomicCounters:" << compileResources.MaxFragmentAtomicCounters
650 << ":MaxCombinedAtomicCounters:" << compileResources.MaxCombinedAtomicCounters
651 << ":MaxAtomicCounterBindings:" << compileResources.MaxAtomicCounterBindings
652 << ":MaxVertexAtomicCounterBuffers:" << compileResources.MaxVertexAtomicCounterBuffers
653 << ":MaxFragmentAtomicCounterBuffers:" << compileResources.MaxFragmentAtomicCounterBuffers
654 << ":MaxCombinedAtomicCounterBuffers:" << compileResources.MaxCombinedAtomicCounterBuffers
655 << ":MaxAtomicCounterBufferSize:" << compileResources.MaxAtomicCounterBufferSize;
Geoff Langb66a9092016-05-16 15:59:14 -0400656 // clang-format on
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400657
658 builtInResourcesString = strstream.str();
659}
660
alokp@chromium.org07620a52010-09-23 17:53:56 +0000661void TCompiler::clearResults()
662{
daniel@transgaming.com4167cc92013-01-11 04:11:53 +0000663 arrayBoundsClamper.Cleanup();
alokp@chromium.org07620a52010-09-23 17:53:56 +0000664 infoSink.info.erase();
665 infoSink.obj.erase();
666 infoSink.debug.erase();
667
Jamie Madilled27c722014-07-02 15:31:23 -0400668 attributes.clear();
669 outputVariables.clear();
alokp@chromium.org07620a52010-09-23 17:53:56 +0000670 uniforms.clear();
Jamie Madill23a8a432014-07-09 13:27:42 -0400671 expandedUniforms.clear();
Zhenyao Mod2d340b2013-09-23 14:57:05 -0400672 varyings.clear();
Jamie Madilled27c722014-07-02 15:31:23 -0400673 interfaceBlocks.clear();
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700674 variablesCollected = false;
zmo@google.coma3b4ab42011-09-16 00:53:26 +0000675
676 builtInFunctionEmulator.Cleanup();
daniel@transgaming.com0aa3b5a2012-11-28 19:43:24 +0000677
678 nameMap.clear();
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200679
680 mSourcePath = NULL;
Corentin Wallezd4b50542015-09-28 12:19:26 -0700681 mTemporaryIndex = 0;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000682}
683
Corentin Wallez71d147f2015-02-11 11:15:24 -0800684bool TCompiler::initCallDag(TIntermNode *root)
zmo@google.comb1762df2011-07-30 02:04:23 +0000685{
Corentin Wallez71d147f2015-02-11 11:15:24 -0800686 mCallDag.clear();
687
688 switch (mCallDag.init(root, &infoSink.info))
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800689 {
Jamie Madillacb4b812016-11-07 13:50:29 -0500690 case CallDAG::INITDAG_SUCCESS:
691 return true;
692 case CallDAG::INITDAG_RECURSION:
693 infoSink.info.prefix(EPrefixError);
694 infoSink.info << "Function recursion detected";
695 return false;
696 case CallDAG::INITDAG_UNDEFINED:
697 infoSink.info.prefix(EPrefixError);
698 infoSink.info << "Unimplemented function detected";
699 return false;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800700 }
701
702 UNREACHABLE();
703 return true;
704}
705
706bool TCompiler::checkCallDepth()
707{
708 std::vector<int> depths(mCallDag.size());
709
710 for (size_t i = 0; i < mCallDag.size(); i++)
711 {
712 int depth = 0;
713 auto &record = mCallDag.getRecordFromIndex(i);
714
715 for (auto &calleeIndex : record.callees)
716 {
717 depth = std::max(depth, depths[calleeIndex] + 1);
718 }
719
720 depths[i] = depth;
721
722 if (depth >= maxCallStackDepth)
723 {
724 // Trace back the function chain to have a meaningful info log.
725 infoSink.info.prefix(EPrefixError);
726 infoSink.info << "Call stack too deep (larger than " << maxCallStackDepth
727 << ") with the following call chain: " << record.name;
728
Cooper Partin4d61f7e2015-08-12 10:56:50 -0700729 int currentFunction = static_cast<int>(i);
Corentin Wallez71d147f2015-02-11 11:15:24 -0800730 int currentDepth = depth;
731
732 while (currentFunction != -1)
733 {
734 infoSink.info << " -> " << mCallDag.getRecordFromIndex(currentFunction).name;
735
736 int nextFunction = -1;
737 for (auto& calleeIndex : mCallDag.getRecordFromIndex(currentFunction).callees)
738 {
739 if (depths[calleeIndex] == currentDepth - 1)
740 {
741 currentDepth--;
742 nextFunction = calleeIndex;
743 }
744 }
745
746 currentFunction = nextFunction;
747 }
748
749 return false;
750 }
751 }
752
753 return true;
754}
755
756bool TCompiler::tagUsedFunctions()
757{
758 // Search from main, starting from the end of the DAG as it usually is the root.
Cooper Partin4d61f7e2015-08-12 10:56:50 -0700759 for (size_t i = mCallDag.size(); i-- > 0;)
Corentin Wallez71d147f2015-02-11 11:15:24 -0800760 {
761 if (mCallDag.getRecordFromIndex(i).name == "main(")
762 {
763 internalTagUsedFunction(i);
764 return true;
765 }
766 }
767
768 infoSink.info.prefix(EPrefixError);
Olli Etuaho792a41d2015-12-15 12:39:16 +0200769 infoSink.info << "Missing main()\n";
Corentin Wallez71d147f2015-02-11 11:15:24 -0800770 return false;
771}
772
773void TCompiler::internalTagUsedFunction(size_t index)
774{
775 if (functionMetadata[index].used)
776 {
777 return;
778 }
779
780 functionMetadata[index].used = true;
781
782 for (int calleeIndex : mCallDag.getRecordFromIndex(index).callees)
783 {
784 internalTagUsedFunction(calleeIndex);
zmo@google.comb1762df2011-07-30 02:04:23 +0000785 }
786}
787
Corentin Walleza094a8a2015-04-07 11:53:06 -0700788// A predicate for the stl that returns if a top-level node is unused
789class TCompiler::UnusedPredicate
790{
791 public:
792 UnusedPredicate(const CallDAG *callDag, const std::vector<FunctionMetadata> *metadatas)
Jamie Madillacb4b812016-11-07 13:50:29 -0500793 : mCallDag(callDag), mMetadatas(metadatas)
Corentin Walleza094a8a2015-04-07 11:53:06 -0700794 {
795 }
796
797 bool operator ()(TIntermNode *node)
798 {
799 const TIntermAggregate *asAggregate = node->getAsAggregate();
Olli Etuaho336b1472016-10-05 16:37:55 +0100800 const TIntermFunctionDefinition *asFunction = node->getAsFunctionDefinition();
Corentin Walleza094a8a2015-04-07 11:53:06 -0700801
Olli Etuaho336b1472016-10-05 16:37:55 +0100802 const TFunctionSymbolInfo *functionInfo = nullptr;
803
804 if (asFunction)
805 {
806 functionInfo = asFunction->getFunctionSymbolInfo();
807 }
808 else if (asAggregate)
809 {
810 if (asAggregate->getOp() == EOpPrototype)
811 {
812 functionInfo = asAggregate->getFunctionSymbolInfo();
813 }
814 }
815 if (functionInfo == nullptr)
Corentin Walleza094a8a2015-04-07 11:53:06 -0700816 {
817 return false;
818 }
819
Olli Etuaho336b1472016-10-05 16:37:55 +0100820 size_t callDagIndex = mCallDag->findIndex(functionInfo);
Corentin Walleza094a8a2015-04-07 11:53:06 -0700821 if (callDagIndex == CallDAG::InvalidIndex)
822 {
823 // This happens only for unimplemented prototypes which are thus unused
Olli Etuaho336b1472016-10-05 16:37:55 +0100824 ASSERT(asAggregate && asAggregate->getOp() == EOpPrototype);
Corentin Walleza094a8a2015-04-07 11:53:06 -0700825 return true;
826 }
827
828 ASSERT(callDagIndex < mMetadatas->size());
829 return !(*mMetadatas)[callDagIndex].used;
830 }
831
832 private:
833 const CallDAG *mCallDag;
834 const std::vector<FunctionMetadata> *mMetadatas;
835};
836
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100837bool TCompiler::pruneUnusedFunctions(TIntermBlock *root)
Corentin Walleza094a8a2015-04-07 11:53:06 -0700838{
Corentin Walleza094a8a2015-04-07 11:53:06 -0700839 UnusedPredicate isUnused(&mCallDag, &functionMetadata);
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100840 TIntermSequence *sequence = root->getSequence();
Corentin Wallezb081e782015-07-20 05:40:04 -0700841
842 if (!sequence->empty())
843 {
844 sequence->erase(std::remove_if(sequence->begin(), sequence->end(), isUnused), sequence->end());
845 }
Corentin Walleza094a8a2015-04-07 11:53:06 -0700846
847 return true;
848}
849
Jamie Madill05a80ce2013-06-20 11:55:49 -0400850bool TCompiler::validateOutputs(TIntermNode* root)
851{
Kimmo Kinnunenb18609b2015-07-16 14:13:11 +0300852 ValidateOutputs validateOutputs(getExtensionBehavior(), compileResources.MaxDrawBuffers);
Jamie Madill05a80ce2013-06-20 11:55:49 -0400853 root->traverse(&validateOutputs);
Kimmo Kinnunenb18609b2015-07-16 14:13:11 +0300854 return (validateOutputs.validateAndCountErrors(infoSink.info) == 0);
Jamie Madill05a80ce2013-06-20 11:55:49 -0400855}
856
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800857bool TCompiler::validateLimitations(TIntermNode* root)
858{
Olli Etuaho8a76dcc2015-12-10 20:25:12 +0200859 ValidateLimitations validate(shaderType, &infoSink.info);
alokp@chromium.orgb59a7782010-11-24 18:38:33 +0000860 root->traverse(&validate);
861 return validate.numErrors() == 0;
862}
863
Jamie Madilleb1a0102013-07-08 13:31:38 -0400864bool TCompiler::limitExpressionComplexity(TIntermNode* root)
865{
Jamie Madillacb4b812016-11-07 13:50:29 -0500866 TMaxDepthTraverser traverser(maxExpressionComplexity + 1);
Jamie Madilleb1a0102013-07-08 13:31:38 -0400867 root->traverse(&traverser);
Jamie Madill6654bc92014-03-26 14:01:57 -0400868
869 if (traverser.getMaxDepth() > maxExpressionComplexity)
870 {
871 infoSink.info << "Expression too complex.";
872 return false;
873 }
874
Olli Etuaho19d1dc92016-03-08 17:18:46 +0200875 if (!ValidateMaxParameters::validate(root, maxFunctionParameters))
876 {
877 infoSink.info << "Function has too many parameters.";
878 return false;
879 }
880
Jamie Madilleb1a0102013-07-08 13:31:38 -0400881 return true;
882}
883
Zhenyao Mo74da9f22013-09-23 14:57:01 -0400884void TCompiler::collectVariables(TIntermNode* root)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000885{
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700886 if (!variablesCollected)
887 {
888 sh::CollectVariables collect(&attributes, &outputVariables, &uniforms, &varyings,
Jamie Madillacb4b812016-11-07 13:50:29 -0500889 &interfaceBlocks, hashFunction, symbolTable,
890 extensionBehavior);
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700891 root->traverse(&collect);
Jamie Madill23a8a432014-07-09 13:27:42 -0400892
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700893 // This is for enforcePackingRestriction().
894 sh::ExpandUniforms(uniforms, &expandedUniforms);
895 variablesCollected = true;
896 }
alokp@chromium.org07620a52010-09-23 17:53:56 +0000897}
zmo@google.comfd747b82011-04-23 01:30:07 +0000898
Corentin Wallez1df16022016-10-27 08:16:56 -0400899bool TCompiler::shouldCollectVariables(ShCompileOptions compileOptions)
900{
901 return (compileOptions & SH_VARIABLES) != 0;
902}
903
904bool TCompiler::wereVariablesCollected() const
905{
906 return variablesCollected;
907}
908
gman@chromium.org8d804792012-10-17 21:33:48 +0000909bool TCompiler::enforcePackingRestrictions()
910{
911 VariablePacker packer;
Jamie Madill23a8a432014-07-09 13:27:42 -0400912 return packer.CheckVariablesWithinPackingLimits(maxUniformVectors, expandedUniforms);
gman@chromium.org8d804792012-10-17 21:33:48 +0000913}
914
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800915void TCompiler::initializeGLPosition(TIntermNode* root)
916{
Zhenyao Mo72111912016-07-20 17:45:56 -0700917 InitVariableList list;
918 sh::ShaderVariable var(GL_FLOAT_VEC4, 0);
919 var.name = "gl_Position";
920 list.push_back(var);
Zhenyao Mod7490962016-11-09 15:49:51 -0800921 InitializeVariables(root, list, symbolTable);
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800922}
923
Qin Jiajia7835b522016-10-08 11:20:17 +0800924void TCompiler::useAllMembersInUnusedStandardAndSharedBlocks(TIntermNode *root)
925{
926 sh::InterfaceBlockList list;
927
928 for (auto block : interfaceBlocks)
929 {
930 if (!block.staticUse &&
931 (block.layout == sh::BLOCKLAYOUT_STANDARD || block.layout == sh::BLOCKLAYOUT_SHARED))
932 {
933 list.push_back(block);
934 }
935 }
936
Zhenyao Mod7490962016-11-09 15:49:51 -0800937 sh::UseInterfaceBlockFields(root, list, symbolTable);
Qin Jiajia7835b522016-10-08 11:20:17 +0800938}
939
Olli Etuaho27776e32016-07-22 14:00:56 +0300940void TCompiler::initializeOutputVariables(TIntermNode *root)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800941{
Zhenyao Mo72111912016-07-20 17:45:56 -0700942 InitVariableList list;
943 if (shaderType == GL_VERTEX_SHADER)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800944 {
Zhenyao Mo72111912016-07-20 17:45:56 -0700945 for (auto var : varyings)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800946 {
Zhenyao Mof9312682016-07-22 12:51:31 -0700947 list.push_back(var);
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800948 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800949 }
Zhenyao Mo72111912016-07-20 17:45:56 -0700950 else
951 {
952 ASSERT(shaderType == GL_FRAGMENT_SHADER);
953 for (auto var : outputVariables)
954 {
955 list.push_back(var);
956 }
957 }
Zhenyao Mod7490962016-11-09 15:49:51 -0800958 InitializeVariables(root, list, symbolTable);
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800959}
960
zmo@google.com5601ea02011-06-10 18:23:25 +0000961const TExtensionBehavior& TCompiler::getExtensionBehavior() const
962{
963 return extensionBehavior;
964}
zmo@google.com32e97312011-08-24 01:03:11 +0000965
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200966const char *TCompiler::getSourcePath() const
967{
968 return mSourcePath;
969}
970
shannon.woods%transgaming.com@gtempaccount.com18b4c4b2013-04-13 03:31:40 +0000971const ShBuiltInResources& TCompiler::getResources() const
972{
973 return compileResources;
974}
975
daniel@transgaming.com4167cc92013-01-11 04:11:53 +0000976const ArrayBoundsClamper& TCompiler::getArrayBoundsClamper() const
977{
978 return arrayBoundsClamper;
979}
980
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000981ShArrayIndexClampingStrategy TCompiler::getArrayIndexClampingStrategy() const
982{
983 return clampingStrategy;
984}
985
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200986const BuiltInFunctionEmulator& TCompiler::getBuiltInFunctionEmulator() const
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000987{
988 return builtInFunctionEmulator;
989}
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700990
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800991void TCompiler::writePragma(ShCompileOptions compileOptions)
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700992{
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700993 if (!(compileOptions & SH_FLATTEN_PRAGMA_STDGL_INVARIANT_ALL))
994 {
995 TInfoSinkBase &sink = infoSink.obj;
996 if (mPragma.stdgl.invariantAll)
997 sink << "#pragma STDGL invariant(all)\n";
998 }
999}
1000
1001bool TCompiler::isVaryingDefined(const char *varyingName)
1002{
1003 ASSERT(variablesCollected);
1004 for (size_t ii = 0; ii < varyings.size(); ++ii)
1005 {
1006 if (varyings[ii].name == varyingName)
1007 {
1008 return true;
1009 }
1010 }
1011
1012 return false;
Zhenyao Mo94ac7b72014-10-15 18:22:08 -07001013}
Jamie Madillacb4b812016-11-07 13:50:29 -05001014
1015} // namespace sh