Coverage Report

Created: 2026-12-01 07:22

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/shaderc/third_party/glslang/glslang/MachineIndependent/iomapper.cpp
Line
Count
Source
1
//
2
// Copyright (C) 2016-2017 LunarG, Inc.
3
//
4
// All rights reserved.
5
//
6
// Redistribution and use in source and binary forms, with or without
7
// modification, are permitted provided that the following conditions
8
// are met:
9
//
10
//    Redistributions of source code must retain the above copyright
11
//    notice, this list of conditions and the following disclaimer.
12
//
13
//    Redistributions in binary form must reproduce the above
14
//    copyright notice, this list of conditions and the following
15
//    disclaimer in the documentation and/or other materials provided
16
//    with the distribution.
17
//
18
//    Neither the name of 3Dlabs Inc. Ltd. nor the names of its
19
//    contributors may be used to endorse or promote products derived
20
//    from this software without specific prior written permission.
21
//
22
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
25
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
26
// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
28
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
30
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
32
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33
// POSSIBILITY OF SUCH DAMAGE.
34
//
35
36
#include "../Include/Common.h"
37
#include "../Include/InfoSink.h"
38
#include "../Include/Types.h"
39
40
#include "gl_types.h"
41
#include "iomapper.h"
42
#include "LiveTraverser.h"
43
#include "SymbolTable.h"
44
45
//
46
// Map IO bindings.
47
//
48
// High-level algorithm for one stage:
49
//
50
// 1. Traverse all code (live+dead) to find the explicitly provided bindings.
51
//
52
// 2. Traverse (just) the live code to determine which non-provided bindings
53
//    require auto-numbering.  We do not auto-number dead ones.
54
//
55
// 3. Traverse all the code to apply the bindings:
56
//    a. explicitly given bindings are offset according to their type
57
//    b. implicit live bindings are auto-numbered into the holes, using
58
//       any open binding slot.
59
//    c. implicit dead bindings are left un-bound.
60
//
61
62
namespace glslang {
63
64
static int getLayoutSetLimit(bool relaxSetBindingLimits)
65
398
{
66
398
    return relaxSetBindingLimits ? INT_MAX : int(TQualifier::layoutSetEnd);
67
398
}
68
69
static int getLayoutBindingLimit(bool relaxSetBindingLimits)
70
386
{
71
386
    return relaxSetBindingLimits ? INT_MAX : int(TQualifier::layoutBindingEnd);
72
386
}
73
74
bool TVarEntryInfo::TOrderByPriority::operator()(const TVarEntryInfo& l, const TVarEntryInfo& r)
75
864
{
76
864
    const TQualifier& lq = l.symbol->getQualifier();
77
864
    const TQualifier& rq = r.symbol->getQualifier();
78
79
    // simple rules:
80
    // has binding gives 2 points
81
    // has set gives 1 point
82
    // who has the most points is more important.
83
864
    int lPoints = (lq.hasBinding() ? 2 : 0) + (lq.hasSet() ? 1 : 0);
84
864
    int rPoints = (rq.hasBinding() ? 2 : 0) + (rq.hasSet() ? 1 : 0);
85
86
864
    if (lPoints == rPoints)
87
788
        return l.id < r.id;
88
76
    return lPoints > rPoints;
89
864
}
90
91
bool TVarEntryInfo::TOrderByPriorityAndLive::operator()(const TVarEntryInfo& l, const TVarEntryInfo& r)
92
0
{
93
0
    const TQualifier& lq = l.symbol->getQualifier();
94
0
    const TQualifier& rq = r.symbol->getQualifier();
95
96
    // simple rules:
97
    // has binding gives 2 points
98
    // has set gives 1 point
99
    // who has the most points is more important.
100
0
    int lPoints = (lq.hasBinding() ? 2 : 0) + (lq.hasSet() ? 1 : 0);
101
0
    int rPoints = (rq.hasBinding() ? 2 : 0) + (rq.hasSet() ? 1 : 0);
102
103
0
    if (l.live != r.live)
104
0
        return l.live > r.live;
105
106
0
    if (lPoints != rPoints)
107
0
        return lPoints > rPoints;
108
109
0
    return l.id < r.id;
110
0
}
111
112
// override function "operator=", if a vector<const _Kty, _Ty> being sort,
113
// when use vc++, the sort function will call :
114
// pair& operator=(const pair<_Other1, _Other2>& _Right)
115
// {
116
//     first = _Right.first;
117
//     second = _Right.second;
118
//     return (*this);
119
// }
120
// that will make a const type handing on left.
121
// override this function can avoid a compiler error.
122
// In the future, if the vc++ compiler can handle such a situation,
123
// this part of the code will be removed.
124
struct TVarLivePair : std::pair<const TString, TVarEntryInfo> {
125
504
    TVarLivePair(const std::pair<const TString, TVarEntryInfo>& _Right) : pair(_Right.first, _Right.second) {}
126
818
    TVarLivePair& operator=(const TVarLivePair& _Right) {
127
818
        const_cast<TString&>(first) = _Right.first;
128
818
        second = _Right.second;
129
818
        return (*this);
130
818
    }
131
1.71k
    TVarLivePair(const TVarLivePair& src) : pair(src) { }
132
};
133
typedef std::vector<TVarLivePair> TVarLiveVector;
134
135
136
class TVarGatherTraverser : public TLiveTraverser {
137
public:
138
    TVarGatherTraverser(const TIntermediate& i, bool traverseDeadCode, TVarLiveMap& inList, TVarLiveMap& outList, TVarLiveMap& uniformList)
139
204
      : TLiveTraverser(i, traverseDeadCode, true, true, false, false)
140
204
      , inputList(inList)
141
204
      , outputList(outList)
142
204
      , uniformList(uniformList)
143
204
    {
144
204
    }
145
146
    virtual void visitSymbol(TIntermSymbol* base)
147
8.96k
    {
148
8.96k
        TVarLiveMap* target = nullptr;
149
8.96k
        if (base->getQualifier().storage == EvqVaryingIn)
150
320
            target = &inputList;
151
8.64k
        else if (base->getQualifier().storage == EvqVaryingOut)
152
290
            target = &outputList;
153
8.35k
        else if (base->getQualifier().isUniformOrBuffer() && !base->getQualifier().isPushConstant() && !base->getQualifier().isShaderRecord())
154
4.30k
            target = &uniformList;
155
        // If a global is being visited, then we should also traverse it incase it's evaluation
156
        // ends up visiting inputs we want to tag as live
157
4.05k
        else if (base->getQualifier().storage == EvqGlobal)
158
540
            addGlobalReference(base->getAccessName());
159
160
8.96k
        if (target) {
161
4.91k
            TVarEntryInfo ent = {base->getId(), base, ! traverseAll, {}, {}, {}, {}, {}, {}, {}};
162
4.91k
            ent.stage = intermediate.getStage();
163
4.91k
            TVarLiveMap::iterator at = target->find(
164
4.91k
                ent.symbol->getAccessName()); // std::lower_bound(target->begin(), target->end(), ent, TVarEntryInfo::TOrderById());
165
4.91k
            if (at != target->end() && at->second.id == ent.id)
166
4.40k
                at->second.live = at->second.live || ! traverseAll; // update live state
167
504
            else
168
504
                (*target)[ent.symbol->getAccessName()] = ent;
169
4.91k
        }
170
8.96k
    }
171
172
private:
173
    TVarLiveMap&    inputList;
174
    TVarLiveMap&    outputList;
175
    TVarLiveMap&    uniformList;
176
};
177
178
class TVarSetTraverser : public TLiveTraverser
179
{
180
public:
181
    TVarSetTraverser(const TIntermediate& i, const TVarLiveMap& inList, const TVarLiveMap& outList, const TVarLiveMap& uniformList)
182
102
      : TLiveTraverser(i, true, true, true, false, true)
183
102
      , inputList(inList)
184
102
      , outputList(outList)
185
102
      , uniformList(uniformList)
186
102
    {
187
102
    }
188
189
4.82k
    virtual void visitSymbol(TIntermSymbol* base) {
190
4.82k
        const TVarLiveMap* source;
191
4.82k
        if (base->getQualifier().storage == EvqVaryingIn)
192
190
            source = &inputList;
193
4.63k
        else if (base->getQualifier().storage == EvqVaryingOut)
194
168
            source = &outputList;
195
4.46k
        else if (base->getQualifier().isUniformOrBuffer())
196
2.38k
            source = &uniformList;
197
2.08k
        else
198
2.08k
            return;
199
200
2.73k
        TVarEntryInfo ent = { base->getId(), {}, {}, {}, {}, {}, {}, {}, {}, {} };
201
        // Fix a defect, when block has no instance name, we need to find its block name
202
2.73k
        TVarLiveMap::const_iterator at = source->find(base->getAccessName());
203
2.73k
        if (at == source->end())
204
30
            return;
205
206
2.70k
        if (at->second.id != ent.id)
207
0
            return;
208
209
2.70k
        if (at->second.newBinding != -1)
210
2.33k
            base->getWritableType().getQualifier().layoutBinding = at->second.newBinding;
211
2.70k
        if (at->second.newSet != -1)
212
2.35k
            base->getWritableType().getQualifier().layoutSet = at->second.newSet;
213
2.70k
        if (at->second.newLocation != -1)
214
20
            base->getWritableType().getQualifier().layoutLocation = at->second.newLocation;
215
2.70k
        if (at->second.newComponent != -1)
216
0
            base->getWritableType().getQualifier().layoutComponent = at->second.newComponent;
217
2.70k
        if (at->second.newIndex != -1)
218
0
            base->getWritableType().getQualifier().layoutIndex = at->second.newIndex;
219
2.70k
        if (at->second.upgradedToPushConstantPacking != ElpNone) {
220
0
            base->getWritableType().getQualifier().layoutPushConstant = true;
221
0
            base->getWritableType().getQualifier().setBlockStorage(EbsPushConstant);
222
0
            base->getWritableType().getQualifier().layoutPacking = at->second.upgradedToPushConstantPacking;
223
0
        }
224
2.70k
    }
225
226
  private:
227
    const TVarLiveMap&    inputList;
228
    const TVarLiveMap&    outputList;
229
    const TVarLiveMap&    uniformList;
230
};
231
232
struct TNotifyUniformAdaptor
233
{
234
    EShLanguage stage;
235
    TIoMapResolver& resolver;
236
    inline TNotifyUniformAdaptor(EShLanguage s, TIoMapResolver& r)
237
102
      : stage(s)
238
102
      , resolver(r)
239
102
    {
240
102
    }
241
242
    inline void operator()(std::pair<const TString, TVarEntryInfo>& entKey)
243
398
    {
244
398
        resolver.notifyBinding(stage, entKey.second);
245
398
    }
246
247
private:
248
    TNotifyUniformAdaptor& operator=(TNotifyUniformAdaptor&) = delete;
249
};
250
251
struct TNotifyInOutAdaptor
252
{
253
    EShLanguage stage;
254
    TIoMapResolver& resolver;
255
    inline TNotifyInOutAdaptor(EShLanguage s, TIoMapResolver& r)
256
102
      : stage(s)
257
102
      , resolver(r)
258
102
    {
259
102
    }
260
261
    inline void operator()(std::pair<const TString, TVarEntryInfo>& entKey)
262
106
    {
263
106
        resolver.notifyInOut(entKey.second.stage, entKey.second);
264
106
    }
265
266
private:
267
    TNotifyInOutAdaptor& operator=(TNotifyInOutAdaptor&) = delete;
268
};
269
270
struct TResolverUniformAdaptor {
271
    TResolverUniformAdaptor(EShLanguage s, TIoMapResolver& r, TVarLiveMap* uniform[EShLangCount], TInfoSink& i,
272
                            bool& e, bool relaxSetBindingLimits)
273
102
      : stage(s)
274
102
      , resolver(r)
275
102
      , infoSink(i)
276
102
      , error(e)
277
102
      , relaxSetBindingLimits(relaxSetBindingLimits)
278
102
    {
279
102
        memcpy(uniformVarMap, uniform, EShLangCount * (sizeof(TVarLiveMap*)));
280
102
    }
281
282
398
    inline void operator()(std::pair<const TString, TVarEntryInfo>& entKey) {
283
398
        TVarEntryInfo& ent = entKey.second;
284
398
        ent.clearNewAssignments();
285
398
        const bool isValid = resolver.validateBinding(stage, ent);
286
398
        if (isValid) {
287
398
            resolver.resolveSet(ent.stage, ent);
288
398
            resolver.resolveBinding(ent.stage, ent);
289
398
            resolver.resolveUniformLocation(ent.stage, ent);
290
291
398
            if (ent.newBinding != -1) {
292
386
                if (ent.newBinding < 0 || ent.newBinding >= getLayoutBindingLimit(relaxSetBindingLimits)) {
293
0
                    TString err = "mapped binding out of range: " + entKey.first;
294
295
0
                    infoSink.info.message(EPrefixInternalError, err.c_str());
296
0
                    error = true;
297
0
                }
298
299
386
                if (ent.symbol->getQualifier().hasBinding()) {
300
4.68k
                    for (uint32_t idx = EShLangVertex; idx < EShLangCount; ++idx) {
301
4.36k
                        if (idx == ent.stage || uniformVarMap[idx] == nullptr)
302
4.36k
                            continue;
303
0
                        auto entKey2 = uniformVarMap[idx]->find(entKey.first);
304
0
                        if (entKey2 != uniformVarMap[idx]->end()) {
305
0
                            entKey2->second.newBinding = ent.newBinding;
306
0
                        }
307
0
                    }
308
312
                }
309
386
            }
310
398
            if (ent.newSet != -1) {
311
398
                if (ent.newSet < 0 || ent.newSet >= getLayoutSetLimit(relaxSetBindingLimits)) {
312
0
                    TString err = "mapped set out of range: " + entKey.first;
313
314
0
                    infoSink.info.message(EPrefixInternalError, err.c_str());
315
0
                    error = true;
316
0
                }
317
398
                if (ent.symbol->getQualifier().hasSet()) {
318
1.68k
                    for (uint32_t idx = EShLangVertex; idx < EShLangCount; ++idx) {
319
1.56k
                        if ((idx == stage) || (uniformVarMap[idx] == nullptr))
320
1.56k
                            continue;
321
0
                        auto entKey2 = uniformVarMap[idx]->find(entKey.first);
322
0
                        if (entKey2 != uniformVarMap[idx]->end()) {
323
0
                            entKey2->second.newSet = ent.newSet;
324
0
                        }
325
0
                    }
326
112
                }
327
398
            }
328
398
        } else {
329
0
            TString errorMsg = "Invalid binding: " + entKey.first;
330
0
            infoSink.info.message(EPrefixInternalError, errorMsg.c_str());
331
0
            error = true;
332
0
        }
333
398
    }
334
335
0
    inline void setStage(EShLanguage s) { stage = s; }
336
337
    EShLanguage     stage;
338
    TIoMapResolver& resolver;
339
    TInfoSink&      infoSink;
340
    bool&           error;
341
    bool            relaxSetBindingLimits;
342
    TVarLiveMap*    uniformVarMap[EShLangCount];
343
private:
344
    TResolverUniformAdaptor& operator=(TResolverUniformAdaptor&) = delete;
345
};
346
347
struct TResolverInOutAdaptor {
348
    TResolverInOutAdaptor(EShLanguage s, TIoMapResolver& r, TInfoSink& i, bool& e)
349
102
      : stage(s)
350
102
      , resolver(r)
351
102
      , infoSink(i)
352
102
      , error(e)
353
102
    {
354
102
    }
355
356
    inline void operator()(std::pair<const TString, TVarEntryInfo>& entKey)
357
106
    {
358
106
        TVarEntryInfo& ent = entKey.second;
359
106
        ent.clearNewAssignments();
360
106
        const bool isValid = resolver.validateInOut(ent.stage, ent);
361
106
        if (isValid) {
362
106
            resolver.resolveInOutLocation(stage, ent);
363
106
            resolver.resolveInOutComponent(stage, ent);
364
106
            resolver.resolveInOutIndex(stage, ent);
365
106
        } else {
366
0
            TString errorMsg;
367
0
            if (ent.symbol->getType().getQualifier().semanticName != nullptr) {
368
0
                errorMsg = "Invalid shader In/Out variable semantic: ";
369
0
                errorMsg += ent.symbol->getType().getQualifier().semanticName;
370
0
            } else {
371
0
                errorMsg = "Invalid shader In/Out variable: ";
372
0
                errorMsg += ent.symbol->getName();
373
0
            }
374
0
            infoSink.info.message(EPrefixInternalError, errorMsg.c_str());
375
0
            error = true;
376
0
        }
377
106
    }
378
379
0
    inline void setStage(EShLanguage s) { stage = s; }
380
381
    EShLanguage     stage;
382
    TIoMapResolver& resolver;
383
    TInfoSink&      infoSink;
384
    bool&           error;
385
386
private:
387
    TResolverInOutAdaptor& operator=(TResolverInOutAdaptor&) = delete;
388
};
389
390
// The class is used for reserving explicit uniform locations and ubo/ssbo/opaque bindings
391
// xxTODO: maybe this logic should be moved into the resolver's "validateInOut" and "validateUniform"
392
393
struct TSymbolValidater
394
{
395
    TSymbolValidater(TIoMapResolver& r, TInfoSink& i, TVarLiveMap* in[EShLangCount], TVarLiveMap* out[EShLangCount],
396
                     TVarLiveMap* uniform[EShLangCount], bool& hadError, EProfile profile, int version)
397
0
        : resolver(r)
398
0
        , infoSink(i)
399
0
        , hadError(hadError)
400
0
        , profile(profile)
401
0
        , version(version)
402
0
    {
403
0
        memcpy(inVarMaps, in, EShLangCount * (sizeof(TVarLiveMap*)));
404
0
        memcpy(outVarMaps, out, EShLangCount * (sizeof(TVarLiveMap*)));
405
0
        memcpy(uniformVarMap, uniform, EShLangCount * (sizeof(TVarLiveMap*)));
406
407
0
        std::map<TString, TString> anonymousMemberMap;
408
0
        std::vector<TRange> usedUniformLocation;
409
0
        std::vector<TString> usedUniformName;
410
0
        usedUniformLocation.clear();
411
0
        usedUniformName.clear();
412
0
        for (int i = 0; i < EShLangCount; i++) {
413
0
            if (uniformVarMap[i]) {
414
0
                for (auto uniformVar : *uniformVarMap[i])
415
0
                {
416
0
                    TIntermSymbol* pSymbol = uniformVar.second.symbol;
417
0
                    TQualifier qualifier = uniformVar.second.symbol->getQualifier();
418
0
                    TString symbolName = pSymbol->getAccessName();
419
420
                    // All the uniform needs multi-stage location check (block/default)
421
0
                    int uniformLocation = qualifier.layoutLocation;
422
423
0
                    if (uniformLocation != TQualifier::layoutLocationEnd) {
424
                        // Total size of current uniform, could be block, struct or other types.
425
0
                        int size = TIntermediate::computeTypeUniformLocationSize(pSymbol->getType());
426
427
0
                        TRange locationRange(uniformLocation, uniformLocation + size - 1);
428
429
                        // Combine location and component ranges
430
0
                        int overlapLocation = -1;
431
0
                        bool diffLocation = false;
432
433
                        // Check for collisions, except for vertex inputs on desktop targeting OpenGL
434
0
                        overlapLocation = checkLocationOverlap(locationRange, usedUniformLocation, symbolName, usedUniformName, diffLocation);
435
436
                        // Overlap locations of uniforms, regardless of components (multi stages)
437
0
                        if (overlapLocation == -1) {
438
0
                            usedUniformLocation.push_back(locationRange);
439
0
                            usedUniformName.push_back(symbolName);
440
0
                        }
441
0
                        else if (overlapLocation >= 0) {
442
0
                            if (diffLocation == true) {
443
0
                                TString err = ("Uniform location should be equal for same uniforms: " +std::to_string(overlapLocation)).c_str();
444
0
                                infoSink.info.message(EPrefixInternalError, err.c_str());
445
0
                                hadError = true;
446
0
                                break;
447
0
                            }
448
0
                            else {
449
0
                                TString err = ("Uniform location overlaps across stages: " + std::to_string(overlapLocation)).c_str();
450
0
                                infoSink.info.message(EPrefixInternalError, err.c_str());
451
0
                                hadError = true;
452
0
                                break;
453
0
                            }
454
0
                        }
455
0
                    }
456
457
0
                    if ((uniformVar.second.symbol->getBasicType() == EbtBlock) &&
458
0
                        IsAnonymous(uniformVar.second.symbol->getName()))
459
0
                    {
460
0
                        auto blockType = uniformVar.second.symbol->getType().getStruct();
461
0
                        for (size_t memberIdx = 0; memberIdx < blockType->size(); ++memberIdx) {
462
0
                            auto memberName = (*blockType)[memberIdx].type->getFieldName();
463
0
                            if (anonymousMemberMap.find(memberName) != anonymousMemberMap.end())
464
0
                            {
465
0
                                if (anonymousMemberMap[memberName] != uniformVar.second.symbol->getType().getTypeName())
466
0
                                {
467
0
                                    TString err = "Invalid block member name: " + memberName;
468
0
                                    infoSink.info.message(EPrefixInternalError, err.c_str());
469
0
                                    hadError = true;
470
0
                                    break;
471
0
                                }
472
0
                            }
473
0
                            else
474
0
                            {
475
0
                                anonymousMemberMap[memberName] = uniformVar.second.symbol->getType().getTypeName();
476
0
                            }
477
0
                        }
478
0
                    }
479
0
                    if (hadError)
480
0
                        break;
481
0
                }
482
0
            }
483
0
        }
484
0
    }
485
486
    // In case we need to new an intermediate, which costs too much
487
    int checkLocationOverlap(const TRange& locationRange, std::vector<TRange>& usedUniformLocation, const TString symbolName, std::vector<TString>& usedUniformName, bool& diffLocation)
488
0
    {
489
0
        for (size_t r = 0; r < usedUniformLocation.size(); ++r) {
490
0
            if (usedUniformName[r] == symbolName) {
491
0
                diffLocation = true;
492
0
                return (usedUniformLocation[r].start == locationRange.start &&
493
0
                        usedUniformLocation[r].last == locationRange.last)
494
0
                       ? -2 : std::max(locationRange.start, usedUniformLocation[r].start);
495
0
            }
496
0
            if (locationRange.overlap(usedUniformLocation[r])) {
497
                // there is a collision; pick one
498
0
                return std::max(locationRange.start, usedUniformLocation[r].start);
499
0
            }
500
0
        }
501
502
0
        return -1; // no collision
503
0
    }
504
505
0
    inline void operator()(std::pair<const TString, TVarEntryInfo>& entKey) {
506
0
        TVarEntryInfo& ent1 = entKey.second;
507
0
        TIntermSymbol* base = ent1.symbol;
508
0
        const TType& type = ent1.symbol->getType();
509
0
        const TString& name = entKey.first;
510
0
        TString mangleName1, mangleName2;
511
0
        EShLanguage stage = ent1.stage;
512
0
        EShLanguage preStage, currentStage, nextStage;
513
514
0
        preStage = EShLangCount;
515
0
        for (int i = stage - 1; i >= 0; i--) {
516
0
            if (inVarMaps[i] != nullptr) {
517
0
                preStage = static_cast<EShLanguage>(i);
518
0
                break;
519
0
            }
520
0
        }
521
0
        currentStage = stage;
522
0
        nextStage = EShLangCount;
523
0
        for (int i = stage + 1; i < EShLangCount; i++) {
524
0
            if (inVarMaps[i] != nullptr) {
525
0
                nextStage = static_cast<EShLanguage>(i);
526
0
                break;
527
0
            }
528
0
        }
529
530
0
        if (type.getQualifier().isArrayedIo(stage)) {
531
0
            TType subType(type, 0);
532
0
            subType.appendMangledName(mangleName1);
533
0
        } else {
534
0
            type.appendMangledName(mangleName1);
535
0
        }
536
537
538
        // basic checking that symbols match
539
        // more extensive checking in the link stage
540
0
        if (base->getQualifier().storage == EvqVaryingIn) {
541
            // validate stage in;
542
0
            if (preStage == EShLangCount)
543
0
                return;
544
0
            if (TSymbolTable::isBuiltInSymbol(base->getId()))
545
0
                return;
546
0
            if (outVarMaps[preStage] != nullptr) {
547
0
                auto ent2 = outVarMaps[preStage]->find(name);
548
0
                uint32_t location = base->getType().getQualifier().layoutLocation;
549
0
                if (ent2 == outVarMaps[preStage]->end() &&
550
0
                    location != glslang::TQualifier::layoutLocationEnd) {
551
0
                    for (auto var = outVarMaps[preStage]->begin(); var != ent2; var++) {
552
0
                        if (var->second.symbol->getType().getQualifier().layoutLocation == location) {
553
0
                            ent2 = var;
554
0
                            break;
555
0
                        }
556
0
                    }
557
0
                }
558
0
                if (ent2 != outVarMaps[preStage]->end()) {
559
0
                    auto& type1 = base->getType();
560
0
                    auto& type2 = ent2->second.symbol->getType();
561
0
                    hadError = hadError || typeCheck(&type1, &type2, name.c_str(), false);
562
0
                    if (ent2->second.symbol->getType().getQualifier().isArrayedIo(preStage)) {
563
0
                        TType subType(ent2->second.symbol->getType(), 0);
564
0
                        subType.appendMangledName(mangleName2);
565
0
                    } else {
566
0
                        ent2->second.symbol->getType().appendMangledName(mangleName2);
567
0
                    }
568
569
0
                    if (mangleName1 == mangleName2) {
570
                        // For ES 3.0 only, other versions have no such restrictions
571
                        // According to ES 3.0 spec: The type and presence of the interpolation qualifiers and
572
                        // storage qualifiers  of variables with the same name declared in all linked shaders must
573
                        // match, otherwise the link command will fail.
574
0
                        if (profile == EEsProfile && version == 300) {
575
                            // Don't need to check smooth qualifier, as it uses the default interpolation mode
576
0
                            if (ent1.stage == EShLangFragment && type1.isBuiltIn() == false) {
577
0
                                if (type1.getQualifier().flat != type2.getQualifier().flat ||
578
0
                                    type1.getQualifier().nopersp != type2.getQualifier().nopersp) {
579
0
                                    TString err = "Interpolation qualifier mismatch : " + entKey.first;
580
0
                                    infoSink.info.message(EPrefixInternalError, err.c_str());
581
0
                                    hadError = true;
582
0
                                }
583
0
                            }
584
0
                        }
585
0
                        return;
586
0
                    }
587
0
                    else {
588
                        // Deal with input/output pairs where one is a block member but the other is loose,
589
                        // e.g. with ARB_separate_shader_objects
590
0
                        if (type1.getBasicType() == EbtBlock &&
591
0
                            type1.isStruct() && !type2.isStruct()) {
592
                            // Iterate through block members tracking layout
593
0
                            glslang::TString name;
594
0
                            type1.getStruct()->begin()->type->appendMangledName(name);
595
0
                            if (name == mangleName2
596
0
                                && type1.getQualifier().layoutLocation == type2.getQualifier().layoutLocation) return;
597
0
                        }
598
0
                        if (type2.getBasicType() == EbtBlock &&
599
0
                            type2.isStruct() && !type1.isStruct()) {
600
                            // Iterate through block members tracking layout
601
0
                            glslang::TString name;
602
0
                            type2.getStruct()->begin()->type->appendMangledName(name);
603
0
                            if (name == mangleName1
604
0
                                && type1.getQualifier().layoutLocation == type2.getQualifier().layoutLocation) return;
605
0
                        }
606
0
                        TString err = "Invalid In/Out variable type : " + entKey.first;
607
0
                        infoSink.info.message(EPrefixInternalError, err.c_str());
608
0
                        hadError = true;
609
0
                    }
610
0
                }
611
0
                else if (!base->getType().isBuiltIn()) {
612
                    // According to spec: A link error is generated if any statically referenced input variable
613
                    // or block does not have a matching output
614
0
                    if (profile == EEsProfile && ent1.live) {
615
0
                        hadError = true;
616
0
                        TString errorStr = name + ": not been declare as a output variable in pre shader stage.";
617
0
                        infoSink.info.message(EPrefixError, errorStr.c_str());
618
0
                    }
619
0
                }
620
0
                return;
621
0
            }
622
0
        } else if (base->getQualifier().storage == EvqVaryingOut) {
623
            // validate stage out;
624
0
            if (nextStage == EShLangCount)
625
0
                return;
626
0
            if (TSymbolTable::isBuiltInSymbol(base->getId()))
627
0
                return;
628
0
            if (inVarMaps[nextStage] != nullptr) {
629
0
                auto ent2 = inVarMaps[nextStage]->find(name);
630
0
                if (ent2 != inVarMaps[nextStage]->end()) {
631
0
                    if (ent2->second.symbol->getType().getQualifier().isArrayedIo(nextStage)) {
632
0
                        TType subType(ent2->second.symbol->getType(), 0);
633
0
                        subType.appendMangledName(mangleName2);
634
0
                    } else {
635
0
                        ent2->second.symbol->getType().appendMangledName(mangleName2);
636
0
                    }
637
0
                    if (mangleName1 == mangleName2)
638
0
                        return;
639
0
                    else {
640
0
                        TString err = "Invalid In/Out variable type : " + entKey.first;
641
0
                        infoSink.info.message(EPrefixInternalError, err.c_str());
642
0
                        hadError = true;
643
0
                    }
644
0
                }
645
0
                return;
646
0
            }
647
0
        } else if (base->getQualifier().isUniformOrBuffer() && !base->getQualifier().isPushConstant()) {
648
            // validate uniform type;
649
0
            for (int i = 0; i < EShLangCount; i++) {
650
0
                if (i != currentStage && uniformVarMap[i] != nullptr) {
651
0
                    auto ent2 = uniformVarMap[i]->find(name);
652
0
                    if (ent2 != uniformVarMap[i]->end()) {
653
0
                        ent2->second.symbol->getType().appendMangledName(mangleName2);
654
0
                        if (mangleName1 != mangleName2) {
655
0
                            ent2->second.symbol->getType().sameElementType(type);
656
0
                            TString err = "Invalid Uniform variable type : " + entKey.first;
657
0
                            infoSink.info.message(EPrefixInternalError, err.c_str());
658
0
                            hadError = true;
659
0
                        }
660
0
                        mangleName2.clear();
661
662
                        // validate instance name of blocks
663
0
                        if (hadError == false &&
664
0
                            base->getType().getBasicType() == EbtBlock &&
665
0
                            IsAnonymous(base->getName()) != IsAnonymous(ent2->second.symbol->getName())) {
666
0
                            TString err = "Matched uniform block names must also either all be lacking "
667
0
                                          "an instance name or all having an instance name: " + entKey.first;
668
0
                            infoSink.info.message(EPrefixInternalError, err.c_str());
669
0
                            hadError = true;
670
0
                        }
671
672
                        // validate uniform block member qualifier and member names
673
0
                        auto& type1 = base->getType();
674
0
                        auto& type2 = ent2->second.symbol->getType();
675
0
                        if (hadError == false && base->getType().getBasicType() == EbtBlock) {
676
0
                            hadError = hadError || typeCheck(&type1, &type2, name.c_str(), true);
677
0
                        }
678
0
                        else {
679
0
                            hadError = hadError || typeCheck(&type1, &type2, name.c_str(), false);
680
0
                        }
681
0
                    }
682
0
                    else if (base->getBasicType() == EbtBlock)
683
0
                    {
684
0
                        if (IsAnonymous(base->getName()))
685
0
                        {
686
                            // The name of anonymous block member can't same with default uniform variable.
687
0
                            auto blockType1 = base->getType().getStruct();
688
0
                            for (size_t memberIdx = 0; memberIdx < blockType1->size(); ++memberIdx) {
689
0
                                auto memberName = (*blockType1)[memberIdx].type->getFieldName();
690
0
                                if (uniformVarMap[i]->find(memberName) != uniformVarMap[i]->end())
691
0
                                {
692
0
                                    TString err = "Invalid Uniform variable name : " + memberName;
693
0
                                    infoSink.info.message(EPrefixInternalError, err.c_str());
694
0
                                    hadError = true;
695
0
                                    break;
696
0
                                }
697
0
                            }
698
0
                        }
699
0
                    }
700
0
                }
701
0
            }
702
0
        }
703
0
    }
704
705
    TVarLiveMap *inVarMaps[EShLangCount], *outVarMaps[EShLangCount], *uniformVarMap[EShLangCount];
706
707
    // Use for mark current shader stage for resolver
708
    TIoMapResolver& resolver;
709
    TInfoSink& infoSink;
710
    bool& hadError;
711
    EProfile profile;
712
    int version;
713
714
private:
715
    TSymbolValidater& operator=(TSymbolValidater&) = delete;
716
717
    bool qualifierCheck(const TType* const type1, const TType* const type2, const std::string& name, bool isBlock)
718
0
    {
719
0
        bool hasError = false;
720
0
        const TQualifier& qualifier1 = type1->getQualifier();
721
0
        const TQualifier& qualifier2 = type2->getQualifier();
722
723
0
        if (((isBlock == false) &&
724
0
            (type1->getQualifier().storage == EvqUniform && type2->getQualifier().storage == EvqUniform)) ||
725
0
            (type1->getQualifier().storage == EvqGlobal && type2->getQualifier().storage == EvqGlobal)) {
726
0
            if (qualifier1.precision != qualifier2.precision) {
727
0
                hasError = true;
728
0
                std::string errorStr = name + ": have precision conflict cross stage.";
729
0
                infoSink.info.message(EPrefixError, errorStr.c_str());
730
0
            }
731
0
            if (qualifier1.hasFormat() && qualifier2.hasFormat()) {
732
0
                if (qualifier1.layoutFormat != qualifier2.layoutFormat) {
733
0
                    hasError = true;
734
0
                    std::string errorStr = name + ": have layout format conflict cross stage.";
735
0
                    infoSink.info.message(EPrefixError, errorStr.c_str());
736
0
                }
737
738
0
            }
739
0
        }
740
741
0
        if (isBlock == true) {
742
0
            if (qualifier1.layoutPacking != qualifier2.layoutPacking) {
743
0
                hasError = true;
744
0
                std::string errorStr = name + ": have layoutPacking conflict cross stage.";
745
0
                infoSink.info.message(EPrefixError, errorStr.c_str());
746
0
            }
747
0
            if (qualifier1.layoutMatrix != qualifier2.layoutMatrix) {
748
0
                hasError = true;
749
0
                std::string errorStr = name + ": have layoutMatrix conflict cross stage.";
750
0
                infoSink.info.message(EPrefixError, errorStr.c_str());
751
0
            }
752
0
            if (qualifier1.layoutOffset != qualifier2.layoutOffset) {
753
0
                hasError = true;
754
0
                std::string errorStr = name + ": have layoutOffset conflict cross stage.";
755
0
                infoSink.info.message(EPrefixError, errorStr.c_str());
756
0
            }
757
0
            if (qualifier1.layoutAlign != qualifier2.layoutAlign) {
758
0
                hasError = true;
759
0
                std::string errorStr = name + ": have layoutAlign conflict cross stage.";
760
0
                infoSink.info.message(EPrefixError, errorStr.c_str());
761
0
            }
762
0
        }
763
764
0
        return hasError;
765
0
    }
766
767
    bool typeCheck(const TType* const type1, const TType* const type2, const std::string& name, bool isBlock)
768
0
    {
769
0
        bool hasError = false;
770
0
        if (!(type1->isStruct() && type2->isStruct())) {
771
0
            hasError = hasError || qualifierCheck(type1, type2, name, isBlock);
772
0
        }
773
0
        else {
774
0
            if (type1->getBasicType() == EbtBlock && type2->getBasicType() == EbtBlock)
775
0
                isBlock = true;
776
0
            const TTypeList* typeList1 = type1->getStruct();
777
0
            const TTypeList* typeList2 = type2->getStruct();
778
779
0
            std::string newName = name;
780
0
            size_t memberCount = typeList1->size();
781
0
            size_t index2 = 0;
782
0
            for (size_t index = 0; index < memberCount; index++, index2++) {
783
                // Skip inactive member
784
0
                if (typeList1->at(index).type->getBasicType() == EbtVoid)
785
0
                    continue;
786
0
                while (index2 < typeList2->size() && typeList2->at(index2).type->getBasicType() == EbtVoid) {
787
0
                    ++index2;
788
0
                }
789
790
                // TypeList1 has more members in list
791
0
                if (index2 == typeList2->size()) {
792
0
                    std::string errorStr = name + ": struct mismatch.";
793
0
                    infoSink.info.message(EPrefixError, errorStr.c_str());
794
0
                    hasError = true;
795
0
                    break;
796
0
                }
797
798
0
                if (typeList1->at(index).type->getFieldName() != typeList2->at(index2).type->getFieldName()) {
799
0
                    std::string errorStr = name + ": member name mismatch.";
800
0
                    infoSink.info.message(EPrefixError, errorStr.c_str());
801
0
                    hasError = true;
802
0
                }
803
0
                else {
804
0
                    newName = typeList1->at(index).type->getFieldName().c_str();
805
0
                }
806
0
                hasError = hasError || typeCheck(typeList1->at(index).type, typeList2->at(index2).type, newName, isBlock);
807
0
            }
808
809
0
            while (index2 < typeList2->size())
810
0
            {
811
                // TypeList2 has more members
812
0
                if (typeList2->at(index2).type->getBasicType() != EbtVoid) {
813
0
                    std::string errorStr = name + ": struct mismatch.";
814
0
                    infoSink.info.message(EPrefixError, errorStr.c_str());
815
0
                    hasError = true;
816
0
                    break;
817
0
                }
818
0
                ++index2;
819
0
            }
820
0
        }
821
0
        return hasError;
822
0
    }
823
};
824
825
struct TSlotCollector {
826
0
    TSlotCollector(TIoMapResolver& r, TInfoSink& i) : resolver(r), infoSink(i) { }
827
828
0
    inline void operator()(std::pair<const TString, TVarEntryInfo>& entKey) {
829
0
        resolver.reserverStorageSlot(entKey.second, infoSink);
830
0
        resolver.reserverResourceSlot(entKey.second, infoSink);
831
0
    }
832
    TIoMapResolver& resolver;
833
    TInfoSink& infoSink;
834
835
private:
836
    TSlotCollector& operator=(TSlotCollector&) = delete;
837
};
838
839
TDefaultIoResolverBase::TDefaultIoResolverBase(const TIntermediate& intermediate)
840
204
    : referenceIntermediate(intermediate)
841
204
    , nextUniformLocation(intermediate.getUniformLocationBase())
842
204
    , nextInputLocation(0)
843
204
    , nextOutputLocation(0)
844
204
{
845
204
    memset(stageMask, false, sizeof(bool) * (EShLangCount + 1));
846
204
    memset(stageIntermediates, 0, sizeof(TIntermediate*) * (EShLangCount));
847
204
    stageIntermediates[intermediate.getStage()] = &intermediate;
848
204
}
849
850
386
int TDefaultIoResolverBase::getBaseBinding(EShLanguage stage, TResourceType res, unsigned int set) const {
851
386
    return stageIntermediates[stage] ? selectBaseBinding(stageIntermediates[stage]->getShiftBinding(res), stageIntermediates[stage]->getShiftBindingForSet(res, set))
852
386
                                     : selectBaseBinding(referenceIntermediate.getShiftBinding(res), referenceIntermediate.getShiftBindingForSet(res, set));
853
386
}
854
855
286
const std::vector<std::string>& TDefaultIoResolverBase::getResourceSetBinding(EShLanguage stage) const {
856
286
    return stageIntermediates[stage] ? stageIntermediates[stage]->getResourceSetBinding()
857
286
                                     : referenceIntermediate.getResourceSetBinding();
858
286
}
859
860
74
bool TDefaultIoResolverBase::doAutoBindingMapping() const { return referenceIntermediate.getAutoMapBindings(); }
861
862
504
bool TDefaultIoResolverBase::doAutoLocationMapping() const { return referenceIntermediate.getAutoMapLocations(); }
863
864
460
TDefaultIoResolverBase::TSlotSet::iterator TDefaultIoResolverBase::findSlot(int resource, int set, int slot) {
865
460
    return std::lower_bound(slots[resource][set].begin(), slots[resource][set].end(), slot);
866
460
}
867
868
0
bool TDefaultIoResolverBase::checkEmpty(int resource, int set, int slot) {
869
0
    TSlotSet::iterator at = findSlot(resource, set, slot);
870
0
    return ! (at != slots[resource][set].end() && *at == slot);
871
0
}
872
873
386
int TDefaultIoResolverBase::reserveSlot(int resource, int set, int slot, int size) {
874
386
    TSlotSet::iterator at = findSlot(resource, set, slot);
875
    // tolerate aliasing, by not double-recording aliases
876
    // (policy about appropriateness of the alias is higher up)
877
772
    for (int i = 0; i < size; i++) {
878
386
        if (at == slots[resource][set].end() || *at != slot + i)
879
376
            at = slots[resource][set].insert(at, slot + i);
880
386
        ++at;
881
386
    }
882
386
    return slot;
883
386
}
884
885
74
int TDefaultIoResolverBase::getFreeSlot(int resource, int set, int base, int size) {
886
74
    TSlotSet::iterator at = findSlot(resource, set, base);
887
74
    if (at == slots[resource][set].end())
888
16
        return reserveSlot(resource, set, base, size);
889
    // look for a big enough gap
890
256
    for (; at != slots[resource][set].end(); ++at) {
891
198
        if (*at - base >= size)
892
0
            break;
893
198
        base = *at + 1;
894
198
    }
895
58
    return reserveSlot(resource, set, base, size);
896
74
}
897
898
398
int TDefaultIoResolverBase::resolveSet(EShLanguage stage, TVarEntryInfo& ent) {
899
398
    const TType& type = ent.symbol->getType();
900
398
    if (type.getQualifier().hasSet()) {
901
112
        return ent.newSet = type.getQualifier().layoutSet;
902
112
    }
903
    // If a command line or API option requested a single descriptor set, use that (if not overrided by spaceN)
904
286
    if (getResourceSetBinding(stage).size() == 1) {
905
0
        return ent.newSet = atoi(getResourceSetBinding(stage)[0].c_str());
906
0
    }
907
286
    return ent.newSet = 0;
908
286
}
909
910
398
int TDefaultIoResolverBase::resolveUniformLocation(EShLanguage /*stage*/, TVarEntryInfo& ent) {
911
398
    const TType& type = ent.symbol->getType();
912
398
    const char* name =  ent.symbol->getAccessName().c_str();
913
    // kick out of not doing this
914
398
    if (! doAutoLocationMapping()) {
915
0
        return ent.newLocation = -1;
916
0
    }
917
    // no locations added if already present, a built-in variable, a block, or an opaque
918
398
    if (type.getQualifier().hasLocation() || type.isBuiltIn() || type.getBasicType() == EbtBlock ||
919
398
        type.isAtomic() || type.isSpirvType() || (type.containsOpaque() && referenceIntermediate.getSpv().openGl == 0)) {
920
398
        return ent.newLocation = -1;
921
398
    }
922
    // no locations on blocks of built-in variables
923
0
    if (type.isStruct()) {
924
0
        if (type.getStruct()->size() < 1) {
925
0
            return ent.newLocation = -1;
926
0
        }
927
0
        if ((*type.getStruct())[0].type->isBuiltIn()) {
928
0
            return ent.newLocation = -1;
929
0
        }
930
0
    }
931
0
    int location = referenceIntermediate.getUniformLocationOverride(name);
932
0
    if (location != -1) {
933
0
        return ent.newLocation = location;
934
0
    }
935
0
    location = nextUniformLocation;
936
0
    nextUniformLocation += TIntermediate::computeTypeUniformLocationSize(type);
937
0
    return ent.newLocation = location;
938
0
}
939
940
106
int TDefaultIoResolverBase::resolveInOutLocation(EShLanguage stage, TVarEntryInfo& ent) {
941
106
    const TType& type = ent.symbol->getType();
942
    // kick out of not doing this
943
106
    if (! doAutoLocationMapping()) {
944
0
        return ent.newLocation = -1;
945
0
    }
946
947
    // no locations added if already present, a built-in variable, or a variable with SPIR-V decorate
948
106
    if (type.getQualifier().hasLocation() || type.isBuiltIn() || type.getQualifier().hasSpirvDecorate()) {
949
98
        return ent.newLocation = -1;
950
98
    }
951
952
    // no locations on blocks of built-in variables
953
8
    if (type.isStruct()) {
954
0
        if (type.getStruct()->size() < 1) {
955
0
            return ent.newLocation = -1;
956
0
        }
957
0
        if ((*type.getStruct())[0].type->isBuiltIn()) {
958
0
            return ent.newLocation = -1;
959
0
        }
960
0
    }
961
    // point to the right input or output location counter
962
8
    int& nextLocation = type.getQualifier().isPipeInput() ? nextInputLocation : nextOutputLocation;
963
    // Placeholder. This does not do proper cross-stage lining up, nor
964
    // work with mixed location/no-location declarations.
965
8
    int location = nextLocation;
966
8
    int typeLocationSize;
967
    // Don’t take into account the outer-most array if the stage’s
968
    // interface is automatically an array.
969
8
    typeLocationSize = computeTypeLocationSize(type, stage);
970
8
    nextLocation += typeLocationSize;
971
8
    return ent.newLocation = location;
972
8
}
973
974
106
int TDefaultIoResolverBase::resolveInOutComponent(EShLanguage /*stage*/, TVarEntryInfo& ent) {
975
106
    return ent.newComponent = -1;
976
106
}
977
978
106
int TDefaultIoResolverBase::resolveInOutIndex(EShLanguage /*stage*/, TVarEntryInfo& ent) { return ent.newIndex = -1; }
979
980
8
uint32_t TDefaultIoResolverBase::computeTypeLocationSize(const TType& type, EShLanguage stage) {
981
8
    int typeLocationSize;
982
    // Don’t take into account the outer-most array if the stage’s
983
    // interface is automatically an array.
984
8
    if (type.getQualifier().isArrayedIo(stage)) {
985
0
        TType elementType(type, 0);
986
0
        typeLocationSize = TIntermediate::computeTypeLocationSize(elementType, stage);
987
8
    } else {
988
8
        typeLocationSize = TIntermediate::computeTypeLocationSize(type, stage);
989
8
    }
990
8
    return typeLocationSize;
991
8
}
992
993
//TDefaultGlslIoResolver
994
0
TResourceType TDefaultGlslIoResolver::getResourceType(const glslang::TType& type) {
995
0
    assert(isValidGlslType(type));
996
0
    if (isImageType(type)) {
997
0
        return EResImage;
998
0
    }
999
0
    if (isTextureType(type)) {
1000
0
        return EResTexture;
1001
0
    }
1002
0
    if (isSsboType(type)) {
1003
0
        return EResSsbo;
1004
0
    }
1005
0
    if (isSamplerType(type)) {
1006
0
        return EResSampler;
1007
0
    }
1008
0
    if (isUboType(type)) {
1009
0
        return EResUbo;
1010
0
    }
1011
0
    if (isCombinedSamplerType(type)) {
1012
0
        return EResCombinedSampler;
1013
0
    }
1014
0
    if (isAsType(type)) {
1015
0
        return EResAs;
1016
0
    }
1017
0
    if (isTensorType(type)) {
1018
0
        return EResTensor;
1019
0
    }
1020
0
    return EResCount;
1021
0
}
1022
1023
TDefaultGlslIoResolver::TDefaultGlslIoResolver(const TIntermediate& intermediate)
1024
0
    : TDefaultIoResolverBase(intermediate)
1025
0
    , preStage(EShLangCount)
1026
0
    , currentStage(EShLangCount)
1027
0
{ }
1028
1029
0
int TDefaultGlslIoResolver::resolveInOutLocation(EShLanguage stage, TVarEntryInfo& ent) {
1030
0
    const TType& type = ent.symbol->getType();
1031
0
    const TString& name = ent.symbol->getAccessName();
1032
0
    if (currentStage != stage) {
1033
0
        preStage = currentStage;
1034
0
        currentStage = stage;
1035
0
    }
1036
    // kick out if not doing this
1037
0
    if (! doAutoLocationMapping()) {
1038
0
        return ent.newLocation = -1;
1039
0
    }
1040
    // expand the location to each element if the symbol is a struct or array
1041
0
    if (type.getQualifier().hasLocation()) {
1042
0
        return ent.newLocation = type.getQualifier().layoutLocation;
1043
0
    }
1044
    // no locations added if already present, a built-in variable, or a variable with SPIR-V decorate
1045
0
    if (type.isBuiltIn() || type.getQualifier().hasSpirvDecorate()) {
1046
0
        return ent.newLocation = -1;
1047
0
    }
1048
    // no locations on blocks of built-in variables
1049
0
    if (type.isStruct()) {
1050
0
        if (type.getStruct()->size() < 1) {
1051
0
            return ent.newLocation = -1;
1052
0
        }
1053
0
        if ((*type.getStruct())[0].type->isBuiltIn()) {
1054
0
            return ent.newLocation = -1;
1055
0
        }
1056
0
    }
1057
0
    int typeLocationSize = computeTypeLocationSize(type, stage);
1058
0
    int location = type.getQualifier().layoutLocation;
1059
0
    bool hasLocation = false;
1060
0
    EShLanguage keyStage(EShLangCount);
1061
0
    TStorageQualifier storage;
1062
0
    storage = EvqInOut;
1063
0
    if (type.getQualifier().isPipeInput()) {
1064
        // If this symbol is a input, search pre stage's out
1065
0
        keyStage = preStage;
1066
0
    }
1067
0
    if (type.getQualifier().isPipeOutput()) {
1068
        // If this symbol is a output, search next stage's in
1069
0
        keyStage = currentStage;
1070
0
    }
1071
    // The in/out in current stage is not declared with location, but it is possible declared
1072
    // with explicit location in other stages, find the storageSlotMap firstly to check whether
1073
    // the in/out has location
1074
0
    int resourceKey = buildStorageKey(keyStage, storage);
1075
0
    if (! storageSlotMap[resourceKey].empty()) {
1076
0
        TVarSlotMap::iterator iter = storageSlotMap[resourceKey].find(name);
1077
0
        if (iter != storageSlotMap[resourceKey].end()) {
1078
            // If interface resource be found, set it has location and this symbol's new location
1079
            // equal the symbol's explicit location declaration in pre or next stage.
1080
            //
1081
            // vs:    out vec4 a;
1082
            // fs:    layout(..., location = 3,...) in vec4 a;
1083
0
            hasLocation = true;
1084
0
            location = iter->second;
1085
            // if we want deal like that:
1086
            // vs:    layout(location=4) out vec4 a;
1087
            //        out vec4 b;
1088
            //
1089
            // fs:    in vec4 a;
1090
            //        layout(location = 4) in vec4 b;
1091
            // we need retraverse the map.
1092
0
        }
1093
0
        if (! hasLocation) {
1094
            // If interface resource note found, It's mean the location in two stage are both implicit declarat.
1095
            // So we should find a new slot for this interface.
1096
            //
1097
            // vs: out vec4 a;
1098
            // fs: in vec4 a;
1099
0
            location = getFreeSlot(0, resourceKey, 0, typeLocationSize);
1100
0
            storageSlotMap[resourceKey][name] = location;
1101
0
        }
1102
0
    } else {
1103
        // the first interface declarated in a program.
1104
0
        TVarSlotMap varSlotMap;
1105
0
        location = getFreeSlot(0, resourceKey, 0, typeLocationSize);
1106
0
        varSlotMap[name] = location;
1107
0
        storageSlotMap[resourceKey] = varSlotMap;
1108
0
    }
1109
    //Update location
1110
0
    return ent.newLocation = location;
1111
0
}
1112
1113
0
int TDefaultGlslIoResolver::resolveUniformLocation(EShLanguage /*stage*/, TVarEntryInfo& ent) {
1114
0
    const TType& type = ent.symbol->getType();
1115
0
    const TString& name = ent.symbol->getAccessName();
1116
    // kick out of not doing this
1117
0
    if (! doAutoLocationMapping()) {
1118
0
        return ent.newLocation = -1;
1119
0
    }
1120
    // expand the location to each element if the symbol is a struct or array
1121
0
    if (type.getQualifier().hasLocation() && (type.isStruct() || type.isArray())) {
1122
0
        return ent.newLocation = type.getQualifier().layoutLocation;
1123
0
    } else {
1124
        // no locations added if already present, a built-in variable, a block, or an opaque
1125
0
        if (type.getQualifier().hasLocation() || type.isBuiltIn() || type.getBasicType() == EbtBlock ||
1126
0
            type.isAtomic() || type.isSpirvType() ||
1127
0
            (type.containsOpaque() && referenceIntermediate.getSpv().openGl == 0)) {
1128
0
            return ent.newLocation = -1;
1129
0
        }
1130
        // no locations on blocks of built-in variables
1131
0
        if (type.isStruct()) {
1132
0
            if (type.getStruct()->size() < 1) {
1133
0
                return ent.newLocation = -1;
1134
0
            }
1135
0
            if ((*type.getStruct())[0].type->isBuiltIn()) {
1136
0
                return ent.newLocation = -1;
1137
0
            }
1138
0
        }
1139
0
    }
1140
0
    int location = referenceIntermediate.getUniformLocationOverride(name.c_str());
1141
0
    if (location != -1) {
1142
0
        return ent.newLocation = location;
1143
0
    }
1144
1145
0
    int size = TIntermediate::computeTypeUniformLocationSize(type);
1146
1147
    // The uniform in current stage is not declared with location, but it is possible declared
1148
    // with explicit location in other stages, find the storageSlotMap firstly to check whether
1149
    // the uniform has location
1150
0
    bool hasLocation = false;
1151
0
    int resourceKey = buildStorageKey(EShLangCount, EvqUniform);
1152
0
    TVarSlotMap& slotMap = storageSlotMap[resourceKey];
1153
    // Check dose shader program has uniform resource
1154
0
    if (! slotMap.empty()) {
1155
        // If uniform resource not empty, try find a same name uniform
1156
0
        TVarSlotMap::iterator iter = slotMap.find(name);
1157
0
        if (iter != slotMap.end()) {
1158
            // If uniform resource be found, set it has location and this symbol's new location
1159
            // equal the uniform's explicit location declaration in other stage.
1160
            //
1161
            // vs:    uniform vec4 a;
1162
            // fs:    layout(..., location = 3,...) uniform vec4 a;
1163
0
            hasLocation = true;
1164
0
            location = iter->second;
1165
0
        }
1166
0
        if (! hasLocation) {
1167
            // No explicit location declaration in other stage.
1168
            // So we should find a new slot for this uniform.
1169
            //
1170
            // vs:    uniform vec4 a;
1171
            // fs:    uniform vec4 a;
1172
0
            location = getFreeSlot(0, resourceKey, 0, computeTypeLocationSize(type, currentStage));
1173
0
            storageSlotMap[resourceKey][name] = location;
1174
0
        }
1175
0
    } else {
1176
        // the first uniform declaration in a program.
1177
0
        TVarSlotMap varSlotMap;
1178
0
        location = getFreeSlot(0, resourceKey, 0, size);
1179
0
        varSlotMap[name] = location;
1180
0
        storageSlotMap[resourceKey] = varSlotMap;
1181
0
    }
1182
0
    return ent.newLocation = location;
1183
0
}
1184
1185
0
int TDefaultGlslIoResolver::resolveBinding(EShLanguage stage, TVarEntryInfo& ent) {
1186
0
    const TType& type = ent.symbol->getType();
1187
0
    const TString& name = ent.symbol->getAccessName();
1188
    // On OpenGL arrays of opaque types take a separate binding for each element
1189
0
    int numBindings = referenceIntermediate.getSpv().openGl != 0 && type.isSizedArray() ? type.getCumulativeArraySize() : 1;
1190
0
    TResourceType resource = getResourceType(type);
1191
    // don't need to handle uniform symbol, it will be handled in resolveUniformLocation
1192
0
    if (resource == EResUbo && type.getBasicType() != EbtBlock) {
1193
0
        return ent.newBinding = -1;
1194
0
    }
1195
    // There is no 'set' qualifier in OpenGL shading language, each resource has its own
1196
    // binding name space, so remap the 'set' to resource type which make each resource
1197
    // binding is valid from 0 to MAX_XXRESOURCE_BINDINGS
1198
0
    int set = referenceIntermediate.getSpv().openGl != 0 ? 0 : ent.newSet;
1199
0
    int resourceKey = referenceIntermediate.getSpv().openGl != 0 || referenceIntermediate.getBindingsPerResourceType() ? resource : 0;
1200
0
    if (resource < EResCount) {
1201
0
        if (type.getQualifier().hasBinding()) {
1202
0
            int newBinding = reserveSlot(resourceKey, set, getBaseBinding(stage, resource, set) + type.getQualifier().layoutBinding, numBindings);
1203
0
            return ent.newBinding = newBinding;
1204
0
        } else {
1205
            // The resource in current stage is not declared with binding, but it is possible declared
1206
            // with explicit binding in other stages, find the resourceSlotMap firstly to check whether
1207
            // the resource has binding, don't need to allocate if it already has a binding
1208
0
            bool hasBinding = false;
1209
0
            ent.newBinding = -1; // leave as -1 if it isn't set below
1210
1211
0
            if (! resourceSlotMap[resourceKey][set].empty()) {
1212
0
                TVarSlotMap::iterator iter = resourceSlotMap[resourceKey][set].find(name);
1213
0
                if (iter != resourceSlotMap[resourceKey][set].end()) {
1214
0
                    hasBinding = true;
1215
0
                    ent.newBinding = iter->second;
1216
0
                }
1217
0
            }
1218
0
            if (!hasBinding && (ent.live && doAutoBindingMapping())) {
1219
                // find free slot, the caller did make sure it passes all vars with binding
1220
                // first and now all are passed that do not have a binding and needs one
1221
0
                int binding = getFreeSlot(resourceKey, set, getBaseBinding(stage, resource, set), numBindings);
1222
0
                resourceSlotMap[resourceKey][set][name] = binding;
1223
0
                ent.newBinding = binding;
1224
0
            }
1225
0
            return ent.newBinding;
1226
0
        }
1227
0
    }
1228
0
    return ent.newBinding = -1;
1229
0
}
1230
1231
0
void TDefaultGlslIoResolver::beginResolve(EShLanguage stage) {
1232
    // reset stage state
1233
0
    if (stage == EShLangCount)
1234
0
        preStage = currentStage = stage;
1235
    // update stage state
1236
0
    else if (currentStage != stage) {
1237
0
        preStage = currentStage;
1238
0
        currentStage = stage;
1239
0
    }
1240
0
}
1241
1242
0
void TDefaultGlslIoResolver::endResolve(EShLanguage /*stage*/) {
1243
    // TODO nothing
1244
0
}
1245
1246
0
void TDefaultGlslIoResolver::beginCollect(EShLanguage stage) {
1247
    // reset stage state
1248
0
    if (stage == EShLangCount)
1249
0
        preStage = currentStage = stage;
1250
    // update stage state
1251
0
    else if (currentStage != stage) {
1252
0
        preStage = currentStage;
1253
0
        currentStage = stage;
1254
0
    }
1255
0
}
1256
1257
0
void TDefaultGlslIoResolver::endCollect(EShLanguage /*stage*/) {
1258
    // TODO nothing
1259
0
}
1260
1261
0
void TDefaultGlslIoResolver::reserverStorageSlot(TVarEntryInfo& ent, TInfoSink& infoSink) {
1262
0
    const TType& type = ent.symbol->getType();
1263
0
    const TString& name = ent.symbol->getAccessName();
1264
0
    TStorageQualifier storage = type.getQualifier().storage;
1265
0
    EShLanguage stage(EShLangCount);
1266
0
    switch (storage) {
1267
0
    case EvqUniform:
1268
0
        if (type.getBasicType() != EbtBlock && type.getQualifier().hasLocation()) {
1269
            //
1270
            // Reserve the slots for the uniforms who has explicit location
1271
0
            int storageKey = buildStorageKey(EShLangCount, EvqUniform);
1272
0
            int location = type.getQualifier().layoutLocation;
1273
0
            TVarSlotMap& varSlotMap = storageSlotMap[storageKey];
1274
0
            TVarSlotMap::iterator iter = varSlotMap.find(name);
1275
0
            if (iter == varSlotMap.end()) {
1276
0
                int numLocations = TIntermediate::computeTypeUniformLocationSize(type);
1277
0
                reserveSlot(0, storageKey, location, numLocations);
1278
0
                varSlotMap[name] = location;
1279
0
            } else {
1280
                // Allocate location by name for OpenGL driver, so the uniform in different
1281
                // stages should be declared with the same location
1282
0
                if (iter->second != location) {
1283
0
                    TString errorMsg = "Invalid location: " + name;
1284
0
                    infoSink.info.message(EPrefixInternalError, errorMsg.c_str());
1285
0
                    hasError = true;
1286
0
                }
1287
0
            }
1288
0
        }
1289
0
        break;
1290
0
    case EvqVaryingIn:
1291
0
    case EvqVaryingOut:
1292
        //
1293
        // Reserve the slots for the inout who has explicit location
1294
0
        if (type.getQualifier().hasLocation()) {
1295
0
            stage = storage == EvqVaryingIn ? preStage : stage;
1296
0
            stage = storage == EvqVaryingOut ? currentStage : stage;
1297
0
            int storageKey = buildStorageKey(stage, EvqInOut);
1298
0
            int location = type.getQualifier().layoutLocation;
1299
0
            TVarSlotMap& varSlotMap = storageSlotMap[storageKey];
1300
0
            TVarSlotMap::iterator iter = varSlotMap.find(name);
1301
0
            if (iter == varSlotMap.end()) {
1302
0
                int numLocations = TIntermediate::computeTypeUniformLocationSize(type);
1303
0
                reserveSlot(0, storageKey, location, numLocations);
1304
0
                varSlotMap[name] = location;
1305
0
            } else {
1306
                // Allocate location by name for OpenGL driver, so the uniform in different
1307
                // stages should be declared with the same location
1308
0
                if (iter->second != location) {
1309
0
                    TString errorMsg = "Invalid location: " + name;
1310
0
                    infoSink.info.message(EPrefixInternalError, errorMsg.c_str());
1311
0
                    hasError = true;
1312
0
                }
1313
0
            }
1314
0
        }
1315
0
        break;
1316
0
    default:
1317
0
        break;
1318
0
    }
1319
0
}
1320
1321
0
void TDefaultGlslIoResolver::reserverResourceSlot(TVarEntryInfo& ent, TInfoSink& infoSink) {
1322
0
    const TType& type = ent.symbol->getType();
1323
0
    const TString& name = ent.symbol->getAccessName();
1324
0
    TResourceType resource = getResourceType(type);
1325
    // getResourceType() returns EResCount for types that are not a binding-based
1326
    // resource (e.g. atomic_uint). Those don't own a resourceSlotMap/slots row, so
1327
    // indexing by EResCount would run off the end of those arrays. resolveBinding()
1328
    // guards the same way.
1329
0
    if (resource >= EResCount)
1330
0
        return;
1331
0
    int set = referenceIntermediate.getSpv().openGl != 0 ? 0 : resolveSet(ent.stage, ent);
1332
0
    int resourceKey = referenceIntermediate.getSpv().openGl != 0 || referenceIntermediate.getBindingsPerResourceType() ? resource : 0;
1333
1334
0
    if (type.getQualifier().hasBinding()) {
1335
0
        TVarSlotMap& varSlotMap = resourceSlotMap[resourceKey][set];
1336
0
        TVarSlotMap::iterator iter = varSlotMap.find(name);
1337
0
        int binding = type.getQualifier().layoutBinding + getBaseBinding(ent.stage, resource, set);
1338
0
        if (iter == varSlotMap.end()) {
1339
            // Reserve the slots for the ubo, ssbo and opaques who has explicit binding
1340
0
            int numBindings = referenceIntermediate.getSpv().openGl != 0 && type.isSizedArray() ? type.getCumulativeArraySize() : 1;
1341
0
            varSlotMap[name] = binding;
1342
0
            reserveSlot(resourceKey, set, binding, numBindings);
1343
0
        } else {
1344
            // Allocate binding by name for OpenGL driver, so the resource in different
1345
            // stages should be declared with the same binding
1346
0
            if (iter->second != binding) {
1347
0
                TString errorMsg = "Invalid binding: " + name;
1348
0
                infoSink.info.message(EPrefixInternalError, errorMsg.c_str());
1349
0
                hasError = true;
1350
0
            }
1351
0
        }
1352
0
    }
1353
0
}
1354
1355
//TDefaultGlslIoResolver end
1356
1357
/*
1358
 * Basic implementation of glslang::TIoMapResolver that replaces the
1359
 * previous offset behavior.
1360
 * It does the same, uses the offsets for the corresponding uniform
1361
 * types. Also respects the EOptionAutoMapBindings flag and binds
1362
 * them if needed.
1363
 */
1364
/*
1365
 * Default resolver
1366
 */
1367
struct TDefaultIoResolver : public TDefaultIoResolverBase {
1368
102
    TDefaultIoResolver(const TIntermediate& intermediate) : TDefaultIoResolverBase(intermediate) { }
1369
1370
398
    bool validateBinding(EShLanguage /*stage*/, TVarEntryInfo& /*ent*/) override { return true; }
1371
1372
398
    TResourceType getResourceType(const glslang::TType& type) override {
1373
398
        assert(isValidGlslType(type));
1374
398
        if (isImageType(type)) {
1375
104
            return EResImage;
1376
104
        }
1377
294
        if (isTextureType(type)) {
1378
84
            return EResTexture;
1379
84
        }
1380
210
        if (isSsboType(type)) {
1381
56
            return EResSsbo;
1382
56
        }
1383
154
        if (isSamplerType(type)) {
1384
48
            return EResSampler;
1385
48
        }
1386
106
        if (isUboType(type)) {
1387
60
            return EResUbo;
1388
60
        }
1389
46
        if (isCombinedSamplerType(type)) {
1390
44
            return EResCombinedSampler;
1391
44
        }
1392
2
        if (isAsType(type)) {
1393
2
            return EResAs;
1394
2
        }
1395
0
        if (isTensorType(type)) {
1396
0
            return EResTensor;
1397
0
        }
1398
0
        return EResCount;
1399
0
    }
1400
1401
398
    int resolveBinding(EShLanguage stage, TVarEntryInfo& ent) override {
1402
398
        const TType& type = ent.symbol->getType();
1403
398
        const int set = getLayoutSet(type);
1404
        // On OpenGL arrays of opaque types take a seperate binding for each element
1405
398
        int numBindings = referenceIntermediate.getSpv().openGl != 0 && type.isSizedArray() ? type.getCumulativeArraySize() : 1;
1406
398
        TResourceType resource = getResourceType(type);
1407
398
        int resourceKey = referenceIntermediate.getBindingsPerResourceType() ? resource : 0;
1408
398
        if (resource < EResCount) {
1409
398
            if (type.getQualifier().hasBinding()) {
1410
312
                return ent.newBinding = reserveSlot(
1411
312
                           resourceKey, set, getBaseBinding(stage, resource, set) + type.getQualifier().layoutBinding, numBindings);
1412
312
            } else if (ent.live && doAutoBindingMapping()) {
1413
                // find free slot, the caller did make sure it passes all vars with binding
1414
                // first and now all are passed that do not have a binding and needs one
1415
74
                return ent.newBinding = getFreeSlot(resourceKey, set, getBaseBinding(stage, resource, set), numBindings);
1416
74
            }
1417
398
        }
1418
12
        return ent.newBinding = -1;
1419
398
    }
1420
};
1421
1422
#ifdef ENABLE_HLSL
1423
/********************************************************************************
1424
The following IO resolver maps types in HLSL register space, as follows:
1425
1426
t - for shader resource views (SRV)
1427
   TEXTURE1D
1428
   TEXTURE1DARRAY
1429
   TEXTURE2D
1430
   TEXTURE2DARRAY
1431
   TEXTURE3D
1432
   TEXTURECUBE
1433
   TEXTURECUBEARRAY
1434
   TEXTURE2DMS
1435
   TEXTURE2DMSARRAY
1436
   STRUCTUREDBUFFER
1437
   BYTEADDRESSBUFFER
1438
   BUFFER
1439
   TBUFFER
1440
1441
s - for samplers
1442
   SAMPLER
1443
   SAMPLER1D
1444
   SAMPLER2D
1445
   SAMPLER3D
1446
   SAMPLERCUBE
1447
   SAMPLERSTATE
1448
   SAMPLERCOMPARISONSTATE
1449
1450
u - for unordered access views (UAV)
1451
   RWBYTEADDRESSBUFFER
1452
   RWSTRUCTUREDBUFFER
1453
   APPENDSTRUCTUREDBUFFER
1454
   CONSUMESTRUCTUREDBUFFER
1455
   RWBUFFER
1456
   RWTEXTURE1D
1457
   RWTEXTURE1DARRAY
1458
   RWTEXTURE2D
1459
   RWTEXTURE2DARRAY
1460
   RWTEXTURE3D
1461
1462
b - for constant buffer views (CBV)
1463
   CBUFFER
1464
   CONSTANTBUFFER
1465
 ********************************************************************************/
1466
struct TDefaultHlslIoResolver : public TDefaultIoResolverBase {
1467
102
    TDefaultHlslIoResolver(const TIntermediate& intermediate) : TDefaultIoResolverBase(intermediate) { }
1468
1469
0
    bool validateBinding(EShLanguage /*stage*/, TVarEntryInfo& /*ent*/) override { return true; }
1470
1471
0
    TResourceType getResourceType(const glslang::TType& type) override {
1472
0
        if (isUavType(type)) {
1473
0
            return EResUav;
1474
0
        }
1475
0
        if (isSrvType(type)) {
1476
0
            return EResTexture;
1477
0
        }
1478
0
        if (isSamplerType(type)) {
1479
0
            return EResSampler;
1480
0
        }
1481
0
        if (isUboType(type)) {
1482
0
            return EResUbo;
1483
0
        }
1484
        // no support for combined samplers in HLSL
1485
0
        if (isAsType(type)) {
1486
0
            return EResAs;
1487
0
        }
1488
        // no support for tensors in HLSL
1489
0
        return EResCount;
1490
0
    }
1491
1492
0
    int resolveBinding(EShLanguage stage, TVarEntryInfo& ent) override {
1493
0
        const TType& type = ent.symbol->getType();
1494
0
        const int set = getLayoutSet(type);
1495
0
        TResourceType resource = getResourceType(type);
1496
0
        int resourceKey = referenceIntermediate.getBindingsPerResourceType() ? resource : 0;
1497
0
        if (resource < EResCount) {
1498
0
            if (type.getQualifier().hasBinding()) {
1499
0
                return ent.newBinding = reserveSlot(resourceKey, set, getBaseBinding(stage, resource, set) + type.getQualifier().layoutBinding);
1500
0
            } else if (ent.live && doAutoBindingMapping()) {
1501
                // find free slot, the caller did make sure it passes all vars with binding
1502
                // first and now all are passed that do not have a binding and needs one
1503
0
                return ent.newBinding = getFreeSlot(resourceKey, set, getBaseBinding(stage, resource, set));
1504
0
            }
1505
0
        }
1506
0
        return ent.newBinding = -1;
1507
0
    }
1508
};
1509
#endif
1510
1511
// Map I/O variables to provided offsets, and make bindings for
1512
// unbound but live variables.
1513
//
1514
// Returns false if the input is too malformed to do this.
1515
926
bool TIoMapper::addStage(EShLanguage stage, TIntermediate& intermediate, TInfoSink& infoSink, TIoMapResolver* resolver) {
1516
926
    bool somethingToDo = ! intermediate.getResourceSetBinding().empty() || intermediate.getAutoMapBindings() ||
1517
824
                         intermediate.getAutoMapLocations();
1518
    // Restrict the stricter condition to further check 'somethingToDo' only if 'somethingToDo' has not been set, reduce
1519
    // unnecessary or insignificant for-loop operation after 'somethingToDo' have been true.
1520
8.34k
    for (int res = 0; (res < EResCount && !somethingToDo); ++res) {
1521
7.41k
        somethingToDo = somethingToDo || (intermediate.getShiftBinding(TResourceType(res)) != 0) ||
1522
7.41k
                        intermediate.hasShiftBindingForSet(TResourceType(res));
1523
7.41k
    }
1524
926
    if (! somethingToDo && resolver == nullptr)
1525
824
        return true;
1526
102
    if (intermediate.getNumEntryPoints() != 1 || intermediate.isRecursive())
1527
0
        return false;
1528
102
    TIntermNode* root = intermediate.getTreeRoot();
1529
102
    if (root == nullptr)
1530
0
        return false;
1531
    // if no resolver is provided, use the default resolver with the given shifts and auto map settings
1532
102
    TDefaultIoResolver defaultResolver(intermediate);
1533
102
#ifdef ENABLE_HLSL
1534
102
    TDefaultHlslIoResolver defaultHlslResolver(intermediate);
1535
102
    if (resolver == nullptr) {
1536
        // TODO: use a passed in IO mapper for this
1537
102
        if (intermediate.usingHlslIoMapping())
1538
0
            resolver = &defaultHlslResolver;
1539
102
        else
1540
102
            resolver = &defaultResolver;
1541
102
    }
1542
#else
1543
    resolver = &defaultResolver;
1544
#endif
1545
102
    resolver->addStage(stage, intermediate);
1546
1547
102
    TVarLiveMap inVarMap, outVarMap, uniformVarMap;
1548
102
    TVarLiveVector inVector, outVector, uniformVector;
1549
102
    TVarGatherTraverser iter_binding_all(intermediate, true, inVarMap, outVarMap, uniformVarMap);
1550
102
    TVarGatherTraverser iter_binding_live(intermediate, false, inVarMap, outVarMap, uniformVarMap);
1551
102
    root->traverse(&iter_binding_all);
1552
102
    iter_binding_live.pushFunction(intermediate.getEntryPointMangledName().c_str());
1553
260
    while (! iter_binding_live.destinations.empty()) {
1554
158
        TIntermNode* destination = iter_binding_live.destinations.back();
1555
158
        iter_binding_live.destinations.pop_back();
1556
158
        destination->traverse(&iter_binding_live);
1557
158
    }
1558
1559
    // sort entries by priority. see TVarEntryInfo::TOrderByPriority for info.
1560
102
    for (auto& var : inVarMap) { inVector.push_back(var); }
1561
102
    std::sort(inVector.begin(), inVector.end(), [](const TVarLivePair& p1, const TVarLivePair& p2) -> bool {
1562
64
        return TVarEntryInfo::TOrderByPriority()(p1.second, p2.second);
1563
64
    });
1564
102
    for (auto& var : outVarMap) { outVector.push_back(var); }
1565
102
    std::sort(outVector.begin(), outVector.end(), [](const TVarLivePair& p1, const TVarLivePair& p2) -> bool {
1566
4
        return TVarEntryInfo::TOrderByPriority()(p1.second, p2.second);
1567
4
    });
1568
398
    for (auto& var : uniformVarMap) { uniformVector.push_back(var); }
1569
796
    std::sort(uniformVector.begin(), uniformVector.end(), [](const TVarLivePair& p1, const TVarLivePair& p2) -> bool {
1570
796
        return TVarEntryInfo::TOrderByPriority()(p1.second, p2.second);
1571
796
    });
1572
102
    bool hadError = false;
1573
102
    TVarLiveMap* dummyUniformVarMap[EShLangCount] = {};
1574
102
    TNotifyInOutAdaptor inOutNotify(stage, *resolver);
1575
102
    TNotifyUniformAdaptor uniformNotify(stage, *resolver);
1576
102
    TResolverUniformAdaptor uniformResolve(stage, *resolver, dummyUniformVarMap, infoSink, hadError,
1577
102
                                           intermediate.getRelaxSetBindingLimits());
1578
102
    TResolverInOutAdaptor inOutResolve(stage, *resolver, infoSink, hadError);
1579
102
    resolver->beginNotifications(stage);
1580
102
    std::for_each(inVector.begin(), inVector.end(), inOutNotify);
1581
102
    std::for_each(outVector.begin(), outVector.end(), inOutNotify);
1582
102
    std::for_each(uniformVector.begin(), uniformVector.end(), uniformNotify);
1583
102
    resolver->endNotifications(stage);
1584
102
    resolver->beginResolve(stage);
1585
102
    for (auto& var : inVector) { inOutResolve(var); }
1586
102
    std::for_each(inVector.begin(), inVector.end(), [&inVarMap](TVarLivePair p) {
1587
60
        auto at = inVarMap.find(p.second.symbol->getAccessName());
1588
60
        if (at != inVarMap.end() && p.second.id == at->second.id)
1589
60
            at->second = p.second;
1590
60
    });
1591
102
    for (auto& var : outVector) { inOutResolve(var); }
1592
102
    std::for_each(outVector.begin(), outVector.end(), [&outVarMap](TVarLivePair p) {
1593
46
        auto at = outVarMap.find(p.second.symbol->getAccessName());
1594
46
        if (at != outVarMap.end() && p.second.id == at->second.id)
1595
46
            at->second = p.second;
1596
46
    });
1597
102
    std::for_each(uniformVector.begin(), uniformVector.end(), uniformResolve);
1598
398
    std::for_each(uniformVector.begin(), uniformVector.end(), [&uniformVarMap](TVarLivePair p) {
1599
398
        auto at = uniformVarMap.find(p.second.symbol->getAccessName());
1600
398
        if (at != uniformVarMap.end() && p.second.id == at->second.id)
1601
398
            at->second = p.second;
1602
398
    });
1603
102
    resolver->endResolve(stage);
1604
102
    if (!hadError) {
1605
102
        TVarSetTraverser iter_iomap(intermediate, inVarMap, outVarMap, uniformVarMap);
1606
102
        root->traverse(&iter_iomap);
1607
102
    }
1608
102
    return !hadError;
1609
102
}
1610
1611
0
TGlslIoMapper::TGlslIoMapper() {
1612
0
    memset(inVarMaps,     0, sizeof(TVarLiveMap*)   * EShLangCount);
1613
0
    memset(outVarMaps,    0, sizeof(TVarLiveMap*)   * EShLangCount);
1614
0
    memset(uniformVarMap, 0, sizeof(TVarLiveMap*)   * EShLangCount);
1615
0
    memset(intermediates, 0, sizeof(TIntermediate*) * EShLangCount);
1616
0
    profile = ENoProfile;
1617
0
    version = 0;
1618
0
    autoPushConstantMaxSize = 128;
1619
0
    autoPushConstantBlockPacking = ElpStd430;
1620
0
}
1621
1622
0
TGlslIoMapper::~TGlslIoMapper() {
1623
0
    for (size_t stage = 0; stage < EShLangCount; stage++) {
1624
0
        if (inVarMaps[stage] != nullptr) {
1625
0
            delete inVarMaps[stage];
1626
0
            inVarMaps[stage] = nullptr;
1627
0
        }
1628
0
        if (outVarMaps[stage] != nullptr) {
1629
0
            delete outVarMaps[stage];
1630
0
            outVarMaps[stage] = nullptr;
1631
0
        }
1632
0
        if (uniformVarMap[stage] != nullptr) {
1633
0
            delete uniformVarMap[stage];
1634
0
            uniformVarMap[stage] = nullptr;
1635
0
        }
1636
0
        if (intermediates[stage] != nullptr)
1637
0
            intermediates[stage] = nullptr;
1638
0
    }
1639
0
}
1640
1641
// Map I/O variables to provided offsets, and make bindings for
1642
// unbound but live variables.
1643
//
1644
// Returns false if the input is too malformed to do this.
1645
0
bool TGlslIoMapper::addStage(EShLanguage stage, TIntermediate& intermediate, TInfoSink& infoSink, TIoMapResolver* resolver) {
1646
0
    bool somethingToDo = !intermediate.getResourceSetBinding().empty() ||
1647
0
        intermediate.getAutoMapBindings() ||
1648
0
        intermediate.getAutoMapLocations();
1649
1650
    // Profile and version are use for symbol validate.
1651
0
    profile = intermediate.getProfile();
1652
0
    version = intermediate.getVersion();
1653
0
    relaxSetBindingLimits |= intermediate.getRelaxSetBindingLimits();
1654
1655
    // Restrict the stricter condition to further check 'somethingToDo' only if 'somethingToDo' has not been set, reduce
1656
    // unnecessary or insignificant for-loop operation after 'somethingToDo' have been true.
1657
0
    for (int res = 0; (res < EResCount && !somethingToDo); ++res) {
1658
0
        somethingToDo = somethingToDo || (intermediate.getShiftBinding(TResourceType(res)) != 0) ||
1659
0
                        intermediate.hasShiftBindingForSet(TResourceType(res));
1660
0
    }
1661
0
    if (! somethingToDo && resolver == nullptr) {
1662
0
        return true;
1663
0
    }
1664
0
    if (intermediate.getNumEntryPoints() != 1 || intermediate.isRecursive()) {
1665
0
        return false;
1666
0
    }
1667
0
    TIntermNode* root = intermediate.getTreeRoot();
1668
0
    if (root == nullptr) {
1669
0
        return false;
1670
0
    }
1671
    // if no resolver is provided, use the default resolver with the given shifts and auto map settings
1672
0
    TDefaultGlslIoResolver defaultResolver(intermediate);
1673
0
#ifdef ENABLE_HLSL
1674
0
    TDefaultHlslIoResolver defaultHlslResolver(intermediate);
1675
0
    if (resolver == nullptr) {
1676
        // TODO: use a passed in IO mapper for this
1677
0
        if (intermediate.usingHlslIoMapping())
1678
0
            resolver = &defaultHlslResolver;
1679
0
        else
1680
0
            resolver = &defaultResolver;
1681
0
    }
1682
#else
1683
    if (resolver == nullptr) {
1684
        resolver = &defaultResolver;
1685
    }
1686
#endif
1687
0
    resolver->addStage(stage, intermediate);
1688
0
    inVarMaps[stage] = new TVarLiveMap(); outVarMaps[stage] = new TVarLiveMap(); uniformVarMap[stage] = new TVarLiveMap();
1689
0
    TVarGatherTraverser iter_binding_all(intermediate, true, *inVarMaps[stage], *outVarMaps[stage],
1690
0
                                         *uniformVarMap[stage]);
1691
0
    TVarGatherTraverser iter_binding_live(intermediate, false, *inVarMaps[stage], *outVarMaps[stage],
1692
0
                                          *uniformVarMap[stage]);
1693
0
    root->traverse(&iter_binding_all);
1694
0
    iter_binding_live.pushFunction(intermediate.getEntryPointMangledName().c_str());
1695
0
    while (! iter_binding_live.destinations.empty()) {
1696
0
        TIntermNode* destination = iter_binding_live.destinations.back();
1697
0
        iter_binding_live.destinations.pop_back();
1698
0
        destination->traverse(&iter_binding_live);
1699
0
    }
1700
1701
0
    TNotifyInOutAdaptor inOutNotify(stage, *resolver);
1702
0
    TNotifyUniformAdaptor uniformNotify(stage, *resolver);
1703
    // Resolve current stage input symbol location with previous stage output here,
1704
    // uniform symbol, ubo, ssbo and opaque symbols are per-program resource,
1705
    // will resolve uniform symbol location and ubo/ssbo/opaque binding in doMap()
1706
0
    resolver->beginNotifications(stage);
1707
0
    std::for_each(inVarMaps[stage]->begin(), inVarMaps[stage]->end(), inOutNotify);
1708
0
    std::for_each(outVarMaps[stage]->begin(), outVarMaps[stage]->end(), inOutNotify);
1709
0
    std::for_each(uniformVarMap[stage]->begin(), uniformVarMap[stage]->end(), uniformNotify);
1710
0
    resolver->endNotifications(stage);
1711
0
    TSlotCollector slotCollector(*resolver, infoSink);
1712
0
    resolver->beginCollect(stage);
1713
0
    std::for_each(inVarMaps[stage]->begin(), inVarMaps[stage]->end(), slotCollector);
1714
0
    std::for_each(outVarMaps[stage]->begin(), outVarMaps[stage]->end(), slotCollector);
1715
0
    std::for_each(uniformVarMap[stage]->begin(), uniformVarMap[stage]->end(), slotCollector);
1716
0
    resolver->endCollect(stage);
1717
0
    intermediates[stage] = &intermediate;
1718
0
    return !hadError;
1719
0
}
1720
1721
0
bool TGlslIoMapper::doMap(TIoMapResolver* resolver, TInfoSink& infoSink) {
1722
0
    resolver->endResolve(EShLangCount);
1723
0
    if (!hadError) {
1724
        //Resolve uniform location, ubo/ssbo/opaque bindings across stages
1725
0
        TResolverUniformAdaptor uniformResolve(EShLangCount, *resolver, uniformVarMap, infoSink, hadError,
1726
0
                                               relaxSetBindingLimits);
1727
0
        TResolverInOutAdaptor inOutResolve(EShLangCount, *resolver, infoSink, hadError);
1728
0
        TSymbolValidater symbolValidater(*resolver, infoSink, inVarMaps,
1729
0
                                         outVarMaps, uniformVarMap, hadError, profile, version);
1730
1731
0
        TVarLiveVector inVectors[EShLangCount];
1732
0
        TVarLiveVector outVectors[EShLangCount];
1733
0
        TVarLiveVector uniformVector;
1734
1735
0
        resolver->beginResolve(EShLangCount);
1736
0
        for (int stage = EShLangVertex; stage < EShLangCount; stage++) {
1737
0
            if (inVarMaps[stage] != nullptr) {
1738
0
                inOutResolve.setStage(EShLanguage(stage));
1739
1740
                // copy vars into a sorted list
1741
0
                std::for_each(inVarMaps[stage]->begin(), inVarMaps[stage]->end(),
1742
0
                        [&inVectors, stage](TVarLivePair p) { inVectors[stage].push_back(p); });
1743
0
                std::sort(inVectors[stage].begin(), inVectors[stage].end(),
1744
0
                        [](const TVarLivePair& p1, const TVarLivePair& p2) -> bool {
1745
0
                            return TVarEntryInfo::TOrderByPriority()(p1.second, p2.second);
1746
0
                });
1747
1748
0
                std::for_each(outVarMaps[stage]->begin(), outVarMaps[stage]->end(),
1749
0
                        [&outVectors, stage](TVarLivePair p) { outVectors[stage].push_back(p); });
1750
0
                std::sort(outVectors[stage].begin(), outVectors[stage].end(),
1751
0
                        [](const TVarLivePair& p1, const TVarLivePair& p2) -> bool {
1752
0
                            return TVarEntryInfo::TOrderByPriority()(p1.second, p2.second);
1753
0
                });
1754
1755
0
                for (auto& var : inVectors[stage]) { symbolValidater(var); }
1756
0
                for (auto& var : inVectors[stage]) { inOutResolve(var); }
1757
0
                for (auto& var : outVectors[stage]) { symbolValidater(var); }
1758
0
                for (auto& var : outVectors[stage]) { inOutResolve(var); }
1759
1760
                // copy results back into maps
1761
0
                std::for_each(inVectors[stage].begin(), inVectors[stage].end(),
1762
0
                    [this, stage](TVarLivePair p) {
1763
0
                        auto at = inVarMaps[stage]->find(p.first);
1764
0
                        if (at != inVarMaps[stage]->end())
1765
0
                            at->second = p.second;
1766
0
                });
1767
1768
0
                std::for_each(outVectors[stage].begin(), outVectors[stage].end(),
1769
0
                    [this, stage](TVarLivePair p) {
1770
0
                        auto at = outVarMaps[stage]->find(p.first);
1771
0
                        if (at != outVarMaps[stage]->end())
1772
0
                            at->second = p.second;
1773
0
                });
1774
1775
0
            }
1776
0
            if (uniformVarMap[stage] != nullptr) {
1777
0
                uniformResolve.setStage(EShLanguage(stage));
1778
0
                for (auto& var : *(uniformVarMap[stage])) { uniformVector.push_back(var); }
1779
0
            }
1780
0
        }
1781
0
        std::sort(uniformVector.begin(), uniformVector.end(), [](const TVarLivePair& p1, const TVarLivePair& p2) -> bool {
1782
0
            return TVarEntryInfo::TOrderByPriorityAndLive()(p1.second, p2.second);
1783
0
        });
1784
0
        for (auto& var : uniformVector) { symbolValidater(var); }
1785
0
        for (auto& var : uniformVector) { uniformResolve(var); }
1786
0
        std::sort(uniformVector.begin(), uniformVector.end(), [](const TVarLivePair& p1, const TVarLivePair& p2) -> bool {
1787
0
            return TVarEntryInfo::TOrderByPriority()(p1.second, p2.second);
1788
0
        });
1789
0
        resolver->endResolve(EShLangCount);
1790
0
        if (autoPushConstantBlockName.length()) {
1791
0
            bool upgraded = false;
1792
0
            for (size_t stage = 0; stage < EShLangCount; stage++) {
1793
0
                if (intermediates[stage] != nullptr) {
1794
0
                    TVarLiveMap** pUniformVarMap = uniformResolve.uniformVarMap;
1795
0
                    auto at = pUniformVarMap[stage]->find(autoPushConstantBlockName);
1796
0
                    if (at == pUniformVarMap[stage]->end())
1797
0
                        continue;
1798
0
                    TQualifier& qualifier = at->second.symbol->getQualifier();
1799
0
                    if (!qualifier.isUniform())
1800
0
                        continue;
1801
0
                    TType& t = at->second.symbol->getWritableType();
1802
0
                    int size, stride;
1803
0
                    TIntermediate::getBaseAlignment(t, size, stride, autoPushConstantBlockPacking,
1804
0
                                                    qualifier.layoutMatrix == ElmRowMajor);
1805
0
                    if (size <= int(autoPushConstantMaxSize)) {
1806
0
                        qualifier.setBlockStorage(EbsPushConstant);
1807
0
                        qualifier.layoutPacking = autoPushConstantBlockPacking;
1808
                        // Push constants don't have set/binding etc. decorations, remove those.
1809
0
                        qualifier.layoutSet = TQualifier::layoutNotSet;
1810
0
                        at->second.clearNewAssignments();
1811
1812
0
                        upgraded = true;
1813
0
                    }
1814
0
                }
1815
0
            }
1816
            // If it's been upgraded to push_constant, then set the flag so when its traversed
1817
            // in the next for loop, all references to this symbol will get their flag changed.
1818
            // so it doesn't get a set/binding assigned to it.
1819
0
            if (upgraded) {
1820
0
                std::for_each(uniformVector.begin(), uniformVector.end(),
1821
0
                                       [this](TVarLivePair& p) {
1822
0
                if (p.first == autoPushConstantBlockName) {
1823
0
                        p.second.upgradedToPushConstantPacking = autoPushConstantBlockPacking;
1824
0
                        p.second.newSet = TQualifier::layoutNotSet;
1825
0
                    }
1826
0
                });
1827
0
            }
1828
0
        }
1829
0
        for (size_t stage = 0; stage < EShLangCount; stage++) {
1830
0
            if (intermediates[stage] != nullptr) {
1831
                // traverse each stage, set new location to each input/output and unifom symbol, set new binding to
1832
                // ubo, ssbo and opaque symbols. Assign push_constant upgrades as well.
1833
0
                TVarLiveMap** pUniformVarMap = uniformResolve.uniformVarMap;
1834
0
                std::for_each(uniformVector.begin(), uniformVector.end(), [pUniformVarMap, stage](TVarLivePair p) {
1835
0
                    auto at = pUniformVarMap[stage]->find(p.second.symbol->getAccessName());
1836
0
                    if (at != pUniformVarMap[stage]->end() && at->second.id == p.second.id){
1837
0
                        if (p.second.upgradedToPushConstantPacking != ElpNone) {
1838
0
                            at->second.upgradedToPushConstantPacking = p.second.upgradedToPushConstantPacking;
1839
0
                        } else {
1840
0
                            int resolvedBinding = at->second.newBinding;
1841
0
                            at->second = p.second;
1842
0
                            if (resolvedBinding > 0)
1843
0
                                at->second.newBinding = resolvedBinding;
1844
0
                        }
1845
0
                    }
1846
0
                });
1847
0
                TVarSetTraverser iter_iomap(*intermediates[stage], *inVarMaps[stage], *outVarMaps[stage],
1848
0
                                            *uniformResolve.uniformVarMap[stage]);
1849
0
                intermediates[stage]->getTreeRoot()->traverse(&iter_iomap);
1850
0
            }
1851
0
        }
1852
0
        return !hadError;
1853
0
    } else {
1854
0
        return false;
1855
0
    }
1856
0
}
1857
1858
} // end namespace glslang