Web: Tighten up sampling code and interfaces.
[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 //
178 // Dump functions.
179 //
180
181 void TSymbol::dumpExtensions(TInfoSink& infoSink) const
182 {
183     int numExtensions = getNumExtensions();
184     if (numExtensions) {
185         infoSink.debug << " <";
186
187         for (int i = 0; i < numExtensions; i++)
188             infoSink.debug << getExtensions()[i] << ",";
189
190         infoSink.debug << ">";
191     }
192 }
193
194 void TVariable::dump(TInfoSink& infoSink, bool complete) const
195 {
196     if (complete) {
197         infoSink.debug << getName().c_str() << ": " << type.getCompleteString();
198         dumpExtensions(infoSink);
199     } else {
200         infoSink.debug << getName().c_str() << ": " << type.getStorageQualifierString() << " "
201                        << type.getBasicTypeString();
202
203         if (type.isArray())
204             infoSink.debug << "[0]";
205     }
206
207     infoSink.debug << "\n";
208 }
209
210 void TFunction::dump(TInfoSink& infoSink, bool complete) const
211 {
212     if (complete) {
213         infoSink.debug << getName().c_str() << ": " << returnType.getCompleteString() << " " << getName().c_str()
214                        << "(";
215
216         int numParams = getParamCount();
217         for (int i = 0; i < numParams; i++) {
218             const TParameter &param = parameters[i];
219             infoSink.debug << param.type->getCompleteString() << " "
220                            << (param.type->isStruct() ? "of " + param.type->getTypeName() + " " : "")
221                            << (param.name ? *param.name : "") << (i < numParams - 1 ? "," : "");
222         }
223
224         infoSink.debug << ")";
225         dumpExtensions(infoSink);
226     } else {
227         infoSink.debug << getName().c_str() << ": " << returnType.getBasicTypeString() << " "
228                        << getMangledName().c_str() << "n";
229     }
230
231     infoSink.debug << "\n";
232 }
233
234 void TAnonMember::dump(TInfoSink& TInfoSink, bool) const
235 {
236     TInfoSink.debug << "anonymous member " << getMemberNumber() << " of " << getAnonContainer().getName().c_str()
237                     << "\n";
238 }
239
240 void TSymbolTableLevel::dump(TInfoSink& infoSink, bool complete) const
241 {
242     tLevel::const_iterator it;
243     for (it = level.begin(); it != level.end(); ++it)
244         (*it).second->dump(infoSink, complete);
245 }
246
247 void TSymbolTable::dump(TInfoSink& infoSink, bool complete) const
248 {
249     for (int level = currentLevel(); level >= 0; --level) {
250         infoSink.debug << "LEVEL " << level << "\n";
251         table[level]->dump(infoSink, complete);
252     }
253 }
254
255 //
256 // Functions have buried pointers to delete.
257 //
258 TFunction::~TFunction()
259 {
260     for (TParamList::iterator i = parameters.begin(); i != parameters.end(); ++i)
261         delete (*i).type;
262 }
263
264 //
265 // Symbol table levels are a map of pointers to symbols that have to be deleted.
266 //
267 TSymbolTableLevel::~TSymbolTableLevel()
268 {
269     for (tLevel::iterator it = level.begin(); it != level.end(); ++it)
270         delete (*it).second;
271
272     delete [] defaultPrecision;
273 }
274
275 //
276 // Change all function entries in the table with the non-mangled name
277 // to be related to the provided built-in operation.
278 //
279 void TSymbolTableLevel::relateToOperator(const char* name, TOperator op)
280 {
281     tLevel::const_iterator candidate = level.lower_bound(name);
282     while (candidate != level.end()) {
283         const TString& candidateName = (*candidate).first;
284         TString::size_type parenAt = candidateName.find_first_of('(');
285         if (parenAt != candidateName.npos && candidateName.compare(0, parenAt, name) == 0) {
286             TFunction* function = (*candidate).second->getAsFunction();
287             function->relateToOperator(op);
288         } else
289             break;
290         ++candidate;
291     }
292 }
293
294 // Make all function overloads of the given name require an extension(s).
295 // Should only be used for a version/profile that actually needs the extension(s).
296 void TSymbolTableLevel::setFunctionExtensions(const char* name, int num, const char* const extensions[])
297 {
298     tLevel::const_iterator candidate = level.lower_bound(name);
299     while (candidate != level.end()) {
300         const TString& candidateName = (*candidate).first;
301         TString::size_type parenAt = candidateName.find_first_of('(');
302         if (parenAt != candidateName.npos && candidateName.compare(0, parenAt, name) == 0) {
303             TSymbol* symbol = candidate->second;
304             symbol->setExtensions(num, extensions);
305         } else
306             break;
307         ++candidate;
308     }
309 }
310
311 //
312 // Make all symbols in this table level read only.
313 //
314 void TSymbolTableLevel::readOnly()
315 {
316     for (tLevel::iterator it = level.begin(); it != level.end(); ++it)
317         (*it).second->makeReadOnly();
318 }
319
320 //
321 // Copy a symbol, but the copy is writable; call readOnly() afterward if that's not desired.
322 //
323 TSymbol::TSymbol(const TSymbol& copyOf)
324 {
325     name = NewPoolTString(copyOf.name->c_str());
326     uniqueId = copyOf.uniqueId;
327     writable = true;
328 }
329
330 TVariable::TVariable(const TVariable& copyOf) : TSymbol(copyOf)
331 {
332     type.deepCopy(copyOf.type);
333     userType = copyOf.userType;
334
335     // we don't support specialization-constant subtrees in cloned tables, only extensions
336     constSubtree = nullptr;
337     extensions = nullptr;
338     memberExtensions = nullptr;
339     if (copyOf.getNumExtensions() > 0)
340         setExtensions(copyOf.getNumExtensions(), copyOf.getExtensions());
341     if (copyOf.hasMemberExtensions()) {
342         for (int m = 0; m < (int)copyOf.type.getStruct()->size(); ++m) {
343             if (copyOf.getNumMemberExtensions(m) > 0)
344                 setMemberExtensions(m, copyOf.getNumMemberExtensions(m), copyOf.getMemberExtensions(m));
345         }
346     }
347
348     if (! copyOf.constArray.empty()) {
349         assert(! copyOf.type.isStruct());
350         TConstUnionArray newArray(copyOf.constArray, 0, copyOf.constArray.size());
351         constArray = newArray;
352     }
353 }
354
355 TVariable* TVariable::clone() const
356 {
357     TVariable *variable = new TVariable(*this);
358
359     return variable;
360 }
361
362 TFunction::TFunction(const TFunction& copyOf) : TSymbol(copyOf)
363 {
364     for (unsigned int i = 0; i < copyOf.parameters.size(); ++i) {
365         TParameter param;
366         parameters.push_back(param);
367         parameters.back().copyParam(copyOf.parameters[i]);
368     }
369
370     extensions = nullptr;
371     if (copyOf.getNumExtensions() > 0)
372         setExtensions(copyOf.getNumExtensions(), copyOf.getExtensions());
373     returnType.deepCopy(copyOf.returnType);
374     mangledName = copyOf.mangledName;
375     op = copyOf.op;
376     defined = copyOf.defined;
377     prototyped = copyOf.prototyped;
378     implicitThis = copyOf.implicitThis;
379     illegalImplicitThis = copyOf.illegalImplicitThis;
380     defaultParamCount = copyOf.defaultParamCount;
381 }
382
383 TFunction* TFunction::clone() const
384 {
385     TFunction *function = new TFunction(*this);
386
387     return function;
388 }
389
390 TAnonMember* TAnonMember::clone() const
391 {
392     // Anonymous members of a given block should be cloned at a higher level,
393     // where they can all be assured to still end up pointing to a single
394     // copy of the original container.
395     assert(0);
396
397     return 0;
398 }
399
400 TSymbolTableLevel* TSymbolTableLevel::clone() const
401 {
402     TSymbolTableLevel *symTableLevel = new TSymbolTableLevel();
403     symTableLevel->anonId = anonId;
404     symTableLevel->thisLevel = thisLevel;
405     std::vector<bool> containerCopied(anonId, false);
406     tLevel::const_iterator iter;
407     for (iter = level.begin(); iter != level.end(); ++iter) {
408         const TAnonMember* anon = iter->second->getAsAnonMember();
409         if (anon) {
410             // Insert all the anonymous members of this same container at once,
411             // avoid inserting the remaining members in the future, once this has been done,
412             // allowing them to all be part of the same new container.
413             if (! containerCopied[anon->getAnonId()]) {
414                 TVariable* container = anon->getAnonContainer().clone();
415                 container->changeName(NewPoolTString(""));
416                 // insert the container and all its members
417                 symTableLevel->insert(*container, false);
418                 containerCopied[anon->getAnonId()] = true;
419             }
420         } else
421             symTableLevel->insert(*iter->second->clone(), false);
422     }
423
424     return symTableLevel;
425 }
426
427 void TSymbolTable::copyTable(const TSymbolTable& copyOf)
428 {
429     assert(adoptedLevels == copyOf.adoptedLevels);
430
431     uniqueId = copyOf.uniqueId;
432     noBuiltInRedeclarations = copyOf.noBuiltInRedeclarations;
433     separateNameSpaces = copyOf.separateNameSpaces;
434     for (unsigned int i = copyOf.adoptedLevels; i < copyOf.table.size(); ++i)
435         table.push_back(copyOf.table[i]->clone());
436 }
437
438 } // end namespace glslang