blob: 7689a032b146cc931717a2b63cb7e29c919789b8 [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 Mo7faf1a12014-04-25 18:03:56 -070099size_t GetGlobalMaxTokenSize(ShShaderSpec spec)
Jamie Madill88f6e942014-02-19 10:27:53 -0500100{
Jamie Madill88f6e942014-02-19 10:27:53 -0500101 // WebGL defines a max token legnth of 256, while ES2 leaves max token
102 // size undefined. ES3 defines a max size of 1024 characters.
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700103 switch (spec)
Jamie Madill88f6e942014-02-19 10:27:53 -0500104 {
Jamie Madillacb4b812016-11-07 13:50:29 -0500105 case SH_WEBGL_SPEC:
106 return 256;
107 default:
108 return 1024;
Jamie Madill88f6e942014-02-19 10:27:53 -0500109 }
110}
111
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000112namespace {
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700113
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800114class TScopedPoolAllocator
115{
116 public:
117 TScopedPoolAllocator(TPoolAllocator* allocator) : mAllocator(allocator)
118 {
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400119 mAllocator->push();
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000120 SetGlobalPoolAllocator(mAllocator);
121 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800122 ~TScopedPoolAllocator()
123 {
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000124 SetGlobalPoolAllocator(NULL);
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400125 mAllocator->pop();
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000126 }
127
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800128 private:
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000129 TPoolAllocator* mAllocator;
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400130};
131
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800132class TScopedSymbolTableLevel
133{
134 public:
135 TScopedSymbolTableLevel(TSymbolTable* table) : mTable(table)
136 {
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400137 ASSERT(mTable->atBuiltInLevel());
138 mTable->push();
139 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800140 ~TScopedSymbolTableLevel()
141 {
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400142 while (!mTable->atBuiltInLevel())
143 mTable->pop();
144 }
145
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800146 private:
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400147 TSymbolTable* mTable;
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000148};
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700149
150int MapSpecToShaderVersion(ShShaderSpec spec)
151{
152 switch (spec)
153 {
Jamie Madillacb4b812016-11-07 13:50:29 -0500154 case SH_GLES2_SPEC:
155 case SH_WEBGL_SPEC:
156 return 100;
157 case SH_GLES3_SPEC:
158 case SH_WEBGL2_SPEC:
159 return 300;
160 case SH_GLES3_1_SPEC:
161 case SH_WEBGL3_SPEC:
162 return 310;
163 default:
164 UNREACHABLE();
165 return 0;
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700166 }
167}
168
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000169} // namespace
170
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800171TShHandleBase::TShHandleBase()
172{
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000173 allocator.push();
174 SetGlobalPoolAllocator(&allocator);
175}
176
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800177TShHandleBase::~TShHandleBase()
178{
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000179 SetGlobalPoolAllocator(NULL);
180 allocator.popAll();
181}
182
Jamie Madill183bde52014-07-02 15:31:19 -0400183TCompiler::TCompiler(sh::GLenum type, ShShaderSpec spec, ShShaderOutput output)
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700184 : variablesCollected(false),
185 shaderType(type),
zmo@google.comf420c422011-09-12 18:27:59 +0000186 shaderSpec(spec),
Jamie Madill68fe74a2014-05-27 12:56:01 -0400187 outputType(output),
Jamie Madilleb1a0102013-07-08 13:31:38 -0400188 maxUniformVectors(0),
189 maxExpressionComplexity(0),
190 maxCallStackDepth(0),
Olli Etuaho19d1dc92016-03-08 17:18:46 +0200191 maxFunctionParameters(0),
shannon.woods%transgaming.com@gtempaccount.comcbb6b6a2013-04-13 03:27:47 +0000192 fragmentPrecisionHigh(false),
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000193 clampingStrategy(SH_CLAMP_WITH_CLAMP_INTRINSIC),
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200194 builtInFunctionEmulator(),
Corentin Wallezd4b50542015-09-28 12:19:26 -0700195 mSourcePath(NULL),
Martin Radev802abe02016-08-04 17:48:32 +0300196 mComputeShaderLocalSizeDeclared(false),
Corentin Wallezd4b50542015-09-28 12:19:26 -0700197 mTemporaryIndex(0)
alokp@chromium.org4888ceb2010-10-01 21:13:12 +0000198{
Martin Radev802abe02016-08-04 17:48:32 +0300199 mComputeShaderLocalSize.fill(1);
alokp@chromium.org4888ceb2010-10-01 21:13:12 +0000200}
201
202TCompiler::~TCompiler()
203{
204}
205
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800206bool TCompiler::shouldRunLoopAndIndexingValidation(ShCompileOptions compileOptions) const
Olli Etuaho5d91dda2015-06-18 15:47:46 +0300207{
208 // If compiling an ESSL 1.00 shader for WebGL, or if its been requested through the API,
209 // validate loop and indexing as well (to verify that the shader only uses minimal functionality
210 // of ESSL 1.00 as in Appendix A of the spec).
211 return (IsWebGLBasedSpec(shaderSpec) && shaderVersion == 100) ||
212 (compileOptions & SH_VALIDATE_LOOP_INDEXING);
213}
214
alokp@chromium.org4888ceb2010-10-01 21:13:12 +0000215bool TCompiler::Init(const ShBuiltInResources& resources)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000216{
shannon.woods%transgaming.com@gtempaccount.com0bbed382013-04-13 03:38:07 +0000217 shaderVersion = 100;
Jamie Madill183bde52014-07-02 15:31:19 -0400218 maxUniformVectors = (shaderType == GL_VERTEX_SHADER) ?
gman@chromium.org8d804792012-10-17 21:33:48 +0000219 resources.MaxVertexUniformVectors :
220 resources.MaxFragmentUniformVectors;
Jamie Madilleb1a0102013-07-08 13:31:38 -0400221 maxExpressionComplexity = resources.MaxExpressionComplexity;
Olli Etuaho19d1dc92016-03-08 17:18:46 +0200222 maxCallStackDepth = resources.MaxCallStackDepth;
223 maxFunctionParameters = resources.MaxFunctionParameters;
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400224
225 SetGlobalPoolAllocator(&allocator);
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000226
alokp@chromium.org07620a52010-09-23 17:53:56 +0000227 // Generate built-in symbol table.
228 if (!InitBuiltInSymbolTable(resources))
229 return false;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000230 InitExtensionBehavior(resources, extensionBehavior);
shannon.woods%transgaming.com@gtempaccount.comcbb6b6a2013-04-13 03:27:47 +0000231 fragmentPrecisionHigh = resources.FragmentPrecisionHigh == 1;
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000232
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000233 arrayBoundsClamper.SetClampingStrategy(resources.ArrayIndexClampingStrategy);
234 clampingStrategy = resources.ArrayIndexClampingStrategy;
235
daniel@transgaming.comc23f4612012-11-28 19:42:57 +0000236 hashFunction = resources.HashFunction;
237
alokp@chromium.org07620a52010-09-23 17:53:56 +0000238 return true;
239}
240
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100241TIntermBlock *TCompiler::compileTreeForTesting(const char *const shaderStrings[],
242 size_t numStrings,
243 ShCompileOptions compileOptions)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000244{
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200245 return compileTreeImpl(shaderStrings, numStrings, compileOptions);
246}
247
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100248TIntermBlock *TCompiler::compileTreeImpl(const char *const shaderStrings[],
249 size_t numStrings,
250 const ShCompileOptions compileOptions)
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200251{
alokp@chromium.org07620a52010-09-23 17:53:56 +0000252 clearResults();
253
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200254 ASSERT(numStrings > 0);
255 ASSERT(GetGlobalPoolAllocator());
alokp@chromium.org07620a52010-09-23 17:53:56 +0000256
David Yen0fbd1282015-02-02 14:46:09 -0800257 // Reset the extension behavior for each compilation unit.
258 ResetExtensionBehavior(extensionBehavior);
259
apatrick@chromium.org0f4cefe2011-01-26 19:30:57 +0000260 // First string is path of source file if flag is set. The actual source follows.
shannon.woods@transgaming.comd64b3da2013-02-28 23:19:26 +0000261 size_t firstSource = 0;
apatrick@chromium.org0f4cefe2011-01-26 19:30:57 +0000262 if (compileOptions & SH_SOURCE_PATH)
263 {
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200264 mSourcePath = shaderStrings[0];
apatrick@chromium.org0f4cefe2011-01-26 19:30:57 +0000265 ++firstSource;
266 }
267
Olli Etuahof119a262016-08-19 15:54:22 +0300268 TParseContext parseContext(symbolTable, extensionBehavior, shaderType, shaderSpec,
Olli Etuahoe1a94c62015-11-16 17:35:25 +0200269 compileOptions, true, infoSink, getResources());
Olli Etuaho853dc1a2014-11-06 17:25:48 +0200270
Olli Etuahoa6996682015-10-12 14:32:30 +0300271 parseContext.setFragmentPrecisionHighOnESSL1(fragmentPrecisionHigh);
Alok Priyadarshi8156b6b2013-09-23 14:56:58 -0400272 SetGlobalParseContext(&parseContext);
alokp@chromium.org07620a52010-09-23 17:53:56 +0000273
274 // We preserve symbols at the built-in level from compile-to-compile.
275 // Start pushing the user-defined symbols at global level.
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400276 TScopedSymbolTableLevel scopedSymbolLevel(&symbolTable);
alokp@chromium.org07620a52010-09-23 17:53:56 +0000277
278 // Parse shader.
279 bool success =
Jamie Madill6e06b1f2015-05-14 10:01:17 -0400280 (PaParseStrings(numStrings - firstSource, &shaderStrings[firstSource], nullptr, &parseContext) == 0) &&
281 (parseContext.getTreeRoot() != nullptr);
shannon.woods%transgaming.com@gtempaccount.com0bbed382013-04-13 03:38:07 +0000282
shannon.woods%transgaming.com@gtempaccount.com5524db02013-04-13 03:38:16 +0000283 shaderVersion = parseContext.getShaderVersion();
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700284 if (success && MapSpecToShaderVersion(shaderSpec) < shaderVersion)
285 {
286 infoSink.info.prefix(EPrefixError);
287 infoSink.info << "unsupported shader version";
288 success = false;
289 }
shannon.woods%transgaming.com@gtempaccount.com0bbed382013-04-13 03:38:07 +0000290
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100291 TIntermBlock *root = nullptr;
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200292
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800293 if (success)
294 {
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700295 mPragma = parseContext.pragma();
Kenneth Russell8bad46d2016-07-01 19:52:52 -0700296 symbolTable.setGlobalInvariant(mPragma.stdgl.invariantAll);
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700297
Martin Radev802abe02016-08-04 17:48:32 +0300298 mComputeShaderLocalSizeDeclared = parseContext.isComputeShaderLocalSizeDeclared();
299 mComputeShaderLocalSize = parseContext.getComputeShaderLocalSize();
300
Jamie Madill6e06b1f2015-05-14 10:01:17 -0400301 root = parseContext.getTreeRoot();
alokp@chromium.orgb59a7782010-11-24 18:38:33 +0000302
Olli Etuahoa6996682015-10-12 14:32:30 +0300303 // Highp might have been auto-enabled based on shader version
304 fragmentPrecisionHigh = parseContext.getFragmentPrecisionHigh();
305
Jamie Madill6654bc92014-03-26 14:01:57 -0400306 // Disallow expressions deemed too complex.
307 if (success && (compileOptions & SH_LIMIT_EXPRESSION_COMPLEXITY))
308 success = limitExpressionComplexity(root);
309
Corentin Wallez71d147f2015-02-11 11:15:24 -0800310 // Create the function DAG and check there is no recursion
zmo@google.comb1762df2011-07-30 02:04:23 +0000311 if (success)
Corentin Wallez71d147f2015-02-11 11:15:24 -0800312 success = initCallDag(root);
313
314 if (success && (compileOptions & SH_LIMIT_CALL_STACK_DEPTH))
315 success = checkCallDepth();
316
317 // Checks which functions are used and if "main" exists
318 if (success)
319 {
320 functionMetadata.clear();
321 functionMetadata.resize(mCallDag.size());
322 success = tagUsedFunctions();
323 }
zmo@google.comb1762df2011-07-30 02:04:23 +0000324
Corentin Walleza094a8a2015-04-07 11:53:06 -0700325 if (success && !(compileOptions & SH_DONT_PRUNE_UNUSED_FUNCTIONS))
326 success = pruneUnusedFunctions(root);
327
Olli Etuahoc6833112015-04-22 15:15:54 +0300328 // Prune empty declarations to work around driver bugs and to keep declaration output simple.
329 if (success)
330 PruneEmptyDeclarations(root);
331
Jamie Madill183bde52014-07-02 15:31:19 -0400332 if (success && shaderVersion == 300 && shaderType == GL_FRAGMENT_SHADER)
Jamie Madill05a80ce2013-06-20 11:55:49 -0400333 success = validateOutputs(root);
334
Olli Etuaho5d91dda2015-06-18 15:47:46 +0300335 if (success && shouldRunLoopAndIndexingValidation(compileOptions))
alokp@chromium.orgb59a7782010-11-24 18:38:33 +0000336 success = validateLimitations(root);
alokp@chromium.org07620a52010-09-23 17:53:56 +0000337
Jamie Madilld5696192016-10-06 11:09:24 -0400338 // Fail compilation if precision emulation not supported.
339 if (success && getResources().WEBGL_debug_shader_precision &&
340 getPragma().debugShaderPrecision)
341 {
342 if (!EmulatePrecision::SupportedInLanguage(outputType))
343 {
344 infoSink.info.prefix(EPrefixError);
345 infoSink.info << "Precision emulation not supported for this output type.";
346 success = false;
347 }
348 }
349
zmo@google.com0c6bb7a2011-08-17 19:39:58 +0000350 // Unroll for-loop markup needs to happen after validateLimitations pass.
351 if (success && (compileOptions & SH_UNROLL_FOR_LOOP_WITH_INTEGER_INDEX))
Zhenyao Mo3cdfcce2014-03-07 13:00:08 -0800352 {
Olli Etuaho8a76dcc2015-12-10 20:25:12 +0200353 ForLoopUnrollMarker marker(ForLoopUnrollMarker::kIntegerIndex,
354 shouldRunLoopAndIndexingValidation(compileOptions));
Zhenyao Mo550c6002014-02-26 15:40:48 -0800355 root->traverse(&marker);
356 }
357 if (success && (compileOptions & SH_UNROLL_FOR_LOOP_WITH_SAMPLER_ARRAY_INDEX))
Zhenyao Mo3cdfcce2014-03-07 13:00:08 -0800358 {
Olli Etuaho8a76dcc2015-12-10 20:25:12 +0200359 ForLoopUnrollMarker marker(ForLoopUnrollMarker::kSamplerArrayIndex,
360 shouldRunLoopAndIndexingValidation(compileOptions));
Zhenyao Mo550c6002014-02-26 15:40:48 -0800361 root->traverse(&marker);
362 if (marker.samplerArrayIndexIsFloatLoopIndex())
363 {
364 infoSink.info.prefix(EPrefixError);
365 infoSink.info << "sampler array index is float loop index";
366 success = false;
367 }
368 }
zmo@google.com0c6bb7a2011-08-17 19:39:58 +0000369
zmo@google.com32e97312011-08-24 01:03:11 +0000370 // Built-in function emulation needs to happen after validateLimitations pass.
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200371 if (success)
372 {
Jamie Madill438dbcf2016-06-17 14:20:05 -0400373 // TODO(jmadill): Remove global pool allocator.
374 GetGlobalPoolAllocator()->lock();
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200375 initBuiltInFunctionEmulator(&builtInFunctionEmulator, compileOptions);
Jamie Madill438dbcf2016-06-17 14:20:05 -0400376 GetGlobalPoolAllocator()->unlock();
zmo@google.com32e97312011-08-24 01:03:11 +0000377 builtInFunctionEmulator.MarkBuiltInFunctionsForEmulation(root);
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200378 }
zmo@google.com32e97312011-08-24 01:03:11 +0000379
daniel@transgaming.com4167cc92013-01-11 04:11:53 +0000380 // Clamping uniform array bounds needs to happen after validateLimitations pass.
381 if (success && (compileOptions & SH_CLAMP_INDIRECT_ARRAY_BOUNDS))
382 arrayBoundsClamper.MarkIndirectArrayBoundsForClamping(root);
383
Ian Ewell924b7de2016-01-21 13:54:28 -0500384 // gl_Position is always written in compatibility output mode
385 if (success && shaderType == GL_VERTEX_SHADER &&
386 ((compileOptions & SH_INIT_GL_POSITION) ||
387 (outputType == SH_GLSL_COMPATIBILITY_OUTPUT)))
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800388 initializeGLPosition(root);
Zhenyao Moac44cd22013-09-23 14:57:09 -0400389
Qiankun Miao705a9192016-08-29 10:05:27 +0800390 if (success && !(compileOptions & SH_DONT_REMOVE_INVARIANT_FOR_FRAGMENT_INPUT) &&
391 shaderType == GL_FRAGMENT_SHADER && IsGLSL420OrNewer(outputType))
392 sh::RemoveInvariantDeclaration(root);
393
Corentin Wallezd4b50542015-09-28 12:19:26 -0700394 // This pass might emit short circuits so keep it before the short circuit unfolding
395 if (success && (compileOptions & SH_REWRITE_DO_WHILE_LOOPS))
396 RewriteDoWhile(root, getTemporaryIndex());
397
Qiankun Miao09cfac62016-09-06 17:25:16 +0800398 if (success && (compileOptions & SH_ADD_AND_TRUE_TO_LOOP_CONDITION))
399 sh::AddAndTrueToLoopCondition(root);
400
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800401 if (success && (compileOptions & SH_UNFOLD_SHORT_CIRCUIT))
402 {
Zhenyao Mo7cab38b2013-10-15 12:59:30 -0700403 UnfoldShortCircuitAST unfoldShortCircuit;
404 root->traverse(&unfoldShortCircuit);
405 unfoldShortCircuit.updateTree();
406 }
407
Olli Etuaho5c407bb2015-06-01 12:20:39 +0300408 if (success && (compileOptions & SH_REMOVE_POW_WITH_CONSTANT_EXPONENT))
409 {
410 RemovePow(root);
411 }
412
Olli Etuaho4dfe8092015-08-21 17:44:35 +0300413 if (success && shouldCollectVariables(compileOptions))
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800414 {
Zhenyao Mo74da9f22013-09-23 14:57:01 -0400415 collectVariables(root);
Qin Jiajia7835b522016-10-08 11:20:17 +0800416 if (compileOptions & SH_USE_UNUSED_STANDARD_SHARED_BLOCKS)
417 {
418 useAllMembersInUnusedStandardAndSharedBlocks(root);
419 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800420 if (compileOptions & SH_ENFORCE_PACKING_RESTRICTIONS)
421 {
gman@chromium.org8d804792012-10-17 21:33:48 +0000422 success = enforcePackingRestrictions();
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800423 if (!success)
424 {
Jamie Madill075edd82013-07-08 13:30:19 -0400425 infoSink.info.prefix(EPrefixError);
426 infoSink.info << "too many uniforms";
gman@chromium.org8d804792012-10-17 21:33:48 +0000427 }
428 }
Zhenyao Mo72111912016-07-20 17:45:56 -0700429 if (success && (compileOptions & SH_INIT_OUTPUT_VARIABLES))
430 {
Olli Etuaho27776e32016-07-22 14:00:56 +0300431 initializeOutputVariables(root);
Zhenyao Mo72111912016-07-20 17:45:56 -0700432 }
gman@chromium.org8d804792012-10-17 21:33:48 +0000433 }
zmo@google.comfd747b82011-04-23 01:30:07 +0000434
Zhenyao Mocd68fe72014-07-11 10:45:44 -0700435 if (success && (compileOptions & SH_SCALARIZE_VEC_AND_MAT_CONSTRUCTOR_ARGS))
436 {
Olli Etuahob990b552016-10-27 12:29:17 +0100437 ScalarizeVecAndMatConstructorArgs(root, shaderType, fragmentPrecisionHigh,
438 &mTemporaryIndex);
Zhenyao Mocd68fe72014-07-11 10:45:44 -0700439 }
440
Zhenyao Moe740add2014-07-18 17:01:01 -0700441 if (success && (compileOptions & SH_REGENERATE_STRUCT_NAMES))
442 {
443 RegenerateStructNames gen(symbolTable, shaderVersion);
444 root->traverse(&gen);
445 }
Olli Etuaho3d932d82016-04-12 11:10:30 +0300446
Zhenyao Mo4e94fea2016-08-09 14:31:37 -0700447 if (success && shaderType == GL_FRAGMENT_SHADER && shaderVersion == 100 &&
448 compileResources.EXT_draw_buffers && compileResources.MaxDrawBuffers > 1 &&
449 IsExtensionEnabled(extensionBehavior, "GL_EXT_draw_buffers"))
450 {
451 EmulateGLFragColorBroadcast(root, compileResources.MaxDrawBuffers, &outputVariables);
452 }
453
Olli Etuaho3d932d82016-04-12 11:10:30 +0300454 if (success)
455 {
456 DeferGlobalInitializers(root);
457 }
alokp@chromium.org07620a52010-09-23 17:53:56 +0000458 }
459
Zhenyao Mo7faf1a12014-04-25 18:03:56 -0700460 SetGlobalParseContext(NULL);
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200461 if (success)
462 return root;
463
464 return NULL;
465}
466
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800467bool TCompiler::compile(const char *const shaderStrings[],
468 size_t numStrings,
469 ShCompileOptions compileOptionsIn)
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200470{
Corentin Wallez28b65282016-06-16 07:24:50 -0700471#if defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
472 DumpFuzzerCase(shaderStrings, numStrings, shaderType, shaderSpec, outputType, compileOptionsIn);
473#endif // defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
474
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200475 if (numStrings == 0)
476 return true;
477
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800478 ShCompileOptions compileOptions = compileOptionsIn;
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700479
480 // Apply key workarounds.
481 if (shouldFlattenPragmaStdglInvariantAll())
482 {
483 // This should be harmless to do in all cases, but for the moment, do it only conditionally.
484 compileOptions |= SH_FLATTEN_PRAGMA_STDGL_INVARIANT_ALL;
485 }
486
Corentin Wallezb2792db2016-10-07 11:21:09 -0400487 ShCompileOptions unrollFlags =
488 SH_UNROLL_FOR_LOOP_WITH_INTEGER_INDEX | SH_UNROLL_FOR_LOOP_WITH_SAMPLER_ARRAY_INDEX;
489 if ((compileOptions & SH_ADD_AND_TRUE_TO_LOOP_CONDITION) != 0 &&
490 (compileOptions & unrollFlags) != 0)
491 {
492 infoSink.info.prefix(EPrefixError);
493 infoSink.info
494 << "Unsupported compile flag combination: unroll & ADD_TRUE_TO_LOOP_CONDITION";
495 return false;
496 }
497
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200498 TScopedPoolAllocator scopedAlloc(&allocator);
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100499 TIntermBlock *root = compileTreeImpl(shaderStrings, numStrings, compileOptions);
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200500
501 if (root)
502 {
503 if (compileOptions & SH_INTERMEDIATE_TREE)
504 TIntermediate::outputTree(root, infoSink.info);
505
506 if (compileOptions & SH_OBJECT_CODE)
507 translate(root, compileOptions);
508
509 // The IntermNode tree doesn't need to be deleted here, since the
510 // memory will be freed in a big chunk by the PoolAllocator.
511 return true;
512 }
513 return false;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000514}
515
Nicolas Capens49a88872013-06-20 09:54:03 -0400516bool TCompiler::InitBuiltInSymbolTable(const ShBuiltInResources &resources)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000517{
shannon.woods%transgaming.com@gtempaccount.com18b4c4b2013-04-13 03:31:40 +0000518 compileResources = resources;
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400519 setResourceString();
shannonwoods@chromium.org2ac0be92013-05-30 00:02:27 +0000520
Nicolas Capens49a88872013-06-20 09:54:03 -0400521 assert(symbolTable.isEmpty());
522 symbolTable.push(); // COMMON_BUILTINS
523 symbolTable.push(); // ESSL1_BUILTINS
524 symbolTable.push(); // ESSL3_BUILTINS
Martin Radeve93d24e2016-07-28 12:06:05 +0300525 symbolTable.push(); // ESSL3_1_BUILTINS
shannonwoods@chromium.org2ac0be92013-05-30 00:02:27 +0000526
Nicolas Capens49a88872013-06-20 09:54:03 -0400527 TPublicType integer;
Martin Radev2cc85b32016-08-05 16:22:53 +0300528 integer.initializeBasicType(EbtInt);
Nicolas Capens49a88872013-06-20 09:54:03 -0400529
530 TPublicType floatingPoint;
Martin Radev2cc85b32016-08-05 16:22:53 +0300531 floatingPoint.initializeBasicType(EbtFloat);
Nicolas Capens49a88872013-06-20 09:54:03 -0400532
Jamie Madillacb4b812016-11-07 13:50:29 -0500533 switch (shaderType)
Nicolas Capens49a88872013-06-20 09:54:03 -0400534 {
Jamie Madillacb4b812016-11-07 13:50:29 -0500535 case GL_FRAGMENT_SHADER:
536 symbolTable.setDefaultPrecision(integer, EbpMedium);
537 break;
538 case GL_VERTEX_SHADER:
539 symbolTable.setDefaultPrecision(integer, EbpHigh);
540 symbolTable.setDefaultPrecision(floatingPoint, EbpHigh);
541 break;
542 case GL_COMPUTE_SHADER:
543 symbolTable.setDefaultPrecision(integer, EbpHigh);
544 symbolTable.setDefaultPrecision(floatingPoint, EbpHigh);
545 break;
546 default:
547 assert(false && "Language not supported");
Nicolas Capens49a88872013-06-20 09:54:03 -0400548 }
Olli Etuaho183d7e22015-11-20 15:59:09 +0200549 // Set defaults for sampler types that have default precision, even those that are
Zhenyao Moa5a1dfc2013-09-23 14:57:03 -0400550 // only available if an extension exists.
Olli Etuaho183d7e22015-11-20 15:59:09 +0200551 // New sampler types in ESSL3 don't have default precision. ESSL1 types do.
552 initSamplerDefaultPrecision(EbtSampler2D);
553 initSamplerDefaultPrecision(EbtSamplerCube);
554 // SamplerExternalOES is specified in the extension to have default precision.
555 initSamplerDefaultPrecision(EbtSamplerExternalOES);
556 // It isn't specified whether Sampler2DRect has default precision.
557 initSamplerDefaultPrecision(EbtSampler2DRect);
Nicolas Capens49a88872013-06-20 09:54:03 -0400558
Jamie Madill1b452142013-07-12 14:51:11 -0400559 InsertBuiltInFunctions(shaderType, shaderSpec, resources, symbolTable);
Nicolas Capens49a88872013-06-20 09:54:03 -0400560
561 IdentifyBuiltIns(shaderType, shaderSpec, resources, symbolTable);
562
563 return true;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000564}
565
Olli Etuaho183d7e22015-11-20 15:59:09 +0200566void TCompiler::initSamplerDefaultPrecision(TBasicType samplerType)
567{
568 ASSERT(samplerType > EbtGuardSamplerBegin && samplerType < EbtGuardSamplerEnd);
569 TPublicType sampler;
Martin Radev2cc85b32016-08-05 16:22:53 +0300570 sampler.initializeBasicType(samplerType);
Olli Etuaho183d7e22015-11-20 15:59:09 +0200571 symbolTable.setDefaultPrecision(sampler, EbpLow);
572}
573
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400574void TCompiler::setResourceString()
575{
576 std::ostringstream strstream;
Geoff Langb66a9092016-05-16 15:59:14 -0400577
578 // clang-format off
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400579 strstream << ":MaxVertexAttribs:" << compileResources.MaxVertexAttribs
Jamie Madillacb4b812016-11-07 13:50:29 -0500580 << ":MaxVertexUniformVectors:" << compileResources.MaxVertexUniformVectors
581 << ":MaxVaryingVectors:" << compileResources.MaxVaryingVectors
582 << ":MaxVertexTextureImageUnits:" << compileResources.MaxVertexTextureImageUnits
583 << ":MaxCombinedTextureImageUnits:" << compileResources.MaxCombinedTextureImageUnits
584 << ":MaxTextureImageUnits:" << compileResources.MaxTextureImageUnits
585 << ":MaxFragmentUniformVectors:" << compileResources.MaxFragmentUniformVectors
586 << ":MaxDrawBuffers:" << compileResources.MaxDrawBuffers
587 << ":OES_standard_derivatives:" << compileResources.OES_standard_derivatives
588 << ":OES_EGL_image_external:" << compileResources.OES_EGL_image_external
589 << ":OES_EGL_image_external_essl3:" << compileResources.OES_EGL_image_external_essl3
590 << ":NV_EGL_stream_consumer_external:" << compileResources.NV_EGL_stream_consumer_external
591 << ":ARB_texture_rectangle:" << compileResources.ARB_texture_rectangle
592 << ":EXT_draw_buffers:" << compileResources.EXT_draw_buffers
593 << ":FragmentPrecisionHigh:" << compileResources.FragmentPrecisionHigh
594 << ":MaxExpressionComplexity:" << compileResources.MaxExpressionComplexity
595 << ":MaxCallStackDepth:" << compileResources.MaxCallStackDepth
596 << ":MaxFunctionParameters:" << compileResources.MaxFunctionParameters
597 << ":EXT_blend_func_extended:" << compileResources.EXT_blend_func_extended
598 << ":EXT_frag_depth:" << compileResources.EXT_frag_depth
599 << ":EXT_shader_texture_lod:" << compileResources.EXT_shader_texture_lod
600 << ":EXT_shader_framebuffer_fetch:" << compileResources.EXT_shader_framebuffer_fetch
601 << ":NV_shader_framebuffer_fetch:" << compileResources.NV_shader_framebuffer_fetch
602 << ":ARM_shader_framebuffer_fetch:" << compileResources.ARM_shader_framebuffer_fetch
603 << ":MaxVertexOutputVectors:" << compileResources.MaxVertexOutputVectors
604 << ":MaxFragmentInputVectors:" << compileResources.MaxFragmentInputVectors
605 << ":MinProgramTexelOffset:" << compileResources.MinProgramTexelOffset
606 << ":MaxProgramTexelOffset:" << compileResources.MaxProgramTexelOffset
607 << ":MaxDualSourceDrawBuffers:" << compileResources.MaxDualSourceDrawBuffers
608 << ":NV_draw_buffers:" << compileResources.NV_draw_buffers
609 << ":WEBGL_debug_shader_precision:" << compileResources.WEBGL_debug_shader_precision
610 << ":MaxImageUnits:" << compileResources.MaxImageUnits
611 << ":MaxVertexImageUniforms:" << compileResources.MaxVertexImageUniforms
612 << ":MaxFragmentImageUniforms:" << compileResources.MaxFragmentImageUniforms
613 << ":MaxComputeImageUniforms:" << compileResources.MaxComputeImageUniforms
614 << ":MaxCombinedImageUniforms:" << compileResources.MaxCombinedImageUniforms
615 << ":MaxCombinedShaderOutputResources:" << compileResources.MaxCombinedShaderOutputResources
616 << ":MaxComputeWorkGroupCountX:" << compileResources.MaxComputeWorkGroupCount[0]
617 << ":MaxComputeWorkGroupCountY:" << compileResources.MaxComputeWorkGroupCount[1]
618 << ":MaxComputeWorkGroupCountZ:" << compileResources.MaxComputeWorkGroupCount[2]
619 << ":MaxComputeWorkGroupSizeX:" << compileResources.MaxComputeWorkGroupSize[0]
620 << ":MaxComputeWorkGroupSizeY:" << compileResources.MaxComputeWorkGroupSize[1]
621 << ":MaxComputeWorkGroupSizeZ:" << compileResources.MaxComputeWorkGroupSize[2]
622 << ":MaxComputeUniformComponents:" << compileResources.MaxComputeUniformComponents
623 << ":MaxComputeTextureImageUnits:" << compileResources.MaxComputeTextureImageUnits
624 << ":MaxComputeAtomicCounters:" << compileResources.MaxComputeAtomicCounters
625 << ":MaxComputeAtomicCounterBuffers:" << compileResources.MaxComputeAtomicCounterBuffers
626 << ":MaxVertexAtomicCounters:" << compileResources.MaxVertexAtomicCounters
627 << ":MaxFragmentAtomicCounters:" << compileResources.MaxFragmentAtomicCounters
628 << ":MaxCombinedAtomicCounters:" << compileResources.MaxCombinedAtomicCounters
629 << ":MaxAtomicCounterBindings:" << compileResources.MaxAtomicCounterBindings
630 << ":MaxVertexAtomicCounterBuffers:" << compileResources.MaxVertexAtomicCounterBuffers
631 << ":MaxFragmentAtomicCounterBuffers:" << compileResources.MaxFragmentAtomicCounterBuffers
632 << ":MaxCombinedAtomicCounterBuffers:" << compileResources.MaxCombinedAtomicCounterBuffers
633 << ":MaxAtomicCounterBufferSize:" << compileResources.MaxAtomicCounterBufferSize;
Geoff Langb66a9092016-05-16 15:59:14 -0400634 // clang-format on
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400635
636 builtInResourcesString = strstream.str();
637}
638
alokp@chromium.org07620a52010-09-23 17:53:56 +0000639void TCompiler::clearResults()
640{
daniel@transgaming.com4167cc92013-01-11 04:11:53 +0000641 arrayBoundsClamper.Cleanup();
alokp@chromium.org07620a52010-09-23 17:53:56 +0000642 infoSink.info.erase();
643 infoSink.obj.erase();
644 infoSink.debug.erase();
645
Jamie Madilled27c722014-07-02 15:31:23 -0400646 attributes.clear();
647 outputVariables.clear();
alokp@chromium.org07620a52010-09-23 17:53:56 +0000648 uniforms.clear();
Jamie Madill23a8a432014-07-09 13:27:42 -0400649 expandedUniforms.clear();
Zhenyao Mod2d340b2013-09-23 14:57:05 -0400650 varyings.clear();
Jamie Madilled27c722014-07-02 15:31:23 -0400651 interfaceBlocks.clear();
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700652 variablesCollected = false;
zmo@google.coma3b4ab42011-09-16 00:53:26 +0000653
654 builtInFunctionEmulator.Cleanup();
daniel@transgaming.com0aa3b5a2012-11-28 19:43:24 +0000655
656 nameMap.clear();
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200657
658 mSourcePath = NULL;
Corentin Wallezd4b50542015-09-28 12:19:26 -0700659 mTemporaryIndex = 0;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000660}
661
Corentin Wallez71d147f2015-02-11 11:15:24 -0800662bool TCompiler::initCallDag(TIntermNode *root)
zmo@google.comb1762df2011-07-30 02:04:23 +0000663{
Corentin Wallez71d147f2015-02-11 11:15:24 -0800664 mCallDag.clear();
665
666 switch (mCallDag.init(root, &infoSink.info))
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800667 {
Jamie Madillacb4b812016-11-07 13:50:29 -0500668 case CallDAG::INITDAG_SUCCESS:
669 return true;
670 case CallDAG::INITDAG_RECURSION:
671 infoSink.info.prefix(EPrefixError);
672 infoSink.info << "Function recursion detected";
673 return false;
674 case CallDAG::INITDAG_UNDEFINED:
675 infoSink.info.prefix(EPrefixError);
676 infoSink.info << "Unimplemented function detected";
677 return false;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800678 }
679
680 UNREACHABLE();
681 return true;
682}
683
684bool TCompiler::checkCallDepth()
685{
686 std::vector<int> depths(mCallDag.size());
687
688 for (size_t i = 0; i < mCallDag.size(); i++)
689 {
690 int depth = 0;
691 auto &record = mCallDag.getRecordFromIndex(i);
692
693 for (auto &calleeIndex : record.callees)
694 {
695 depth = std::max(depth, depths[calleeIndex] + 1);
696 }
697
698 depths[i] = depth;
699
700 if (depth >= maxCallStackDepth)
701 {
702 // Trace back the function chain to have a meaningful info log.
703 infoSink.info.prefix(EPrefixError);
704 infoSink.info << "Call stack too deep (larger than " << maxCallStackDepth
705 << ") with the following call chain: " << record.name;
706
Cooper Partin4d61f7e2015-08-12 10:56:50 -0700707 int currentFunction = static_cast<int>(i);
Corentin Wallez71d147f2015-02-11 11:15:24 -0800708 int currentDepth = depth;
709
710 while (currentFunction != -1)
711 {
712 infoSink.info << " -> " << mCallDag.getRecordFromIndex(currentFunction).name;
713
714 int nextFunction = -1;
715 for (auto& calleeIndex : mCallDag.getRecordFromIndex(currentFunction).callees)
716 {
717 if (depths[calleeIndex] == currentDepth - 1)
718 {
719 currentDepth--;
720 nextFunction = calleeIndex;
721 }
722 }
723
724 currentFunction = nextFunction;
725 }
726
727 return false;
728 }
729 }
730
731 return true;
732}
733
734bool TCompiler::tagUsedFunctions()
735{
736 // Search from main, starting from the end of the DAG as it usually is the root.
Cooper Partin4d61f7e2015-08-12 10:56:50 -0700737 for (size_t i = mCallDag.size(); i-- > 0;)
Corentin Wallez71d147f2015-02-11 11:15:24 -0800738 {
739 if (mCallDag.getRecordFromIndex(i).name == "main(")
740 {
741 internalTagUsedFunction(i);
742 return true;
743 }
744 }
745
746 infoSink.info.prefix(EPrefixError);
Olli Etuaho792a41d2015-12-15 12:39:16 +0200747 infoSink.info << "Missing main()\n";
Corentin Wallez71d147f2015-02-11 11:15:24 -0800748 return false;
749}
750
751void TCompiler::internalTagUsedFunction(size_t index)
752{
753 if (functionMetadata[index].used)
754 {
755 return;
756 }
757
758 functionMetadata[index].used = true;
759
760 for (int calleeIndex : mCallDag.getRecordFromIndex(index).callees)
761 {
762 internalTagUsedFunction(calleeIndex);
zmo@google.comb1762df2011-07-30 02:04:23 +0000763 }
764}
765
Corentin Walleza094a8a2015-04-07 11:53:06 -0700766// A predicate for the stl that returns if a top-level node is unused
767class TCompiler::UnusedPredicate
768{
769 public:
770 UnusedPredicate(const CallDAG *callDag, const std::vector<FunctionMetadata> *metadatas)
Jamie Madillacb4b812016-11-07 13:50:29 -0500771 : mCallDag(callDag), mMetadatas(metadatas)
Corentin Walleza094a8a2015-04-07 11:53:06 -0700772 {
773 }
774
775 bool operator ()(TIntermNode *node)
776 {
777 const TIntermAggregate *asAggregate = node->getAsAggregate();
Olli Etuaho336b1472016-10-05 16:37:55 +0100778 const TIntermFunctionDefinition *asFunction = node->getAsFunctionDefinition();
Corentin Walleza094a8a2015-04-07 11:53:06 -0700779
Olli Etuaho336b1472016-10-05 16:37:55 +0100780 const TFunctionSymbolInfo *functionInfo = nullptr;
781
782 if (asFunction)
783 {
784 functionInfo = asFunction->getFunctionSymbolInfo();
785 }
786 else if (asAggregate)
787 {
788 if (asAggregate->getOp() == EOpPrototype)
789 {
790 functionInfo = asAggregate->getFunctionSymbolInfo();
791 }
792 }
793 if (functionInfo == nullptr)
Corentin Walleza094a8a2015-04-07 11:53:06 -0700794 {
795 return false;
796 }
797
Olli Etuaho336b1472016-10-05 16:37:55 +0100798 size_t callDagIndex = mCallDag->findIndex(functionInfo);
Corentin Walleza094a8a2015-04-07 11:53:06 -0700799 if (callDagIndex == CallDAG::InvalidIndex)
800 {
801 // This happens only for unimplemented prototypes which are thus unused
Olli Etuaho336b1472016-10-05 16:37:55 +0100802 ASSERT(asAggregate && asAggregate->getOp() == EOpPrototype);
Corentin Walleza094a8a2015-04-07 11:53:06 -0700803 return true;
804 }
805
806 ASSERT(callDagIndex < mMetadatas->size());
807 return !(*mMetadatas)[callDagIndex].used;
808 }
809
810 private:
811 const CallDAG *mCallDag;
812 const std::vector<FunctionMetadata> *mMetadatas;
813};
814
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100815bool TCompiler::pruneUnusedFunctions(TIntermBlock *root)
Corentin Walleza094a8a2015-04-07 11:53:06 -0700816{
Corentin Walleza094a8a2015-04-07 11:53:06 -0700817 UnusedPredicate isUnused(&mCallDag, &functionMetadata);
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100818 TIntermSequence *sequence = root->getSequence();
Corentin Wallezb081e782015-07-20 05:40:04 -0700819
820 if (!sequence->empty())
821 {
822 sequence->erase(std::remove_if(sequence->begin(), sequence->end(), isUnused), sequence->end());
823 }
Corentin Walleza094a8a2015-04-07 11:53:06 -0700824
825 return true;
826}
827
Jamie Madill05a80ce2013-06-20 11:55:49 -0400828bool TCompiler::validateOutputs(TIntermNode* root)
829{
Kimmo Kinnunenb18609b2015-07-16 14:13:11 +0300830 ValidateOutputs validateOutputs(getExtensionBehavior(), compileResources.MaxDrawBuffers);
Jamie Madill05a80ce2013-06-20 11:55:49 -0400831 root->traverse(&validateOutputs);
Kimmo Kinnunenb18609b2015-07-16 14:13:11 +0300832 return (validateOutputs.validateAndCountErrors(infoSink.info) == 0);
Jamie Madill05a80ce2013-06-20 11:55:49 -0400833}
834
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800835bool TCompiler::validateLimitations(TIntermNode* root)
836{
Olli Etuaho8a76dcc2015-12-10 20:25:12 +0200837 ValidateLimitations validate(shaderType, &infoSink.info);
alokp@chromium.orgb59a7782010-11-24 18:38:33 +0000838 root->traverse(&validate);
839 return validate.numErrors() == 0;
840}
841
Jamie Madilleb1a0102013-07-08 13:31:38 -0400842bool TCompiler::limitExpressionComplexity(TIntermNode* root)
843{
Jamie Madillacb4b812016-11-07 13:50:29 -0500844 TMaxDepthTraverser traverser(maxExpressionComplexity + 1);
Jamie Madilleb1a0102013-07-08 13:31:38 -0400845 root->traverse(&traverser);
Jamie Madill6654bc92014-03-26 14:01:57 -0400846
847 if (traverser.getMaxDepth() > maxExpressionComplexity)
848 {
849 infoSink.info << "Expression too complex.";
850 return false;
851 }
852
Olli Etuaho19d1dc92016-03-08 17:18:46 +0200853 if (!ValidateMaxParameters::validate(root, maxFunctionParameters))
854 {
855 infoSink.info << "Function has too many parameters.";
856 return false;
857 }
858
Jamie Madilleb1a0102013-07-08 13:31:38 -0400859 return true;
860}
861
Zhenyao Mo74da9f22013-09-23 14:57:01 -0400862void TCompiler::collectVariables(TIntermNode* root)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000863{
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700864 if (!variablesCollected)
865 {
866 sh::CollectVariables collect(&attributes, &outputVariables, &uniforms, &varyings,
Jamie Madillacb4b812016-11-07 13:50:29 -0500867 &interfaceBlocks, hashFunction, symbolTable,
868 extensionBehavior);
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700869 root->traverse(&collect);
Jamie Madill23a8a432014-07-09 13:27:42 -0400870
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700871 // This is for enforcePackingRestriction().
872 sh::ExpandUniforms(uniforms, &expandedUniforms);
873 variablesCollected = true;
874 }
alokp@chromium.org07620a52010-09-23 17:53:56 +0000875}
zmo@google.comfd747b82011-04-23 01:30:07 +0000876
Corentin Wallez1df16022016-10-27 08:16:56 -0400877bool TCompiler::shouldCollectVariables(ShCompileOptions compileOptions)
878{
879 return (compileOptions & SH_VARIABLES) != 0;
880}
881
882bool TCompiler::wereVariablesCollected() const
883{
884 return variablesCollected;
885}
886
gman@chromium.org8d804792012-10-17 21:33:48 +0000887bool TCompiler::enforcePackingRestrictions()
888{
889 VariablePacker packer;
Jamie Madill23a8a432014-07-09 13:27:42 -0400890 return packer.CheckVariablesWithinPackingLimits(maxUniformVectors, expandedUniforms);
gman@chromium.org8d804792012-10-17 21:33:48 +0000891}
892
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800893void TCompiler::initializeGLPosition(TIntermNode* root)
894{
Zhenyao Mo72111912016-07-20 17:45:56 -0700895 InitVariableList list;
896 sh::ShaderVariable var(GL_FLOAT_VEC4, 0);
897 var.name = "gl_Position";
898 list.push_back(var);
899 InitializeVariables(root, list);
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800900}
901
Qin Jiajia7835b522016-10-08 11:20:17 +0800902void TCompiler::useAllMembersInUnusedStandardAndSharedBlocks(TIntermNode *root)
903{
904 sh::InterfaceBlockList list;
905
906 for (auto block : interfaceBlocks)
907 {
908 if (!block.staticUse &&
909 (block.layout == sh::BLOCKLAYOUT_STANDARD || block.layout == sh::BLOCKLAYOUT_SHARED))
910 {
911 list.push_back(block);
912 }
913 }
914
915 sh::UseInterfaceBlockFields(root, list);
916}
917
Olli Etuaho27776e32016-07-22 14:00:56 +0300918void TCompiler::initializeOutputVariables(TIntermNode *root)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800919{
Zhenyao Mo72111912016-07-20 17:45:56 -0700920 InitVariableList list;
921 if (shaderType == GL_VERTEX_SHADER)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800922 {
Zhenyao Mo72111912016-07-20 17:45:56 -0700923 for (auto var : varyings)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800924 {
Zhenyao Mof9312682016-07-22 12:51:31 -0700925 list.push_back(var);
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800926 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800927 }
Zhenyao Mo72111912016-07-20 17:45:56 -0700928 else
929 {
930 ASSERT(shaderType == GL_FRAGMENT_SHADER);
931 for (auto var : outputVariables)
932 {
933 list.push_back(var);
934 }
935 }
936 InitializeVariables(root, list);
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800937}
938
zmo@google.com5601ea02011-06-10 18:23:25 +0000939const TExtensionBehavior& TCompiler::getExtensionBehavior() const
940{
941 return extensionBehavior;
942}
zmo@google.com32e97312011-08-24 01:03:11 +0000943
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200944const char *TCompiler::getSourcePath() const
945{
946 return mSourcePath;
947}
948
shannon.woods%transgaming.com@gtempaccount.com18b4c4b2013-04-13 03:31:40 +0000949const ShBuiltInResources& TCompiler::getResources() const
950{
951 return compileResources;
952}
953
daniel@transgaming.com4167cc92013-01-11 04:11:53 +0000954const ArrayBoundsClamper& TCompiler::getArrayBoundsClamper() const
955{
956 return arrayBoundsClamper;
957}
958
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000959ShArrayIndexClampingStrategy TCompiler::getArrayIndexClampingStrategy() const
960{
961 return clampingStrategy;
962}
963
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200964const BuiltInFunctionEmulator& TCompiler::getBuiltInFunctionEmulator() const
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000965{
966 return builtInFunctionEmulator;
967}
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700968
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800969void TCompiler::writePragma(ShCompileOptions compileOptions)
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700970{
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700971 if (!(compileOptions & SH_FLATTEN_PRAGMA_STDGL_INVARIANT_ALL))
972 {
973 TInfoSinkBase &sink = infoSink.obj;
974 if (mPragma.stdgl.invariantAll)
975 sink << "#pragma STDGL invariant(all)\n";
976 }
977}
978
979bool TCompiler::isVaryingDefined(const char *varyingName)
980{
981 ASSERT(variablesCollected);
982 for (size_t ii = 0; ii < varyings.size(); ++ii)
983 {
984 if (varyings[ii].name == varyingName)
985 {
986 return true;
987 }
988 }
989
990 return false;
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700991}
Jamie Madillacb4b812016-11-07 13:50:29 -0500992
993} // namespace sh