1 // Copyright (c) 2015-2016 The Khronos Group Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 #ifndef SOURCE_VAL_VALIDATION_STATE_H_ 16 #define SOURCE_VAL_VALIDATION_STATE_H_ 17 18 #include <algorithm> 19 #include <map> 20 #include <set> 21 #include <string> 22 #include <tuple> 23 #include <unordered_map> 24 #include <unordered_set> 25 #include <vector> 26 27 #include "source/assembly_grammar.h" 28 #include "source/diagnostic.h" 29 #include "source/disassemble.h" 30 #include "source/enum_set.h" 31 #include "source/latest_version_spirv_header.h" 32 #include "source/name_mapper.h" 33 #include "source/spirv_definition.h" 34 #include "source/spirv_validator_options.h" 35 #include "source/val/decoration.h" 36 #include "source/val/function.h" 37 #include "source/val/instruction.h" 38 #include "spirv-tools/libspirv.h" 39 40 namespace spvtools { 41 namespace val { 42 43 /// This enum represents the sections of a SPIRV module. See section 2.4 44 /// of the SPIRV spec for additional details of the order. The enumerant values 45 /// are in the same order as the vector returned by GetModuleOrder 46 enum ModuleLayoutSection { 47 kLayoutCapabilities, /// < Section 2.4 #1 48 kLayoutExtensions, /// < Section 2.4 #2 49 kLayoutExtInstImport, /// < Section 2.4 #3 50 kLayoutMemoryModel, /// < Section 2.4 #4 51 kLayoutSamplerImageAddressMode, /// < Section 2.4 #5 52 kLayoutEntryPoint, /// < Section 2.4 #6 53 kLayoutExecutionMode, /// < Section 2.4 #7 54 kLayoutDebug1, /// < Section 2.4 #8 > 1 55 kLayoutDebug2, /// < Section 2.4 #8 > 2 56 kLayoutDebug3, /// < Section 2.4 #8 > 3 57 kLayoutAnnotations, /// < Section 2.4 #9 58 kLayoutTypes, /// < Section 2.4 #10 59 kLayoutFunctionDeclarations, /// < Section 2.4 #11 60 kLayoutFunctionDefinitions /// < Section 2.4 #12 61 }; 62 63 /// This class manages the state of the SPIR-V validation as it is being parsed. 64 class ValidationState_t { 65 public: 66 // Features that can optionally be turned on by a capability or environment. 67 struct Feature { 68 bool declare_int16_type = false; // Allow OpTypeInt with 16 bit width? 69 bool declare_float16_type = false; // Allow OpTypeFloat with 16 bit width? 70 bool free_fp_rounding_mode = false; // Allow the FPRoundingMode decoration 71 // and its values to be used without 72 // requiring any capability 73 74 // Allow functionalities enabled by VariablePointers or 75 // VariablePointersStorageBuffer capability. 76 bool variable_pointers = false; 77 78 // Permit group oerations Reduce, InclusiveScan, ExclusiveScan 79 bool group_ops_reduce_and_scans = false; 80 81 // Allow OpTypeInt with 8 bit width? 82 bool declare_int8_type = false; 83 84 // Target environment uses relaxed block layout. 85 // This is true for Vulkan 1.1 or later. 86 bool env_relaxed_block_layout = false; 87 88 // Allow an OpTypeInt with 8 bit width to be used in more than just int 89 // conversion opcodes 90 bool use_int8_type = false; 91 92 // SPIR-V 1.4 allows us to select between any two composite values 93 // of the same type. 94 bool select_between_composites = false; 95 96 // SPIR-V 1.4 allows two memory access operands for OpCopyMemory and 97 // OpCopyMemorySized. 98 bool copy_memory_permits_two_memory_accesses = false; 99 100 // SPIR-V 1.4 allows UConvert as a spec constant op in any environment. 101 // The Kernel capability already enables it, separately from this flag. 102 bool uconvert_spec_constant_op = false; 103 104 // SPIR-V 1.4 allows Function and Private variables to be NonWritable 105 bool nonwritable_var_in_function_or_private = false; 106 107 // Whether LocalSizeId execution mode is allowed by the environment. 108 bool env_allow_localsizeid = false; 109 }; 110 111 ValidationState_t(const spv_const_context context, 112 const spv_const_validator_options opt, 113 const uint32_t* words, const size_t num_words, 114 const uint32_t max_warnings); 115 116 /// Returns the context context()117 spv_const_context context() const { return context_; } 118 119 /// Returns the command line options options()120 spv_const_validator_options options() const { return options_; } 121 122 /// Sets the ID of the generator for this module. setGenerator(uint32_t gen)123 void setGenerator(uint32_t gen) { generator_ = gen; } 124 125 /// Returns the ID of the generator for this module. generator()126 uint32_t generator() const { return generator_; } 127 128 /// Sets the SPIR-V version of this module. setVersion(uint32_t ver)129 void setVersion(uint32_t ver) { version_ = ver; } 130 131 /// Gets the SPIR-V version of this module. version()132 uint32_t version() const { return version_; } 133 134 /// Forward declares the id in the module 135 spv_result_t ForwardDeclareId(uint32_t id); 136 137 /// Removes a forward declared ID if it has been defined 138 spv_result_t RemoveIfForwardDeclared(uint32_t id); 139 140 /// Registers an ID as a forward pointer 141 spv_result_t RegisterForwardPointer(uint32_t id); 142 143 /// Returns whether or not an ID is a forward pointer 144 bool IsForwardPointer(uint32_t id) const; 145 146 /// Assigns a name to an ID 147 void AssignNameToId(uint32_t id, std::string name); 148 149 /// Returns a string representation of the ID in the format <id>[Name] where 150 /// the <id> is the numeric valid of the id and the Name is a name assigned by 151 /// the OpName instruction 152 std::string getIdName(uint32_t id) const; 153 154 /// Accessor function for ID bound. 155 uint32_t getIdBound() const; 156 157 /// Mutator function for ID bound. 158 void setIdBound(uint32_t bound); 159 160 /// Returns the number of ID which have been forward referenced but not 161 /// defined 162 size_t unresolved_forward_id_count() const; 163 164 /// Returns a vector of unresolved forward ids. 165 std::vector<uint32_t> UnresolvedForwardIds() const; 166 167 /// Returns true if the id has been defined 168 bool IsDefinedId(uint32_t id) const; 169 170 /// Increments the total number of instructions in the file. increment_total_instructions()171 void increment_total_instructions() { total_instructions_++; } 172 173 /// Increments the total number of functions in the file. increment_total_functions()174 void increment_total_functions() { total_functions_++; } 175 176 /// Allocates internal storage. Note, calling this will invalidate any 177 /// pointers to |ordered_instructions_| or |module_functions_| and, hence, 178 /// should only be called at the beginning of validation. 179 void preallocateStorage(); 180 181 /// Returns the current layout section which is being processed 182 ModuleLayoutSection current_layout_section() const; 183 184 /// Increments the module_layout_order_section_ 185 void ProgressToNextLayoutSectionOrder(); 186 187 /// Determines if the op instruction is in a previous layout section 188 bool IsOpcodeInPreviousLayoutSection(SpvOp op); 189 190 /// Determines if the op instruction is part of the current section 191 bool IsOpcodeInCurrentLayoutSection(SpvOp op); 192 193 DiagnosticStream diag(spv_result_t error_code, const Instruction* inst); 194 195 /// Returns the function states 196 std::vector<Function>& functions(); 197 198 /// Returns the function states 199 Function& current_function(); 200 const Function& current_function() const; 201 202 /// Returns function state with the given id, or nullptr if no such function. 203 const Function* function(uint32_t id) const; 204 Function* function(uint32_t id); 205 206 /// Returns true if the called after a function instruction but before the 207 /// function end instruction 208 bool in_function_body() const; 209 210 /// Returns true if called after a label instruction but before a branch 211 /// instruction 212 bool in_block() const; 213 214 struct EntryPointDescription { 215 std::string name; 216 std::vector<uint32_t> interfaces; 217 }; 218 219 /// Registers |id| as an entry point with |execution_model| and |interfaces|. RegisterEntryPoint(const uint32_t id,SpvExecutionModel execution_model,EntryPointDescription && desc)220 void RegisterEntryPoint(const uint32_t id, SpvExecutionModel execution_model, 221 EntryPointDescription&& desc) { 222 entry_points_.push_back(id); 223 entry_point_to_execution_models_[id].insert(execution_model); 224 entry_point_descriptions_[id].emplace_back(desc); 225 } 226 227 /// Returns a list of entry point function ids entry_points()228 const std::vector<uint32_t>& entry_points() const { return entry_points_; } 229 230 /// Returns the set of entry points that root call graphs that contain 231 /// recursion. recursive_entry_points()232 const std::set<uint32_t>& recursive_entry_points() const { 233 return recursive_entry_points_; 234 } 235 236 /// Registers execution mode for the given entry point. RegisterExecutionModeForEntryPoint(uint32_t entry_point,SpvExecutionMode execution_mode)237 void RegisterExecutionModeForEntryPoint(uint32_t entry_point, 238 SpvExecutionMode execution_mode) { 239 entry_point_to_execution_modes_[entry_point].insert(execution_mode); 240 } 241 242 /// Returns the interface descriptions of a given entry point. entry_point_descriptions(uint32_t entry_point)243 const std::vector<EntryPointDescription>& entry_point_descriptions( 244 uint32_t entry_point) { 245 return entry_point_descriptions_.at(entry_point); 246 } 247 248 /// Returns Execution Models for the given Entry Point. 249 /// Returns nullptr if none found (would trigger assertion). GetExecutionModels(uint32_t entry_point)250 const std::set<SpvExecutionModel>* GetExecutionModels( 251 uint32_t entry_point) const { 252 const auto it = entry_point_to_execution_models_.find(entry_point); 253 if (it == entry_point_to_execution_models_.end()) { 254 assert(0); 255 return nullptr; 256 } 257 return &it->second; 258 } 259 260 /// Returns Execution Modes for the given Entry Point. 261 /// Returns nullptr if none found. GetExecutionModes(uint32_t entry_point)262 const std::set<SpvExecutionMode>* GetExecutionModes( 263 uint32_t entry_point) const { 264 const auto it = entry_point_to_execution_modes_.find(entry_point); 265 if (it == entry_point_to_execution_modes_.end()) { 266 return nullptr; 267 } 268 return &it->second; 269 } 270 271 /// Traverses call tree and computes function_to_entry_points_. 272 /// Note: called after fully parsing the binary. 273 void ComputeFunctionToEntryPointMapping(); 274 275 /// Traverse call tree and computes recursive_entry_points_. 276 /// Note: called after fully parsing the binary and calling 277 /// ComputeFunctionToEntryPointMapping. 278 void ComputeRecursiveEntryPoints(); 279 280 /// Returns all the entry points that can call |func|. 281 const std::vector<uint32_t>& FunctionEntryPoints(uint32_t func) const; 282 283 /// Returns all the entry points that statically use |id|. 284 /// 285 /// Note: requires ComputeFunctionToEntryPointMapping to have been called. 286 std::set<uint32_t> EntryPointReferences(uint32_t id) const; 287 288 /// Inserts an <id> to the set of functions that are target of OpFunctionCall. AddFunctionCallTarget(const uint32_t id)289 void AddFunctionCallTarget(const uint32_t id) { 290 function_call_targets_.insert(id); 291 current_function().AddFunctionCallTarget(id); 292 } 293 294 /// Returns whether or not a function<id> is the target of OpFunctionCall. IsFunctionCallTarget(const uint32_t id)295 bool IsFunctionCallTarget(const uint32_t id) { 296 return (function_call_targets_.find(id) != function_call_targets_.end()); 297 } 298 IsFunctionCallDefined(const uint32_t id)299 bool IsFunctionCallDefined(const uint32_t id) { 300 return (id_to_function_.find(id) != id_to_function_.end()); 301 } 302 /// Registers the capability and its dependent capabilities 303 void RegisterCapability(SpvCapability cap); 304 305 /// Registers the extension. 306 void RegisterExtension(Extension ext); 307 308 /// Registers the function in the module. Subsequent instructions will be 309 /// called against this function 310 spv_result_t RegisterFunction(uint32_t id, uint32_t ret_type_id, 311 SpvFunctionControlMask function_control, 312 uint32_t function_type_id); 313 314 /// Register a function end instruction 315 spv_result_t RegisterFunctionEnd(); 316 317 /// Returns true if the capability is enabled in the module. HasCapability(SpvCapability cap)318 bool HasCapability(SpvCapability cap) const { 319 return module_capabilities_.Contains(cap); 320 } 321 322 /// Returns a reference to the set of capabilities in the module. 323 /// This is provided for debuggability. module_capabilities()324 const CapabilitySet& module_capabilities() const { 325 return module_capabilities_; 326 } 327 328 /// Returns true if the extension is enabled in the module. HasExtension(Extension ext)329 bool HasExtension(Extension ext) const { 330 return module_extensions_.Contains(ext); 331 } 332 333 /// Returns true if any of the capabilities is enabled, or if |capabilities| 334 /// is an empty set. 335 bool HasAnyOfCapabilities(const CapabilitySet& capabilities) const; 336 337 /// Returns true if any of the extensions is enabled, or if |extensions| 338 /// is an empty set. 339 bool HasAnyOfExtensions(const ExtensionSet& extensions) const; 340 341 /// Sets the addressing model of this module (logical/physical). 342 void set_addressing_model(SpvAddressingModel am); 343 344 /// Returns true if the OpMemoryModel was found. has_memory_model_specified()345 bool has_memory_model_specified() const { 346 return addressing_model_ != SpvAddressingModelMax && 347 memory_model_ != SpvMemoryModelMax; 348 } 349 350 /// Returns the addressing model of this module, or Logical if uninitialized. 351 SpvAddressingModel addressing_model() const; 352 353 /// Returns the addressing model of this module, or Logical if uninitialized. pointer_size_and_alignment()354 uint32_t pointer_size_and_alignment() const { 355 return pointer_size_and_alignment_; 356 } 357 358 /// Sets the memory model of this module. 359 void set_memory_model(SpvMemoryModel mm); 360 361 /// Returns the memory model of this module, or Simple if uninitialized. 362 SpvMemoryModel memory_model() const; 363 364 /// Sets the bit width for sampler/image type variables. If not set, they are 365 /// considered opaque 366 void set_samplerimage_variable_address_mode(uint32_t bit_width); 367 368 /// Get the addressing mode currently set. If 0, it means addressing mode is 369 /// invalid Sampler/Image type variables must be considered opaque This mode 370 /// is only valid after the instruction has been read 371 uint32_t samplerimage_variable_address_mode() const; 372 373 /// Returns true if the OpSamplerImageAddressingModeNV was found. has_samplerimage_variable_address_mode_specified()374 bool has_samplerimage_variable_address_mode_specified() const { 375 return sampler_image_addressing_mode_ != 0; 376 } 377 grammar()378 const AssemblyGrammar& grammar() const { return grammar_; } 379 380 /// Inserts the instruction into the list of ordered instructions in the file. 381 Instruction* AddOrderedInstruction(const spv_parsed_instruction_t* inst); 382 383 /// Registers the instruction. This will add the instruction to the list of 384 /// definitions and register sampled image consumers. 385 void RegisterInstruction(Instruction* inst); 386 387 /// Registers the debug instruction information. 388 void RegisterDebugInstruction(const Instruction* inst); 389 390 /// Registers the decoration for the given <id> RegisterDecorationForId(uint32_t id,const Decoration & dec)391 void RegisterDecorationForId(uint32_t id, const Decoration& dec) { 392 auto& dec_list = id_decorations_[id]; 393 dec_list.insert(dec); 394 } 395 396 /// Registers the list of decorations for the given <id> 397 template <class InputIt> RegisterDecorationsForId(uint32_t id,InputIt begin,InputIt end)398 void RegisterDecorationsForId(uint32_t id, InputIt begin, InputIt end) { 399 std::set<Decoration>& cur_decs = id_decorations_[id]; 400 cur_decs.insert(begin, end); 401 } 402 403 /// Registers the list of decorations for the given member of the given 404 /// structure. 405 template <class InputIt> RegisterDecorationsForStructMember(uint32_t struct_id,uint32_t member_index,InputIt begin,InputIt end)406 void RegisterDecorationsForStructMember(uint32_t struct_id, 407 uint32_t member_index, InputIt begin, 408 InputIt end) { 409 std::set<Decoration>& cur_decs = id_decorations_[struct_id]; 410 for (InputIt iter = begin; iter != end; ++iter) { 411 Decoration dec = *iter; 412 dec.set_struct_member_index(member_index); 413 cur_decs.insert(dec); 414 } 415 } 416 417 /// Returns all the decorations for the given <id>. If no decorations exist 418 /// for the <id>, it registers an empty set for it in the map and 419 /// returns the empty set. id_decorations(uint32_t id)420 std::set<Decoration>& id_decorations(uint32_t id) { 421 return id_decorations_[id]; 422 } 423 424 /// Returns the range of decorations for the given field of the given <id>. 425 struct FieldDecorationsIter { 426 std::set<Decoration>::const_iterator begin; 427 std::set<Decoration>::const_iterator end; 428 }; id_member_decorations(uint32_t id,uint32_t member_index)429 FieldDecorationsIter id_member_decorations(uint32_t id, 430 uint32_t member_index) { 431 const auto& decorations = id_decorations_[id]; 432 433 // The decorations are sorted by member_index, so this look up will give the 434 // exact range of decorations for this member index. 435 Decoration min_decoration((SpvDecoration)0, {}, member_index); 436 Decoration max_decoration(SpvDecorationMax, {}, member_index); 437 438 FieldDecorationsIter result; 439 result.begin = decorations.lower_bound(min_decoration); 440 result.end = decorations.upper_bound(max_decoration); 441 442 return result; 443 } 444 445 // Returns const pointer to the internal decoration container. id_decorations()446 const std::map<uint32_t, std::set<Decoration>>& id_decorations() const { 447 return id_decorations_; 448 } 449 450 /// Returns true if the given id <id> has the given decoration <dec>, 451 /// otherwise returns false. HasDecoration(uint32_t id,SpvDecoration dec)452 bool HasDecoration(uint32_t id, SpvDecoration dec) { 453 const auto& decorations = id_decorations_.find(id); 454 if (decorations == id_decorations_.end()) return false; 455 456 return std::any_of( 457 decorations->second.begin(), decorations->second.end(), 458 [dec](const Decoration& d) { return dec == d.dec_type(); }); 459 } 460 461 /// Finds id's def, if it exists. If found, returns the definition otherwise 462 /// nullptr 463 const Instruction* FindDef(uint32_t id) const; 464 465 /// Finds id's def, if it exists. If found, returns the definition otherwise 466 /// nullptr 467 Instruction* FindDef(uint32_t id); 468 469 /// Returns the instructions in the order they appear in the binary ordered_instructions()470 const std::vector<Instruction>& ordered_instructions() const { 471 return ordered_instructions_; 472 } 473 474 /// Returns a map of instructions mapped by their result id all_definitions()475 const std::unordered_map<uint32_t, Instruction*>& all_definitions() const { 476 return all_definitions_; 477 } 478 479 /// Returns a vector containing the instructions that consume the given 480 /// SampledImage id. 481 std::vector<Instruction*> getSampledImageConsumers(uint32_t id) const; 482 483 /// Records cons_id as a consumer of sampled_image_id. 484 void RegisterSampledImageConsumer(uint32_t sampled_image_id, 485 Instruction* consumer); 486 487 // Record a function's storage class consumer instruction 488 void RegisterStorageClassConsumer(SpvStorageClass storage_class, 489 Instruction* consumer); 490 491 /// Returns the set of Global Variables. global_vars()492 std::unordered_set<uint32_t>& global_vars() { return global_vars_; } 493 494 /// Returns the set of Local Variables. local_vars()495 std::unordered_set<uint32_t>& local_vars() { return local_vars_; } 496 497 /// Returns the number of Global Variables. num_global_vars()498 size_t num_global_vars() { return global_vars_.size(); } 499 500 /// Returns the number of Local Variables. num_local_vars()501 size_t num_local_vars() { return local_vars_.size(); } 502 503 /// Inserts a new <id> to the set of Global Variables. registerGlobalVariable(const uint32_t id)504 void registerGlobalVariable(const uint32_t id) { global_vars_.insert(id); } 505 506 /// Inserts a new <id> to the set of Local Variables. registerLocalVariable(const uint32_t id)507 void registerLocalVariable(const uint32_t id) { local_vars_.insert(id); } 508 509 // Returns true if using relaxed block layout, equivalent to 510 // VK_KHR_relaxed_block_layout. IsRelaxedBlockLayout()511 bool IsRelaxedBlockLayout() const { 512 return features_.env_relaxed_block_layout || options()->relax_block_layout; 513 } 514 515 // Returns true if allowing localsizeid, either because the environment always 516 // allows it, or because it is enabled from the command-line. IsLocalSizeIdAllowed()517 bool IsLocalSizeIdAllowed() const { 518 return features_.env_allow_localsizeid || options()->allow_localsizeid; 519 } 520 521 /// Sets the struct nesting depth for a given struct ID set_struct_nesting_depth(uint32_t id,uint32_t depth)522 void set_struct_nesting_depth(uint32_t id, uint32_t depth) { 523 struct_nesting_depth_[id] = depth; 524 } 525 526 /// Returns the nesting depth of a given structure ID struct_nesting_depth(uint32_t id)527 uint32_t struct_nesting_depth(uint32_t id) { 528 return struct_nesting_depth_[id]; 529 } 530 531 /// Records the has a nested block/bufferblock decorated struct for a given 532 /// struct ID SetHasNestedBlockOrBufferBlockStruct(uint32_t id,bool has)533 void SetHasNestedBlockOrBufferBlockStruct(uint32_t id, bool has) { 534 struct_has_nested_blockorbufferblock_struct_[id] = has; 535 } 536 537 /// For a given struct ID returns true if it has a nested block/bufferblock 538 /// decorated struct GetHasNestedBlockOrBufferBlockStruct(uint32_t id)539 bool GetHasNestedBlockOrBufferBlockStruct(uint32_t id) { 540 return struct_has_nested_blockorbufferblock_struct_[id]; 541 } 542 543 /// Records that the structure type has a member decorated with a built-in. RegisterStructTypeWithBuiltInMember(uint32_t id)544 void RegisterStructTypeWithBuiltInMember(uint32_t id) { 545 builtin_structs_.insert(id); 546 } 547 548 /// Returns true if the struct type with the given Id has a BuiltIn member. IsStructTypeWithBuiltInMember(uint32_t id)549 bool IsStructTypeWithBuiltInMember(uint32_t id) const { 550 return (builtin_structs_.find(id) != builtin_structs_.end()); 551 } 552 553 // Returns the state of optional features. features()554 const Feature& features() const { return features_; } 555 556 /// Adds the instruction data to unique_type_declarations_. 557 /// Returns false if an identical type declaration already exists. 558 bool RegisterUniqueTypeDeclaration(const Instruction* inst); 559 560 // Returns type_id of the scalar component of |id|. 561 // |id| can be either 562 // - scalar, vector or matrix type 563 // - object of either scalar, vector or matrix type 564 uint32_t GetComponentType(uint32_t id) const; 565 566 // Returns 567 // - 1 for scalar types or objects 568 // - vector size for vector types or objects 569 // - num columns for matrix types or objects 570 // Should not be called with any other arguments (will return zero and invoke 571 // assertion). 572 uint32_t GetDimension(uint32_t id) const; 573 574 // Returns bit width of scalar or component. 575 // |id| can be 576 // - scalar, vector or matrix type 577 // - object of either scalar, vector or matrix type 578 // Will invoke assertion and return 0 if |id| is none of the above. 579 uint32_t GetBitWidth(uint32_t id) const; 580 581 // Provides detailed information on matrix type. 582 // Returns false iff |id| is not matrix type. 583 bool GetMatrixTypeInfo(uint32_t id, uint32_t* num_rows, uint32_t* num_cols, 584 uint32_t* column_type, uint32_t* component_type) const; 585 586 // Collects struct member types into |member_types|. 587 // Returns false iff not struct type or has no members. 588 // Deletes prior contents of |member_types|. 589 bool GetStructMemberTypes(uint32_t struct_type_id, 590 std::vector<uint32_t>* member_types) const; 591 592 // Returns true iff |id| is a type corresponding to the name of the function. 593 // Only works for types not for objects. 594 bool IsVoidType(uint32_t id) const; 595 bool IsFloatScalarType(uint32_t id) const; 596 bool IsFloatVectorType(uint32_t id) const; 597 bool IsFloatScalarOrVectorType(uint32_t id) const; 598 bool IsFloatMatrixType(uint32_t id) const; 599 bool IsIntScalarType(uint32_t id) const; 600 bool IsIntVectorType(uint32_t id) const; 601 bool IsIntScalarOrVectorType(uint32_t id) const; 602 bool IsUnsignedIntScalarType(uint32_t id) const; 603 bool IsUnsignedIntVectorType(uint32_t id) const; 604 bool IsSignedIntScalarType(uint32_t id) const; 605 bool IsSignedIntVectorType(uint32_t id) const; 606 bool IsBoolScalarType(uint32_t id) const; 607 bool IsBoolVectorType(uint32_t id) const; 608 bool IsBoolScalarOrVectorType(uint32_t id) const; 609 bool IsPointerType(uint32_t id) const; 610 bool IsAccelerationStructureType(uint32_t id) const; 611 bool IsCooperativeMatrixType(uint32_t id) const; 612 bool IsFloatCooperativeMatrixType(uint32_t id) const; 613 bool IsIntCooperativeMatrixType(uint32_t id) const; 614 bool IsUnsignedIntCooperativeMatrixType(uint32_t id) const; 615 bool IsUnsigned64BitHandle(uint32_t id) const; 616 617 // Returns true if |id| is a type id that contains |type| (or integer or 618 // floating point type) of |width| bits. 619 bool ContainsSizedIntOrFloatType(uint32_t id, SpvOp type, 620 uint32_t width) const; 621 // Returns true if |id| is a type id that contains a 8- or 16-bit int or 622 // 16-bit float that is not generally enabled for use. 623 bool ContainsLimitedUseIntOrFloatType(uint32_t id) const; 624 625 // Returns true if |id| is a type that contains a runtime-sized array. 626 // Does not consider a pointers as contains the array. 627 bool ContainsRuntimeArray(uint32_t id) const; 628 629 // Generic type traversal. 630 // Only traverse pointers and functions if |traverse_all_types| is true. 631 // Recursively tests |f| against the type hierarchy headed by |id|. 632 bool ContainsType(uint32_t id, 633 const std::function<bool(const Instruction*)>& f, 634 bool traverse_all_types = true) const; 635 636 // Gets value from OpConstant and OpSpecConstant as uint64. 637 // Returns false on failure (no instruction, wrong instruction, not int). 638 bool GetConstantValUint64(uint32_t id, uint64_t* val) const; 639 640 // Returns type_id if id has type or zero otherwise. 641 uint32_t GetTypeId(uint32_t id) const; 642 643 // Returns opcode of the instruction which issued the id or OpNop if the 644 // instruction is not registered. 645 SpvOp GetIdOpcode(uint32_t id) const; 646 647 // Returns type_id for given id operand if it has a type or zero otherwise. 648 // |operand_index| is expected to be pointing towards an operand which is an 649 // id. 650 uint32_t GetOperandTypeId(const Instruction* inst, 651 size_t operand_index) const; 652 653 // Provides information on pointer type. Returns false iff not pointer type. 654 bool GetPointerTypeInfo(uint32_t id, uint32_t* data_type, 655 uint32_t* storage_class) const; 656 657 // Is the ID the type of a pointer to a uniform block: Block-decorated struct 658 // in uniform storage class? The result is only valid after internal method 659 // CheckDecorationsOfBuffers has been called. IsPointerToUniformBlock(uint32_t type_id)660 bool IsPointerToUniformBlock(uint32_t type_id) const { 661 return pointer_to_uniform_block_.find(type_id) != 662 pointer_to_uniform_block_.cend(); 663 } 664 // Save the ID of a pointer to uniform block. RegisterPointerToUniformBlock(uint32_t type_id)665 void RegisterPointerToUniformBlock(uint32_t type_id) { 666 pointer_to_uniform_block_.insert(type_id); 667 } 668 // Is the ID the type of a struct used as a uniform block? 669 // The result is only valid after internal method CheckDecorationsOfBuffers 670 // has been called. IsStructForUniformBlock(uint32_t type_id)671 bool IsStructForUniformBlock(uint32_t type_id) const { 672 return struct_for_uniform_block_.find(type_id) != 673 struct_for_uniform_block_.cend(); 674 } 675 // Save the ID of a struct of a uniform block. RegisterStructForUniformBlock(uint32_t type_id)676 void RegisterStructForUniformBlock(uint32_t type_id) { 677 struct_for_uniform_block_.insert(type_id); 678 } 679 // Is the ID the type of a pointer to a storage buffer: BufferBlock-decorated 680 // struct in uniform storage class, or Block-decorated struct in StorageBuffer 681 // storage class? The result is only valid after internal method 682 // CheckDecorationsOfBuffers has been called. IsPointerToStorageBuffer(uint32_t type_id)683 bool IsPointerToStorageBuffer(uint32_t type_id) const { 684 return pointer_to_storage_buffer_.find(type_id) != 685 pointer_to_storage_buffer_.cend(); 686 } 687 // Save the ID of a pointer to a storage buffer. RegisterPointerToStorageBuffer(uint32_t type_id)688 void RegisterPointerToStorageBuffer(uint32_t type_id) { 689 pointer_to_storage_buffer_.insert(type_id); 690 } 691 // Is the ID the type of a struct for storage buffer? 692 // The result is only valid after internal method CheckDecorationsOfBuffers 693 // has been called. IsStructForStorageBuffer(uint32_t type_id)694 bool IsStructForStorageBuffer(uint32_t type_id) const { 695 return struct_for_storage_buffer_.find(type_id) != 696 struct_for_storage_buffer_.cend(); 697 } 698 // Save the ID of a struct of a storage buffer. RegisterStructForStorageBuffer(uint32_t type_id)699 void RegisterStructForStorageBuffer(uint32_t type_id) { 700 struct_for_storage_buffer_.insert(type_id); 701 } 702 703 // Is the ID the type of a pointer to a storage image? That is, the pointee 704 // type is an image type which is known to not use a sampler. IsPointerToStorageImage(uint32_t type_id)705 bool IsPointerToStorageImage(uint32_t type_id) const { 706 return pointer_to_storage_image_.find(type_id) != 707 pointer_to_storage_image_.cend(); 708 } 709 // Save the ID of a pointer to a storage image. RegisterPointerToStorageImage(uint32_t type_id)710 void RegisterPointerToStorageImage(uint32_t type_id) { 711 pointer_to_storage_image_.insert(type_id); 712 } 713 714 // Tries to evaluate a 32-bit signed or unsigned scalar integer constant. 715 // Returns tuple <is_int32, is_const_int32, value>. 716 // OpSpecConstant* return |is_const_int32| as false since their values cannot 717 // be relied upon during validation. 718 std::tuple<bool, bool, uint32_t> EvalInt32IfConst(uint32_t id) const; 719 720 // Returns the disassembly string for the given instruction. 721 std::string Disassemble(const Instruction& inst) const; 722 723 // Returns the disassembly string for the given instruction. 724 std::string Disassemble(const uint32_t* words, uint16_t num_words) const; 725 726 // Returns the string name for |decoration|. SpvDecorationString(uint32_t decoration)727 std::string SpvDecorationString(uint32_t decoration) { 728 spv_operand_desc desc = nullptr; 729 if (grammar_.lookupOperand(SPV_OPERAND_TYPE_DECORATION, decoration, 730 &desc) != SPV_SUCCESS) { 731 return std::string("Unknown"); 732 } 733 return std::string(desc->name); 734 } 735 736 // Returns whether type m1 and type m2 are cooperative matrices with 737 // the same "shape" (matching scope, rows, cols). If any are specialization 738 // constants, we assume they can match because we can't prove they don't. 739 spv_result_t CooperativeMatrixShapesMatch(const Instruction* inst, 740 uint32_t m1, uint32_t m2); 741 742 // Returns true if |lhs| and |rhs| logically match and, if the decorations of 743 // |rhs| are a subset of |lhs|. 744 // 745 // 1. Must both be either OpTypeArray or OpTypeStruct 746 // 2. If OpTypeArray, then 747 // * Length must be the same 748 // * Element type must match or logically match 749 // 3. If OpTypeStruct, then 750 // * Both have same number of elements 751 // * Element N for both structs must match or logically match 752 // 753 // If |check_decorations| is false, then the decorations are not checked. 754 bool LogicallyMatch(const Instruction* lhs, const Instruction* rhs, 755 bool check_decorations); 756 757 // Traces |inst| to find a single base pointer. Returns the base pointer. 758 // Will trace through the following instructions: 759 // * OpAccessChain 760 // * OpInBoundsAccessChain 761 // * OpPtrAccessChain 762 // * OpInBoundsPtrAccessChain 763 // * OpCopyObject 764 const Instruction* TracePointer(const Instruction* inst) const; 765 766 // Validates the storage class for the target environment. 767 bool IsValidStorageClass(SpvStorageClass storage_class) const; 768 769 // Takes a Vulkan Valid Usage ID (VUID) as |id| and optional |reference| and 770 // will return a non-empty string only if ID is known and targeting Vulkan. 771 // VUIDs are found in the Vulkan-Docs repo in the form "[[VUID-ref-ref-id]]" 772 // where "id" is always an 5 char long number (with zeros padding) and matches 773 // to |id|. |reference| is used if there is a "common validity" and the VUID 774 // shares the same |id| value. 775 // 776 // More details about Vulkan validation can be found in Vulkan Guide: 777 // https://github.com/KhronosGroup/Vulkan-Guide/blob/master/chapters/validation_overview.md 778 std::string VkErrorID(uint32_t id, const char* reference = nullptr) const; 779 780 // Testing method to allow setting the current layout section. SetCurrentLayoutSectionForTesting(ModuleLayoutSection section)781 void SetCurrentLayoutSectionForTesting(ModuleLayoutSection section) { 782 current_layout_section_ = section; 783 } 784 785 private: 786 ValidationState_t(const ValidationState_t&); 787 788 const spv_const_context context_; 789 790 /// Stores the Validator command line options. Must be a valid options object. 791 const spv_const_validator_options options_; 792 793 /// The SPIR-V binary module we're validating. 794 const uint32_t* words_; 795 const size_t num_words_; 796 797 /// The generator of the SPIR-V. 798 uint32_t generator_ = 0; 799 800 /// The version of the SPIR-V. 801 uint32_t version_ = 0; 802 803 /// The total number of instructions in the binary. 804 size_t total_instructions_ = 0; 805 /// The total number of functions in the binary. 806 size_t total_functions_ = 0; 807 808 /// IDs which have been forward declared but have not been defined 809 std::unordered_set<uint32_t> unresolved_forward_ids_; 810 811 /// IDs that have been declared as forward pointers. 812 std::unordered_set<uint32_t> forward_pointer_ids_; 813 814 /// Stores a vector of instructions that use the result of a given 815 /// OpSampledImage instruction. 816 std::unordered_map<uint32_t, std::vector<Instruction*>> 817 sampled_image_consumers_; 818 819 /// A map of operand IDs and their names defined by the OpName instruction 820 std::unordered_map<uint32_t, std::string> operand_names_; 821 822 /// The section of the code being processed 823 ModuleLayoutSection current_layout_section_; 824 825 /// A list of functions in the module. 826 /// Pointers to objects in this container are guaranteed to be stable and 827 /// valid until the end of lifetime of the validation state. 828 std::vector<Function> module_functions_; 829 830 /// Capabilities declared in the module 831 CapabilitySet module_capabilities_; 832 833 /// Extensions declared in the module 834 ExtensionSet module_extensions_; 835 836 /// List of all instructions in the order they appear in the binary 837 std::vector<Instruction> ordered_instructions_; 838 839 /// Instructions that can be referenced by Ids 840 std::unordered_map<uint32_t, Instruction*> all_definitions_; 841 842 /// IDs that are entry points, ie, arguments to OpEntryPoint. 843 std::vector<uint32_t> entry_points_; 844 845 /// Maps an entry point id to its descriptions. 846 std::unordered_map<uint32_t, std::vector<EntryPointDescription>> 847 entry_point_descriptions_; 848 849 /// IDs that are entry points, ie, arguments to OpEntryPoint, and root a call 850 /// graph that recurses. 851 std::set<uint32_t> recursive_entry_points_; 852 853 /// Functions IDs that are target of OpFunctionCall. 854 std::unordered_set<uint32_t> function_call_targets_; 855 856 /// ID Bound from the Header 857 uint32_t id_bound_; 858 859 /// Set of Global Variable IDs (Storage Class other than 'Function') 860 std::unordered_set<uint32_t> global_vars_; 861 862 /// Set of Local Variable IDs ('Function' Storage Class) 863 std::unordered_set<uint32_t> local_vars_; 864 865 /// Set of struct types that have members with a BuiltIn decoration. 866 std::unordered_set<uint32_t> builtin_structs_; 867 868 /// Structure Nesting Depth 869 std::unordered_map<uint32_t, uint32_t> struct_nesting_depth_; 870 871 /// Structure has nested blockorbufferblock struct 872 std::unordered_map<uint32_t, bool> 873 struct_has_nested_blockorbufferblock_struct_; 874 875 /// Stores the list of decorations for a given <id> 876 std::map<uint32_t, std::set<Decoration>> id_decorations_; 877 878 /// Stores type declarations which need to be unique (i.e. non-aggregates), 879 /// in the form [opcode, operand words], result_id is not stored. 880 /// Using ordered set to avoid the need for a vector hash function. 881 /// The size of this container is expected not to exceed double-digits. 882 std::set<std::vector<uint32_t>> unique_type_declarations_; 883 884 AssemblyGrammar grammar_; 885 886 SpvAddressingModel addressing_model_; 887 SpvMemoryModel memory_model_; 888 // pointer size derived from addressing model. Assumes all storage classes 889 // have the same pointer size (for physical pointer types). 890 uint32_t pointer_size_and_alignment_; 891 892 /// bit width of sampler/image type variables. Valid values are 32 and 64 893 uint32_t sampler_image_addressing_mode_; 894 895 /// NOTE: See correspoding getter functions 896 bool in_function_; 897 898 /// The state of optional features. These are determined by capabilities 899 /// declared by the module and the environment. 900 Feature features_; 901 902 /// Maps function ids to function stat objects. 903 std::unordered_map<uint32_t, Function*> id_to_function_; 904 905 /// Mapping entry point -> execution models. It is presumed that the same 906 /// function could theoretically be used as 'main' by multiple OpEntryPoint 907 /// instructions. 908 std::unordered_map<uint32_t, std::set<SpvExecutionModel>> 909 entry_point_to_execution_models_; 910 911 /// Mapping entry point -> execution modes. 912 std::unordered_map<uint32_t, std::set<SpvExecutionMode>> 913 entry_point_to_execution_modes_; 914 915 /// Mapping function -> array of entry points inside this 916 /// module which can (indirectly) call the function. 917 std::unordered_map<uint32_t, std::vector<uint32_t>> function_to_entry_points_; 918 const std::vector<uint32_t> empty_ids_; 919 920 // The IDs of types of pointers to Block-decorated structs in Uniform storage 921 // class. This is populated at the start of ValidateDecorations. 922 std::unordered_set<uint32_t> pointer_to_uniform_block_; 923 // The IDs of struct types for uniform blocks. 924 // This is populated at the start of ValidateDecorations. 925 std::unordered_set<uint32_t> struct_for_uniform_block_; 926 // The IDs of types of pointers to BufferBlock-decorated structs in Uniform 927 // storage class, or Block-decorated structs in StorageBuffer storage class. 928 // This is populated at the start of ValidateDecorations. 929 std::unordered_set<uint32_t> pointer_to_storage_buffer_; 930 // The IDs of struct types for storage buffers. 931 // This is populated at the start of ValidateDecorations. 932 std::unordered_set<uint32_t> struct_for_storage_buffer_; 933 // The IDs of types of pointers to storage images. This is populated in the 934 // TypePass. 935 std::unordered_set<uint32_t> pointer_to_storage_image_; 936 937 /// Maps ids to friendly names. 938 std::unique_ptr<spvtools::FriendlyNameMapper> friendly_mapper_; 939 spvtools::NameMapper name_mapper_; 940 941 /// Variables used to reduce the number of diagnostic messages. 942 uint32_t num_of_warnings_; 943 uint32_t max_num_of_warnings_; 944 }; 945 946 } // namespace val 947 } // namespace spvtools 948 949 #endif // SOURCE_VAL_VALIDATION_STATE_H_ 950