yum-mirror/glslang
git clone https://git.yummers.dev/yum-mirror/glslang
b11b0383
vulkan-sdk-1.4.350.0
1// 2// Copyright (C) 2002-2005 3Dlabs Inc. Ltd. 3// Copyright (C) 2013-2016 LunarG, Inc. 4// Copyright (C) 2016-2020 Google, Inc. 5// Modifications Copyright(C) 2021 Advanced Micro Devices, Inc.All rights reserved. 6// 7// All rights reserved. 8// 9// Redistribution and use in source and binary forms, with or without 10// modification, are permitted provided that the following conditions 11// are met: 12// 13// Redistributions of source code must retain the above copyright 14// notice, this list of conditions and the following disclaimer. 15// 16// Redistributions in binary form must reproduce the above 17// copyright notice, this list of conditions and the following 18// disclaimer in the documentation and/or other materials provided 19// with the distribution. 20// 21// Neither the name of 3Dlabs Inc. Ltd. nor the names of its 22// contributors may be used to endorse or promote products derived 23// from this software without specific prior written permission. 24// 25// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 26// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 27// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 28// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 29// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 30// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 31// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 32// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 33// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 34// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 35// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 36// POSSIBILITY OF SUCH DAMAGE. 37// 38 39// this only applies to the standalone wrapper, not the front end in general 40#ifndef _CRT_SECURE_NO_WARNINGS 41#define _CRT_SECURE_NO_WARNINGS 42#endif 43 44#include "glslang/Public/ResourceLimits.h" 45#include "Worklist.h" 46#include "DirStackFileIncluder.h" 47#include "./../glslang/Public/ShaderLang.h" 48#include "../glslang/MachineIndependent/localintermediate.h" 49#include "../SPIRV/GlslangToSpv.h" 50#include "../SPIRV/GLSL.std.450.h" 51#include "../SPIRV/disassemble.h" 52 53#include <array> 54#include <atomic> 55#include <cctype> 56#include <cmath> 57#include <cstdlib> 58#include <cstring> 59#include <iterator> 60#include <map> 61#include <memory> 62#include <set> 63#include <thread> 64#include <type_traits> 65 66#include "../glslang/OSDependent/osinclude.h" 67 68// Build-time generated includes 69#include "glslang/build_info.h" 70 71#include "glslang/glsl_intrinsic_header.h" 72 73extern "C" { 74GLSLANG_EXPORT void ShOutputHtml () ; 75} 76 77// Command-line options 78enum TOptions : uint64_t { 79EOptionNone = 0 , 80EOptionIntermediate = ( 1ull << 0 ) , 81EOptionSuppressInfolog = ( 1ull << 1 ) , 82EOptionMemoryLeakMode = ( 1ull << 2 ) , 83EOptionRelaxedErrors = ( 1ull << 3 ) , 84EOptionGiveWarnings = ( 1ull << 4 ) , 85EOptionLinkProgram = ( 1ull << 5 ) , 86EOptionMultiThreaded = ( 1ull << 6 ) , 87EOptionDumpConfig = ( 1ull << 7 ) , 88EOptionDumpReflection = ( 1ull << 8 ) , 89EOptionSuppressWarnings = ( 1ull << 9 ) , 90EOptionDumpVersions = ( 1ull << 10 ) , 91EOptionSpv = ( 1ull << 11 ) , 92EOptionHumanReadableSpv = ( 1ull << 12 ) , 93EOptionVulkanRules = ( 1ull << 13 ) , 94EOptionDefaultDesktop = ( 1ull << 14 ) , 95EOptionOutputPreprocessed = ( 1ull << 15 ) , 96EOptionOutputHexadecimal = ( 1ull << 16 ) , 97EOptionReadHlsl = ( 1ull << 17 ) , 98EOptionCascadingErrors = ( 1ull << 18 ) , 99EOptionAutoMapBindings = ( 1ull << 19 ) , 100EOptionFlattenUniformArrays = ( 1ull << 20 ) , 101EOptionNoStorageFormat = ( 1ull << 21 ) , 102EOptionKeepUncalled = ( 1ull << 22 ) , 103EOptionHlslOffsets = ( 1ull << 23 ) , 104EOptionHlslIoMapping = ( 1ull << 24 ) , 105EOptionAutoMapLocations = ( 1ull << 25 ) , 106EOptionDebug = ( 1ull << 26 ) , 107EOptionStdin = ( 1ull << 27 ) , 108EOptionOptimizeDisable = ( 1ull << 28 ) , 109EOptionOptimizeSize = ( 1ull << 29 ) , 110EOptionInvertY = ( 1ull << 30 ) , 111EOptionDumpBareVersion = ( 1ull << 31 ) , 112EOptionCompileOnly = ( 1ull << 32 ) , 113EOptionDisplayErrorColumn = ( 1ull << 33 ) , 114EOptionLinkTimeOptimization = ( 1ull << 34 ) , 115EOptionValidateCrossStageIO = ( 1ull << 35 ) , 116EOptionBindingsPerResourceType = ( 1ull << 36 ) , 117} ; 118bool targetHlslFunctionality1 = false ; 119bool SpvToolsDisassembler = false ; 120bool SpvToolsValidate = false ; 121bool NaNClamp = false ; 122bool stripDebugInfo = false ; 123bool emitNonSemanticShaderDebugInfo = false ; 124bool emitNonSemanticShaderDebugSource = false ; 125bool beQuiet = false ; 126bool VulkanRulesRelaxed = false ; 127bool autoSampledTextures = false ; 128 129// 130// Return codes from main/exit(). 131// 132enum TFailCode { 133ESuccess = 0 , 134EFailUsage , 135EFailCompile , 136EFailLink , 137EFailCompilerCreate , 138EFailThreadCreate , 139EFailLinkerCreate 140} ; 141 142// 143// Forward declarations. 144// 145EShLanguage FindLanguage ( const std :: string & name , bool parseSuffix = true ) ; 146void CompileFile ( const char * fileName , ShHandle ) ; 147void usage () ; 148char * ReadFileData ( const char * fileName ) ; 149void FreeFileData ( char * data ) ; 150void InfoLogMsg ( const char * msg , const char * name , const int num ) ; 151 152// Globally track if any compile or link failure. 153std :: atomic < int8_t > CompileFailed { 0 } ; 154std :: atomic < int8_t > LinkFailed { 0 } ; 155std :: atomic < int8_t > CompileOrLinkFailed { 0 } ; 156 157// array of unique places to leave the shader names and infologs for the asynchronous compiles 158std :: vector < std :: unique_ptr < glslang :: TWorkItem >> WorkItems ; 159 160std :: string ConfigFile ; 161 162// 163// Parse either a .conf file provided by the user or the default from glslang::DefaultTBuiltInResource 164// 165void ProcessConfigFile () 166{ 167if ( ConfigFile . size () == 0 ) 168* GetResources () = * GetDefaultResources () ; 169else { 170char * configString = ReadFileData ( ConfigFile . c_str ()) ; 171DecodeResourceLimits ( GetResources () , configString ) ; 172FreeFileData ( configString ) ; 173} 174} 175 176int ReflectOptions = EShReflectionDefault ; 177std :: underlying_type_t < TOptions > Options = EOptionNone ; 178const char * ExecutableName = nullptr ; 179const char * binaryFileName = nullptr ; 180const char * depencyFileName = nullptr ; 181const char * entryPointName = nullptr ; 182const char * sourceEntryPointName = nullptr ; 183const char * shaderStageName = nullptr ; 184const char * variableName = nullptr ; 185bool HlslEnable16BitTypes = false ; 186bool HlslDX9compatible = false ; 187bool HlslDxPositionW = false ; 188bool EnhancedMsgs = false ; 189bool AbsolutePath = false ; 190bool DumpBuiltinSymbols = false ; 191std :: vector < std :: string > IncludeDirectoryList ; 192 193// Source environment 194// (source 'Client' is currently the same as target 'Client') 195int ClientInputSemanticsVersion = 100 ; 196 197// Target environment 198glslang :: EShClient Client = glslang :: EShClientNone ; // will stay EShClientNone if only validating 199glslang :: EShTargetClientVersion ClientVersion ; // not valid until Client is set 200glslang :: EShTargetLanguage TargetLanguage = glslang :: EShTargetNone ; 201glslang :: EShTargetLanguageVersion TargetVersion ; // not valid until TargetLanguage is set 202 203// GLSL version 204int GlslVersion = 0 ; // GLSL version specified on CLI, overrides #version in shader source 205 206std :: vector < std :: string > Processes ; // what should be recorded by OpModuleProcessed, or equivalent 207 208// Per descriptor-set binding base data 209typedef std :: map < unsigned int , unsigned int > TPerSetBaseBinding ; 210 211std :: vector < std :: pair < std :: string , int >> uniformLocationOverrides ; 212int uniformBase = 0 ; 213 214std :: array < std :: array < unsigned int , EShLangCount > , glslang :: EResCount > baseBinding ; 215std :: array < std :: array < TPerSetBaseBinding , EShLangCount > , glslang :: EResCount > baseBindingForSet ; 216std :: array < std :: vector < std :: string > , EShLangCount > baseResourceSetBinding ; 217 218std :: vector < std :: pair < std :: string , glslang :: TBlockStorageClass >> blockStorageOverrides ; 219 220bool setGlobalUniformBlock = false ; 221std :: string globalUniformName ; 222unsigned int globalUniformBinding ; 223unsigned int globalUniformSet ; 224 225bool setGlobalBufferBlock = false ; 226std :: string atomicCounterBlockName ; 227unsigned int atomicCounterBlockSet ; 228 229// Add things like "#define ..." to a preamble to use in the beginning of the shader. 230class TPreamble { 231public : 232TPreamble () { } 233 234bool isSet () const { return text . size () > 0 ; } 235const char * get () const { return text . c_str () ; } 236 237// #define... 238void addDef ( std :: string def ) 239{ 240text . append ( "#define " ) ; 241fixLine ( def ) ; 242 243Processes . push_back ( "define-macro " ) ; 244Processes . back () . append ( def ) ; 245 246// The first "=" needs to turn into a space 247const size_t equal = def . find_first_of ( "=" ) ; 248if ( equal != def . npos ) 249def [ equal ] = ' ' ; 250 251text . append ( def ) ; 252text . append ( " \n " ) ; 253} 254 255// #undef... 256void addUndef ( std :: string undef ) 257{ 258text . append ( "#undef " ) ; 259fixLine ( undef ) ; 260 261Processes . push_back ( "undef-macro " ) ; 262Processes . back () . append ( undef ) ; 263 264text . append ( undef ) ; 265text . append ( " \n " ) ; 266} 267 268void addText ( std :: string preambleText ) 269{ 270fixLine ( preambleText ) ; 271 272Processes . push_back ( "preamble-text" ) ; 273Processes . back () . append ( preambleText ) ; 274 275text . append ( preambleText ) ; 276text . append ( " \n " ) ; 277} 278 279protected : 280void fixLine ( std :: string & line ) 281{ 282// Can't go past a newline in the line 283const size_t end = line . find_first_of ( " \n " ) ; 284if ( end != line . npos ) 285line = line . substr ( 0 , end ) ; 286} 287 288std :: string text ; // contents of preamble 289} ; 290 291// Track the user's #define and #undef from the command line. 292TPreamble UserPreamble ; 293std :: string PreambleString ; 294 295// 296// Create the default name for saving a binary if -o is not provided. 297// 298const char * GetBinaryName ( EShLanguage stage ) 299{ 300const char * name ; 301if ( binaryFileName == nullptr ) { 302switch ( stage ) { 303case EShLangVertex : name = "vert.spv" ; break ; 304case EShLangTessControl : name = "tesc.spv" ; break ; 305case EShLangTessEvaluation : name = "tese.spv" ; break ; 306case EShLangGeometry : name = "geom.spv" ; break ; 307case EShLangFragment : name = "frag.spv" ; break ; 308case EShLangCompute : name = "comp.spv" ; break ; 309case EShLangRayGen : name = "rgen.spv" ; break ; 310case EShLangIntersect : name = "rint.spv" ; break ; 311case EShLangAnyHit : name = "rahit.spv" ; break ; 312case EShLangClosestHit : name = "rchit.spv" ; break ; 313case EShLangMiss : name = "rmiss.spv" ; break ; 314case EShLangCallable : name = "rcall.spv" ; break ; 315case EShLangMesh : name = "mesh.spv" ; break ; 316case EShLangTask : name = "task.spv" ; break ; 317default : name = "unknown" ; break ; 318} 319} else 320name = binaryFileName ; 321 322return name ; 323} 324 325// 326// *.conf => this is a config file that can set limits/resources 327// 328bool SetConfigFile ( const std :: string & name ) 329{ 330if ( name . size () < 5 ) 331return false ; 332 333if ( name . compare ( name . size () - 5 , 5 , ".conf" ) == 0 ) { 334ConfigFile = name ; 335return true ; 336} 337 338return false ; 339} 340 341// 342// Give error and exit with failure code. 343// 344void Error ( const char * message , const char * detail = nullptr ) 345{ 346fprintf ( stderr , "%s: Error: " , ExecutableName ) ; 347if ( detail != nullptr ) 348fprintf ( stderr , "%s: " , detail ) ; 349fprintf ( stderr , "%s (use -h for usage) \n " , message ) ; 350exit ( EFailUsage ) ; 351} 352 353// 354// Process an optional binding base of one the forms: 355// --argname [stage] base // base for stage (if given) or all stages (if not) 356// --argname [stage] [base set]... // set/base pairs: set the base for given binding set. 357 358// Where stage is one of the forms accepted by FindLanguage, and base is an integer 359// 360void ProcessBindingBase ( int & argc , char **& argv , glslang :: TResourceType res ) 361{ 362if ( argc < 2 ) 363usage () ; 364 365EShLanguage lang = EShLangCount ; 366int singleBase = 0 ; 367TPerSetBaseBinding perSetBase ; 368int arg = 1 ; 369 370// Parse stage, if given 371if ( ! isdigit ( argv [ arg ][ 0 ])) { 372if ( argc < 3 ) // this form needs one more argument 373usage () ; 374 375lang = FindLanguage ( argv [ arg ++ ] , false ) ; 376} 377 378if (( argc - arg ) >= 2 && isdigit ( argv [ arg + 0 ][ 0 ]) && isdigit ( argv [ arg + 1 ][ 0 ])) { 379// Parse a per-set binding base 380do { 381const int baseNum = atoi ( argv [ arg ++ ]) ; 382const int setNum = atoi ( argv [ arg ++ ]) ; 383perSetBase [ setNum ] = baseNum ; 384} while (( argc - arg ) >= 2 && isdigit ( argv [ arg + 0 ][ 0 ]) && isdigit ( argv [ arg + 1 ][ 0 ])) ; 385} else { 386// Parse single binding base 387singleBase = atoi ( argv [ arg ++ ]) ; 388} 389 390argc -= ( arg - 1 ) ; 391argv += ( arg - 1 ) ; 392 393// Set one or all languages 394const int langMin = ( lang < EShLangCount ) ? lang + 0 : 0 ; 395const int langMax = ( lang < EShLangCount ) ? lang + 1 : EShLangCount ; 396 397for ( int lang = langMin ; lang < langMax ; ++ lang ) { 398if ( ! perSetBase . empty ()) 399baseBindingForSet [ res ][ lang ] . insert ( perSetBase . begin () , perSetBase . end ()) ; 400else 401baseBinding [ res ][ lang ] = singleBase ; 402} 403} 404 405void ProcessResourceSetBindingBase ( int & argc , char **& argv , std :: array < std :: vector < std :: string > , EShLangCount >& base ) 406{ 407if ( argc < 2 ) 408usage () ; 409 410if ( ! isdigit ( argv [ 1 ][ 0 ])) { 411if ( argc < 3 ) // this form needs one more argument 412usage () ; 413 414// Parse form: --argname stage [regname set base...], or: 415// --argname stage set 416const EShLanguage lang = FindLanguage ( argv [ 1 ] , false ) ; 417 418argc -- ; 419argv ++ ; 420 421while ( argc > 1 && argv [ 1 ] != nullptr && argv [ 1 ][ 0 ] != '-' ) { 422base [ lang ] . push_back ( argv [ 1 ]) ; 423 424argc -- ; 425argv ++ ; 426} 427 428// Must have one arg, or a multiple of three (for [regname set binding] triples) 429if ( base [ lang ] . size () != 1 && ( base [ lang ] . size () % 3 ) != 0 ) 430usage () ; 431 432} else { 433// Parse form: --argname set 434for ( int lang = 0 ; lang < EShLangCount ; ++ lang ) 435base [ lang ] . push_back ( argv [ 1 ]) ; 436 437argc -- ; 438argv ++ ; 439} 440} 441 442// 443// Process an optional binding base of one the forms: 444// --argname name {uniform|buffer|push_constant} 445void ProcessBlockStorage ( int & argc , char **& argv , std :: vector < std :: pair < std :: string , glslang :: TBlockStorageClass >>& storage ) 446{ 447if ( argc < 3 ) 448usage () ; 449 450glslang :: TBlockStorageClass blockStorage = glslang :: EbsNone ; 451 452std :: string strBacking ( argv [ 2 ]) ; 453if ( strBacking == "uniform" ) 454blockStorage = glslang :: EbsUniform ; 455else if ( strBacking == "buffer" ) 456blockStorage = glslang :: EbsStorageBuffer ; 457else if ( strBacking == "push_constant" ) 458blockStorage = glslang :: EbsPushConstant ; 459else { 460printf ( "%s: invalid block storage \n " , strBacking . c_str ()) ; 461usage () ; 462} 463 464storage . push_back ( std :: make_pair ( std :: string ( argv [ 1 ]) , blockStorage )) ; 465 466argc -= 2 ; 467argv += 2 ; 468} 469 470inline bool isNonDigit ( char c ) { 471// a non-digit character valid in a glsl identifier 472return ( c == '_' ) || ( c >= 'a' && c <= 'z' ) || ( c >= 'A' && c <= 'Z' ) ; 473} 474 475// whether string isa valid identifier to be used in glsl 476bool isValidIdentifier ( const char * str ) { 477std :: string idn ( str ) ; 478 479if ( idn . length () == 0 ) { 480return false ; 481} 482 483if ( idn . length () >= 3 && idn . substr ( 0 , 3 ) == "gl_" ) { 484// identifiers startin with "gl_" are reserved 485return false ; 486} 487 488if ( ! isNonDigit ( idn [ 0 ])) { 489return false ; 490} 491 492for ( unsigned int i = 1 ; i < idn . length () ; ++ i ) { 493if ( ! ( isdigit ( idn [ i ]) || isNonDigit ( idn [ i ]))) { 494return false ; 495} 496} 497 498return true ; 499} 500 501// Process settings for either the global buffer block or global unfirom block 502// of the form: 503// --argname name set binding 504void ProcessGlobalBlockSettings ( int & argc , char **& argv , std :: string * name , unsigned int * set , unsigned int * binding ) 505{ 506if ( argc < 4 ) 507usage () ; 508 509unsigned int curArg = 1 ; 510 511assert ( name || set || binding ) ; 512 513if ( name ) { 514if ( ! isValidIdentifier ( argv [ curArg ])) { 515printf ( "%s: invalid identifier \n " , argv [ curArg ]) ; 516usage () ; 517} 518* name = argv [ curArg ] ; 519 520curArg ++ ; 521} 522 523if ( set ) { 524errno = 0 ; 525int setVal = static_cast < int > ( :: strtol ( argv [ curArg ] , nullptr , 10 )) ; 526if ( errno || setVal < 0 ) { 527printf ( "%s: invalid set \n " , argv [ curArg ]) ; 528usage () ; 529} 530* set = setVal ; 531 532curArg ++ ; 533} 534 535if ( binding ) { 536errno = 0 ; 537int bindingVal = static_cast < int > ( :: strtol ( argv [ curArg ] , nullptr , 10 )) ; 538if ( errno || bindingVal < 0 ) { 539printf ( "%s: invalid binding \n " , argv [ curArg ]) ; 540usage () ; 541} 542* binding = bindingVal ; 543 544curArg ++ ; 545} 546 547argc -= ( curArg - 1 ) ; 548argv += ( curArg - 1 ) ; 549} 550 551// 552// Do all command-line argument parsing. This includes building up the work-items 553// to be processed later, and saving all the command-line options. 554// 555// Does not return (it exits) if command-line is fatally flawed. 556// 557void ProcessArguments ( std :: vector < std :: unique_ptr < glslang :: TWorkItem >>& workItems , int argc , char * argv []) 558{ 559for ( int res = 0 ; res < glslang :: EResCount ; ++ res ) 560baseBinding [ res ] . fill ( 0 ) ; 561 562ExecutableName = argv [ 0 ] ; 563workItems . reserve ( argc ) ; 564 565const auto bumpArg = [ & ]() { 566if ( argc > 0 ) { 567argc -- ; 568argv ++ ; 569} 570} ; 571 572// read a string directly attached to a single-letter option 573const auto getStringOperand = [ & ]( const char * desc ) { 574if ( argv [ 0 ][ 2 ] == 0 ) { 575printf ( "%s must immediately follow option (no spaces) \n " , desc ) ; 576exit ( EFailUsage ) ; 577} 578return argv [ 0 ] + 2 ; 579} ; 580 581// read a number attached to a single-letter option 582const auto getAttachedNumber = [ & ]( const char * desc ) { 583int num = atoi ( argv [ 0 ] + 2 ) ; 584if ( num == 0 ) { 585printf ( "%s: expected attached non-0 number \n " , desc ) ; 586exit ( EFailUsage ) ; 587} 588return num ; 589} ; 590 591// minimum needed (without overriding something else) to target Vulkan SPIR-V 592const auto setVulkanSpv = []() { 593if ( Client == glslang :: EShClientNone ) 594ClientVersion = glslang :: EShTargetVulkan_1_0 ; 595Client = glslang :: EShClientVulkan ; 596Options |= EOptionSpv ; 597Options |= EOptionVulkanRules ; 598Options |= EOptionLinkProgram ; 599} ; 600 601// minimum needed (without overriding something else) to target OpenGL SPIR-V 602const auto setOpenGlSpv = []() { 603if ( Client == glslang :: EShClientNone ) 604ClientVersion = glslang :: EShTargetOpenGL_450 ; 605Client = glslang :: EShClientOpenGL ; 606Options |= EOptionSpv ; 607Options |= EOptionLinkProgram ; 608// undo a -H default to Vulkan 609Options &= ~ EOptionVulkanRules ; 610} ; 611 612const auto getUniformOverride = [ getStringOperand ]() { 613const char * arg = getStringOperand ( "-u<name>:<location>" ) ; 614const char * split = strchr ( arg , ':' ) ; 615if ( split == nullptr ) { 616printf ( "%s: missing location \n " , arg ) ; 617exit ( EFailUsage ) ; 618} 619errno = 0 ; 620int location = static_cast < int > ( :: strtol ( split + 1 , nullptr , 10 )) ; 621if ( errno ) { 622printf ( "%s: invalid location \n " , arg ) ; 623exit ( EFailUsage ) ; 624} 625return std :: make_pair ( std :: string ( arg , split - arg ) , location ) ; 626} ; 627 628for ( bumpArg () ; argc >= 1 ; bumpArg ()) { 629if ( argv [ 0 ][ 0 ] == '-' ) { 630switch ( argv [ 0 ][ 1 ]) { 631case '-' : 632{ 633std :: string lowerword ( argv [ 0 ] + 2 ) ; 634std :: transform ( lowerword . begin () , lowerword . end () , lowerword . begin () , :: tolower ) ; 635 636// handle --word style options 637if ( lowerword == "auto-map-bindings" || // synonyms 638lowerword == "auto-map-binding" || 639lowerword == "amb" ) { 640Options |= EOptionAutoMapBindings ; 641} else if ( lowerword == "auto-map-locations" || // synonyms 642lowerword == "aml" ) { 643Options |= EOptionAutoMapLocations ; 644} else if ( lowerword == "uniform-base" ) { 645if ( argc <= 1 ) 646Error ( "no <base> provided" , lowerword . c_str ()) ; 647uniformBase = static_cast < int > ( :: strtol ( argv [ 1 ] , nullptr , 10 )) ; 648bumpArg () ; 649break ; 650} else if ( lowerword == "client" ) { 651if ( argc > 1 ) { 652if ( strcmp ( argv [ 1 ] , "vulkan100" ) == 0 ) 653setVulkanSpv () ; 654else if ( strcmp ( argv [ 1 ] , "opengl100" ) == 0 ) 655setOpenGlSpv () ; 656else 657Error ( "expects vulkan100 or opengl100" , lowerword . c_str ()) ; 658} else 659Error ( "expects vulkan100 or opengl100" , lowerword . c_str ()) ; 660bumpArg () ; 661} else if ( lowerword == "define-macro" || 662lowerword == "d" ) { 663if ( argc > 1 ) 664UserPreamble . addDef ( argv [ 1 ]) ; 665else 666Error ( "expects <name[=def]>" , argv [ 0 ]) ; 667bumpArg () ; 668} else if ( lowerword == "dump-builtin-symbols" ) { 669DumpBuiltinSymbols = true ; 670} else if ( lowerword == "entry-point" ) { 671entryPointName = argv [ 1 ] ; 672if ( argc <= 1 ) 673Error ( "no <name> provided" , lowerword . c_str ()) ; 674bumpArg () ; 675} else if ( lowerword == "flatten-uniform-arrays" || // synonyms 676lowerword == "flatten-uniform-array" || 677lowerword == "fua" ) { 678Options |= EOptionFlattenUniformArrays ; 679} else if ( lowerword == "glsl-version" ) { 680if ( argc > 1 ) { 681if ( strcmp ( argv [ 1 ] , "100" ) == 0 ) { 682GlslVersion = 100 ; 683} else if ( strcmp ( argv [ 1 ] , "110" ) == 0 ) { 684GlslVersion = 110 ; 685} else if ( strcmp ( argv [ 1 ] , "120" ) == 0 ) { 686GlslVersion = 120 ; 687} else if ( strcmp ( argv [ 1 ] , "130" ) == 0 ) { 688GlslVersion = 130 ; 689} else if ( strcmp ( argv [ 1 ] , "140" ) == 0 ) { 690GlslVersion = 140 ; 691} else if ( strcmp ( argv [ 1 ] , "150" ) == 0 ) { 692GlslVersion = 150 ; 693} else if ( strcmp ( argv [ 1 ] , "300es" ) == 0 ) { 694GlslVersion = 300 ; 695} else if ( strcmp ( argv [ 1 ] , "310es" ) == 0 ) { 696GlslVersion = 310 ; 697} else if ( strcmp ( argv [ 1 ] , "320es" ) == 0 ) { 698GlslVersion = 320 ; 699} else if ( strcmp ( argv [ 1 ] , "330" ) == 0 ) { 700GlslVersion = 330 ; 701} else if ( strcmp ( argv [ 1 ] , "400" ) == 0 ) { 702GlslVersion = 400 ; 703} else if ( strcmp ( argv [ 1 ] , "410" ) == 0 ) { 704GlslVersion = 410 ; 705} else if ( strcmp ( argv [ 1 ] , "420" ) == 0 ) { 706GlslVersion = 420 ; 707} else if ( strcmp ( argv [ 1 ] , "430" ) == 0 ) { 708GlslVersion = 430 ; 709} else if ( strcmp ( argv [ 1 ] , "440" ) == 0 ) { 710GlslVersion = 440 ; 711} else if ( strcmp ( argv [ 1 ] , "450" ) == 0 ) { 712GlslVersion = 450 ; 713} else if ( strcmp ( argv [ 1 ] , "460" ) == 0 ) { 714GlslVersion = 460 ; 715} else 716Error ( "--glsl-version expected one of: 100, 110, 120, 130, 140, 150, \n " 717"300es, 310es, 320es, 330 \n " 718"400, 410, 420, 430, 440, 450, 460" ) ; 719} 720bumpArg () ; 721} else if ( lowerword == "hlsl-offsets" ) { 722Options |= EOptionHlslOffsets ; 723} else if ( lowerword == "hlsl-iomap" || 724lowerword == "hlsl-iomapper" || 725lowerword == "hlsl-iomapping" ) { 726Options |= EOptionHlslIoMapping ; 727} else if ( lowerword == "hlsl-enable-16bit-types" ) { 728HlslEnable16BitTypes = true ; 729} else if ( lowerword == "hlsl-dx9-compatible" ) { 730HlslDX9compatible = true ; 731} else if ( lowerword == "hlsl-dx-position-w" ) { 732HlslDxPositionW = true ; 733} else if ( lowerword == "enhanced-msgs" ) { 734EnhancedMsgs = true ; 735} else if ( lowerword == "absolute-path" ) { 736AbsolutePath = true ; 737} else if ( lowerword == "auto-sampled-textures" ) { 738autoSampledTextures = true ; 739} else if ( lowerword == "invert-y" || // synonyms 740lowerword == "iy" ) { 741Options |= EOptionInvertY ; 742} else if ( lowerword == "keep-uncalled" || // synonyms 743lowerword == "ku" ) { 744Options |= EOptionKeepUncalled ; 745} else if ( lowerword == "nan-clamp" ) { 746NaNClamp = true ; 747} else if ( lowerword == "no-storage-format" || // synonyms 748lowerword == "nsf" ) { 749Options |= EOptionNoStorageFormat ; 750} else if ( lowerword == "preamble-text" || 751lowerword == "p" ) { 752if ( argc > 1 ) 753UserPreamble . addText ( argv [ 1 ]) ; 754else 755Error ( "expects <text>" , argv [ 0 ]) ; 756bumpArg () ; 757} else if ( lowerword == "relaxed-errors" ) { 758Options |= EOptionRelaxedErrors ; 759} else if ( lowerword == "reflect-strict-array-suffix" ) { 760ReflectOptions |= EShReflectionStrictArraySuffix ; 761} else if ( lowerword == "reflect-basic-array-suffix" ) { 762ReflectOptions |= EShReflectionBasicArraySuffix ; 763} else if ( lowerword == "reflect-intermediate-io" ) { 764ReflectOptions |= EShReflectionIntermediateIO ; 765} else if ( lowerword == "reflect-separate-buffers" ) { 766ReflectOptions |= EShReflectionSeparateBuffers ; 767} else if ( lowerword == "reflect-all-block-variables" ) { 768ReflectOptions |= EShReflectionAllBlockVariables ; 769} else if ( lowerword == "reflect-unwrap-io-blocks" ) { 770ReflectOptions |= EShReflectionUnwrapIOBlocks ; 771} else if ( lowerword == "reflect-all-io-variables" ) { 772ReflectOptions |= EShReflectionAllIOVariables ; 773} else if ( lowerword == "reflect-shared-std140-ubo" ) { 774ReflectOptions |= EShReflectionSharedStd140UBO ; 775} else if ( lowerword == "reflect-shared-std140-ssbo" ) { 776ReflectOptions |= EShReflectionSharedStd140SSBO ; 777} else if ( lowerword == "resource-set-bindings" || // synonyms 778lowerword == "resource-set-binding" || 779lowerword == "rsb" ) { 780ProcessResourceSetBindingBase ( argc , argv , baseResourceSetBinding ) ; 781} else if ( lowerword == "set-block-storage" || 782lowerword == "sbs" ) { 783ProcessBlockStorage ( argc , argv , blockStorageOverrides ) ; 784} else if ( lowerword == "set-atomic-counter-block" || 785lowerword == "sacb" ) { 786ProcessGlobalBlockSettings ( argc , argv , & atomicCounterBlockName , & atomicCounterBlockSet , nullptr ) ; 787setGlobalBufferBlock = true ; 788} else if ( lowerword == "set-default-uniform-block" || 789lowerword == "sdub" ) { 790ProcessGlobalBlockSettings ( argc , argv , & globalUniformName , & globalUniformSet , & globalUniformBinding ) ; 791setGlobalUniformBlock = true ; 792} else if ( lowerword == "shift-image-bindings" || // synonyms 793lowerword == "shift-image-binding" || 794lowerword == "sib" ) { 795ProcessBindingBase ( argc , argv , glslang :: EResImage ) ; 796} else if ( lowerword == "shift-sampler-bindings" || // synonyms 797lowerword == "shift-sampler-binding" || 798lowerword == "ssb" ) { 799ProcessBindingBase ( argc , argv , glslang :: EResSampler ) ; 800} else if ( lowerword == "shift-uav-bindings" || // synonyms 801lowerword == "shift-uav-binding" || 802lowerword == "suavb" ) { 803ProcessBindingBase ( argc , argv , glslang :: EResUav ) ; 804} else if ( lowerword == "shift-texture-bindings" || // synonyms 805lowerword == "shift-texture-binding" || 806lowerword == "stb" ) { 807ProcessBindingBase ( argc , argv , glslang :: EResTexture ) ; 808} else if ( lowerword == "shift-ubo-bindings" || // synonyms 809lowerword == "shift-ubo-binding" || 810lowerword == "shift-cbuffer-bindings" || 811lowerword == "shift-cbuffer-binding" || 812lowerword == "sub" || 813lowerword == "scb" ) { 814ProcessBindingBase ( argc , argv , glslang :: EResUbo ) ; 815} else if ( lowerword == "shift-ssbo-bindings" || // synonyms 816lowerword == "shift-ssbo-binding" || 817lowerword == "sbb" ) { 818ProcessBindingBase ( argc , argv , glslang :: EResSsbo ) ; 819} else if ( lowerword == "shift-combined-sampler-bindings" || 820lowerword == "shift-combined-sampler-binding" || 821lowerword == "scsb" ) { 822ProcessBindingBase ( argc , argv , glslang :: EResCombinedSampler ) ; 823} else if ( lowerword == "shift-as-bindings" || 824lowerword == "shift-as-binding" || 825lowerword == "sab" ) { 826ProcessBindingBase ( argc , argv , glslang :: EResAs ) ; 827} else if ( lowerword == "source-entrypoint" || // synonyms 828lowerword == "sep" ) { 829if ( argc <= 1 ) 830Error ( "no <entry-point> provided" , lowerword . c_str ()) ; 831sourceEntryPointName = argv [ 1 ] ; 832bumpArg () ; 833break ; 834} else if ( lowerword == "spirv-dis" ) { 835SpvToolsDisassembler = true ; 836} else if ( lowerword == "spirv-val" ) { 837SpvToolsValidate = true ; 838} else if ( lowerword == "stdin" ) { 839Options |= EOptionStdin ; 840shaderStageName = argv [ 1 ] ; 841} else if ( lowerword == "suppress-warnings" ) { 842Options |= EOptionSuppressWarnings ; 843} else if ( lowerword == "target-env" ) { 844if ( argc > 1 ) { 845if ( strcmp ( argv [ 1 ] , "vulkan1.0" ) == 0 ) { 846setVulkanSpv () ; 847ClientVersion = glslang :: EShTargetVulkan_1_0 ; 848} else if ( strcmp ( argv [ 1 ] , "vulkan1.1" ) == 0 ) { 849setVulkanSpv () ; 850ClientVersion = glslang :: EShTargetVulkan_1_1 ; 851} else if ( strcmp ( argv [ 1 ] , "vulkan1.2" ) == 0 ) { 852setVulkanSpv () ; 853ClientVersion = glslang :: EShTargetVulkan_1_2 ; 854} else if ( strcmp ( argv [ 1 ] , "vulkan1.3" ) == 0 ) { 855setVulkanSpv () ; 856ClientVersion = glslang :: EShTargetVulkan_1_3 ; 857} else if ( strcmp ( argv [ 1 ] , "vulkan1.4" ) == 0 ) { 858setVulkanSpv () ; 859ClientVersion = glslang :: EShTargetVulkan_1_4 ; 860} else if ( strcmp ( argv [ 1 ] , "opengl" ) == 0 ) { 861setOpenGlSpv () ; 862ClientVersion = glslang :: EShTargetOpenGL_450 ; 863} else if ( strcmp ( argv [ 1 ] , "spirv1.0" ) == 0 ) { 864TargetLanguage = glslang :: EShTargetSpv ; 865TargetVersion = glslang :: EShTargetSpv_1_0 ; 866} else if ( strcmp ( argv [ 1 ] , "spirv1.1" ) == 0 ) { 867TargetLanguage = glslang :: EShTargetSpv ; 868TargetVersion = glslang :: EShTargetSpv_1_1 ; 869} else if ( strcmp ( argv [ 1 ] , "spirv1.2" ) == 0 ) { 870TargetLanguage = glslang :: EShTargetSpv ; 871TargetVersion = glslang :: EShTargetSpv_1_2 ; 872} else if ( strcmp ( argv [ 1 ] , "spirv1.3" ) == 0 ) { 873TargetLanguage = glslang :: EShTargetSpv ; 874TargetVersion = glslang :: EShTargetSpv_1_3 ; 875} else if ( strcmp ( argv [ 1 ] , "spirv1.4" ) == 0 ) { 876TargetLanguage = glslang :: EShTargetSpv ; 877TargetVersion = glslang :: EShTargetSpv_1_4 ; 878} else if ( strcmp ( argv [ 1 ] , "spirv1.5" ) == 0 ) { 879TargetLanguage = glslang :: EShTargetSpv ; 880TargetVersion = glslang :: EShTargetSpv_1_5 ; 881} else if ( strcmp ( argv [ 1 ] , "spirv1.6" ) == 0 ) { 882TargetLanguage = glslang :: EShTargetSpv ; 883TargetVersion = glslang :: EShTargetSpv_1_6 ; 884} else 885Error ( "--target-env expected one of: vulkan1.0, vulkan1.1, vulkan1.2, \n " 886"vulkan1.3, vulkan1.4, opengl, spirv1.0, spirv1.1, spirv1.2, spirv1.3, \n " 887"spirv1.4, spirv1.5 or spirv1.6" ) ; 888} 889bumpArg () ; 890} else if ( lowerword == "undef-macro" || 891lowerword == "u" ) { 892if ( argc > 1 ) 893UserPreamble . addUndef ( argv [ 1 ]) ; 894else 895Error ( "expects <name>" , argv [ 0 ]) ; 896bumpArg () ; 897} else if ( lowerword == "variable-name" || // synonyms 898lowerword == "vn" ) { 899Options |= EOptionOutputHexadecimal ; 900if ( argc <= 1 ) 901Error ( "no <C-variable-name> provided" , lowerword . c_str ()) ; 902variableName = argv [ 1 ] ; 903bumpArg () ; 904break ; 905} else if ( lowerword == "quiet" ) { 906beQuiet = true ; 907} else if ( lowerword == "depfile" ) { 908if ( argc <= 1 ) 909Error ( "no <depfile-name> provided" , lowerword . c_str ()) ; 910depencyFileName = argv [ 1 ] ; 911bumpArg () ; 912} else if ( lowerword == "version" ) { 913Options |= EOptionDumpVersions ; 914} else if ( lowerword == "no-link" ) { 915Options |= EOptionCompileOnly ; 916} else if ( lowerword == "error-column" ) { 917Options |= EOptionDisplayErrorColumn ; 918} else if ( lowerword == "lto" ) { 919Options |= EOptionLinkTimeOptimization ; 920} else if ( lowerword == "validate-io" ) { 921Options |= EOptionValidateCrossStageIO ; 922} else if ( lowerword == "bindings-per-resource-type" ) { 923Options |= EOptionBindingsPerResourceType ; 924} else if ( lowerword == "help" ) { 925usage () ; 926break ; 927} else { 928Error ( "unrecognized command-line option" , argv [ 0 ]) ; 929} 930} 931break ; 932case 'C' : 933Options |= EOptionCascadingErrors ; 934break ; 935case 'D' : 936if ( argv [ 0 ][ 2 ] == 0 ) 937Options |= EOptionReadHlsl ; 938else 939UserPreamble . addDef ( getStringOperand ( "-D<name[=def]>" )) ; 940break ; 941case 'u' : 942uniformLocationOverrides . push_back ( getUniformOverride ()) ; 943break ; 944case 'E' : 945Options |= EOptionOutputPreprocessed ; 946break ; 947case 'G' : 948// OpenGL client 949setOpenGlSpv () ; 950if ( argv [ 0 ][ 2 ] != 0 ) 951ClientInputSemanticsVersion = getAttachedNumber ( "-G<num> client input semantics" ) ; 952if ( ClientInputSemanticsVersion != 100 ) 953Error ( "unknown client version for -G, should be 100" ) ; 954break ; 955case 'H' : 956Options |= EOptionHumanReadableSpv ; 957if (( Options & EOptionSpv ) == 0 ) { 958// default to Vulkan 959setVulkanSpv () ; 960} 961break ; 962case 'I' : 963IncludeDirectoryList . push_back ( getStringOperand ( "-I<dir> include path" )) ; 964break ; 965case 'O' : 966if ( argv [ 0 ][ 2 ] == 'd' ) 967Options |= EOptionOptimizeDisable ; 968else if ( argv [ 0 ][ 2 ] == 's' ) 969#if ENABLE_OPT 970Options |= EOptionOptimizeSize ; 971#else 972Error ( "-Os not available; optimizer not linked" ) ; 973#endif 974else 975Error ( "unknown -O option" ) ; 976break ; 977case 'P' : 978UserPreamble . addText ( getStringOperand ( "-P<text>" )) ; 979break ; 980case 'R' : 981VulkanRulesRelaxed = true ; 982break ; 983case 'S' : 984if ( argc <= 1 ) 985Error ( "no <stage> specified for -S" ) ; 986shaderStageName = argv [ 1 ] ; 987bumpArg () ; 988break ; 989case 'U' : 990UserPreamble . addUndef ( getStringOperand ( "-U<name>" )) ; 991break ; 992case 'V' : 993setVulkanSpv () ; 994if ( argv [ 0 ][ 2 ] != 0 ) 995ClientInputSemanticsVersion = getAttachedNumber ( "-V<num> client input semantics" ) ; 996if ( ClientInputSemanticsVersion != 100 ) 997Error ( "unknown client version for -V, should be 100" ) ; 998break ; 999case 'c' : 1000Options |= EOptionDumpConfig ; 1001break ; 1002case 'd' : 1003if ( strncmp ( & argv [ 0 ][ 1 ] , "dumpversion" , strlen ( & argv [ 0 ][ 1 ]) + 1 ) == 0 || 1004strncmp ( & argv [ 0 ][ 1 ] , "dumpfullversion" , strlen ( & argv [ 0 ][ 1 ]) + 1 ) == 0 ) 1005Options |= EOptionDumpBareVersion ; 1006else 1007Options |= EOptionDefaultDesktop ; 1008break ; 1009case 'e' : 1010entryPointName = argv [ 1 ] ; 1011if ( argc <= 1 ) 1012Error ( "no <name> provided for -e" ) ; 1013bumpArg () ; 1014break ; 1015case 'f' : 1016if ( strcmp ( & argv [ 0 ][ 2 ] , "hlsl_functionality1" ) == 0 ) 1017targetHlslFunctionality1 = true ; 1018else 1019Error ( "-f: expected hlsl_functionality1" ) ; 1020break ; 1021case 'g' : 1022// Override previous -g or -g0 argument 1023stripDebugInfo = false ; 1024emitNonSemanticShaderDebugInfo = false ; 1025Options &= ~ EOptionDebug ; 1026if ( argv [ 0 ][ 2 ] == '0' ) 1027stripDebugInfo = true ; 1028else { 1029Options |= EOptionDebug ; 1030if ( argv [ 0 ][ 2 ] == 'V' ) { 1031emitNonSemanticShaderDebugInfo = true ; 1032if ( argv [ 0 ][ 3 ] == 'S' ) { 1033emitNonSemanticShaderDebugSource = true ; 1034} else { 1035emitNonSemanticShaderDebugSource = false ; 1036} 1037} 1038} 1039break ; 1040case 'h' : 1041usage () ; 1042break ; 1043case 'i' : 1044Options |= EOptionIntermediate ; 1045break ; 1046case 'l' : 1047Options |= EOptionLinkProgram ; 1048break ; 1049case 'm' : 1050Options |= EOptionMemoryLeakMode ; 1051break ; 1052case 'o' : 1053if ( argc <= 1 ) 1054Error ( "no <file> provided for -o" ) ; 1055binaryFileName = argv [ 1 ] ; 1056bumpArg () ; 1057break ; 1058case 'q' : 1059Options |= EOptionDumpReflection ; 1060break ; 1061case 'r' : 1062Options |= EOptionRelaxedErrors ; 1063break ; 1064case 's' : 1065Options |= EOptionSuppressInfolog ; 1066break ; 1067case 't' : 1068Options |= EOptionMultiThreaded ; 1069break ; 1070case 'v' : 1071Options |= EOptionDumpVersions ; 1072break ; 1073case 'w' : 1074Options |= EOptionSuppressWarnings ; 1075break ; 1076case 'x' : 1077Options |= EOptionOutputHexadecimal ; 1078break ; 1079default : 1080Error ( "unrecognized command-line option" , argv [ 0 ]) ; 1081break ; 1082} 1083} else { 1084std :: string name ( argv [ 0 ]) ; 1085if ( ! SetConfigFile ( name )) { 1086workItems . push_back ( std :: unique_ptr < glslang :: TWorkItem > ( new glslang :: TWorkItem ( name ))) ; 1087} 1088} 1089} 1090 1091// Make sure that -S is always specified if --stdin is specified 1092if (( Options & EOptionStdin ) && shaderStageName == nullptr ) 1093Error ( "must provide -S when --stdin is given" ) ; 1094 1095// Make sure that -E is not specified alongside linking (which includes SPV generation) 1096// Or things that require linking 1097if ( Options & EOptionOutputPreprocessed ) { 1098if ( Options & EOptionLinkProgram ) 1099Error ( "can't use -E when linking is selected" ) ; 1100if ( Options & EOptionDumpReflection ) 1101Error ( "reflection requires linking, which can't be used when -E when is selected" ) ; 1102} 1103 1104// reflection requires linking 1105if (( Options & EOptionDumpReflection ) && ! ( Options & EOptionLinkProgram )) 1106Error ( "reflection requires -l for linking" ) ; 1107 1108// link time optimization makes no sense unless linking 1109if (( Options & EOptionLinkTimeOptimization ) && ! ( Options & EOptionLinkProgram )) 1110Error ( "link time optimization requires -l for linking" ) ; 1111 1112// cross stage IO validation makes no sense unless linking 1113if (( Options & EOptionValidateCrossStageIO ) && ! ( Options & EOptionLinkProgram )) 1114Error ( "cross stage IO validation requires -l for linking" ) ; 1115 1116// -o or -x makes no sense if there is no target binary 1117if ( binaryFileName && ( Options & EOptionSpv ) == 0 ) 1118Error ( "no binary generation requested (e.g., -V)" ) ; 1119 1120if (( Options & EOptionFlattenUniformArrays ) != 0 && 1121( Options & EOptionReadHlsl ) == 0 ) 1122Error ( "uniform array flattening only valid when compiling HLSL source." ) ; 1123 1124if (( Options & EOptionReadHlsl ) && ( Client == glslang :: EShClientOpenGL )) { 1125Error ( "Using HLSL input under OpenGL semantics is not currently supported." ) ; 1126} 1127 1128// rationalize client and target language 1129if ( TargetLanguage == glslang :: EShTargetNone ) { 1130switch ( ClientVersion ) { 1131case glslang :: EShTargetVulkan_1_0 : 1132TargetLanguage = glslang :: EShTargetSpv ; 1133TargetVersion = glslang :: EShTargetSpv_1_0 ; 1134break ; 1135case glslang :: EShTargetVulkan_1_1 : 1136TargetLanguage = glslang :: EShTargetSpv ; 1137TargetVersion = glslang :: EShTargetSpv_1_3 ; 1138break ; 1139case glslang :: EShTargetVulkan_1_2 : 1140TargetLanguage = glslang :: EShTargetSpv ; 1141TargetVersion = glslang :: EShTargetSpv_1_5 ; 1142break ; 1143case glslang :: EShTargetVulkan_1_3 : 1144TargetLanguage = glslang :: EShTargetSpv ; 1145TargetVersion = glslang :: EShTargetSpv_1_6 ; 1146break ; 1147case glslang :: EShTargetVulkan_1_4 : 1148TargetLanguage = glslang :: EShTargetSpv ; 1149TargetVersion = glslang :: EShTargetSpv_1_6 ; 1150break ; 1151case glslang :: EShTargetOpenGL_450 : 1152TargetLanguage = glslang :: EShTargetSpv ; 1153TargetVersion = glslang :: EShTargetSpv_1_0 ; 1154break ; 1155default : 1156break ; 1157} 1158} 1159if ( TargetLanguage != glslang :: EShTargetNone && Client == glslang :: EShClientNone ) 1160Error ( "To generate SPIR-V, also specify client semantics. See -G and -V." ) ; 1161} 1162 1163// 1164// Translate the meaningful subset of command-line options to parser-behavior options. 1165// 1166void SetMessageOptions ( EShMessages & messages ) 1167{ 1168if ( Options & EOptionRelaxedErrors ) 1169messages = ( EShMessages )( messages | EShMsgRelaxedErrors ) ; 1170if ( Options & EOptionIntermediate ) 1171messages = ( EShMessages )( messages | EShMsgAST ) ; 1172if ( Options & EOptionSuppressWarnings ) 1173messages = ( EShMessages )( messages | EShMsgSuppressWarnings ) ; 1174if ( Options & EOptionSpv ) 1175messages = ( EShMessages )( messages | EShMsgSpvRules ) ; 1176if ( Options & EOptionVulkanRules ) 1177messages = ( EShMessages )( messages | EShMsgVulkanRules ) ; 1178if ( Options & EOptionOutputPreprocessed ) 1179messages = ( EShMessages )( messages | EShMsgOnlyPreprocessor ) ; 1180if ( Options & EOptionReadHlsl ) 1181messages = ( EShMessages )( messages | EShMsgReadHlsl ) ; 1182if ( Options & EOptionCascadingErrors ) 1183messages = ( EShMessages )( messages | EShMsgCascadingErrors ) ; 1184if ( Options & EOptionKeepUncalled ) 1185messages = ( EShMessages )( messages | EShMsgKeepUncalled ) ; 1186if ( Options & EOptionHlslOffsets ) 1187messages = ( EShMessages )( messages | EShMsgHlslOffsets ) ; 1188if ( Options & EOptionDebug ) 1189messages = ( EShMessages )( messages | EShMsgDebugInfo ) ; 1190if ( HlslEnable16BitTypes ) 1191messages = ( EShMessages )( messages | EShMsgHlslEnable16BitTypes ) ; 1192if (( Options & EOptionOptimizeDisable ) || ! ENABLE_OPT ) 1193messages = ( EShMessages )( messages | EShMsgHlslLegalization ) ; 1194if ( HlslDX9compatible ) 1195messages = ( EShMessages )( messages | EShMsgHlslDX9Compatible ) ; 1196if ( DumpBuiltinSymbols ) 1197messages = ( EShMessages )( messages | EShMsgBuiltinSymbolTable ) ; 1198if ( EnhancedMsgs ) 1199messages = ( EShMessages )( messages | EShMsgEnhanced ) ; 1200if ( AbsolutePath ) 1201messages = ( EShMessages )( messages | EShMsgAbsolutePath ) ; 1202if ( Options & EOptionDisplayErrorColumn ) 1203messages = ( EShMessages )( messages | EShMsgDisplayErrorColumn ) ; 1204if ( Options & EOptionLinkTimeOptimization ) 1205messages = ( EShMessages )( messages | EShMsgLinkTimeOptimization ) ; 1206if ( Options & EOptionValidateCrossStageIO ) 1207messages = ( EShMessages )( messages | EShMsgValidateCrossStageIO ) ; 1208} 1209 1210// 1211// Thread entry point, for non-linking asynchronous mode. 1212// 1213void CompileShaders ( glslang :: TWorklist & worklist ) 1214{ 1215if ( Options & EOptionDebug ) 1216Error ( "cannot generate debug information unless linking to generate code" ) ; 1217 1218// NOTE: TWorkList::remove is thread-safe 1219glslang :: TWorkItem * workItem ; 1220if ( Options & EOptionStdin ) { 1221if ( worklist . remove ( workItem )) { 1222ShHandle compiler = ShConstructCompiler ( FindLanguage ( "stdin" ) , 0 ) ; 1223if ( compiler == nullptr ) 1224return ; 1225 1226CompileFile ( "stdin" , compiler ) ; 1227 1228if ( ! ( Options & EOptionSuppressInfolog )) 1229workItem -> results = ShGetInfoLog ( compiler ) ; 1230 1231ShDestruct ( compiler ) ; 1232} 1233} else { 1234while ( worklist . remove ( workItem )) { 1235ShHandle compiler = ShConstructCompiler ( FindLanguage ( workItem -> name ) , 0 ) ; 1236if ( compiler == nullptr ) 1237return ; 1238 1239 1240CompileFile ( workItem -> name . c_str () , compiler ) ; 1241 1242if ( ! ( Options & EOptionSuppressInfolog )) 1243workItem -> results = ShGetInfoLog ( compiler ) ; 1244 1245ShDestruct ( compiler ) ; 1246} 1247} 1248} 1249 1250// Outputs the given string, but only if it is non-null and non-empty. 1251// This prevents erroneous newlines from appearing. 1252void PutsIfNonEmpty ( const char * str ) 1253{ 1254if ( str && str [ 0 ]) { 1255puts ( str ) ; 1256} 1257} 1258 1259// Outputs the given string to stderr, but only if it is non-null and non-empty. 1260// This prevents erroneous newlines from appearing. 1261void StderrIfNonEmpty ( const char * str ) 1262{ 1263if ( str && str [ 0 ]) 1264fprintf ( stderr , "%s \n " , str ) ; 1265} 1266 1267// Simple bundling of what makes a compilation unit for ease in passing around, 1268// and separation of handling file IO versus API (programmatic) compilation. 1269struct ShaderCompUnit { 1270EShLanguage stage ; 1271static const int maxCount = 1 ; 1272int count ; // live number of strings/names 1273const char * text [ maxCount ] ; // memory owned/managed externally 1274std :: string fileName [ maxCount ] ; // hold's the memory, but... 1275const char * fileNameList [ maxCount ] ; // downstream interface wants pointers 1276 1277ShaderCompUnit ( EShLanguage stage ) : stage ( stage ) , count ( 0 ) { } 1278 1279ShaderCompUnit ( const ShaderCompUnit & rhs ) 1280{ 1281stage = rhs . stage ; 1282count = rhs . count ; 1283for ( int i = 0 ; i < count ; ++ i ) { 1284fileName [ i ] = rhs . fileName [ i ] ; 1285text [ i ] = rhs . text [ i ] ; 1286fileNameList [ i ] = rhs . fileName [ i ] . c_str () ; 1287} 1288} 1289 1290void addString ( std :: string & ifileName , const char * itext ) 1291{ 1292assert ( count < maxCount ) ; 1293fileName [ count ] = ifileName ; 1294text [ count ] = itext ; 1295fileNameList [ count ] = fileName [ count ] . c_str () ; 1296++ count ; 1297} 1298} ; 1299 1300// Writes a string into a depfile, escaping some special characters following the Makefile rules. 1301static void writeEscapedDepString ( std :: ofstream & file , const std :: string & str ) 1302{ 1303for ( char c : str ) { 1304switch ( c ) { 1305case ' ' : 1306case ':' : 1307case '#' : 1308case '[' : 1309case ']' : 1310case ' \\ ' : 1311file << ' \\ ' ; 1312break ; 1313case '$' : 1314file << '$' ; 1315break ; 1316} 1317file << c ; 1318} 1319} 1320 1321// Writes a depfile similar to gcc -MMD foo.c 1322bool writeDepFile ( std :: string depfile , std :: vector < std :: string >& binaryFiles , const std :: vector < std :: string >& sources ) 1323{ 1324std :: ofstream file ( depfile ) ; 1325if ( file . fail ()) 1326return false ; 1327 1328for ( auto binaryFile = binaryFiles . begin () ; binaryFile != binaryFiles . end () ; binaryFile ++ ) { 1329writeEscapedDepString ( file , * binaryFile ) ; 1330file << ":" ; 1331for ( auto sourceFile = sources . begin () ; sourceFile != sources . end () ; sourceFile ++ ) { 1332file << " " ; 1333writeEscapedDepString ( file , * sourceFile ) ; 1334} 1335file << std :: endl ; 1336} 1337return true ; 1338} 1339 1340// 1341// For linking mode: Will independently parse each compilation unit, but then put them 1342// in the same program and link them together, making at most one linked module per 1343// pipeline stage. 1344// 1345// Uses the new C++ interface instead of the old handle-based interface. 1346// 1347 1348void CompileAndLinkShaderUnits ( std :: vector < ShaderCompUnit > compUnits ) 1349{ 1350// keep track of what to free 1351std :: list < glslang :: TShader *> shaders ; 1352 1353EShMessages messages = EShMsgDefault ; 1354SetMessageOptions ( messages ) ; 1355 1356DirStackFileIncluder includer ; 1357std :: for_each ( IncludeDirectoryList . begin () , IncludeDirectoryList . end () , [ & includer ]( const std :: string & dir ) { 1358includer . pushExternalDirectory ( dir ) ; }) ; 1359 1360std :: vector < std :: string > sources ; 1361 1362// 1363// Per-shader processing... 1364// 1365 1366glslang :: TProgram & program = * new glslang :: TProgram ; 1367const bool compileOnly = ( Options & EOptionCompileOnly ) != 0 ; 1368for ( auto it = compUnits . cbegin () ; it != compUnits . cend () ; ++ it ) { 1369const auto & compUnit = * it ; 1370for ( int i = 0 ; i < compUnit . count ; i ++ ) { 1371sources . push_back ( compUnit . fileNameList [ i ]) ; 1372} 1373glslang :: TShader * shader = new glslang :: TShader ( compUnit . stage ) ; 1374shader -> setStringsWithLengthsAndNames ( compUnit . text , nullptr , compUnit . fileNameList , compUnit . count ) ; 1375if ( entryPointName ) 1376shader -> setEntryPoint ( entryPointName ) ; 1377if ( sourceEntryPointName ) { 1378if ( entryPointName == nullptr ) 1379printf ( "Warning: Changing source entry point name without setting an entry-point name. \n " 1380"Use '-e <name>'. \n " ) ; 1381shader -> setSourceEntryPoint ( sourceEntryPointName ) ; 1382} 1383 1384if ( compileOnly ) 1385shader -> setCompileOnly () ; 1386 1387shader -> setOverrideVersion ( GlslVersion ) ; 1388 1389std :: string intrinsicString = getIntrinsic ( compUnit . text , compUnit . count ) ; 1390 1391PreambleString = "" ; 1392if ( UserPreamble . isSet ()) 1393PreambleString . append ( UserPreamble . get ()) ; 1394 1395if ( ! intrinsicString . empty ()) 1396PreambleString . append ( intrinsicString ) ; 1397 1398shader -> setPreamble ( PreambleString . c_str ()) ; 1399shader -> addProcesses ( Processes ) ; 1400 1401// Set IO mapper binding shift values 1402for ( int r = 0 ; r < glslang :: EResCount ; ++ r ) { 1403const glslang :: TResourceType res = glslang :: TResourceType ( r ) ; 1404 1405// Set base bindings 1406shader -> setShiftBinding ( res , baseBinding [ res ][ compUnit . stage ]) ; 1407 1408// Set bindings for particular resource sets 1409// TODO: use a range based for loop here, when available in all environments. 1410for ( auto i = baseBindingForSet [ res ][ compUnit . stage ] . begin () ; 1411i != baseBindingForSet [ res ][ compUnit . stage ] . end () ; ++ i ) 1412shader -> setShiftBindingForSet ( res , i -> second , i -> first ) ; 1413} 1414shader -> setNoStorageFormat (( Options & EOptionNoStorageFormat ) != 0 ) ; 1415shader -> setResourceSetBinding ( baseResourceSetBinding [ compUnit . stage ]) ; 1416 1417if ( autoSampledTextures ) 1418shader -> setTextureSamplerTransformMode ( EShTexSampTransUpgradeTextureRemoveSampler ) ; 1419 1420if ( Options & EOptionAutoMapBindings ) 1421shader -> setAutoMapBindings ( true ) ; 1422 1423if ( Options & EOptionAutoMapLocations ) 1424shader -> setAutoMapLocations ( true ) ; 1425 1426for ( auto & uniOverride : uniformLocationOverrides ) { 1427shader -> addUniformLocationOverride ( uniOverride . first . c_str () , 1428uniOverride . second ) ; 1429} 1430 1431shader -> setUniformLocationBase ( uniformBase ) ; 1432 1433if ( VulkanRulesRelaxed ) { 1434for ( auto & storageOverride : blockStorageOverrides ) { 1435shader -> addBlockStorageOverride ( storageOverride . first . c_str () , 1436storageOverride . second ) ; 1437} 1438 1439if ( setGlobalBufferBlock ) { 1440shader -> setAtomicCounterBlockName ( atomicCounterBlockName . c_str ()) ; 1441shader -> setAtomicCounterBlockSet ( atomicCounterBlockSet ) ; 1442} 1443 1444if ( setGlobalUniformBlock ) { 1445shader -> setGlobalUniformBlockName ( globalUniformName . c_str ()) ; 1446shader -> setGlobalUniformSet ( globalUniformSet ) ; 1447shader -> setGlobalUniformBinding ( globalUniformBinding ) ; 1448} 1449} 1450 1451shader -> setNanMinMaxClamp ( NaNClamp ) ; 1452 1453#ifdef ENABLE_HLSL 1454shader -> setFlattenUniformArrays (( Options & EOptionFlattenUniformArrays ) != 0 ) ; 1455if ( Options & EOptionHlslIoMapping ) 1456shader -> setHlslIoMapping ( true ) ; 1457#endif 1458 1459if ( Options & EOptionInvertY ) 1460shader -> setInvertY ( true ) ; 1461 1462if ( HlslDxPositionW ) 1463shader -> setDxPositionW ( true ) ; 1464 1465if ( EnhancedMsgs ) 1466shader -> setEnhancedMsgs () ; 1467 1468if ( emitNonSemanticShaderDebugInfo ) 1469shader -> setDebugInfo ( true ) ; 1470 1471if ( Options & EOptionBindingsPerResourceType ) 1472shader -> setBindingsPerResourceType () ; 1473 1474// Set up the environment, some subsettings take precedence over earlier 1475// ways of setting things. 1476if ( Options & EOptionSpv ) { 1477shader -> setEnvInput (( Options & EOptionReadHlsl ) ? glslang :: EShSourceHlsl 1478: glslang :: EShSourceGlsl , 1479compUnit . stage , Client , ClientInputSemanticsVersion ) ; 1480shader -> setEnvClient ( Client , ClientVersion ) ; 1481shader -> setEnvTarget ( TargetLanguage , TargetVersion ) ; 1482#ifdef ENABLE_HLSL 1483if ( targetHlslFunctionality1 ) 1484shader -> setEnvTargetHlslFunctionality1 () ; 1485#endif 1486if ( VulkanRulesRelaxed ) 1487shader -> setEnvInputVulkanRulesRelaxed () ; 1488} 1489 1490shaders . push_back ( shader ) ; 1491 1492const int defaultVersion = Options & EOptionDefaultDesktop ? 110 : 100 ; 1493 1494if ( Options & EOptionOutputPreprocessed ) { 1495std :: string str ; 1496if ( shader -> preprocess ( GetResources () , defaultVersion , ENoProfile , false , false , messages , & str , includer )) { 1497PutsIfNonEmpty ( str . c_str ()) ; 1498} else { 1499CompileFailed = 1 ; 1500} 1501StderrIfNonEmpty ( shader -> getInfoLog ()) ; 1502StderrIfNonEmpty ( shader -> getInfoDebugLog ()) ; 1503continue ; 1504} 1505 1506if ( ! shader -> parse ( GetResources () , defaultVersion , false , messages , includer )) 1507CompileFailed = 1 ; 1508 1509if ( ! compileOnly ) 1510program . addShader ( shader ) ; 1511 1512if ( ! ( Options & EOptionSuppressInfolog ) && 1513! ( Options & EOptionMemoryLeakMode )) { 1514if ( ! beQuiet ) 1515PutsIfNonEmpty ( compUnit . fileName [ 0 ] . c_str ()) ; 1516PutsIfNonEmpty ( shader -> getInfoLog ()) ; 1517PutsIfNonEmpty ( shader -> getInfoDebugLog ()) ; 1518} 1519} 1520 1521// 1522// Program-level processing... 1523// 1524 1525if ( ! compileOnly ) { 1526// Link 1527if ( ! ( Options & EOptionOutputPreprocessed ) && ! program . link ( messages )) 1528LinkFailed = true ; 1529 1530// Map IO 1531if ( Options & EOptionSpv ) { 1532if ( ! program . mapIO ()) 1533LinkFailed = true ; 1534} 1535 1536// Report 1537if ( ! ( Options & EOptionSuppressInfolog ) && ! ( Options & EOptionMemoryLeakMode )) { 1538PutsIfNonEmpty ( program . getInfoLog ()) ; 1539PutsIfNonEmpty ( program . getInfoDebugLog ()) ; 1540} 1541 1542// Reflect 1543if ( Options & EOptionDumpReflection ) { 1544program . buildReflection ( ReflectOptions ) ; 1545program . dumpReflection () ; 1546} 1547} 1548 1549std :: vector < std :: string > outputFiles ; 1550 1551// Dump SPIR-V 1552if ( Options & EOptionSpv ) { 1553#ifdef ENABLE_SPIRV 1554CompileOrLinkFailed . fetch_or ( CompileFailed ) ; 1555CompileOrLinkFailed . fetch_or ( LinkFailed ) ; 1556if ( static_cast < bool > ( CompileOrLinkFailed . load ())) 1557printf ( "SPIR-V is not generated for failed compile or link \n " ) ; 1558else { 1559std :: vector < glslang :: TIntermediate *> intermediates ; 1560if ( ! compileOnly ) { 1561for ( int stage = 0 ; stage < EShLangCount ; ++ stage ) { 1562if ( auto * i = program . getIntermediate (( EShLanguage ) stage )) { 1563intermediates . emplace_back ( i ) ; 1564} 1565} 1566} else { 1567for ( const auto * shader : shaders ) { 1568if ( auto * i = shader -> getIntermediate ()) { 1569intermediates . emplace_back ( i ) ; 1570} 1571} 1572} 1573for ( auto * intermediate : intermediates ) { 1574std :: vector < unsigned int > spirv ; 1575spv :: SpvBuildLogger logger ; 1576glslang :: SpvOptions spvOptions ; 1577if ( Options & EOptionDebug ) { 1578spvOptions . generateDebugInfo = true ; 1579if ( emitNonSemanticShaderDebugInfo ) { 1580spvOptions . emitNonSemanticShaderDebugInfo = true ; 1581if ( emitNonSemanticShaderDebugSource ) { 1582spvOptions . emitNonSemanticShaderDebugSource = true ; 1583} 1584} 1585} else if ( stripDebugInfo ) 1586spvOptions . stripDebugInfo = true ; 1587spvOptions . disableOptimizer = ( Options & EOptionOptimizeDisable ) != 0 ; 1588spvOptions . optimizeSize = ( Options & EOptionOptimizeSize ) != 0 ; 1589spvOptions . disassemble = SpvToolsDisassembler ; 1590spvOptions . validate = SpvToolsValidate ; 1591spvOptions . compileOnly = compileOnly ; 1592glslang :: GlslangToSpv ( * intermediate , spirv , & logger , & spvOptions ) ; 1593 1594// Dump the spv to a file or stdout, etc., but only if not doing 1595// memory/perf testing, as it's not internal to programmatic use. 1596if ( ! ( Options & EOptionMemoryLeakMode )) { 1597printf ( "%s" , logger . getAllMessages () . c_str ()) ; 1598const auto filename = GetBinaryName ( intermediate -> getStage ()) ; 1599if ( Options & EOptionOutputHexadecimal ) { 1600if ( ! glslang :: OutputSpvHex ( spirv , filename , variableName )) 1601exit ( EFailUsage ) ; 1602} else { 1603if ( ! glslang :: OutputSpvBin ( spirv , filename )) 1604exit ( EFailUsage ) ; 1605} 1606 1607outputFiles . push_back ( filename ) ; 1608if ( ! SpvToolsDisassembler && ( Options & EOptionHumanReadableSpv )) 1609spv :: Disassemble ( std :: cout , spirv ) ; 1610} 1611} 1612} 1613#else 1614Error ( "This configuration of glslang does not have SPIR-V support" ) ; 1615#endif 1616} 1617 1618CompileOrLinkFailed . fetch_or ( CompileFailed ) ; 1619CompileOrLinkFailed . fetch_or ( LinkFailed ) ; 1620if ( depencyFileName && ! static_cast < bool > ( CompileOrLinkFailed . load ())) { 1621std :: set < std :: string > includedFiles = includer . getIncludedFiles () ; 1622sources . insert ( sources . end () , includedFiles . begin () , includedFiles . end ()) ; 1623 1624writeDepFile ( depencyFileName , outputFiles , sources ) ; 1625} 1626 1627// Free everything up, program has to go before the shaders 1628// because it might have merged stuff from the shaders, and 1629// the stuff from the shaders has to have its destructors called 1630// before the pools holding the memory in the shaders is freed. 1631delete & program ; 1632while ( shaders . size () > 0 ) { 1633delete shaders . back () ; 1634shaders . pop_back () ; 1635} 1636} 1637 1638// 1639// Do file IO part of compile and link, handing off the pure 1640// API/programmatic mode to CompileAndLinkShaderUnits(), which can 1641// be put in a loop for testing memory footprint and performance. 1642// 1643// This is just for linking mode: meaning all the shaders will be put into the 1644// the same program linked together. 1645// 1646// This means there are a limited number of work items (not multi-threading mode) 1647// and that the point is testing at the linking level. Hence, to enable 1648// performance and memory testing, the actual compile/link can be put in 1649// a loop, independent of processing the work items and file IO. 1650// 1651void CompileAndLinkShaderFiles ( glslang :: TWorklist & Worklist ) 1652{ 1653std :: vector < ShaderCompUnit > compUnits ; 1654 1655// If this is using stdin, we can't really detect multiple different file 1656// units by input type. We need to assume that we're just being given one 1657// file of a certain type. 1658if (( Options & EOptionStdin ) != 0 ) { 1659ShaderCompUnit compUnit ( FindLanguage ( "stdin" )) ; 1660std :: istreambuf_iterator < char > begin ( std :: cin ) , end ; 1661std :: string tempString ( begin , end ) ; 1662char * fileText = strdup ( tempString . c_str ()) ; 1663std :: string fileName = "stdin" ; 1664compUnit . addString ( fileName , fileText ) ; 1665compUnits . push_back ( compUnit ) ; 1666} else { 1667// Transfer all the work items from to a simple list of 1668// of compilation units. (We don't care about the thread 1669// work-item distribution properties in this path, which 1670// is okay due to the limited number of shaders, know since 1671// they are all getting linked together.) 1672glslang :: TWorkItem * workItem ; 1673while ( Worklist . remove ( workItem )) { 1674ShaderCompUnit compUnit ( FindLanguage ( workItem -> name )) ; 1675char * fileText = ReadFileData ( workItem -> name . c_str ()) ; 1676if ( fileText == nullptr ) 1677usage () ; 1678compUnit . addString ( workItem -> name , fileText ) ; 1679compUnits . push_back ( compUnit ) ; 1680} 1681} 1682 1683// Actual call to programmatic processing of compile and link, 1684// in a loop for testing memory and performance. This part contains 1685// all the perf/memory that a programmatic consumer will care about. 1686for ( int i = 0 ; i < (( Options & EOptionMemoryLeakMode ) ? 100 : 1 ) ; ++ i ) { 1687for ( int j = 0 ; j < (( Options & EOptionMemoryLeakMode ) ? 100 : 1 ) ; ++ j ) 1688CompileAndLinkShaderUnits ( compUnits ) ; 1689 1690if ( Options & EOptionMemoryLeakMode ) 1691glslang :: OS_DumpMemoryCounters () ; 1692} 1693 1694// free memory from ReadFileData, which got stored in a const char* 1695// as the first string above 1696for ( auto it = compUnits . begin () ; it != compUnits . end () ; ++ it ) 1697FreeFileData ( const_cast < char *> ( it -> text [ 0 ])) ; 1698} 1699 1700int singleMain () 1701{ 1702glslang :: TWorklist workList ; 1703std :: for_each ( WorkItems . begin () , WorkItems . end () , [ & workList ]( std :: unique_ptr < glslang :: TWorkItem >& item ) { 1704assert ( item ) ; 1705workList . add ( item . get ()) ; 1706}) ; 1707 1708if ( Options & EOptionDumpConfig ) { 1709printf ( "%s" , GetDefaultTBuiltInResourceString () . c_str ()) ; 1710if ( workList . empty ()) 1711return ESuccess ; 1712} 1713 1714if ( Options & EOptionDumpBareVersion ) { 1715int spirvGeneratorVersion = 0 ; 1716#ifdef ENABLE_SPIRV 1717spirvGeneratorVersion = glslang :: GetSpirvGeneratorVersion () ; 1718#endif 1719printf ( "%d:%d.%d.%d%s \n " , spirvGeneratorVersion , GLSLANG_VERSION_MAJOR , GLSLANG_VERSION_MINOR , 1720GLSLANG_VERSION_PATCH , GLSLANG_VERSION_FLAVOR ) ; 1721if ( workList . empty ()) 1722return ESuccess ; 1723} else if ( Options & EOptionDumpVersions ) { 1724int spirvGeneratorVersion = 0 ; 1725#ifdef ENABLE_SPIRV 1726spirvGeneratorVersion = glslang :: GetSpirvGeneratorVersion () ; 1727#endif 1728printf ( "Glslang Version: %d:%d.%d.%d%s \n " , spirvGeneratorVersion , GLSLANG_VERSION_MAJOR , 1729GLSLANG_VERSION_MINOR , GLSLANG_VERSION_PATCH , GLSLANG_VERSION_FLAVOR ) ; 1730printf ( "ESSL Version: %s \n " , glslang :: GetEsslVersionString ()) ; 1731printf ( "GLSL Version: %s \n " , glslang :: GetGlslVersionString ()) ; 1732std :: string spirvVersion ; 1733#if ENABLE_SPIRV 1734glslang :: GetSpirvVersion ( spirvVersion ) ; 1735#endif 1736printf ( "SPIR-V Version %s \n " , spirvVersion . c_str ()) ; 1737printf ( "GLSL.std.450 Version %d, Revision %d \n " , GLSLstd450Version , GLSLstd450Revision ) ; 1738printf ( "Khronos Tool ID %d \n " , glslang :: GetKhronosToolId ()) ; 1739printf ( "SPIR-V Generator Version %d \n " , spirvGeneratorVersion ) ; 1740printf ( "GL_KHR_vulkan_glsl version %d \n " , 100 ) ; 1741printf ( "ARB_GL_gl_spirv version %d \n " , 100 ) ; 1742if ( workList . empty ()) 1743return ESuccess ; 1744} 1745 1746if ( workList . empty () && (( Options & EOptionStdin ) == 0 )) { 1747usage () ; 1748} 1749 1750if ( Options & EOptionStdin ) { 1751WorkItems . push_back ( std :: unique_ptr < glslang :: TWorkItem > { new glslang :: TWorkItem ( "stdin" )}) ; 1752workList . add ( WorkItems . back () . get ()) ; 1753} 1754 1755ProcessConfigFile () ; 1756 1757if (( Options & EOptionReadHlsl ) && ! (( Options & EOptionOutputPreprocessed ) || ( Options & EOptionSpv ))) 1758Error ( "HLSL requires SPIR-V code generation (or preprocessing only)" ) ; 1759 1760// 1761// Two modes: 1762// 1) linking all arguments together, single-threaded, new C++ interface 1763// 2) independent arguments, can be tackled by multiple asynchronous threads, for testing thread safety, using the old handle interface 1764// 1765if ( Options & ( EOptionLinkProgram | EOptionOutputPreprocessed )) { 1766glslang :: InitializeProcess () ; 1767glslang :: InitializeProcess () ; // also test reference counting of users 1768glslang :: InitializeProcess () ; // also test reference counting of users 1769glslang :: FinalizeProcess () ; // also test reference counting of users 1770glslang :: FinalizeProcess () ; // also test reference counting of users 1771CompileAndLinkShaderFiles ( workList ) ; 1772glslang :: FinalizeProcess () ; 1773} else { 1774ShInitialize () ; 1775ShInitialize () ; // also test reference counting of users 1776ShFinalize () ; // also test reference counting of users 1777 1778bool printShaderNames = workList . size () > 1 ; 1779 1780if ( Options & EOptionMultiThreaded ) { 1781std :: array < std :: thread , 16 > threads ; 1782for ( unsigned int t = 0 ; t < threads . size () ; ++ t ) { 1783threads [ t ] = std :: thread ( CompileShaders , std :: ref ( workList )) ; 1784if ( threads [ t ] . get_id () == std :: thread :: id ()) { 1785fprintf ( stderr , "Failed to create thread \n " ) ; 1786return EFailThreadCreate ; 1787} 1788} 1789 1790std :: for_each ( threads . begin () , threads . end () , []( std :: thread & t ) { t . join () ; }) ; 1791} else 1792CompileShaders ( workList ) ; 1793 1794// Print out all the resulting infologs 1795for ( size_t w = 0 ; w < WorkItems . size () ; ++ w ) { 1796if ( WorkItems [ w ]) { 1797if ( printShaderNames || WorkItems [ w ] -> results . size () > 0 ) 1798PutsIfNonEmpty ( WorkItems [ w ] -> name . c_str ()) ; 1799PutsIfNonEmpty ( WorkItems [ w ] -> results . c_str ()) ; 1800} 1801} 1802 1803ShFinalize () ; 1804} 1805 1806if ( CompileFailed . load ()) 1807return EFailCompile ; 1808if ( LinkFailed . load ()) 1809return EFailLink ; 1810 1811return 0 ; 1812} 1813 1814int C_DECL main ( int argc , char * argv []) 1815{ 1816ProcessArguments ( WorkItems , argc , argv ) ; 1817 1818int ret = 0 ; 1819 1820// Loop over the entire init/finalize cycle to watch memory changes 1821const int iterations = 1 ; 1822if ( iterations > 1 ) 1823glslang :: OS_DumpMemoryCounters () ; 1824for ( int i = 0 ; i < iterations ; ++ i ) { 1825ret = singleMain () ; 1826if ( iterations > 1 ) 1827glslang :: OS_DumpMemoryCounters () ; 1828} 1829 1830return ret ; 1831} 1832 1833// 1834// Deduce the language from the filename. Files must end in one of the 1835// following extensions: 1836// 1837// .vert = vertex 1838// .tesc = tessellation control 1839// .tese = tessellation evaluation 1840// .geom = geometry 1841// .frag = fragment 1842// .comp = compute 1843// .rgen = ray generation 1844// .rint = ray intersection 1845// .rahit = ray any hit 1846// .rchit = ray closest hit 1847// .rmiss = ray miss 1848// .rcall = ray callable 1849// .mesh = mesh 1850// .task = task 1851// Additionally, the file names may end in .<stage>.glsl and .<stage>.hlsl 1852// where <stage> is one of the stages listed above. 1853// 1854EShLanguage FindLanguage ( const std :: string & name , bool parseStageName ) 1855{ 1856std :: string stageName ; 1857if ( shaderStageName ) 1858stageName = shaderStageName ; 1859else if ( parseStageName ) { 1860// Note: "first" extension means "first from the end", i.e. 1861// if the file is named foo.vert.glsl, then "glsl" is first, 1862// "vert" is second. 1863size_t firstExtStart = name . find_last_of ( "." ) ; 1864bool hasFirstExt = firstExtStart != std :: string :: npos ; 1865size_t secondExtStart = hasFirstExt ? name . find_last_of ( "." , firstExtStart - 1 ) : std :: string :: npos ; 1866bool hasSecondExt = secondExtStart != std :: string :: npos ; 1867std :: string firstExt = name . substr ( firstExtStart + 1 , std :: string :: npos ) ; 1868bool usesUnifiedExt = hasFirstExt && ( firstExt == "glsl" || firstExt == "hlsl" ) ; 1869if ( usesUnifiedExt && firstExt == "hlsl" ) 1870Options |= EOptionReadHlsl ; 1871if ( hasFirstExt && ! usesUnifiedExt ) 1872stageName = firstExt ; 1873else if ( usesUnifiedExt && hasSecondExt ) 1874stageName = name . substr ( secondExtStart + 1 , firstExtStart - secondExtStart - 1 ) ; 1875else { 1876usage () ; 1877return EShLangVertex ; 1878} 1879} else 1880stageName = name ; 1881 1882if ( stageName == "vert" ) 1883return EShLangVertex ; 1884else if ( stageName == "tesc" ) 1885return EShLangTessControl ; 1886else if ( stageName == "tese" ) 1887return EShLangTessEvaluation ; 1888else if ( stageName == "geom" ) 1889return EShLangGeometry ; 1890else if ( stageName == "frag" ) 1891return EShLangFragment ; 1892else if ( stageName == "comp" ) 1893return EShLangCompute ; 1894else if ( stageName == "rgen" ) 1895return EShLangRayGen ; 1896else if ( stageName == "rint" ) 1897return EShLangIntersect ; 1898else if ( stageName == "rahit" ) 1899return EShLangAnyHit ; 1900else if ( stageName == "rchit" ) 1901return EShLangClosestHit ; 1902else if ( stageName == "rmiss" ) 1903return EShLangMiss ; 1904else if ( stageName == "rcall" ) 1905return EShLangCallable ; 1906else if ( stageName == "mesh" ) 1907return EShLangMesh ; 1908else if ( stageName == "task" ) 1909return EShLangTask ; 1910 1911usage () ; 1912return EShLangVertex ; 1913} 1914 1915// 1916// Read a file's data into a string, and compile it using the old interface ShCompile, 1917// for non-linkable results. 1918// 1919void CompileFile ( const char * fileName , ShHandle compiler ) 1920{ 1921int ret = 0 ; 1922char * shaderString ; 1923if (( Options & EOptionStdin ) != 0 ) { 1924std :: istreambuf_iterator < char > begin ( std :: cin ) , end ; 1925std :: string tempString ( begin , end ) ; 1926shaderString = strdup ( tempString . c_str ()) ; 1927} else { 1928shaderString = ReadFileData ( fileName ) ; 1929} 1930 1931// move to length-based strings, rather than null-terminated strings 1932int * lengths = new int [ 1 ] ; 1933lengths [ 0 ] = ( int ) strlen ( shaderString ) ; 1934 1935EShMessages messages = EShMsgDefault ; 1936SetMessageOptions ( messages ) ; 1937 1938if ( UserPreamble . isSet ()) 1939Error ( "-D, -U and -P options require -l (linking) \n " ) ; 1940 1941for ( int i = 0 ; i < (( Options & EOptionMemoryLeakMode ) ? 100 : 1 ) ; ++ i ) { 1942for ( int j = 0 ; j < (( Options & EOptionMemoryLeakMode ) ? 100 : 1 ) ; ++ j ) { 1943// ret = ShCompile(compiler, shaderStrings, NumShaderStrings, lengths, EShOptNone, &Resources, Options, (Options & EOptionDefaultDesktop) ? 110 : 100, false, messages); 1944ret = ShCompile ( compiler , & shaderString , 1 , nullptr , EShOptNone , GetResources () , 0 , 1945( Options & EOptionDefaultDesktop ) ? 110 : 100 , false , messages , fileName ) ; 1946// const char* multi[12] = { "# ve", "rsion", " 300 e", "s", "\n#err", 1947// "or should be l", "ine 1", "string 5\n", "float glo", "bal", 1948// ";\n#error should be line 2\n void main() {", "global = 2.3;}" }; 1949// const char* multi[7] = { "/", "/", "\\", "\n", "\n", "#", "version 300 es" }; 1950// ret = ShCompile(compiler, multi, 7, nullptr, EShOptNone, &Resources, Options, (Options & EOptionDefaultDesktop) ? 110 : 100, false, messages); 1951} 1952 1953if ( Options & EOptionMemoryLeakMode ) 1954glslang :: OS_DumpMemoryCounters () ; 1955} 1956 1957delete [] lengths ; 1958FreeFileData ( shaderString ) ; 1959 1960if ( ret == 0 ) 1961CompileFailed = true ; 1962} 1963 1964// 1965// print usage to stdout 1966// 1967void usage () 1968{ 1969printf ( "Usage: glslang [option]... [file]... \n " 1970" \n " 1971"'file' with one of the following three endings can be auto-classified: \n " 1972"1) .<stage>, where <stage> is one of: \n " 1973" vert for a vertex shader \n " 1974" tesc for a tessellation control shader \n " 1975" tese for a tessellation evaluation shader \n " 1976" geom for a geometry shader \n " 1977" frag for a fragment shader \n " 1978" comp for a compute shader \n " 1979" mesh for a mesh shader \n " 1980" task for a task shader \n " 1981" rgen for a ray generation shader \n " 1982" rint for a ray intersection shader \n " 1983" rahit for a ray any hit shader \n " 1984" rchit for a ray closest hit shader \n " 1985" rmiss for a ray miss shader \n " 1986" rcall for a ray callable shader \n " 1987"2) .<stage>.glsl or .<stage>.hlsl compound suffix, where stage options are \n " 1988" described above \n " 1989"3) .conf, to provide a config file that replaces the default configuration (see \n " 1990" -c option below for generating a template) \n " 1991" \n " 1992"Options: \n " 1993" -C cascading errors; risk crash from accumulation of error recoveries \n " 1994" -D input is HLSL (this is the default when any suffix is .hlsl) \n " 1995" -D<name[=def]> | --D <name[=def]> | --define-macro <name[=def]> \n " 1996" define a pre-processor macro \n " 1997" -E print pre-processed GLSL; cannot be used with -l; errors will \n " 1998" appear on stderr \n " 1999" -G[ver] create SPIR-V binary under OpenGL semantics; turns on -l; default \n " 2000" file name is <stage>.spv (-o overrides this); ver, when present, \n " 2001" is the version of the input semantics which will appear in \n " 2002" '#define GL_SPIRV ver'; --client opengl100 is the same as -G100; a \n " 2003" --target-env for OpenGL will also imply -G; currently only \n " 2004" supports GLSL \n " 2005" -H print human readable form of SPIR-V; turns on -V \n " 2006" -I<dir> add <dir> to the include search path; includer's directory is \n " 2007" searched first, followed by left-to-right order of -I \n " 2008" -Od disables optimization; may cause illegal SPIR-V for HLSL \n " 2009" -Os optimizes SPIR-V to minimize size \n " 2010" -P<text> | --P <text> | --preamble-text <text> \n " 2011" inject custom preamble text which is treated as if it appeared \n " 2012" immediately after the version declaration (if any) \n " 2013" -R use relaxed verification rules for generating Vulkan SPIR-V, \n " 2014" allowing the use of default uniforms, atomic_uints, and the \n " 2015" gl_VertexID and gl_InstanceID keywords \n " 2016" -S <stage> uses the specified <stage> rather than parsing the file extension; \n " 2017" choices for <stage> include vert, tesc, tese, geom, frag, and \n " 2018" comp; a full list of options is given above \n " 2019" -U<name> | --undef-macro <name> | --U <name> \n " 2020" undefine a pre-processor macro \n " 2021" -V[ver] create SPIR-V binary under Vulkan semantics; turns on -l; default \n " 2022" file name is <stage>.spv (-o overrides this); ver, when present, \n " 2023" is the version of the input semantics which will appear in \n " 2024" '#define VULKAN ver'; --client vulkan100 is the same as -V100; a \n " 2025" '--target-env' for Vulkan will also imply '-V' \n " 2026" -c configuration dump; creates the default configuration file \n " 2027" (redirect to a .conf file) \n " 2028" -d default to desktop (#version 110) when there is no shader #version \n " 2029" (default is ES version 100) \n " 2030" -e <name> | --entry-point <name> \n " 2031" specify <name> as the entry-point function name \n " 2032" -f{hlsl_functionality1} \n " 2033" 'hlsl_functionality1' enables use of the \n " 2034" SPV_GOOGLE_hlsl_functionality1 extension \n " 2035" -g generate debug information \n " 2036" -g0 strip debug information \n " 2037" -gV generate nonsemantic shader debug information \n " 2038" -gVS generate nonsemantic shader debug information with source \n " 2039" -h | --help print this usage message \n " 2040" -i intermediate tree (glslang AST) is printed out \n " 2041" -l link all input files together to form a single module \n " 2042" -m memory leak mode \n " 2043" -o <file> save binary to <file>; requires a binary option (e.g., -V) \n " 2044" -q dump reflection query database; requires -l for linking \n " 2045" -r | --relaxed-errors \n " 2046" relaxed GLSL semantic error-checking mode \n " 2047" -s silence syntax and semantic error reporting \n " 2048" -t multi-threaded mode \n " 2049" -u<name>:<loc> \n " 2050" specify a uniform location override for --aml \n " 2051" -v | --version \n " 2052" print version strings \n " 2053" -w | --suppress-warnings \n " 2054" suppress GLSL warnings, except as required by '#extension : warn' \n " 2055" -x save binary output as text-based 32-bit hexadecimal numbers \n " 2056" --absolute-path prints absolute path for messages \n " 2057" --auto-map-binding | --auto-map-bindings | --amb \n " 2058" automatically bind uniform variables without \n " 2059" explicit bindings \n " 2060" --auto-map-locations | --aml automatically locate input/output lacking \n " 2061" 'location' (fragile, not cross stage) \n " 2062" --auto-sampled-textures removes sampler variables and converts \n " 2063" existing textures to sampled textures \n " 2064" --client {vulkan<ver> | opengl<ver>} \n " 2065" see -V and -G \n " 2066" --depfile <file> writes depfile for build systems \n " 2067" --dump-builtin-symbols prints builtin symbol table prior each \n " 2068" compile \n " 2069" -dumpfullversion | -dumpversion print bare major.minor.patchlevel \n " 2070" --enhanced-msgs print more readable error messages (GLSL \n " 2071" only) \n " 2072" --error-column display the column of the error along the \n " 2073" line \n " 2074" --flatten-uniform-array | --flatten-uniform-arrays | --fua \n " 2075" flatten uniform texture/sampler arrays to \n " 2076" scalars \n " 2077" --glsl-version {100 | 110 | 120 | 130 | 140 | 150 | \n " 2078" 300es | 310es | 320es | 330 | \n " 2079" 400 | 410 | 420 | 430 | 440 | 450 | 460} \n " 2080" set GLSL version; overrides #version in \n " 2081" shader source \n " 2082" --hlsl-dx-position-w W component of SV_Position in HLSL fragment \n " 2083" shaders compatible with DirectX \n " 2084" --hlsl-dx9-compatible interprets sampler declarations as a \n " 2085" texture/sampler combo like DirectX9 would, \n " 2086" and recognizes DirectX9-specific semantics \n " 2087" --hlsl-enable-16bit-types allow 16-bit types in SPIR-V for HLSL \n " 2088" --hlsl-iomap | --hlsl-iomapper | --hlsl-iomapping \n " 2089" perform IO mapping in HLSL register space \n " 2090" --hlsl-offsets allow block offsets to follow HLSL rules; \n " 2091" works independently of source language \n " 2092" --invert-y | --iy invert position.Y output in vertex shader \n " 2093" --keep-uncalled | --ku don't eliminate uncalled functions \n " 2094" --lto perform link time optimization \n " 2095" --nan-clamp favor non-NaN operand in min, max, and clamp \n " 2096" --no-link only compile shader; do not link (GLSL only) \n " 2097" NOTE: this option will set the export \n " 2098" linkage attribute on all functions \n " 2099" --no-storage-format | --nsf use Unknown image format \n " 2100" --quiet do not print anything to stdout unless \n " 2101" requested by another option \n " 2102" --reflect-all-block-variables reflect all variables in blocks, whether \n " 2103" inactive or active \n " 2104" --reflect-basic-array-suffix arrays of basic types will have trailing [0] \n " 2105" --reflect-intermediate-io reflection includes inputs/outputs of linked \n " 2106" shaders rather than just vertex/fragment \n " 2107" --reflect-separate-buffers reflect buffer variables and blocks \n " 2108" separately to uniforms \n " 2109" --reflect-strict-array-suffix use strict array suffix rules when \n " 2110" reflecting \n " 2111" --reflect-unwrap-io-blocks unwrap input/output blocks the same as \n " 2112" uniform blocks \n " 2113" --resource-set-binding <stage> [name] <set> [binding]... \n " 2114" set descriptor set and binding for \n " 2115" individual resources \n " 2116" --resource-set-binding [stage] <set> \n " 2117" set descriptor set for all resources \n " 2118" --resource-set-bindings | --rsb synonyms for --resource-set-binding \n " 2119" --set-atomic-counter-block <name> <set> \n " 2120" set name and descriptor set for atomic \n " 2121" counter blocks with -R opt \n " 2122" --sacb synonym for set-atomic-counter-block \n " 2123" --set-block-backing name {uniform | buffer | push_constant} \n " 2124" changes the backing type of a uniform, \n " 2125" buffer, or push_constant block declared in \n " 2126" the program when using the -R option; this \n " 2127" can be used to change the backing for \n " 2128" existing blocks as well as implicit ones \n " 2129" such as 'gl_DefaultUniformBlock' \n " 2130" --set-default-uniform-block <name> <set> <binding> \n " 2131" set name, descriptor set, and binding for \n " 2132" global default-uniform-block with -R opt \n " 2133" --sdub synonym for set-default-uniform-block \n " 2134" --shift-image-binding [stage] <num> \n " 2135" base binding number for images (UAV) \n " 2136" --shift-image-binding [stage] <num> <set>... \n " 2137" per-descriptor-set shift values \n " 2138" --shift-image-bindings | --sib synonyms for --shift-image-binding \n " 2139" --shift-sampler-binding [stage] <num> \n " 2140" base binding number for samplers \n " 2141" --shift-sampler-binding [stage] <num> <set>... \n " 2142" per-descriptor-set shift values \n " 2143" --shift-sampler-bindings | --ssb synonyms for --shift-sampler-binding \n " 2144" --shift-ssbo-binding [stage] <num> \n " 2145" base binding number for SSBOs \n " 2146" --shift-ssbo-binding [stage] <num> <set>... \n " 2147" per-descriptor-set shift values \n " 2148" --shift-ssbo-bindings | --sbb synonyms for --shift-ssbo-binding \n " 2149" --shift-texture-binding [stage] <num> \n " 2150" base binding number for textures \n " 2151" --shift-texture-binding [stage] <num> <set>... \n " 2152" per-descriptor-set shift values \n " 2153" --shift-texture-bindings | --stb synonyms for --shift-texture-binding \n " 2154" --shift-uav-binding [stage] <num> base binding number for UAVs \n " 2155" --shift-uav-binding [stage] <num> <set>... \n " 2156" per-descriptor-set shift values \n " 2157" --shift-uav-bindings | --suavb synonyms for --shift-uav-binding \n " 2158" --shift-ubo-binding [stage] <num> base binding number for UBOs \n " 2159" --shift-ubo-binding [stage] <num> <set>... \n " 2160" per-descriptor-set shift values \n " 2161" --shift-ubo-bindings | --sub | \n " 2162" --shift-cbuffer-binding | --shift-cbuffer-bindings | --scb \n " 2163" synonyms for --shift-ubo-binding \n " 2164" --shift-combined-sampler-binding [stage] <num> \n " 2165" base binding number for combined samplers \n " 2166" --shift-combined-sampler-binding [stage] <num> <set>... \n " 2167" per-descriptor-set shift values \n " 2168" --shift-combined-sampler-bindings | --scsb \n " 2169" synonyms for --shift-combined-sampler-binding \n " 2170" --shift-as-binding [stage] <num> \n " 2171" base binding number for acceleration structures \n " 2172" --shift-as-binding [stage] <num> <set>... \n " 2173" per-descriptor-set shift values \n " 2174" --shift-as-bindings | --sab \n " 2175" synonyms for --shift-as-binding \n " 2176" --spirv-dis output standard-form disassembly; works only \n " 2177" when a SPIR-V generation option is also used \n " 2178" --spirv-val execute the SPIRV-Tools validator \n " 2179" --source-entrypoint <name> | --sep <name> \n " 2180" the given shader source function is renamed \n " 2181" to be the <name> given in -e \n " 2182" --stdin read from stdin instead of from a file; \n " 2183" requires providing the shader stage using -S \n " 2184" --target-env {vulkan1.0 | vulkan1.1 | vulkan1.2 | vulkan1.3 | vulkan1.4 | \n " 2185" opengl | spirv1.0 | spirv1.1 | spirv1.2 | spirv1.3 | \n " 2186" spirv1.4 | spirv1.5 | spirv1.6} \n " 2187" set the execution environment the generated \n " 2188" code will be executed in; defaults to: \n " 2189" * vulkan1.0 under --client vulkan<ver> \n " 2190" * opengl under --client opengl<ver> \n " 2191" * spirv1.0 under --target-env vulkan1.0 \n " 2192" * spirv1.3 under --target-env vulkan1.1 \n " 2193" * spirv1.5 under --target-env vulkan1.2 \n " 2194" * spirv1.6 under --target-env vulkan1.3 \n " 2195" * spirv1.6 under --target-env vulkan1.4 \n " 2196" multiple --target-env can be specified \n " 2197" --uniform-base <base> set a base to use for generated uniform \n " 2198" locations \n " 2199" --variable-name <name> | --vn <name> \n " 2200" creates a C header file that contains a \n " 2201" uint32_t array named <name> initialized with \n " 2202" the shader binary code \n " 2203" --validate-io validate cross stage IO \n " 2204" --bindings-per-resource-type \n " ) ; 2205 2206exit ( EFailUsage ) ; 2207} 2208 2209#if ! defined _MSC_VER && ! defined MINGW_HAS_SECURE_API 2210 2211#include <errno.h> 2212 2213int fopen_s ( 2214FILE ** pFile , 2215const char * filename , 2216const char * mode 2217) 2218{ 2219if ( ! pFile || ! filename || ! mode ) { 2220return EINVAL ; 2221} 2222 2223FILE * f = fopen ( filename , mode ) ; 2224if ( ! f ) { 2225if ( errno != 0 ) { 2226return errno ; 2227} else { 2228return ENOENT ; 2229} 2230} 2231* pFile = f ; 2232 2233return 0 ; 2234} 2235 2236#endif 2237 2238// 2239// Malloc a string of sufficient size and read a string into it. 2240// 2241char * ReadFileData ( const char * fileName ) 2242{ 2243FILE * in = nullptr ; 2244int errorCode = fopen_s ( & in , fileName , "r" ) ; 2245if ( errorCode || in == nullptr ) 2246Error ( "unable to open input file" ) ; 2247 2248int count = 0 ; 2249while ( fgetc ( in ) != EOF ) 2250count ++ ; 2251 2252fseek ( in , 0 , SEEK_SET ) ; 2253 2254if ( count > 3 ) { 2255unsigned char head [ 3 ] ; 2256if ( fread ( head , 1 , 3 , in ) == 3 ) { 2257if ( head [ 0 ] == 0xef && head [ 1 ] == 0xbb && head [ 2 ] == 0xbf ) { 2258// skip BOM 2259count -= 3 ; 2260} else { 2261fseek ( in , 0 , SEEK_SET ) ; 2262} 2263} else { 2264Error ( "can't read input file" ) ; 2265} 2266} 2267 2268char * return_data = ( char * ) malloc ( count + 1 ) ; // freed in FreeFileData() 2269if (( int ) fread ( return_data , 1 , count , in ) != count ) { 2270free ( return_data ) ; 2271Error ( "can't read input file" ) ; 2272} 2273 2274return_data [ count ] = ' \0 ' ; 2275fclose ( in ) ; 2276 2277return return_data ; 2278} 2279 2280void FreeFileData ( char * data ) 2281{ 2282free ( data ) ; 2283} 2284 2285void InfoLogMsg ( const char * msg , const char * name , const int num ) 2286{ 2287if ( num >= 0 ) 2288printf ( "#### %s %s %d INFO LOG #### \n " , msg , name , num ) ; 2289else 2290printf ( "#### %s %s INFO LOG #### \n " , msg , name ) ; 2291}