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