Merge pull request #1888 from Roy-AMD/Adjusting-code-interface
[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 EbtInt:                mangledName += 'i';      break;
65     case EbtUint:               mangledName += 'u';      break;
66     case EbtBool:               mangledName += 'b';      break;
67 #ifndef GLSLANG_WEB
68     case EbtDouble:             mangledName += 'd';      break;
69     case EbtFloat16:            mangledName += "f16";    break;
70     case EbtInt8:               mangledName += "i8";     break;
71     case EbtUint8:              mangledName += "u8";     break;
72     case EbtInt16:              mangledName += "i16";    break;
73     case EbtUint16:             mangledName += "u16";    break;
74     case EbtInt64:              mangledName += "i64";    break;
75     case EbtUint64:             mangledName += "u64";    break;
76     case EbtAtomicUint:         mangledName += "au";     break;
77     case EbtAccStructNV:        mangledName += "asnv";   break;
78 #endif
79     case EbtSampler:
80         switch (sampler.type) {
81 #ifndef GLSLANG_WEB
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.isImageClass())
89             mangledName += "I";  // a normal image or subpass
90         else if (sampler.isPureSampler())
91             mangledName += "p";  // a "pure" sampler
92         else if (!sampler.isCombined())
93             mangledName += "t";  // a "pure" texture
94         else
95             mangledName += "s";  // traditional combined sampler
96         if (sampler.isArrayed())
97             mangledName += "A";
98         if (sampler.isShadow())
99             mangledName += "S";
100         if (sampler.isExternal())
101             mangledName += "E";
102         if (sampler.isYuv())
103             mangledName += "Y";
104         switch (sampler.dim) {
105         case Esd2D:       mangledName += "2";  break;
106         case Esd3D:       mangledName += "3";  break;
107         case EsdCube:     mangledName += "C";  break;
108 #ifndef GLSLANG_WEB
109         case Esd1D:       mangledName += "1";  break;
110         case EsdRect:     mangledName += "R2"; break;
111         case EsdBuffer:   mangledName += "B";  break;
112         case EsdSubpass:  mangledName += "P";  break;
113 #endif
114         default: break; // some compilers want this
115         }
116
117         if (sampler.hasReturnStruct()) {
118             // Name mangle for sampler return struct uses struct table index.
119             mangledName += "-tx-struct";
120
121             char text[16]; // plenty enough space for the small integers.
122             snprintf(text, sizeof(text), "%d-", sampler.getStructReturnIndex());
123             mangledName += text;
124         } else {
125             switch (sampler.getVectorSize()) {
126             case 1: mangledName += "1"; break;
127             case 2: mangledName += "2"; break;
128             case 3: mangledName += "3"; break;
129             case 4: break; // default to prior name mangle behavior
130             }
131         }
132
133         if (sampler.isMultiSample())
134             mangledName += "M";
135         break;
136     case EbtStruct:
137     case EbtBlock:
138         if (basicType == EbtStruct)
139             mangledName += "struct-";
140         else
141             mangledName += "block-";
142         if (typeName)
143             mangledName += *typeName;
144         for (unsigned int i = 0; i < structure->size(); ++i) {
145             mangledName += '-';
146             (*structure)[i].type->buildMangledName(mangledName);
147         }
148     default:
149         break;
150     }
151
152     if (getVectorSize() > 0)
153         mangledName += static_cast<char>('0' + getVectorSize());
154     else {
155         mangledName += static_cast<char>('0' + getMatrixCols());
156         mangledName += static_cast<char>('0' + getMatrixRows());
157     }
158
159     if (arraySizes) {
160         const int maxSize = 11;
161         char buf[maxSize];
162         for (int i = 0; i < arraySizes->getNumDims(); ++i) {
163             if (arraySizes->getDimNode(i)) {
164                 if (arraySizes->getDimNode(i)->getAsSymbolNode())
165                     snprintf(buf, maxSize, "s%d", arraySizes->getDimNode(i)->getAsSymbolNode()->getId());
166                 else
167                     snprintf(buf, maxSize, "s%p", arraySizes->getDimNode(i));
168             } else
169                 snprintf(buf, maxSize, "%d", arraySizes->getDimSize(i));
170             mangledName += '[';
171             mangledName += buf;
172             mangledName += ']';
173         }
174     }
175 }
176
177 #ifndef GLSLANG_WEB
178
179 //
180 // Dump functions.
181 //
182
183 void TSymbol::dumpExtensions(TInfoSink& infoSink) const
184 {
185     int numExtensions = getNumExtensions();
186     if (numExtensions) {
187         infoSink.debug << " <";
188
189         for (int i = 0; i < numExtensions; i++)
190             infoSink.debug << getExtensions()[i] << ",";
191
192         infoSink.debug << ">";
193     }
194 }
195
196 void TVariable::dump(TInfoSink& infoSink, bool complete) const
197 {
198     if (complete) {
199         infoSink.debug << getName().c_str() << ": " << type.getCompleteString();
200         dumpExtensions(infoSink);
201     } else {
202         infoSink.debug << getName().c_str() << ": " << type.getStorageQualifierString() << " "
203                        << type.getBasicTypeString();
204
205         if (type.isArray())
206             infoSink.debug << "[0]";
207     }
208
209     infoSink.debug << "\n";
210 }
211
212 void TFunction::dump(TInfoSink& infoSink, bool complete) const
213 {
214     if (complete) {
215         infoSink.debug << getName().c_str() << ": " << returnType.getCompleteString() << " " << getName().c_str()
216                        << "(";
217
218         int numParams = getParamCount();
219         for (int i = 0; i < numParams; i++) {
220             const TParameter &param = parameters[i];
221             infoSink.debug << param.type->getCompleteString() << " "
222                            << (param.type->isStruct() ? "of " + param.type->getTypeName() + " " : "")
223                            << (param.name ? *param.name : "") << (i < numParams - 1 ? "," : "");
224         }
225
226         infoSink.debug << ")";
227         dumpExtensions(infoSink);
228     } else {
229         infoSink.debug << getName().c_str() << ": " << returnType.getBasicTypeString() << " "
230                        << getMangledName().c_str() << "n";
231     }
232
233     infoSink.debug << "\n";
234 }
235
236 void TAnonMember::dump(TInfoSink& TInfoSink, bool) const
237 {
238     TInfoSink.debug << "anonymous member " << getMemberNumber() << " of " << getAnonContainer().getName().c_str()
239                     << "\n";
240 }
241
242 void TSymbolTableLevel::dump(TInfoSink& infoSink, bool complete) const
243 {
244     tLevel::const_iterator it;
245     for (it = level.begin(); it != level.end(); ++it)
246         (*it).second->dump(infoSink, complete);
247 }
248
249 void TSymbolTable::dump(TInfoSink& infoSink, bool complete) const
250 {
251     for (int level = currentLevel(); level >= 0; --level) {
252         infoSink.debug << "LEVEL " << level << "\n";
253         table[level]->dump(infoSink, complete);
254     }
255 }
256
257 #endif
258
259 //
260 // Functions have buried pointers to delete.
261 //
262 TFunction::~TFunction()
263 {
264     for (TParamList::iterator i = parameters.begin(); i != parameters.end(); ++i)
265         delete (*i).type;
266 }
267
268 //
269 // Symbol table levels are a map of pointers to symbols that have to be deleted.
270 //
271 TSymbolTableLevel::~TSymbolTableLevel()
272 {
273     for (tLevel::iterator it = level.begin(); it != level.end(); ++it)
274         delete (*it).second;
275
276     delete [] defaultPrecision;
277 }
278
279 //
280 // Change all function entries in the table with the non-mangled name
281 // to be related to the provided built-in operation.
282 //
283 void TSymbolTableLevel::relateToOperator(const char* name, TOperator op)
284 {
285     tLevel::const_iterator candidate = level.lower_bound(name);
286     while (candidate != level.end()) {
287         const TString& candidateName = (*candidate).first;
288         TString::size_type parenAt = candidateName.find_first_of('(');
289         if (parenAt != candidateName.npos && candidateName.compare(0, parenAt, name) == 0) {
290             TFunction* function = (*candidate).second->getAsFunction();
291             function->relateToOperator(op);
292         } else
293             break;
294         ++candidate;
295     }
296 }
297
298 // Make all function overloads of the given name require an extension(s).
299 // Should only be used for a version/profile that actually needs the extension(s).
300 void TSymbolTableLevel::setFunctionExtensions(const char* name, int num, const char* const extensions[])
301 {
302     tLevel::const_iterator candidate = level.lower_bound(name);
303     while (candidate != level.end()) {
304         const TString& candidateName = (*candidate).first;
305         TString::size_type parenAt = candidateName.find_first_of('(');
306         if (parenAt != candidateName.npos && candidateName.compare(0, parenAt, name) == 0) {
307             TSymbol* symbol = candidate->second;
308             symbol->setExtensions(num, extensions);
309         } else
310             break;
311         ++candidate;
312     }
313 }
314
315 //
316 // Make all symbols in this table level read only.
317 //
318 void TSymbolTableLevel::readOnly()
319 {
320     for (tLevel::iterator it = level.begin(); it != level.end(); ++it)
321         (*it).second->makeReadOnly();
322 }
323
324 //
325 // Copy a symbol, but the copy is writable; call readOnly() afterward if that's not desired.
326 //
327 TSymbol::TSymbol(const TSymbol& copyOf)
328 {
329     name = NewPoolTString(copyOf.name->c_str());
330     uniqueId = copyOf.uniqueId;
331     writable = true;
332 }
333
334 TVariable::TVariable(const TVariable& copyOf) : TSymbol(copyOf)
335 {
336     type.deepCopy(copyOf.type);
337     userType = copyOf.userType;
338
339     // we don't support specialization-constant subtrees in cloned tables, only extensions
340     constSubtree = nullptr;
341     extensions = nullptr;
342     memberExtensions = nullptr;
343     if (copyOf.getNumExtensions() > 0)
344         setExtensions(copyOf.getNumExtensions(), copyOf.getExtensions());
345     if (copyOf.hasMemberExtensions()) {
346         for (int m = 0; m < (int)copyOf.type.getStruct()->size(); ++m) {
347             if (copyOf.getNumMemberExtensions(m) > 0)
348                 setMemberExtensions(m, copyOf.getNumMemberExtensions(m), copyOf.getMemberExtensions(m));
349         }
350     }
351
352     if (! copyOf.constArray.empty()) {
353         assert(! copyOf.type.isStruct());
354         TConstUnionArray newArray(copyOf.constArray, 0, copyOf.constArray.size());
355         constArray = newArray;
356     }
357 }
358
359 TVariable* TVariable::clone() const
360 {
361     TVariable *variable = new TVariable(*this);
362
363     return variable;
364 }
365
366 TFunction::TFunction(const TFunction& copyOf) : TSymbol(copyOf)
367 {
368     for (unsigned int i = 0; i < copyOf.parameters.size(); ++i) {
369         TParameter param;
370         parameters.push_back(param);
371         parameters.back().copyParam(copyOf.parameters[i]);
372     }
373
374     extensions = nullptr;
375     if (copyOf.getNumExtensions() > 0)
376         setExtensions(copyOf.getNumExtensions(), copyOf.getExtensions());
377     returnType.deepCopy(copyOf.returnType);
378     mangledName = copyOf.mangledName;
379     op = copyOf.op;
380     defined = copyOf.defined;
381     prototyped = copyOf.prototyped;
382     implicitThis = copyOf.implicitThis;
383     illegalImplicitThis = copyOf.illegalImplicitThis;
384     defaultParamCount = copyOf.defaultParamCount;
385 }
386
387 TFunction* TFunction::clone() const
388 {
389     TFunction *function = new TFunction(*this);
390
391     return function;
392 }
393
394 TAnonMember* TAnonMember::clone() const
395 {
396     // Anonymous members of a given block should be cloned at a higher level,
397     // where they can all be assured to still end up pointing to a single
398     // copy of the original container.
399     assert(0);
400
401     return 0;
402 }
403
404 TSymbolTableLevel* TSymbolTableLevel::clone() const
405 {
406     TSymbolTableLevel *symTableLevel = new TSymbolTableLevel();
407     symTableLevel->anonId = anonId;
408     symTableLevel->thisLevel = thisLevel;
409     std::vector<bool> containerCopied(anonId, false);
410     tLevel::const_iterator iter;
411     for (iter = level.begin(); iter != level.end(); ++iter) {
412         const TAnonMember* anon = iter->second->getAsAnonMember();
413         if (anon) {
414             // Insert all the anonymous members of this same container at once,
415             // avoid inserting the remaining members in the future, once this has been done,
416             // allowing them to all be part of the same new container.
417             if (! containerCopied[anon->getAnonId()]) {
418                 TVariable* container = anon->getAnonContainer().clone();
419                 container->changeName(NewPoolTString(""));
420                 // insert the container and all its members
421                 symTableLevel->insert(*container, false);
422                 containerCopied[anon->getAnonId()] = true;
423             }
424         } else
425             symTableLevel->insert(*iter->second->clone(), false);
426     }
427
428     return symTableLevel;
429 }
430
431 void TSymbolTable::copyTable(const TSymbolTable& copyOf)
432 {
433     assert(adoptedLevels == copyOf.adoptedLevels);
434
435     uniqueId = copyOf.uniqueId;
436     noBuiltInRedeclarations = copyOf.noBuiltInRedeclarations;
437     separateNameSpaces = copyOf.separateNameSpaces;
438     for (unsigned int i = copyOf.adoptedLevels; i < copyOf.table.size(); ++i)
439         table.push_back(copyOf.table[i]->clone());
440 }
441
442 } // end namespace glslang