-
Notifications
You must be signed in to change notification settings - Fork 816
/
ShaderLang.cpp
2131 lines (1843 loc) · 76.9 KB
/
ShaderLang.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
// Copyright (C) 2013-2016 LunarG, Inc.
// Copyright (C) 2015-2020 Google, Inc.
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
//
// Implement the top-level of interface to the compiler/linker,
// as defined in ShaderLang.h
// This is the platform independent interface between an OGL driver
// and the shading language compiler/linker.
//
#include <cstring>
#include <iostream>
#include <sstream>
#include <memory>
#include "SymbolTable.h"
#include "ParseHelper.h"
#include "Scan.h"
#include "ScanContext.h"
#ifdef ENABLE_HLSL
#include "../HLSL/hlslParseHelper.h"
#include "../HLSL/hlslParseables.h"
#include "../HLSL/hlslScanContext.h"
#endif
#include "../Include/ShHandle.h"
#include "../../OGLCompilersDLL/InitializeDll.h"
#include "preprocessor/PpContext.h"
#define SH_EXPORTING
#include "../Public/ShaderLang.h"
#include "reflection.h"
#include "iomapper.h"
#include "Initialize.h"
// TODO: this really shouldn't be here, it is only because of the trial addition
// of printing pre-processed tokens, which requires knowing the string literal
// token to print ", but none of that seems appropriate for this file.
#include "preprocessor/PpTokens.h"
// Build-time generated includes
#include "glslang/build_info.h"
namespace { // anonymous namespace for file-local functions and symbols
// Total number of successful initializers of glslang: a refcount
// Shared global; access should be protected by a global mutex/critical section.
int NumberOfClients = 0;
using namespace glslang;
// Create a language specific version of parseables.
TBuiltInParseables* CreateBuiltInParseables(TInfoSink& infoSink, EShSource source)
{
switch (source) {
case EShSourceGlsl: return new TBuiltIns(); // GLSL builtIns
#ifdef ENABLE_HLSL
case EShSourceHlsl: return new TBuiltInParseablesHlsl(); // HLSL intrinsics
#endif
default:
infoSink.info.message(EPrefixInternalError, "Unable to determine source language");
return nullptr;
}
}
// Create a language specific version of a parse context.
TParseContextBase* CreateParseContext(TSymbolTable& symbolTable, TIntermediate& intermediate,
int version, EProfile profile, EShSource source,
EShLanguage language, TInfoSink& infoSink,
SpvVersion spvVersion, bool forwardCompatible, EShMessages messages,
bool parsingBuiltIns, std::string sourceEntryPointName = "")
{
switch (source) {
case EShSourceGlsl: {
if (sourceEntryPointName.size() == 0)
intermediate.setEntryPointName("main");
TString entryPoint = sourceEntryPointName.c_str();
return new TParseContext(symbolTable, intermediate, parsingBuiltIns, version, profile, spvVersion,
language, infoSink, forwardCompatible, messages, &entryPoint);
}
#ifdef ENABLE_HLSL
case EShSourceHlsl:
return new HlslParseContext(symbolTable, intermediate, parsingBuiltIns, version, profile, spvVersion,
language, infoSink, sourceEntryPointName.c_str(), forwardCompatible, messages);
#endif
default:
infoSink.info.message(EPrefixInternalError, "Unable to determine source language");
return nullptr;
}
}
// Local mapping functions for making arrays of symbol tables....
const int VersionCount = 17; // index range in MapVersionToIndex
int MapVersionToIndex(int version)
{
int index = 0;
switch (version) {
case 100: index = 0; break;
case 110: index = 1; break;
case 120: index = 2; break;
case 130: index = 3; break;
case 140: index = 4; break;
case 150: index = 5; break;
case 300: index = 6; break;
case 330: index = 7; break;
case 400: index = 8; break;
case 410: index = 9; break;
case 420: index = 10; break;
case 430: index = 11; break;
case 440: index = 12; break;
case 310: index = 13; break;
case 450: index = 14; break;
case 500: index = 0; break; // HLSL
case 320: index = 15; break;
case 460: index = 16; break;
default: assert(0); break;
}
assert(index < VersionCount);
return index;
}
const int SpvVersionCount = 3; // index range in MapSpvVersionToIndex
int MapSpvVersionToIndex(const SpvVersion& spvVersion)
{
int index = 0;
if (spvVersion.openGl > 0)
index = 1;
else if (spvVersion.vulkan > 0)
index = 2;
assert(index < SpvVersionCount);
return index;
}
const int ProfileCount = 4; // index range in MapProfileToIndex
int MapProfileToIndex(EProfile profile)
{
int index = 0;
switch (profile) {
case ENoProfile: index = 0; break;
case ECoreProfile: index = 1; break;
case ECompatibilityProfile: index = 2; break;
case EEsProfile: index = 3; break;
default: break;
}
assert(index < ProfileCount);
return index;
}
const int SourceCount = 2;
int MapSourceToIndex(EShSource source)
{
int index = 0;
switch (source) {
case EShSourceGlsl: index = 0; break;
case EShSourceHlsl: index = 1; break;
default: break;
}
assert(index < SourceCount);
return index;
}
// only one of these needed for non-ES; ES needs 2 for different precision defaults of built-ins
enum EPrecisionClass {
EPcGeneral,
EPcFragment,
EPcCount
};
// A process-global symbol table per version per profile for built-ins common
// to multiple stages (languages), and a process-global symbol table per version
// per profile per stage for built-ins unique to each stage. They will be sparsely
// populated, so they will only be generated as needed.
//
// Each has a different set of built-ins, and we want to preserve that from
// compile to compile.
//
TSymbolTable* CommonSymbolTable[VersionCount][SpvVersionCount][ProfileCount][SourceCount][EPcCount] = {};
TSymbolTable* SharedSymbolTables[VersionCount][SpvVersionCount][ProfileCount][SourceCount][EShLangCount] = {};
TPoolAllocator* PerProcessGPA = nullptr;
//
// Parse and add to the given symbol table the content of the given shader string.
//
bool InitializeSymbolTable(const TString& builtIns, int version, EProfile profile, const SpvVersion& spvVersion, EShLanguage language,
EShSource source, TInfoSink& infoSink, TSymbolTable& symbolTable)
{
TIntermediate intermediate(language, version, profile);
intermediate.setSource(source);
std::unique_ptr<TParseContextBase> parseContext(CreateParseContext(symbolTable, intermediate, version, profile, source,
language, infoSink, spvVersion, true, EShMsgDefault,
true));
TShader::ForbidIncluder includer;
TPpContext ppContext(*parseContext, "", includer);
TScanContext scanContext(*parseContext);
parseContext->setScanContext(&scanContext);
parseContext->setPpContext(&ppContext);
//
// Push the symbol table to give it an initial scope. This
// push should not have a corresponding pop, so that built-ins
// are preserved, and the test for an empty table fails.
//
symbolTable.push();
const char* builtInShaders[2];
size_t builtInLengths[2];
builtInShaders[0] = builtIns.c_str();
builtInLengths[0] = builtIns.size();
if (builtInLengths[0] == 0)
return true;
TInputScanner input(1, builtInShaders, builtInLengths);
if (! parseContext->parseShaderStrings(ppContext, input) != 0) {
infoSink.info.message(EPrefixInternalError, "Unable to parse built-ins");
printf("Unable to parse built-ins\n%s\n", infoSink.info.c_str());
printf("%s\n", builtInShaders[0]);
return false;
}
return true;
}
int CommonIndex(EProfile profile, EShLanguage language)
{
return (profile == EEsProfile && language == EShLangFragment) ? EPcFragment : EPcGeneral;
}
//
// To initialize per-stage shared tables, with the common table already complete.
//
void InitializeStageSymbolTable(TBuiltInParseables& builtInParseables, int version, EProfile profile, const SpvVersion& spvVersion,
EShLanguage language, EShSource source, TInfoSink& infoSink, TSymbolTable** commonTable,
TSymbolTable** symbolTables)
{
#ifdef GLSLANG_WEB
profile = EEsProfile;
version = 310;
#endif
(*symbolTables[language]).adoptLevels(*commonTable[CommonIndex(profile, language)]);
InitializeSymbolTable(builtInParseables.getStageString(language), version, profile, spvVersion, language, source,
infoSink, *symbolTables[language]);
builtInParseables.identifyBuiltIns(version, profile, spvVersion, language, *symbolTables[language]);
if (profile == EEsProfile && version >= 300)
(*symbolTables[language]).setNoBuiltInRedeclarations();
if (version == 110)
(*symbolTables[language]).setSeparateNameSpaces();
}
//
// Initialize the full set of shareable symbol tables;
// The common (cross-stage) and those shareable per-stage.
//
bool InitializeSymbolTables(TInfoSink& infoSink, TSymbolTable** commonTable, TSymbolTable** symbolTables, int version, EProfile profile, const SpvVersion& spvVersion, EShSource source)
{
#ifdef GLSLANG_WEB
profile = EEsProfile;
version = 310;
#endif
std::unique_ptr<TBuiltInParseables> builtInParseables(CreateBuiltInParseables(infoSink, source));
if (builtInParseables == nullptr)
return false;
builtInParseables->initialize(version, profile, spvVersion);
// do the common tables
InitializeSymbolTable(builtInParseables->getCommonString(), version, profile, spvVersion, EShLangVertex, source,
infoSink, *commonTable[EPcGeneral]);
if (profile == EEsProfile)
InitializeSymbolTable(builtInParseables->getCommonString(), version, profile, spvVersion, EShLangFragment, source,
infoSink, *commonTable[EPcFragment]);
// do the per-stage tables
// always have vertex and fragment
InitializeStageSymbolTable(*builtInParseables, version, profile, spvVersion, EShLangVertex, source,
infoSink, commonTable, symbolTables);
InitializeStageSymbolTable(*builtInParseables, version, profile, spvVersion, EShLangFragment, source,
infoSink, commonTable, symbolTables);
#ifndef GLSLANG_WEB
// check for tessellation
if ((profile != EEsProfile && version >= 150) ||
(profile == EEsProfile && version >= 310)) {
InitializeStageSymbolTable(*builtInParseables, version, profile, spvVersion, EShLangTessControl, source,
infoSink, commonTable, symbolTables);
InitializeStageSymbolTable(*builtInParseables, version, profile, spvVersion, EShLangTessEvaluation, source,
infoSink, commonTable, symbolTables);
}
// check for geometry
if ((profile != EEsProfile && version >= 150) ||
(profile == EEsProfile && version >= 310))
InitializeStageSymbolTable(*builtInParseables, version, profile, spvVersion, EShLangGeometry, source,
infoSink, commonTable, symbolTables);
#endif
// check for compute
if ((profile != EEsProfile && version >= 420) ||
(profile == EEsProfile && version >= 310))
InitializeStageSymbolTable(*builtInParseables, version, profile, spvVersion, EShLangCompute, source,
infoSink, commonTable, symbolTables);
// check for ray tracing stages
if (profile != EEsProfile && version >= 450) {
InitializeStageSymbolTable(*builtInParseables, version, profile, spvVersion, EShLangRayGen, source,
infoSink, commonTable, symbolTables);
InitializeStageSymbolTable(*builtInParseables, version, profile, spvVersion, EShLangIntersect, source,
infoSink, commonTable, symbolTables);
InitializeStageSymbolTable(*builtInParseables, version, profile, spvVersion, EShLangAnyHit, source,
infoSink, commonTable, symbolTables);
InitializeStageSymbolTable(*builtInParseables, version, profile, spvVersion, EShLangClosestHit, source,
infoSink, commonTable, symbolTables);
InitializeStageSymbolTable(*builtInParseables, version, profile, spvVersion, EShLangMiss, source,
infoSink, commonTable, symbolTables);
InitializeStageSymbolTable(*builtInParseables, version, profile, spvVersion, EShLangCallable, source,
infoSink, commonTable, symbolTables);
}
// check for mesh
if ((profile != EEsProfile && version >= 450) ||
(profile == EEsProfile && version >= 320))
InitializeStageSymbolTable(*builtInParseables, version, profile, spvVersion, EShLangMeshNV, source,
infoSink, commonTable, symbolTables);
// check for task
if ((profile != EEsProfile && version >= 450) ||
(profile == EEsProfile && version >= 320))
InitializeStageSymbolTable(*builtInParseables, version, profile, spvVersion, EShLangTaskNV, source,
infoSink, commonTable, symbolTables);
return true;
}
bool AddContextSpecificSymbols(const TBuiltInResource* resources, TInfoSink& infoSink, TSymbolTable& symbolTable, int version,
EProfile profile, const SpvVersion& spvVersion, EShLanguage language, EShSource source)
{
std::unique_ptr<TBuiltInParseables> builtInParseables(CreateBuiltInParseables(infoSink, source));
if (builtInParseables == nullptr)
return false;
builtInParseables->initialize(*resources, version, profile, spvVersion, language);
InitializeSymbolTable(builtInParseables->getCommonString(), version, profile, spvVersion, language, source, infoSink, symbolTable);
builtInParseables->identifyBuiltIns(version, profile, spvVersion, language, symbolTable, *resources);
return true;
}
//
// To do this on the fly, we want to leave the current state of our thread's
// pool allocator intact, so:
// - Switch to a new pool for parsing the built-ins
// - Do the parsing, which builds the symbol table, using the new pool
// - Switch to the process-global pool to save a copy of the resulting symbol table
// - Free up the new pool used to parse the built-ins
// - Switch back to the original thread's pool
//
// This only gets done the first time any thread needs a particular symbol table
// (lazy evaluation).
//
void SetupBuiltinSymbolTable(int version, EProfile profile, const SpvVersion& spvVersion, EShSource source)
{
TInfoSink infoSink;
// Make sure only one thread tries to do this at a time
glslang::GetGlobalLock();
// See if it's already been done for this version/profile combination
int versionIndex = MapVersionToIndex(version);
int spvVersionIndex = MapSpvVersionToIndex(spvVersion);
int profileIndex = MapProfileToIndex(profile);
int sourceIndex = MapSourceToIndex(source);
if (CommonSymbolTable[versionIndex][spvVersionIndex][profileIndex][sourceIndex][EPcGeneral]) {
glslang::ReleaseGlobalLock();
return;
}
// Switch to a new pool
TPoolAllocator& previousAllocator = GetThreadPoolAllocator();
TPoolAllocator* builtInPoolAllocator = new TPoolAllocator;
SetThreadPoolAllocator(builtInPoolAllocator);
// Dynamically allocate the local symbol tables so we can control when they are deallocated WRT when the pool is popped.
TSymbolTable* commonTable[EPcCount];
TSymbolTable* stageTables[EShLangCount];
for (int precClass = 0; precClass < EPcCount; ++precClass)
commonTable[precClass] = new TSymbolTable;
for (int stage = 0; stage < EShLangCount; ++stage)
stageTables[stage] = new TSymbolTable;
// Generate the local symbol tables using the new pool
InitializeSymbolTables(infoSink, commonTable, stageTables, version, profile, spvVersion, source);
// Switch to the process-global pool
SetThreadPoolAllocator(PerProcessGPA);
// Copy the local symbol tables from the new pool to the global tables using the process-global pool
for (int precClass = 0; precClass < EPcCount; ++precClass) {
if (! commonTable[precClass]->isEmpty()) {
CommonSymbolTable[versionIndex][spvVersionIndex][profileIndex][sourceIndex][precClass] = new TSymbolTable;
CommonSymbolTable[versionIndex][spvVersionIndex][profileIndex][sourceIndex][precClass]->copyTable(*commonTable[precClass]);
CommonSymbolTable[versionIndex][spvVersionIndex][profileIndex][sourceIndex][precClass]->readOnly();
}
}
for (int stage = 0; stage < EShLangCount; ++stage) {
if (! stageTables[stage]->isEmpty()) {
SharedSymbolTables[versionIndex][spvVersionIndex][profileIndex][sourceIndex][stage] = new TSymbolTable;
SharedSymbolTables[versionIndex][spvVersionIndex][profileIndex][sourceIndex][stage]->adoptLevels(*CommonSymbolTable
[versionIndex][spvVersionIndex][profileIndex][sourceIndex][CommonIndex(profile, (EShLanguage)stage)]);
SharedSymbolTables[versionIndex][spvVersionIndex][profileIndex][sourceIndex][stage]->copyTable(*stageTables[stage]);
SharedSymbolTables[versionIndex][spvVersionIndex][profileIndex][sourceIndex][stage]->readOnly();
}
}
// Clean up the local tables before deleting the pool they used.
for (int precClass = 0; precClass < EPcCount; ++precClass)
delete commonTable[precClass];
for (int stage = 0; stage < EShLangCount; ++stage)
delete stageTables[stage];
delete builtInPoolAllocator;
SetThreadPoolAllocator(&previousAllocator);
glslang::ReleaseGlobalLock();
}
// Function to Print all builtins
void DumpBuiltinSymbolTable(TInfoSink& infoSink, const TSymbolTable& symbolTable)
{
#ifndef GLSLANG_WEB
infoSink.debug << "BuiltinSymbolTable {\n";
symbolTable.dump(infoSink, true);
infoSink.debug << "}\n";
#endif
}
// Return true if the shader was correctly specified for version/profile/stage.
bool DeduceVersionProfile(TInfoSink& infoSink, EShLanguage stage, bool versionNotFirst, int defaultVersion,
EShSource source, int& version, EProfile& profile, const SpvVersion& spvVersion)
{
const int FirstProfileVersion = 150;
bool correct = true;
if (source == EShSourceHlsl) {
version = 500; // shader model; currently a characteristic of glslang, not the input
profile = ECoreProfile; // allow doubles in prototype parsing
return correct;
}
// Get a version...
if (version == 0) {
version = defaultVersion;
// infoSink.info.message(EPrefixWarning, "#version: statement missing; use #version on first line of shader");
}
// Get a good profile...
if (profile == ENoProfile) {
if (version == 300 || version == 310 || version == 320) {
correct = false;
infoSink.info.message(EPrefixError, "#version: versions 300, 310, and 320 require specifying the 'es' profile");
profile = EEsProfile;
} else if (version == 100)
profile = EEsProfile;
else if (version >= FirstProfileVersion)
profile = ECoreProfile;
else
profile = ENoProfile;
} else {
// a profile was provided...
if (version < 150) {
correct = false;
infoSink.info.message(EPrefixError, "#version: versions before 150 do not allow a profile token");
if (version == 100)
profile = EEsProfile;
else
profile = ENoProfile;
} else if (version == 300 || version == 310 || version == 320) {
if (profile != EEsProfile) {
correct = false;
infoSink.info.message(EPrefixError, "#version: versions 300, 310, and 320 support only the es profile");
}
profile = EEsProfile;
} else {
if (profile == EEsProfile) {
correct = false;
infoSink.info.message(EPrefixError, "#version: only version 300, 310, and 320 support the es profile");
if (version >= FirstProfileVersion)
profile = ECoreProfile;
else
profile = ENoProfile;
}
// else: typical desktop case... e.g., "#version 410 core"
}
}
// Fix version...
switch (version) {
// ES versions
case 100: break;
case 300: break;
case 310: break;
case 320: break;
// desktop versions
case 110: break;
case 120: break;
case 130: break;
case 140: break;
case 150: break;
case 330: break;
case 400: break;
case 410: break;
case 420: break;
case 430: break;
case 440: break;
case 450: break;
case 460: break;
// unknown version
default:
correct = false;
infoSink.info.message(EPrefixError, "version not supported");
if (profile == EEsProfile)
version = 310;
else {
version = 450;
profile = ECoreProfile;
}
break;
}
#ifndef GLSLANG_WEB
// Correct for stage type...
switch (stage) {
case EShLangGeometry:
if ((profile == EEsProfile && version < 310) ||
(profile != EEsProfile && version < 150)) {
correct = false;
infoSink.info.message(EPrefixError, "#version: geometry shaders require es profile with version 310 or non-es profile with version 150 or above");
version = (profile == EEsProfile) ? 310 : 150;
if (profile == EEsProfile || profile == ENoProfile)
profile = ECoreProfile;
}
break;
case EShLangTessControl:
case EShLangTessEvaluation:
if ((profile == EEsProfile && version < 310) ||
(profile != EEsProfile && version < 150)) {
correct = false;
infoSink.info.message(EPrefixError, "#version: tessellation shaders require es profile with version 310 or non-es profile with version 150 or above");
version = (profile == EEsProfile) ? 310 : 400; // 150 supports the extension, correction is to 400 which does not
if (profile == EEsProfile || profile == ENoProfile)
profile = ECoreProfile;
}
break;
case EShLangCompute:
if ((profile == EEsProfile && version < 310) ||
(profile != EEsProfile && version < 420)) {
correct = false;
infoSink.info.message(EPrefixError, "#version: compute shaders require es profile with version 310 or above, or non-es profile with version 420 or above");
version = profile == EEsProfile ? 310 : 420;
}
break;
case EShLangRayGen:
case EShLangIntersect:
case EShLangAnyHit:
case EShLangClosestHit:
case EShLangMiss:
case EShLangCallable:
if (profile == EEsProfile || version < 460) {
correct = false;
infoSink.info.message(EPrefixError, "#version: ray tracing shaders require non-es profile with version 460 or above");
version = 460;
}
break;
case EShLangMeshNV:
case EShLangTaskNV:
if ((profile == EEsProfile && version < 320) ||
(profile != EEsProfile && version < 450)) {
correct = false;
infoSink.info.message(EPrefixError, "#version: mesh/task shaders require es profile with version 320 or above, or non-es profile with version 450 or above");
version = profile == EEsProfile ? 320 : 450;
}
default:
break;
}
if (profile == EEsProfile && version >= 300 && versionNotFirst) {
correct = false;
infoSink.info.message(EPrefixError, "#version: statement must appear first in es-profile shader; before comments or newlines");
}
// Check for SPIR-V compatibility
if (spvVersion.spv != 0) {
switch (profile) {
case EEsProfile:
if (version < 310) {
correct = false;
infoSink.info.message(EPrefixError, "#version: ES shaders for SPIR-V require version 310 or higher");
version = 310;
}
break;
case ECompatibilityProfile:
infoSink.info.message(EPrefixError, "#version: compilation for SPIR-V does not support the compatibility profile");
break;
default:
if (spvVersion.vulkan > 0 && version < 140) {
correct = false;
infoSink.info.message(EPrefixError, "#version: Desktop shaders for Vulkan SPIR-V require version 140 or higher");
version = 140;
}
if (spvVersion.openGl >= 100 && version < 330) {
correct = false;
infoSink.info.message(EPrefixError, "#version: Desktop shaders for OpenGL SPIR-V require version 330 or higher");
version = 330;
}
break;
}
}
#endif
return correct;
}
// There are multiple paths in for setting environment stuff.
// TEnvironment takes precedence, for what it sets, so sort all this out.
// Ideally, the internal code could be made to use TEnvironment, but for
// now, translate it to the historically used parameters.
void TranslateEnvironment(const TEnvironment* environment, EShMessages& messages, EShSource& source,
EShLanguage& stage, SpvVersion& spvVersion)
{
// Set up environmental defaults, first ignoring 'environment'.
if (messages & EShMsgSpvRules)
spvVersion.spv = EShTargetSpv_1_0;
if (messages & EShMsgVulkanRules) {
spvVersion.vulkan = EShTargetVulkan_1_0;
spvVersion.vulkanGlsl = 100;
} else if (spvVersion.spv != 0)
spvVersion.openGl = 100;
// Now, override, based on any content set in 'environment'.
// 'environment' must be cleared to ESh*None settings when items
// are not being set.
if (environment != nullptr) {
// input language
if (environment->input.languageFamily != EShSourceNone) {
stage = environment->input.stage;
switch (environment->input.dialect) {
case EShClientNone:
break;
case EShClientVulkan:
spvVersion.vulkanGlsl = environment->input.dialectVersion;
break;
case EShClientOpenGL:
spvVersion.openGl = environment->input.dialectVersion;
break;
case EShClientCount:
assert(0);
break;
}
switch (environment->input.languageFamily) {
case EShSourceNone:
break;
case EShSourceGlsl:
source = EShSourceGlsl;
messages = static_cast<EShMessages>(messages & ~EShMsgReadHlsl);
break;
case EShSourceHlsl:
source = EShSourceHlsl;
messages = static_cast<EShMessages>(messages | EShMsgReadHlsl);
break;
case EShSourceCount:
assert(0);
break;
}
}
// client
switch (environment->client.client) {
case EShClientVulkan:
spvVersion.vulkan = environment->client.version;
break;
default:
break;
}
// generated code
switch (environment->target.language) {
case EshTargetSpv:
spvVersion.spv = environment->target.version;
break;
default:
break;
}
}
}
// Most processes are recorded when set in the intermediate representation,
// These are the few that are not.
void RecordProcesses(TIntermediate& intermediate, EShMessages messages, const std::string& sourceEntryPointName)
{
if ((messages & EShMsgRelaxedErrors) != 0)
intermediate.addProcess("relaxed-errors");
if ((messages & EShMsgSuppressWarnings) != 0)
intermediate.addProcess("suppress-warnings");
if ((messages & EShMsgKeepUncalled) != 0)
intermediate.addProcess("keep-uncalled");
if (sourceEntryPointName.size() > 0) {
intermediate.addProcess("source-entrypoint");
intermediate.addProcessArgument(sourceEntryPointName);
}
}
// This is the common setup and cleanup code for PreprocessDeferred and
// CompileDeferred.
// It takes any callable with a signature of
// bool (TParseContextBase& parseContext, TPpContext& ppContext,
// TInputScanner& input, bool versionWillBeError,
// TSymbolTable& , TIntermediate& ,
// EShOptimizationLevel , EShMessages );
// Which returns false if a failure was detected and true otherwise.
//
template<typename ProcessingContext>
bool ProcessDeferred(
TCompiler* compiler,
const char* const shaderStrings[],
const int numStrings,
const int* inputLengths,
const char* const stringNames[],
const char* customPreamble,
const EShOptimizationLevel optLevel,
const TBuiltInResource* resources,
int defaultVersion, // use 100 for ES environment, 110 for desktop; this is the GLSL version, not SPIR-V or Vulkan
EProfile defaultProfile,
// set version/profile to defaultVersion/defaultProfile regardless of the #version
// directive in the source code
bool forceDefaultVersionAndProfile,
bool forwardCompatible, // give errors for use of deprecated features
EShMessages messages, // warnings/errors/AST; things to print out
TIntermediate& intermediate, // returned tree, etc.
ProcessingContext& processingContext,
bool requireNonempty,
TShader::Includer& includer,
const std::string sourceEntryPointName = "",
const TEnvironment* environment = nullptr) // optional way of fully setting all versions, overriding the above
{
// This must be undone (.pop()) by the caller, after it finishes consuming the created tree.
GetThreadPoolAllocator().push();
if (numStrings == 0)
return true;
// Move to length-based strings, rather than null-terminated strings.
// Also, add strings to include the preamble and to ensure the shader is not null,
// which lets the grammar accept what was a null (post preprocessing) shader.
//
// Shader will look like
// string 0: system preamble
// string 1: custom preamble
// string 2...numStrings+1: user's shader
// string numStrings+2: "int;"
const int numPre = 2;
const int numPost = requireNonempty? 1 : 0;
const int numTotal = numPre + numStrings + numPost;
std::unique_ptr<size_t[]> lengths(new size_t[numTotal]);
std::unique_ptr<const char*[]> strings(new const char*[numTotal]);
std::unique_ptr<const char*[]> names(new const char*[numTotal]);
for (int s = 0; s < numStrings; ++s) {
strings[s + numPre] = shaderStrings[s];
if (inputLengths == nullptr || inputLengths[s] < 0)
lengths[s + numPre] = strlen(shaderStrings[s]);
else
lengths[s + numPre] = inputLengths[s];
}
if (stringNames != nullptr) {
for (int s = 0; s < numStrings; ++s)
names[s + numPre] = stringNames[s];
} else {
for (int s = 0; s < numStrings; ++s)
names[s + numPre] = nullptr;
}
// Get all the stages, languages, clients, and other environment
// stuff sorted out.
EShSource sourceGuess = (messages & EShMsgReadHlsl) != 0 ? EShSourceHlsl : EShSourceGlsl;
SpvVersion spvVersion;
EShLanguage stage = compiler->getLanguage();
TranslateEnvironment(environment, messages, sourceGuess, stage, spvVersion);
#ifdef ENABLE_HLSL
EShSource source = sourceGuess;
if (environment != nullptr && environment->target.hlslFunctionality1)
intermediate.setHlslFunctionality1();
#else
const EShSource source = EShSourceGlsl;
#endif
// First, without using the preprocessor or parser, find the #version, so we know what
// symbol tables, processing rules, etc. to set up. This does not need the extra strings
// outlined above, just the user shader, after the system and user preambles.
glslang::TInputScanner userInput(numStrings, &strings[numPre], &lengths[numPre]);
int version = 0;
EProfile profile = ENoProfile;
bool versionNotFirstToken = false;
bool versionNotFirst = (source == EShSourceHlsl)
? true
: userInput.scanVersion(version, profile, versionNotFirstToken);
bool versionNotFound = version == 0;
if (forceDefaultVersionAndProfile && source == EShSourceGlsl) {
#ifndef GLSLANG_WEB
if (! (messages & EShMsgSuppressWarnings) && ! versionNotFound &&
(version != defaultVersion || profile != defaultProfile)) {
compiler->infoSink.info << "Warning, (version, profile) forced to be ("
<< defaultVersion << ", " << ProfileName(defaultProfile)
<< "), while in source code it is ("
<< version << ", " << ProfileName(profile) << ")\n";
}
#endif
if (versionNotFound) {
versionNotFirstToken = false;
versionNotFirst = false;
versionNotFound = false;
}
version = defaultVersion;
profile = defaultProfile;
}
bool goodVersion = DeduceVersionProfile(compiler->infoSink, stage,
versionNotFirst, defaultVersion, source, version, profile, spvVersion);
#ifdef GLSLANG_WEB
profile = EEsProfile;
version = 310;
#endif
bool versionWillBeError = (versionNotFound || (profile == EEsProfile && version >= 300 && versionNotFirst));
#ifndef GLSLANG_WEB
bool warnVersionNotFirst = false;
if (! versionWillBeError && versionNotFirstToken) {
if (messages & EShMsgRelaxedErrors)
warnVersionNotFirst = true;
else
versionWillBeError = true;
}
#endif
intermediate.setSource(source);
intermediate.setVersion(version);
intermediate.setProfile(profile);
intermediate.setSpv(spvVersion);
RecordProcesses(intermediate, messages, sourceEntryPointName);
if (spvVersion.vulkan > 0)
intermediate.setOriginUpperLeft();
#ifdef ENABLE_HLSL
if ((messages & EShMsgHlslOffsets) || source == EShSourceHlsl)
intermediate.setHlslOffsets();
#endif
if (messages & EShMsgDebugInfo) {
intermediate.setSourceFile(names[numPre]);
for (int s = 0; s < numStrings; ++s) {
// The string may not be null-terminated, so make sure we provide
// the length along with the string.
intermediate.addSourceText(strings[numPre + s], lengths[numPre + s]);
}
}
SetupBuiltinSymbolTable(version, profile, spvVersion, source);
TSymbolTable* cachedTable = SharedSymbolTables[MapVersionToIndex(version)]
[MapSpvVersionToIndex(spvVersion)]
[MapProfileToIndex(profile)]
[MapSourceToIndex(source)]
[stage];
// Dynamically allocate the symbol table so we can control when it is deallocated WRT the pool.
std::unique_ptr<TSymbolTable> symbolTable(new TSymbolTable);
if (cachedTable)
symbolTable->adoptLevels(*cachedTable);
// Add built-in symbols that are potentially context dependent;
// they get popped again further down.
if (! AddContextSpecificSymbols(resources, compiler->infoSink, *symbolTable, version, profile, spvVersion,
stage, source)) {
return false;
}
if (messages & EShMsgBuiltinSymbolTable)
DumpBuiltinSymbolTable(compiler->infoSink, *symbolTable);
//
// Now we can process the full shader under proper symbols and rules.
//
std::unique_ptr<TParseContextBase> parseContext(CreateParseContext(*symbolTable, intermediate, version, profile, source,
stage, compiler->infoSink,
spvVersion, forwardCompatible, messages, false, sourceEntryPointName));
TPpContext ppContext(*parseContext, names[numPre] ? names[numPre] : "", includer);
// only GLSL (bison triggered, really) needs an externally set scan context
glslang::TScanContext scanContext(*parseContext);
if (source == EShSourceGlsl)
parseContext->setScanContext(&scanContext);
parseContext->setPpContext(&ppContext);
parseContext->setLimits(*resources);
if (! goodVersion)
parseContext->addError();
#ifndef GLSLANG_WEB
if (warnVersionNotFirst) {
TSourceLoc loc;
loc.init();
parseContext->warn(loc, "Illegal to have non-comment, non-whitespace tokens before #version", "#version", "");
}
#endif
parseContext->initializeExtensionBehavior();
// Fill in the strings as outlined above.
std::string preamble;
parseContext->getPreamble(preamble);
strings[0] = preamble.c_str();
lengths[0] = strlen(strings[0]);
names[0] = nullptr;
strings[1] = customPreamble;
lengths[1] = strlen(strings[1]);
names[1] = nullptr;
assert(2 == numPre);
if (requireNonempty) {
const int postIndex = numStrings + numPre;
strings[postIndex] = "\n int;";
lengths[postIndex] = strlen(strings[numStrings + numPre]);
names[postIndex] = nullptr;
}
TInputScanner fullInput(numStrings + numPre + numPost, strings.get(), lengths.get(), names.get(), numPre, numPost);
// Push a new symbol allocation scope that will get used for the shader's globals.
symbolTable->push();
bool success = processingContext(*parseContext, ppContext, fullInput,