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() const117 spv_const_context context() const { return context_; } 118 119 /// Returns the command line options options() const120 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() const126 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() const132 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(spv::Op op); 189 190 /// Determines if the op instruction is part of the current section 191 bool IsOpcodeInCurrentLayoutSection(spv::Op 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, spv::ExecutionModel execution_model, EntryPointDescription&& desc)220 void RegisterEntryPoint(const uint32_t id, 221 spv::ExecutionModel execution_model, 222 EntryPointDescription&& desc) { 223 entry_points_.push_back(id); 224 entry_point_to_execution_models_[id].insert(execution_model); 225 entry_point_descriptions_[id].emplace_back(desc); 226 } 227 228 /// Returns a list of entry point function ids entry_points() const229 const std::vector<uint32_t>& entry_points() const { return entry_points_; } 230 231 /// Returns the set of entry points that root call graphs that contain 232 /// recursion. recursive_entry_points() const233 const std::set<uint32_t>& recursive_entry_points() const { 234 return recursive_entry_points_; 235 } 236 237 /// Registers execution mode for the given entry point. RegisterExecutionModeForEntryPoint(uint32_t entry_point, spv::ExecutionMode execution_mode)238 void RegisterExecutionModeForEntryPoint(uint32_t entry_point, 239 spv::ExecutionMode execution_mode) { 240 entry_point_to_execution_modes_[entry_point].insert(execution_mode); 241 } 242 243 /// Returns the interface descriptions of a given entry point. entry_point_descriptions( uint32_t entry_point)244 const std::vector<EntryPointDescription>& entry_point_descriptions( 245 uint32_t entry_point) { 246 return entry_point_descriptions_.at(entry_point); 247 } 248 249 /// Returns Execution Models for the given Entry Point. 250 /// Returns nullptr if none found (would trigger assertion). GetExecutionModels( uint32_t entry_point) const251 const std::set<spv::ExecutionModel>* GetExecutionModels( 252 uint32_t entry_point) const { 253 const auto it = entry_point_to_execution_models_.find(entry_point); 254 if (it == entry_point_to_execution_models_.end()) { 255 assert(0); 256 return nullptr; 257 } 258 return &it->second; 259 } 260 261 /// Returns Execution Modes for the given Entry Point. 262 /// Returns nullptr if none found. GetExecutionModes( uint32_t entry_point) const263 const std::set<spv::ExecutionMode>* GetExecutionModes( 264 uint32_t entry_point) const { 265 const auto it = entry_point_to_execution_modes_.find(entry_point); 266 if (it == entry_point_to_execution_modes_.end()) { 267 return nullptr; 268 } 269 return &it->second; 270 } 271 272 /// Traverses call tree and computes function_to_entry_points_. 273 /// Note: called after fully parsing the binary. 274 void ComputeFunctionToEntryPointMapping(); 275 276 /// Traverse call tree and computes recursive_entry_points_. 277 /// Note: called after fully parsing the binary and calling 278 /// ComputeFunctionToEntryPointMapping. 279 void ComputeRecursiveEntryPoints(); 280 281 /// Returns all the entry points that can call |func|. 282 const std::vector<uint32_t>& FunctionEntryPoints(uint32_t func) const; 283 284 /// Returns all the entry points that statically use |id|. 285 /// 286 /// Note: requires ComputeFunctionToEntryPointMapping to have been called. 287 std::set<uint32_t> EntryPointReferences(uint32_t id) const; 288 289 /// Inserts an <id> to the set of functions that are target of OpFunctionCall. AddFunctionCallTarget(const uint32_t id)290 void AddFunctionCallTarget(const uint32_t id) { 291 function_call_targets_.insert(id); 292 current_function().AddFunctionCallTarget(id); 293 } 294 295 /// Returns whether or not a function<id> is the target of OpFunctionCall. IsFunctionCallTarget(const uint32_t id)296 bool IsFunctionCallTarget(const uint32_t id) { 297 return (function_call_targets_.find(id) != function_call_targets_.end()); 298 } 299 IsFunctionCallDefined(const uint32_t id)300 bool IsFunctionCallDefined(const uint32_t id) { 301 return (id_to_function_.find(id) != id_to_function_.end()); 302 } 303 /// Registers the capability and its dependent capabilities 304 void RegisterCapability(spv::Capability cap); 305 306 /// Registers the extension. 307 void RegisterExtension(Extension ext); 308 309 /// Registers the function in the module. Subsequent instructions will be 310 /// called against this function 311 spv_result_t RegisterFunction(uint32_t id, uint32_t ret_type_id, 312 spv::FunctionControlMask function_control, 313 uint32_t function_type_id); 314 315 /// Register a function end instruction 316 spv_result_t RegisterFunctionEnd(); 317 318 /// Returns true if the capability is enabled in the module. HasCapability(spv::Capability cap) const319 bool HasCapability(spv::Capability cap) const { 320 return module_capabilities_.contains(cap); 321 } 322 323 /// Returns a reference to the set of capabilities in the module. 324 /// This is provided for debuggability. module_capabilities() const325 const CapabilitySet& module_capabilities() const { 326 return module_capabilities_; 327 } 328 329 /// Returns true if the extension is enabled in the module. HasExtension(Extension ext) const330 bool HasExtension(Extension ext) const { 331 return module_extensions_.contains(ext); 332 } 333 334 /// Returns true if any of the capabilities is enabled, or if |capabilities| 335 /// is an empty set. 336 bool HasAnyOfCapabilities(const CapabilitySet& capabilities) const; 337 338 /// Returns true if any of the extensions is enabled, or if |extensions| 339 /// is an empty set. 340 bool HasAnyOfExtensions(const ExtensionSet& extensions) const; 341 342 /// Sets the addressing model of this module (logical/physical). 343 void set_addressing_model(spv::AddressingModel am); 344 345 /// Returns true if the OpMemoryModel was found. has_memory_model_specified() const346 bool has_memory_model_specified() const { 347 return addressing_model_ != spv::AddressingModel::Max && 348 memory_model_ != spv::MemoryModel::Max; 349 } 350 351 /// Returns the addressing model of this module, or Logical if uninitialized. 352 spv::AddressingModel addressing_model() const; 353 354 /// Returns the addressing model of this module, or Logical if uninitialized. pointer_size_and_alignment() const355 uint32_t pointer_size_and_alignment() const { 356 return pointer_size_and_alignment_; 357 } 358 359 /// Sets the memory model of this module. 360 void set_memory_model(spv::MemoryModel mm); 361 362 /// Returns the memory model of this module, or Simple if uninitialized. 363 spv::MemoryModel memory_model() const; 364 365 /// Sets the bit width for sampler/image type variables. If not set, they are 366 /// considered opaque 367 void set_samplerimage_variable_address_mode(uint32_t bit_width); 368 369 /// Get the addressing mode currently set. If 0, it means addressing mode is 370 /// invalid Sampler/Image type variables must be considered opaque This mode 371 /// is only valid after the instruction has been read 372 uint32_t samplerimage_variable_address_mode() const; 373 374 /// Returns true if the OpSamplerImageAddressingModeNV was found. has_samplerimage_variable_address_mode_specified() const375 bool has_samplerimage_variable_address_mode_specified() const { 376 return sampler_image_addressing_mode_ != 0; 377 } 378 grammar() const379 const AssemblyGrammar& grammar() const { return grammar_; } 380 381 /// Inserts the instruction into the list of ordered instructions in the file. 382 Instruction* AddOrderedInstruction(const spv_parsed_instruction_t* inst); 383 384 /// Registers the instruction. This will add the instruction to the list of 385 /// definitions and register sampled image consumers. 386 void RegisterInstruction(Instruction* inst); 387 388 /// Registers the debug instruction information. 389 void RegisterDebugInstruction(const Instruction* inst); 390 391 /// Registers the decoration for the given <id> RegisterDecorationForId(uint32_t id, const Decoration& dec)392 void RegisterDecorationForId(uint32_t id, const Decoration& dec) { 393 auto& dec_list = id_decorations_[id]; 394 dec_list.insert(dec); 395 } 396 397 /// Registers the list of decorations for the given <id> 398 template <class InputIt> RegisterDecorationsForId(uint32_t id, InputIt begin, InputIt end)399 void RegisterDecorationsForId(uint32_t id, InputIt begin, InputIt end) { 400 std::set<Decoration>& cur_decs = id_decorations_[id]; 401 cur_decs.insert(begin, end); 402 } 403 404 /// Registers the list of decorations for the given member of the given 405 /// structure. 406 template <class InputIt> RegisterDecorationsForStructMember(uint32_t struct_id, uint32_t member_index, InputIt begin, InputIt end)407 void RegisterDecorationsForStructMember(uint32_t struct_id, 408 uint32_t member_index, InputIt begin, 409 InputIt end) { 410 std::set<Decoration>& cur_decs = id_decorations_[struct_id]; 411 for (InputIt iter = begin; iter != end; ++iter) { 412 Decoration dec = *iter; 413 dec.set_struct_member_index(member_index); 414 cur_decs.insert(dec); 415 } 416 } 417 418 /// Returns all the decorations for the given <id>. If no decorations exist 419 /// for the <id>, it registers an empty set for it in the map and 420 /// returns the empty set. id_decorations(uint32_t id)421 std::set<Decoration>& id_decorations(uint32_t id) { 422 return id_decorations_[id]; 423 } 424 425 /// Returns the range of decorations for the given field of the given <id>. 426 struct FieldDecorationsIter { 427 std::set<Decoration>::const_iterator begin; 428 std::set<Decoration>::const_iterator end; 429 }; id_member_decorations(uint32_t id, uint32_t member_index)430 FieldDecorationsIter id_member_decorations(uint32_t id, 431 uint32_t member_index) { 432 const auto& decorations = id_decorations_[id]; 433 434 // The decorations are sorted by member_index, so this look up will give the 435 // exact range of decorations for this member index. 436 Decoration min_decoration((spv::Decoration)0, {}, member_index); 437 Decoration max_decoration(spv::Decoration::Max, {}, member_index); 438 439 FieldDecorationsIter result; 440 result.begin = decorations.lower_bound(min_decoration); 441 result.end = decorations.upper_bound(max_decoration); 442 443 return result; 444 } 445 446 // Returns const pointer to the internal decoration container. id_decorations() const447 const std::map<uint32_t, std::set<Decoration>>& id_decorations() const { 448 return id_decorations_; 449 } 450 451 /// Returns true if the given id <id> has the given decoration <dec>, 452 /// otherwise returns false. HasDecoration(uint32_t id, spv::Decoration dec)453 bool HasDecoration(uint32_t id, spv::Decoration dec) { 454 const auto& decorations = id_decorations_.find(id); 455 if (decorations == id_decorations_.end()) return false; 456 457 return std::any_of( 458 decorations->second.begin(), decorations->second.end(), 459 [dec](const Decoration& d) { return dec == d.dec_type(); }); 460 } 461 462 /// Finds id's def, if it exists. If found, returns the definition otherwise 463 /// nullptr 464 const Instruction* FindDef(uint32_t id) const; 465 466 /// Finds id's def, if it exists. If found, returns the definition otherwise 467 /// nullptr 468 Instruction* FindDef(uint32_t id); 469 470 /// Returns the instructions in the order they appear in the binary ordered_instructions() const471 const std::vector<Instruction>& ordered_instructions() const { 472 return ordered_instructions_; 473 } 474 475 /// Returns a map of instructions mapped by their result id all_definitions() const476 const std::unordered_map<uint32_t, Instruction*>& all_definitions() const { 477 return all_definitions_; 478 } 479 480 /// Returns a vector containing the instructions that consume the given 481 /// SampledImage id. 482 std::vector<Instruction*> getSampledImageConsumers(uint32_t id) const; 483 484 /// Records cons_id as a consumer of sampled_image_id. 485 void RegisterSampledImageConsumer(uint32_t sampled_image_id, 486 Instruction* consumer); 487 488 // Record a cons_id as a consumer of texture_id 489 // if texture 'texture_id' has a QCOM image processing decoration 490 // and consumer is a load or a sampled image instruction 491 void RegisterQCOMImageProcessingTextureConsumer(uint32_t texture_id, 492 const Instruction* consumer0, 493 const Instruction* consumer1); 494 495 // Record a function's storage class consumer instruction 496 void RegisterStorageClassConsumer(spv::StorageClass storage_class, 497 Instruction* consumer); 498 499 /// Returns the set of Global Variables. global_vars()500 std::unordered_set<uint32_t>& global_vars() { return global_vars_; } 501 502 /// Returns the set of Local Variables. local_vars()503 std::unordered_set<uint32_t>& local_vars() { return local_vars_; } 504 505 /// Returns the number of Global Variables. num_global_vars()506 size_t num_global_vars() { return global_vars_.size(); } 507 508 /// Returns the number of Local Variables. num_local_vars()509 size_t num_local_vars() { return local_vars_.size(); } 510 511 /// Inserts a new <id> to the set of Global Variables. registerGlobalVariable(const uint32_t id)512 void registerGlobalVariable(const uint32_t id) { global_vars_.insert(id); } 513 514 /// Inserts a new <id> to the set of Local Variables. registerLocalVariable(const uint32_t id)515 void registerLocalVariable(const uint32_t id) { local_vars_.insert(id); } 516 517 // Returns true if using relaxed block layout, equivalent to 518 // VK_KHR_relaxed_block_layout. IsRelaxedBlockLayout() const519 bool IsRelaxedBlockLayout() const { 520 return features_.env_relaxed_block_layout || options()->relax_block_layout; 521 } 522 523 // Returns true if allowing localsizeid, either because the environment always 524 // allows it, or because it is enabled from the command-line. IsLocalSizeIdAllowed() const525 bool IsLocalSizeIdAllowed() const { 526 return features_.env_allow_localsizeid || options()->allow_localsizeid; 527 } 528 529 /// Sets the struct nesting depth for a given struct ID set_struct_nesting_depth(uint32_t id, uint32_t depth)530 void set_struct_nesting_depth(uint32_t id, uint32_t depth) { 531 struct_nesting_depth_[id] = depth; 532 } 533 534 /// Returns the nesting depth of a given structure ID struct_nesting_depth(uint32_t id)535 uint32_t struct_nesting_depth(uint32_t id) { 536 return struct_nesting_depth_[id]; 537 } 538 539 /// Records the has a nested block/bufferblock decorated struct for a given 540 /// struct ID SetHasNestedBlockOrBufferBlockStruct(uint32_t id, bool has)541 void SetHasNestedBlockOrBufferBlockStruct(uint32_t id, bool has) { 542 struct_has_nested_blockorbufferblock_struct_[id] = has; 543 } 544 545 /// For a given struct ID returns true if it has a nested block/bufferblock 546 /// decorated struct GetHasNestedBlockOrBufferBlockStruct(uint32_t id)547 bool GetHasNestedBlockOrBufferBlockStruct(uint32_t id) { 548 return struct_has_nested_blockorbufferblock_struct_[id]; 549 } 550 551 /// Records that the structure type has a member decorated with a built-in. RegisterStructTypeWithBuiltInMember(uint32_t id)552 void RegisterStructTypeWithBuiltInMember(uint32_t id) { 553 builtin_structs_.insert(id); 554 } 555 556 /// Returns true if the struct type with the given Id has a BuiltIn member. IsStructTypeWithBuiltInMember(uint32_t id) const557 bool IsStructTypeWithBuiltInMember(uint32_t id) const { 558 return (builtin_structs_.find(id) != builtin_structs_.end()); 559 } 560 561 // Returns the state of optional features. features() const562 const Feature& features() const { return features_; } 563 564 /// Adds the instruction data to unique_type_declarations_. 565 /// Returns false if an identical type declaration already exists. 566 bool RegisterUniqueTypeDeclaration(const Instruction* inst); 567 568 // Returns type_id of the scalar component of |id|. 569 // |id| can be either 570 // - scalar, vector or matrix type 571 // - object of either scalar, vector or matrix type 572 uint32_t GetComponentType(uint32_t id) const; 573 574 // Returns 575 // - 1 for scalar types or objects 576 // - vector size for vector types or objects 577 // - num columns for matrix types or objects 578 // Should not be called with any other arguments (will return zero and invoke 579 // assertion). 580 uint32_t GetDimension(uint32_t id) const; 581 582 // Returns bit width of scalar or component. 583 // |id| can be 584 // - scalar, vector or matrix type 585 // - object of either scalar, vector or matrix type 586 // Will invoke assertion and return 0 if |id| is none of the above. 587 uint32_t GetBitWidth(uint32_t id) const; 588 589 // Provides detailed information on matrix type. 590 // Returns false iff |id| is not matrix type. 591 bool GetMatrixTypeInfo(uint32_t id, uint32_t* num_rows, uint32_t* num_cols, 592 uint32_t* column_type, uint32_t* component_type) const; 593 594 // Collects struct member types into |member_types|. 595 // Returns false iff not struct type or has no members. 596 // Deletes prior contents of |member_types|. 597 bool GetStructMemberTypes(uint32_t struct_type_id, 598 std::vector<uint32_t>* member_types) const; 599 600 // Returns true iff |id| is a type corresponding to the name of the function. 601 // Only works for types not for objects. 602 bool IsVoidType(uint32_t id) const; 603 bool IsFloatScalarType(uint32_t id) const; 604 bool IsFloatVectorType(uint32_t id) const; 605 bool IsFloatScalarOrVectorType(uint32_t id) const; 606 bool IsFloatMatrixType(uint32_t id) const; 607 bool IsIntScalarType(uint32_t id) const; 608 bool IsIntVectorType(uint32_t id) const; 609 bool IsIntScalarOrVectorType(uint32_t id) const; 610 bool IsUnsignedIntScalarType(uint32_t id) const; 611 bool IsUnsignedIntVectorType(uint32_t id) const; 612 bool IsUnsignedIntScalarOrVectorType(uint32_t id) const; 613 bool IsSignedIntScalarType(uint32_t id) const; 614 bool IsSignedIntVectorType(uint32_t id) const; 615 bool IsBoolScalarType(uint32_t id) const; 616 bool IsBoolVectorType(uint32_t id) const; 617 bool IsBoolScalarOrVectorType(uint32_t id) const; 618 bool IsPointerType(uint32_t id) const; 619 bool IsAccelerationStructureType(uint32_t id) const; 620 bool IsCooperativeMatrixType(uint32_t id) const; 621 bool IsCooperativeMatrixNVType(uint32_t id) const; 622 bool IsCooperativeMatrixKHRType(uint32_t id) const; 623 bool IsCooperativeMatrixAType(uint32_t id) const; 624 bool IsCooperativeMatrixBType(uint32_t id) const; 625 bool IsCooperativeMatrixAccType(uint32_t id) const; 626 bool IsFloatCooperativeMatrixType(uint32_t id) const; 627 bool IsIntCooperativeMatrixType(uint32_t id) const; 628 bool IsUnsignedIntCooperativeMatrixType(uint32_t id) const; 629 bool IsUnsigned64BitHandle(uint32_t id) const; 630 631 // Returns true if |id| is a type id that contains |type| (or integer or 632 // floating point type) of |width| bits. 633 bool ContainsSizedIntOrFloatType(uint32_t id, spv::Op type, 634 uint32_t width) const; 635 // Returns true if |id| is a type id that contains a 8- or 16-bit int or 636 // 16-bit float that is not generally enabled for use. 637 bool ContainsLimitedUseIntOrFloatType(uint32_t id) const; 638 639 // Returns true if |id| is a type that contains a runtime-sized array. 640 // Does not consider a pointers as contains the array. 641 bool ContainsRuntimeArray(uint32_t id) const; 642 643 // Generic type traversal. 644 // Only traverse pointers and functions if |traverse_all_types| is true. 645 // Recursively tests |f| against the type hierarchy headed by |id|. 646 bool ContainsType(uint32_t id, 647 const std::function<bool(const Instruction*)>& f, 648 bool traverse_all_types = true) const; 649 650 // Gets value from OpConstant and OpSpecConstant as uint64. 651 // Returns false on failure (no instruction, wrong instruction, not int). 652 bool GetConstantValUint64(uint32_t id, uint64_t* val) const; 653 654 // Returns type_id if id has type or zero otherwise. 655 uint32_t GetTypeId(uint32_t id) const; 656 657 // Returns opcode of the instruction which issued the id or OpNop if the 658 // instruction is not registered. 659 spv::Op GetIdOpcode(uint32_t id) const; 660 661 // Returns type_id for given id operand if it has a type or zero otherwise. 662 // |operand_index| is expected to be pointing towards an operand which is an 663 // id. 664 uint32_t GetOperandTypeId(const Instruction* inst, 665 size_t operand_index) const; 666 667 // Provides information on pointer type. Returns false iff not pointer type. 668 bool GetPointerTypeInfo(uint32_t id, uint32_t* data_type, 669 spv::StorageClass* storage_class) const; 670 671 // Is the ID the type of a pointer to a uniform block: Block-decorated struct 672 // in uniform storage class? The result is only valid after internal method 673 // CheckDecorationsOfBuffers has been called. IsPointerToUniformBlock(uint32_t type_id) const674 bool IsPointerToUniformBlock(uint32_t type_id) const { 675 return pointer_to_uniform_block_.find(type_id) != 676 pointer_to_uniform_block_.cend(); 677 } 678 // Save the ID of a pointer to uniform block. RegisterPointerToUniformBlock(uint32_t type_id)679 void RegisterPointerToUniformBlock(uint32_t type_id) { 680 pointer_to_uniform_block_.insert(type_id); 681 } 682 // Is the ID the type of a struct used as a uniform block? 683 // The result is only valid after internal method CheckDecorationsOfBuffers 684 // has been called. IsStructForUniformBlock(uint32_t type_id) const685 bool IsStructForUniformBlock(uint32_t type_id) const { 686 return struct_for_uniform_block_.find(type_id) != 687 struct_for_uniform_block_.cend(); 688 } 689 // Save the ID of a struct of a uniform block. RegisterStructForUniformBlock(uint32_t type_id)690 void RegisterStructForUniformBlock(uint32_t type_id) { 691 struct_for_uniform_block_.insert(type_id); 692 } 693 // Is the ID the type of a pointer to a storage buffer: BufferBlock-decorated 694 // struct in uniform storage class, or Block-decorated struct in StorageBuffer 695 // storage class? The result is only valid after internal method 696 // CheckDecorationsOfBuffers has been called. IsPointerToStorageBuffer(uint32_t type_id) const697 bool IsPointerToStorageBuffer(uint32_t type_id) const { 698 return pointer_to_storage_buffer_.find(type_id) != 699 pointer_to_storage_buffer_.cend(); 700 } 701 // Save the ID of a pointer to a storage buffer. RegisterPointerToStorageBuffer(uint32_t type_id)702 void RegisterPointerToStorageBuffer(uint32_t type_id) { 703 pointer_to_storage_buffer_.insert(type_id); 704 } 705 // Is the ID the type of a struct for storage buffer? 706 // The result is only valid after internal method CheckDecorationsOfBuffers 707 // has been called. IsStructForStorageBuffer(uint32_t type_id) const708 bool IsStructForStorageBuffer(uint32_t type_id) const { 709 return struct_for_storage_buffer_.find(type_id) != 710 struct_for_storage_buffer_.cend(); 711 } 712 // Save the ID of a struct of a storage buffer. RegisterStructForStorageBuffer(uint32_t type_id)713 void RegisterStructForStorageBuffer(uint32_t type_id) { 714 struct_for_storage_buffer_.insert(type_id); 715 } 716 717 // Is the ID the type of a pointer to a storage image? That is, the pointee 718 // type is an image type which is known to not use a sampler. IsPointerToStorageImage(uint32_t type_id) const719 bool IsPointerToStorageImage(uint32_t type_id) const { 720 return pointer_to_storage_image_.find(type_id) != 721 pointer_to_storage_image_.cend(); 722 } 723 // Save the ID of a pointer to a storage image. RegisterPointerToStorageImage(uint32_t type_id)724 void RegisterPointerToStorageImage(uint32_t type_id) { 725 pointer_to_storage_image_.insert(type_id); 726 } 727 728 // Tries to evaluate a 32-bit signed or unsigned scalar integer constant. 729 // Returns tuple <is_int32, is_const_int32, value>. 730 // OpSpecConstant* return |is_const_int32| as false since their values cannot 731 // be relied upon during validation. 732 std::tuple<bool, bool, uint32_t> EvalInt32IfConst(uint32_t id) const; 733 734 // Returns the disassembly string for the given instruction. 735 std::string Disassemble(const Instruction& inst) const; 736 737 // Returns the disassembly string for the given instruction. 738 std::string Disassemble(const uint32_t* words, uint16_t num_words) const; 739 740 // Returns the string name for |decoration|. SpvDecorationString(uint32_t decoration)741 std::string SpvDecorationString(uint32_t decoration) { 742 spv_operand_desc desc = nullptr; 743 if (grammar_.lookupOperand(SPV_OPERAND_TYPE_DECORATION, decoration, 744 &desc) != SPV_SUCCESS) { 745 return std::string("Unknown"); 746 } 747 return std::string(desc->name); 748 } SpvDecorationString(spv::Decoration decoration)749 std::string SpvDecorationString(spv::Decoration decoration) { 750 return SpvDecorationString(uint32_t(decoration)); 751 } 752 753 // Returns whether type m1 and type m2 are cooperative matrices with 754 // the same "shape" (matching scope, rows, cols). If any are specialization 755 // constants, we assume they can match because we can't prove they don't. 756 spv_result_t CooperativeMatrixShapesMatch(const Instruction* inst, 757 uint32_t m1, uint32_t m2); 758 759 // Returns true if |lhs| and |rhs| logically match and, if the decorations of 760 // |rhs| are a subset of |lhs|. 761 // 762 // 1. Must both be either OpTypeArray or OpTypeStruct 763 // 2. If OpTypeArray, then 764 // * Length must be the same 765 // * Element type must match or logically match 766 // 3. If OpTypeStruct, then 767 // * Both have same number of elements 768 // * Element N for both structs must match or logically match 769 // 770 // If |check_decorations| is false, then the decorations are not checked. 771 bool LogicallyMatch(const Instruction* lhs, const Instruction* rhs, 772 bool check_decorations); 773 774 // Traces |inst| to find a single base pointer. Returns the base pointer. 775 // Will trace through the following instructions: 776 // * OpAccessChain 777 // * OpInBoundsAccessChain 778 // * OpPtrAccessChain 779 // * OpInBoundsPtrAccessChain 780 // * OpCopyObject 781 const Instruction* TracePointer(const Instruction* inst) const; 782 783 // Validates the storage class for the target environment. 784 bool IsValidStorageClass(spv::StorageClass storage_class) const; 785 786 // Takes a Vulkan Valid Usage ID (VUID) as |id| and optional |reference| and 787 // will return a non-empty string only if ID is known and targeting Vulkan. 788 // VUIDs are found in the Vulkan-Docs repo in the form "[[VUID-ref-ref-id]]" 789 // where "id" is always an 5 char long number (with zeros padding) and matches 790 // to |id|. |reference| is used if there is a "common validity" and the VUID 791 // shares the same |id| value. 792 // 793 // More details about Vulkan validation can be found in Vulkan Guide: 794 // https://github.com/KhronosGroup/Vulkan-Guide/blob/master/chapters/validation_overview.md 795 std::string VkErrorID(uint32_t id, const char* reference = nullptr) const; 796 797 // Testing method to allow setting the current layout section. SetCurrentLayoutSectionForTesting(ModuleLayoutSection section)798 void SetCurrentLayoutSectionForTesting(ModuleLayoutSection section) { 799 current_layout_section_ = section; 800 } 801 802 // Check if instruction 'id' is a consumer of a texture decorated 803 // with a QCOM image processing decoration IsQCOMImageProcessingTextureConsumer(uint32_t id)804 bool IsQCOMImageProcessingTextureConsumer(uint32_t id) { 805 return qcom_image_processing_consumers_.find(id) != 806 qcom_image_processing_consumers_.end(); 807 } 808 809 private: 810 ValidationState_t(const ValidationState_t&); 811 812 const spv_const_context context_; 813 814 /// Stores the Validator command line options. Must be a valid options object. 815 const spv_const_validator_options options_; 816 817 /// The SPIR-V binary module we're validating. 818 const uint32_t* words_; 819 const size_t num_words_; 820 821 /// The generator of the SPIR-V. 822 uint32_t generator_ = 0; 823 824 /// The version of the SPIR-V. 825 uint32_t version_ = 0; 826 827 /// The total number of instructions in the binary. 828 size_t total_instructions_ = 0; 829 /// The total number of functions in the binary. 830 size_t total_functions_ = 0; 831 832 /// IDs which have been forward declared but have not been defined 833 std::unordered_set<uint32_t> unresolved_forward_ids_; 834 835 /// IDs that have been declared as forward pointers. 836 std::unordered_set<uint32_t> forward_pointer_ids_; 837 838 /// Stores a vector of instructions that use the result of a given 839 /// OpSampledImage instruction. 840 std::unordered_map<uint32_t, std::vector<Instruction*>> 841 sampled_image_consumers_; 842 843 /// Stores load instructions that load textures used 844 // in QCOM image processing functions 845 std::unordered_set<uint32_t> qcom_image_processing_consumers_; 846 847 /// A map of operand IDs and their names defined by the OpName instruction 848 std::unordered_map<uint32_t, std::string> operand_names_; 849 850 /// The section of the code being processed 851 ModuleLayoutSection current_layout_section_; 852 853 /// A list of functions in the module. 854 /// Pointers to objects in this container are guaranteed to be stable and 855 /// valid until the end of lifetime of the validation state. 856 std::vector<Function> module_functions_; 857 858 /// Capabilities declared in the module 859 CapabilitySet module_capabilities_; 860 861 /// Extensions declared in the module 862 ExtensionSet module_extensions_; 863 864 /// List of all instructions in the order they appear in the binary 865 std::vector<Instruction> ordered_instructions_; 866 867 /// Instructions that can be referenced by Ids 868 std::unordered_map<uint32_t, Instruction*> all_definitions_; 869 870 /// IDs that are entry points, ie, arguments to OpEntryPoint. 871 std::vector<uint32_t> entry_points_; 872 873 /// Maps an entry point id to its descriptions. 874 std::unordered_map<uint32_t, std::vector<EntryPointDescription>> 875 entry_point_descriptions_; 876 877 /// IDs that are entry points, ie, arguments to OpEntryPoint, and root a call 878 /// graph that recurses. 879 std::set<uint32_t> recursive_entry_points_; 880 881 /// Functions IDs that are target of OpFunctionCall. 882 std::unordered_set<uint32_t> function_call_targets_; 883 884 /// ID Bound from the Header 885 uint32_t id_bound_; 886 887 /// Set of Global Variable IDs (Storage Class other than 'Function') 888 std::unordered_set<uint32_t> global_vars_; 889 890 /// Set of Local Variable IDs ('Function' Storage Class) 891 std::unordered_set<uint32_t> local_vars_; 892 893 /// Set of struct types that have members with a BuiltIn decoration. 894 std::unordered_set<uint32_t> builtin_structs_; 895 896 /// Structure Nesting Depth 897 std::unordered_map<uint32_t, uint32_t> struct_nesting_depth_; 898 899 /// Structure has nested blockorbufferblock struct 900 std::unordered_map<uint32_t, bool> 901 struct_has_nested_blockorbufferblock_struct_; 902 903 /// Stores the list of decorations for a given <id> 904 std::map<uint32_t, std::set<Decoration>> id_decorations_; 905 906 /// Stores type declarations which need to be unique (i.e. non-aggregates), 907 /// in the form [opcode, operand words], result_id is not stored. 908 /// Using ordered set to avoid the need for a vector hash function. 909 /// The size of this container is expected not to exceed double-digits. 910 std::set<std::vector<uint32_t>> unique_type_declarations_; 911 912 AssemblyGrammar grammar_; 913 914 spv::AddressingModel addressing_model_; 915 spv::MemoryModel memory_model_; 916 // pointer size derived from addressing model. Assumes all storage classes 917 // have the same pointer size (for physical pointer types). 918 uint32_t pointer_size_and_alignment_; 919 920 /// bit width of sampler/image type variables. Valid values are 32 and 64 921 uint32_t sampler_image_addressing_mode_; 922 923 /// NOTE: See correspoding getter functions 924 bool in_function_; 925 926 /// The state of optional features. These are determined by capabilities 927 /// declared by the module and the environment. 928 Feature features_; 929 930 /// Maps function ids to function stat objects. 931 std::unordered_map<uint32_t, Function*> id_to_function_; 932 933 /// Mapping entry point -> execution models. It is presumed that the same 934 /// function could theoretically be used as 'main' by multiple OpEntryPoint 935 /// instructions. 936 std::unordered_map<uint32_t, std::set<spv::ExecutionModel>> 937 entry_point_to_execution_models_; 938 939 /// Mapping entry point -> execution modes. 940 std::unordered_map<uint32_t, std::set<spv::ExecutionMode>> 941 entry_point_to_execution_modes_; 942 943 /// Mapping function -> array of entry points inside this 944 /// module which can (indirectly) call the function. 945 std::unordered_map<uint32_t, std::vector<uint32_t>> function_to_entry_points_; 946 const std::vector<uint32_t> empty_ids_; 947 948 // The IDs of types of pointers to Block-decorated structs in Uniform storage 949 // class. This is populated at the start of ValidateDecorations. 950 std::unordered_set<uint32_t> pointer_to_uniform_block_; 951 // The IDs of struct types for uniform blocks. 952 // This is populated at the start of ValidateDecorations. 953 std::unordered_set<uint32_t> struct_for_uniform_block_; 954 // The IDs of types of pointers to BufferBlock-decorated structs in Uniform 955 // storage class, or Block-decorated structs in StorageBuffer storage class. 956 // This is populated at the start of ValidateDecorations. 957 std::unordered_set<uint32_t> pointer_to_storage_buffer_; 958 // The IDs of struct types for storage buffers. 959 // This is populated at the start of ValidateDecorations. 960 std::unordered_set<uint32_t> struct_for_storage_buffer_; 961 // The IDs of types of pointers to storage images. This is populated in the 962 // TypePass. 963 std::unordered_set<uint32_t> pointer_to_storage_image_; 964 965 /// Maps ids to friendly names. 966 std::unique_ptr<spvtools::FriendlyNameMapper> friendly_mapper_; 967 spvtools::NameMapper name_mapper_; 968 969 /// Variables used to reduce the number of diagnostic messages. 970 uint32_t num_of_warnings_; 971 uint32_t max_num_of_warnings_; 972 }; 973 974 } // namespace val 975 } // namespace spvtools 976 977 #endif // SOURCE_VAL_VALIDATION_STATE_H_ 978