Merge pull request #1698 from jeffbolznv/private_storage_variables
[platform/upstream/glslang.git] / glslang / MachineIndependent / SymbolTable.cpp
1 //
2 // Copyright (C) 2002-2005  3Dlabs Inc. Ltd.
3 // Copyright (C) 2012-2013 LunarG, Inc.
4 // Copyright (C) 2017 ARM Limited.
5 // Copyright (C) 2015-2018 Google, Inc.
6 //
7 // All rights reserved.
8 //
9 // Redistribution and use in source and binary forms, with or without
10 // modification, are permitted provided that the following conditions
11 // are met:
12 //
13 //    Redistributions of source code must retain the above copyright
14 //    notice, this list of conditions and the following disclaimer.
15 //
16 //    Redistributions in binary form must reproduce the above
17 //    copyright notice, this list of conditions and the following
18 //    disclaimer in the documentation and/or other materials provided
19 //    with the distribution.
20 //
21 //    Neither the name of 3Dlabs Inc. Ltd. nor the names of its
22 //    contributors may be used to endorse or promote products derived
23 //    from this software without specific prior written permission.
24 //
25 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
28 // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
29 // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
30 // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
31 // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
32 // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
33 // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34 // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36 // POSSIBILITY OF SUCH DAMAGE.
37 //
38
39 //
40 // Symbol table for parsing.  Most functionality and main ideas
41 // are documented in the header file.
42 //
43
44 #include "SymbolTable.h"
45
46 namespace glslang {
47
48 //
49 // TType helper function needs a place to live.
50 //
51
52 //
53 // Recursively generate mangled names.
54 //
55 void TType::buildMangledName(TString& mangledName) const
56 {
57     if (isMatrix())
58         mangledName += 'm';
59     else if (isVector())
60         mangledName += 'v';
61
62     switch (basicType) {
63     case EbtFloat:              mangledName += 'f';      break;
64     case EbtDouble:             mangledName += 'd';      break;
65     case EbtFloat16:            mangledName += "f16";    break;
66     case EbtInt:                mangledName += 'i';      break;
67     case EbtUint:               mangledName += 'u';      break;
68     case EbtInt8:               mangledName += "i8";     break;
69     case EbtUint8:              mangledName += "u8";     break;
70     case EbtInt16:              mangledName += "i16";    break;
71     case EbtUint16:             mangledName += "u16";    break;
72     case EbtInt64:              mangledName += "i64";    break;
73     case EbtUint64:             mangledName += "u64";    break;
74     case EbtBool:               mangledName += 'b';      break;
75     case EbtAtomicUint:         mangledName += "au";     break;
76 #ifdef NV_EXTENSIONS
77     case EbtAccStructNV:        mangledName += "asnv";   break;
78 #endif
79     case EbtSampler:
80         switch (sampler.type) {
81 #ifdef AMD_EXTENSIONS
82         case EbtFloat16: mangledName += "f16"; break;
83 #endif
84         case EbtInt:   mangledName += "i"; break;
85         case EbtUint:  mangledName += "u"; break;
86         default: break; // some compilers want this
87         }
88         if (sampler.image)
89             mangledName += "I";  // a normal image
90         else if (sampler.sampler)
91             mangledName += "p";  // a "pure" sampler
92         else if (!sampler.combined)
93             mangledName += "t";  // a "pure" texture
94         else
95             mangledName += "s";  // traditional combined sampler
96         if (sampler.arrayed)
97             mangledName += "A";
98         if (sampler.shadow)
99             mangledName += "S";
100         if (sampler.external)
101             mangledName += "E";
102         if (sampler.yuv)
103             mangledName += "Y";
104         switch (sampler.dim) {
105         case Esd1D:       mangledName += "1";  break;
106         case Esd2D:       mangledName += "2";  break;
107         case Esd3D:       mangledName += "3";  break;
108         case EsdCube:     mangledName += "C";  break;
109         case EsdRect:     mangledName += "R2"; break;
110         case EsdBuffer:   mangledName += "B";  break;
111         case EsdSubpass:  mangledName += "P";  break;
112         default: break; // some compilers want this
113         }
114
115         if (sampler.hasReturnStruct()) {
116             // Name mangle for sampler return struct uses struct table index.
117             mangledName += "-tx-struct";
118
119             char text[16]; // plenty enough space for the small integers.
120             snprintf(text, sizeof(text), "%d-", sampler.structReturnIndex);
121             mangledName += text;
122         } else {
123             switch (sampler.getVectorSize()) {
124             case 1: mangledName += "1"; break;
125             case 2: mangledName += "2"; break;
126             case 3: mangledName += "3"; break;
127             case 4: break; // default to prior name mangle behavior
128             }
129         }
130
131         if (sampler.ms)
132             mangledName += "M";
133         break;
134     case EbtStruct:
135     case EbtBlock:
136         if (basicType == EbtStruct)
137             mangledName += "struct-";
138         else
139             mangledName += "block-";
140         if (typeName)
141             mangledName += *typeName;
142         for (unsigned int i = 0; i < structure->size(); ++i) {
143             mangledName += '-';
144             (*structure)[i].type->buildMangledName(mangledName);
145         }
146     default:
147         break;
148     }
149
150     if (getVectorSize() > 0)
151         mangledName += static_cast<char>('0' + getVectorSize());
152     else {
153         mangledName += static_cast<char>('0' + getMatrixCols());
154         mangledName += static_cast<char>('0' + getMatrixRows());
155     }
156
157     if (arraySizes) {
158         const int maxSize = 11;
159         char buf[maxSize];
160         for (int i = 0; i < arraySizes->getNumDims(); ++i) {
161             if (arraySizes->getDimNode(i)) {
162                 if (arraySizes->getDimNode(i)->getAsSymbolNode())
163                     snprintf(buf, maxSize, "s%d", arraySizes->getDimNode(i)->getAsSymbolNode()->getId());
164                 else
165                     snprintf(buf, maxSize, "s%p", arraySizes->getDimNode(i));
166             } else
167                 snprintf(buf, maxSize, "%d", arraySizes->getDimSize(i));
168             mangledName += '[';
169             mangledName += buf;
170             mangledName += ']';
171         }
172     }
173 }
174
175 //
176 // Dump functions.
177 //
178
179 void TSymbol::dumpExtensions(TInfoSink& infoSink) const
180 {
181     int numExtensions = getNumExtensions();
182     if (numExtensions) {
183         infoSink.debug << " <";
184
185         for (int i = 0; i < numExtensions; i++)
186             infoSink.debug << getExtensions()[i] << ",";
187
188         infoSink.debug << ">";
189     }
190 }
191
192 void TVariable::dump(TInfoSink& infoSink, bool complete) const
193 {
194     if (complete) {
195         infoSink.debug << getName().c_str() << ": " << type.getCompleteString();
196         dumpExtensions(infoSink);
197     } else {
198         infoSink.debug << getName().c_str() << ": " << type.getStorageQualifierString() << " "
199                        << type.getBasicTypeString();
200
201         if (type.isArray())
202             infoSink.debug << "[0]";
203     }
204
205     infoSink.debug << "\n";
206 }
207
208 void TFunction::dump(TInfoSink& infoSink, bool complete) const
209 {
210     if (complete) {
211         infoSink.debug << getName().c_str() << ": " << returnType.getCompleteString() << " " << getName().c_str()
212                        << "(";
213
214         int numParams = getParamCount();
215         for (int i = 0; i < numParams; i++) {
216             const TParameter &param = parameters[i];
217             infoSink.debug << param.type->getCompleteString() << " "
218                            << (param.type->isStruct() ? "of " + param.type->getTypeName() + " " : "")
219                            << (param.name ? *param.name : "") << (i < numParams - 1 ? "," : "");
220         }
221
222         infoSink.debug << ")";
223         dumpExtensions(infoSink);
224     } else {
225         infoSink.debug << getName().c_str() << ": " << returnType.getBasicTypeString() << " "
226                        << getMangledName().c_str() << "n";
227     }
228
229     infoSink.debug << "\n";
230 }
231
232 void TAnonMember::dump(TInfoSink& TInfoSink, bool) const
233 {
234     TInfoSink.debug << "anonymous member " << getMemberNumber() << " of " << getAnonContainer().getName().c_str()
235                     << "\n";
236 }
237
238 void TSymbolTableLevel::dump(TInfoSink& infoSink, bool complete) const
239 {
240     tLevel::const_iterator it;
241     for (it = level.begin(); it != level.end(); ++it)
242         (*it).second->dump(infoSink, complete);
243 }
244
245 void TSymbolTable::dump(TInfoSink& infoSink, bool complete) const
246 {
247     for (int level = currentLevel(); level >= 0; --level) {
248         infoSink.debug << "LEVEL " << level << "\n";
249         table[level]->dump(infoSink, complete);
250     }
251 }
252
253 //
254 // Functions have buried pointers to delete.
255 //
256 TFunction::~TFunction()
257 {
258     for (TParamList::iterator i = parameters.begin(); i != parameters.end(); ++i)
259         delete (*i).type;
260 }
261
262 //
263 // Symbol table levels are a map of pointers to symbols that have to be deleted.
264 //
265 TSymbolTableLevel::~TSymbolTableLevel()
266 {
267     for (tLevel::iterator it = level.begin(); it != level.end(); ++it)
268         delete (*it).second;
269
270     delete [] defaultPrecision;
271 }
272
273 //
274 // Change all function entries in the table with the non-mangled name
275 // to be related to the provided built-in operation.
276 //
277 void TSymbolTableLevel::relateToOperator(const char* name, TOperator op)
278 {
279     tLevel::const_iterator candidate = level.lower_bound(name);
280     while (candidate != level.end()) {
281         const TString& candidateName = (*candidate).first;
282         TString::size_type parenAt = candidateName.find_first_of('(');
283         if (parenAt != candidateName.npos && candidateName.compare(0, parenAt, name) == 0) {
284             TFunction* function = (*candidate).second->getAsFunction();
285             function->relateToOperator(op);
286         } else
287             break;
288         ++candidate;
289     }
290 }
291
292 // Make all function overloads of the given name require an extension(s).
293 // Should only be used for a version/profile that actually needs the extension(s).
294 void TSymbolTableLevel::setFunctionExtensions(const char* name, int num, const char* const extensions[])
295 {
296     tLevel::const_iterator candidate = level.lower_bound(name);
297     while (candidate != level.end()) {
298         const TString& candidateName = (*candidate).first;
299         TString::size_type parenAt = candidateName.find_first_of('(');
300         if (parenAt != candidateName.npos && candidateName.compare(0, parenAt, name) == 0) {
301             TSymbol* symbol = candidate->second;
302             symbol->setExtensions(num, extensions);
303         } else
304             break;
305         ++candidate;
306     }
307 }
308
309 //
310 // Make all symbols in this table level read only.
311 //
312 void TSymbolTableLevel::readOnly()
313 {
314     for (tLevel::iterator it = level.begin(); it != level.end(); ++it)
315         (*it).second->makeReadOnly();
316 }
317
318 //
319 // Copy a symbol, but the copy is writable; call readOnly() afterward if that's not desired.
320 //
321 TSymbol::TSymbol(const TSymbol& copyOf)
322 {
323     name = NewPoolTString(copyOf.name->c_str());
324     uniqueId = copyOf.uniqueId;
325     writable = true;
326 }
327
328 TVariable::TVariable(const TVariable& copyOf) : TSymbol(copyOf)
329 {
330     type.deepCopy(copyOf.type);
331     userType = copyOf.userType;
332
333     // we don't support specialization-constant subtrees in cloned tables, only extensions
334     constSubtree = nullptr;
335     extensions = nullptr;
336     memberExtensions = nullptr;
337     if (copyOf.getNumExtensions() > 0)
338         setExtensions(copyOf.getNumExtensions(), copyOf.getExtensions());
339     if (copyOf.hasMemberExtensions()) {
340         for (int m = 0; m < (int)copyOf.type.getStruct()->size(); ++m) {
341             if (copyOf.getNumMemberExtensions(m) > 0)
342                 setMemberExtensions(m, copyOf.getNumMemberExtensions(m), copyOf.getMemberExtensions(m));
343         }
344     }
345
346     if (! copyOf.constArray.empty()) {
347         assert(! copyOf.type.isStruct());
348         TConstUnionArray newArray(copyOf.constArray, 0, copyOf.constArray.size());
349         constArray = newArray;
350     }
351 }
352
353 TVariable* TVariable::clone() const
354 {
355     TVariable *variable = new TVariable(*this);
356
357     return variable;
358 }
359
360 TFunction::TFunction(const TFunction& copyOf) : TSymbol(copyOf)
361 {
362     for (unsigned int i = 0; i < copyOf.parameters.size(); ++i) {
363         TParameter param;
364         parameters.push_back(param);
365         parameters.back().copyParam(copyOf.parameters[i]);
366     }
367
368     extensions = nullptr;
369     if (copyOf.getNumExtensions() > 0)
370         setExtensions(copyOf.getNumExtensions(), copyOf.getExtensions());
371     returnType.deepCopy(copyOf.returnType);
372     mangledName = copyOf.mangledName;
373     op = copyOf.op;
374     defined = copyOf.defined;
375     prototyped = copyOf.prototyped;
376     implicitThis = copyOf.implicitThis;
377     illegalImplicitThis = copyOf.illegalImplicitThis;
378     defaultParamCount = copyOf.defaultParamCount;
379 }
380
381 TFunction* TFunction::clone() const
382 {
383     TFunction *function = new TFunction(*this);
384
385     return function;
386 }
387
388 TAnonMember* TAnonMember::clone() const
389 {
390     // Anonymous members of a given block should be cloned at a higher level,
391     // where they can all be assured to still end up pointing to a single
392     // copy of the original container.
393     assert(0);
394
395     return 0;
396 }
397
398 TSymbolTableLevel* TSymbolTableLevel::clone() const
399 {
400     TSymbolTableLevel *symTableLevel = new TSymbolTableLevel();
401     symTableLevel->anonId = anonId;
402     symTableLevel->thisLevel = thisLevel;
403     std::vector<bool> containerCopied(anonId, false);
404     tLevel::const_iterator iter;
405     for (iter = level.begin(); iter != level.end(); ++iter) {
406         const TAnonMember* anon = iter->second->getAsAnonMember();
407         if (anon) {
408             // Insert all the anonymous members of this same container at once,
409             // avoid inserting the remaining members in the future, once this has been done,
410             // allowing them to all be part of the same new container.
411             if (! containerCopied[anon->getAnonId()]) {
412                 TVariable* container = anon->getAnonContainer().clone();
413                 container->changeName(NewPoolTString(""));
414                 // insert the container and all its members
415                 symTableLevel->insert(*container, false);
416                 containerCopied[anon->getAnonId()] = true;
417             }
418         } else
419             symTableLevel->insert(*iter->second->clone(), false);
420     }
421
422     return symTableLevel;
423 }
424
425 void TSymbolTable::copyTable(const TSymbolTable& copyOf)
426 {
427     assert(adoptedLevels == copyOf.adoptedLevels);
428
429     uniqueId = copyOf.uniqueId;
430     noBuiltInRedeclarations = copyOf.noBuiltInRedeclarations;
431     separateNameSpaces = copyOf.separateNameSpaces;
432     for (unsigned int i = copyOf.adoptedLevels; i < copyOf.table.size(); ++i)
433         table.push_back(copyOf.table[i]->clone());
434 }
435
436 } // end namespace glslang