1 //
2 // Copyright (c) 2017 The ANGLE Project Authors. All rights reserved.
3 // Use of this source code is governed by a BSD-style license that can be
4 // found in the LICENSE file.
5 //
6 
7 #include "compiler/translator/HashNames.h"
8 
9 #include "compiler/translator/IntermNode.h"
10 
11 namespace sh
12 {
13 
14 namespace
15 {
16 
17 // GLSL ES 3.00.6 section 3.9: the maximum length of an identifier is 1024 characters.
18 static const unsigned int kESSLMaxIdentifierLength = 1024u;
19 
20 static const char *kHashedNamePrefix = "webgl_";
21 
22 // Can't prefix with just _ because then we might introduce a double underscore, which is not safe
23 // in GLSL (ESSL 3.00.6 section 3.8: All identifiers containing a double underscore are reserved for
24 // use by the underlying implementation). u is short for user-defined.
25 static const char *kUnhashedNamePrefix              = "_u";
26 static const unsigned int kUnhashedNamePrefixLength = 2u;
27 
HashName(const TString & name,ShHashFunction64 hashFunction)28 TString HashName(const TString &name, ShHashFunction64 hashFunction)
29 {
30     ASSERT(!name.empty());
31     ASSERT(hashFunction);
32     khronos_uint64_t number = (*hashFunction)(name.c_str(), name.length());
33     TStringStream stream;
34     stream << kHashedNamePrefix << std::hex << number;
35     TString hashedName = stream.str();
36     return hashedName;
37 }
38 
39 }  // anonymous namespace
40 
HashName(const TName & name,ShHashFunction64 hashFunction,NameMap * nameMap)41 TString HashName(const TName &name, ShHashFunction64 hashFunction, NameMap *nameMap)
42 {
43     if (name.getString().empty() || name.isInternal())
44     {
45         return name.getString();
46     }
47     if (hashFunction == nullptr)
48     {
49         if (name.getString().length() + kUnhashedNamePrefixLength > kESSLMaxIdentifierLength)
50         {
51             // If the identifier length is already close to the limit, we can't prefix it. This is
52             // not a problem since there are no builtins or ANGLE's internal variables that would
53             // have as long names and could conflict.
54             return name.getString();
55         }
56         return kUnhashedNamePrefix + name.getString();
57     }
58     if (nameMap)
59     {
60         NameMap::const_iterator it = nameMap->find(name.getString().c_str());
61         if (it != nameMap->end())
62             return it->second.c_str();
63     }
64     TString hashedName = HashName(name.getString(), hashFunction);
65     if (nameMap)
66     {
67         (*nameMap)[name.getString().c_str()] = hashedName.c_str();
68     }
69     return hashedName;
70 }
71 
72 }  // namespace sh
73