Coverage Report

Created: 2025-07-12 07:43

/src/shaderc/third_party/spirv-tools/source/val/validate.cpp
Line
Count
Source (jump to first uncovered line)
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
#include "source/val/validate.h"
16
17
#include <functional>
18
#include <iterator>
19
#include <memory>
20
#include <string>
21
#include <vector>
22
23
#include "source/binary.h"
24
#include "source/diagnostic.h"
25
#include "source/extensions.h"
26
#include "source/opcode.h"
27
#include "source/spirv_constant.h"
28
#include "source/spirv_endian.h"
29
#include "source/spirv_target_env.h"
30
#include "source/table2.h"
31
#include "source/val/construct.h"
32
#include "source/val/instruction.h"
33
#include "source/val/validation_state.h"
34
#include "spirv-tools/libspirv.h"
35
36
namespace {
37
// TODO(issue 1950): The validator only returns a single message anyway, so no
38
// point in generating more than 1 warning.
39
static uint32_t kDefaultMaxNumOfWarnings = 1;
40
}  // namespace
41
42
namespace spvtools {
43
namespace val {
44
namespace {
45
46
// Parses OpExtension instruction and registers extension.
47
void RegisterExtension(ValidationState_t& _,
48
1.11k
                       const spv_parsed_instruction_t* inst) {
49
1.11k
  const std::string extension_str = spvtools::GetExtensionString(inst);
50
1.11k
  Extension extension;
51
1.11k
  if (!GetExtensionFromString(extension_str.c_str(), &extension)) {
52
    // The error will be logged in the ProcessInstruction pass.
53
46
    return;
54
46
  }
55
56
1.07k
  _.RegisterExtension(extension);
57
1.07k
}
58
59
// Parses the beginning of the module searching for OpExtension instructions.
60
// Registers extensions if recognized. Returns SPV_REQUESTED_TERMINATION
61
// once an instruction which is not spv::Op::OpCapability and
62
// spv::Op::OpExtension is encountered. According to the SPIR-V spec extensions
63
// are declared after capabilities and before everything else.
64
spv_result_t ProcessExtensions(void* user_data,
65
6.03k
                               const spv_parsed_instruction_t* inst) {
66
6.03k
  const spv::Op opcode = static_cast<spv::Op>(inst->opcode);
67
6.03k
  if (opcode == spv::Op::OpCapability) return SPV_SUCCESS;
68
69
3.04k
  if (opcode == spv::Op::OpExtension) {
70
1.11k
    ValidationState_t& _ = *(reinterpret_cast<ValidationState_t*>(user_data));
71
1.11k
    RegisterExtension(_, inst);
72
1.11k
    return SPV_SUCCESS;
73
1.11k
  }
74
75
  // OpExtension block is finished, requesting termination.
76
1.92k
  return SPV_REQUESTED_TERMINATION;
77
3.04k
}
78
79
spv_result_t ProcessInstruction(void* user_data,
80
243k
                                const spv_parsed_instruction_t* inst) {
81
243k
  ValidationState_t& _ = *(reinterpret_cast<ValidationState_t*>(user_data));
82
83
243k
  auto* instruction = _.AddOrderedInstruction(inst);
84
243k
  _.RegisterDebugInstruction(instruction);
85
86
243k
  return SPV_SUCCESS;
87
243k
}
88
89
1.86k
spv_result_t ValidateForwardDecls(ValidationState_t& _) {
90
1.86k
  if (_.unresolved_forward_id_count() == 0) return SPV_SUCCESS;
91
92
0
  std::stringstream ss;
93
0
  std::vector<uint32_t> ids = _.UnresolvedForwardIds();
94
95
0
  std::transform(
96
0
      std::begin(ids), std::end(ids),
97
0
      std::ostream_iterator<std::string>(ss, " "),
98
0
      bind(&ValidationState_t::getIdName, std::ref(_), std::placeholders::_1));
99
100
0
  auto id_str = ss.str();
101
0
  return _.diag(SPV_ERROR_INVALID_ID, nullptr)
102
0
         << "The following forward referenced IDs have not been defined:\n"
103
0
         << id_str.substr(0, id_str.size() - 1);
104
1.86k
}
105
106
// Entry point validation. Based on 2.16.1 (Universal Validation Rules) of the
107
// SPIRV spec:
108
// * There is at least one OpEntryPoint instruction, unless the Linkage
109
//   capability is being used.
110
// * No function can be targeted by both an OpEntryPoint instruction and an
111
//   OpFunctionCall instruction.
112
//
113
// Additionally enforces that entry points for Vulkan should not have recursion.
114
1.80k
spv_result_t ValidateEntryPoints(ValidationState_t& _) {
115
1.80k
  _.ComputeFunctionToEntryPointMapping();
116
1.80k
  _.ComputeRecursiveEntryPoints();
117
118
1.80k
  if (_.entry_points().empty() && !_.HasCapability(spv::Capability::Linkage)) {
119
0
    return _.diag(SPV_ERROR_INVALID_BINARY, nullptr)
120
0
           << "No OpEntryPoint instruction was found. This is only allowed if "
121
0
              "the Linkage capability is being used.";
122
0
  }
123
124
1.80k
  for (const auto& entry_point : _.entry_points()) {
125
1.80k
    if (_.IsFunctionCallTarget(entry_point)) {
126
0
      return _.diag(SPV_ERROR_INVALID_BINARY, _.FindDef(entry_point))
127
0
             << "A function (" << entry_point
128
0
             << ") may not be targeted by both an OpEntryPoint instruction and "
129
0
                "an OpFunctionCall instruction.";
130
0
    }
131
132
    // For Vulkan, the static function-call graph for an entry point
133
    // must not contain cycles.
134
1.80k
    if (spvIsVulkanEnv(_.context()->target_env)) {
135
1.80k
      if (_.recursive_entry_points().find(entry_point) !=
136
1.80k
          _.recursive_entry_points().end()) {
137
0
        return _.diag(SPV_ERROR_INVALID_BINARY, _.FindDef(entry_point))
138
0
               << _.VkErrorID(4634)
139
0
               << "Entry points may not have a call graph with cycles.";
140
0
      }
141
1.80k
    }
142
1.80k
  }
143
144
1.80k
  if (auto error = ValidateFloatControls2(_)) {
145
0
    return error;
146
0
  }
147
1.80k
  if (auto error = ValidateDuplicateExecutionModes(_)) {
148
0
    return error;
149
0
  }
150
151
1.80k
  return SPV_SUCCESS;
152
1.80k
}
153
154
spv_result_t ValidateBinaryUsingContextAndValidationState(
155
    const spv_context_t& context, const uint32_t* words, const size_t num_words,
156
1.92k
    spv_diagnostic* pDiagnostic, ValidationState_t* vstate) {
157
1.92k
  auto binary = std::unique_ptr<spv_const_binary_t>(
158
1.92k
      new spv_const_binary_t{words, num_words});
159
160
1.92k
  spv_endianness_t endian;
161
1.92k
  spv_position_t position = {};
162
1.92k
  if (spvBinaryEndianness(binary.get(), &endian)) {
163
0
    return DiagnosticStream(position, context.consumer, "",
164
0
                            SPV_ERROR_INVALID_BINARY)
165
0
           << "Invalid SPIR-V magic number.";
166
0
  }
167
168
1.92k
  spv_header_t header;
169
1.92k
  if (spvBinaryHeaderGet(binary.get(), endian, &header)) {
170
0
    return DiagnosticStream(position, context.consumer, "",
171
0
                            SPV_ERROR_INVALID_BINARY)
172
0
           << "Invalid SPIR-V header.";
173
0
  }
174
175
1.92k
  if (header.version > spvVersionForTargetEnv(context.target_env)) {
176
0
    return DiagnosticStream(position, context.consumer, "",
177
0
                            SPV_ERROR_WRONG_VERSION)
178
0
           << "Invalid SPIR-V binary version "
179
0
           << SPV_SPIRV_VERSION_MAJOR_PART(header.version) << "."
180
0
           << SPV_SPIRV_VERSION_MINOR_PART(header.version)
181
0
           << " for target environment "
182
0
           << spvTargetEnvDescription(context.target_env) << ".";
183
0
  }
184
185
1.92k
  if (header.bound > vstate->options()->universal_limits_.max_id_bound) {
186
0
    return DiagnosticStream(position, context.consumer, "",
187
0
                            SPV_ERROR_INVALID_BINARY)
188
0
           << "Invalid SPIR-V.  The id bound is larger than the max id bound "
189
0
           << vstate->options()->universal_limits_.max_id_bound << ".";
190
0
  }
191
192
  // Look for OpExtension instructions and register extensions.
193
  // This parse should not produce any error messages. Hijack the context and
194
  // replace the message consumer so that we do not pollute any state in input
195
  // consumer.
196
1.92k
  spv_context_t hijacked_context = context;
197
1.92k
  hijacked_context.consumer = [](spv_message_level_t, const char*,
198
1.92k
                                 const spv_position_t&, const char*) {};
199
1.92k
  spvBinaryParse(&hijacked_context, vstate, words, num_words,
200
1.92k
                 /* parsed_header = */ nullptr, ProcessExtensions,
201
1.92k
                 /* diagnostic = */ nullptr);
202
203
  // Parse the module and perform inline validation checks. These checks do
204
  // not require the knowledge of the whole module.
205
1.92k
  if (auto error = spvBinaryParse(&context, vstate, words, num_words,
206
1.92k
                                  /*parsed_header =*/nullptr,
207
1.92k
                                  ProcessInstruction, pDiagnostic)) {
208
20
    return error;
209
20
  }
210
211
1.90k
  bool has_mask_task_nv = false;
212
1.90k
  bool has_mask_task_ext = false;
213
1.90k
  std::vector<Instruction*> visited_entry_points;
214
230k
  for (auto& instruction : vstate->ordered_instructions()) {
215
230k
    {
216
      // In order to do this work outside of Process Instruction we need to be
217
      // able to, briefly, de-const the instruction.
218
230k
      Instruction* inst = const_cast<Instruction*>(&instruction);
219
220
230k
      if (inst->opcode() == spv::Op::OpEntryPoint) {
221
1.88k
        const auto entry_point = inst->GetOperandAs<uint32_t>(1);
222
1.88k
        const auto execution_model = inst->GetOperandAs<spv::ExecutionModel>(0);
223
1.88k
        const std::string desc_name = inst->GetOperandAs<std::string>(2);
224
225
1.88k
        ValidationState_t::EntryPointDescription desc;
226
1.88k
        desc.name = desc_name;
227
228
1.88k
        std::vector<uint32_t> interfaces;
229
3.12k
        for (size_t j = 3; j < inst->operands().size(); ++j)
230
1.24k
          desc.interfaces.push_back(inst->word(inst->operand(j).offset));
231
232
1.88k
        vstate->RegisterEntryPoint(entry_point, execution_model,
233
1.88k
                                   std::move(desc));
234
235
1.88k
        if (visited_entry_points.size() > 0) {
236
0
          for (const Instruction* check_inst : visited_entry_points) {
237
0
            const auto check_execution_model =
238
0
                check_inst->GetOperandAs<spv::ExecutionModel>(0);
239
0
            const std::string check_name =
240
0
                check_inst->GetOperandAs<std::string>(2);
241
242
0
            if (desc_name == check_name &&
243
0
                execution_model == check_execution_model) {
244
0
              return vstate->diag(SPV_ERROR_INVALID_DATA, inst)
245
0
                     << "2 Entry points cannot share the same name and "
246
0
                        "ExecutionMode.";
247
0
            }
248
0
          }
249
0
        }
250
1.88k
        visited_entry_points.push_back(inst);
251
252
1.88k
        has_mask_task_nv |= (execution_model == spv::ExecutionModel::TaskNV ||
253
1.88k
                             execution_model == spv::ExecutionModel::MeshNV);
254
1.88k
        has_mask_task_ext |= (execution_model == spv::ExecutionModel::TaskEXT ||
255
1.88k
                              execution_model == spv::ExecutionModel::MeshEXT);
256
1.88k
      }
257
230k
      if (inst->opcode() == spv::Op::OpFunctionCall) {
258
1.55k
        if (!vstate->in_function_body()) {
259
0
          return vstate->diag(SPV_ERROR_INVALID_LAYOUT, &instruction)
260
0
                 << "A FunctionCall must happen within a function body.";
261
0
        }
262
263
1.55k
        const auto called_id = inst->GetOperandAs<uint32_t>(2);
264
1.55k
        vstate->AddFunctionCallTarget(called_id);
265
1.55k
      }
266
267
230k
      if (vstate->in_function_body()) {
268
131k
        inst->set_function(&(vstate->current_function()));
269
131k
        inst->set_block(vstate->current_function().current_block());
270
271
131k
        if (vstate->in_block() && spvOpcodeIsBlockTerminator(inst->opcode())) {
272
11.7k
          vstate->current_function().current_block()->set_terminator(inst);
273
11.7k
        }
274
131k
      }
275
276
230k
      if (auto error = IdPass(*vstate, inst)) return error;
277
230k
    }
278
279
230k
    if (auto error = CapabilityPass(*vstate, &instruction)) return error;
280
230k
    if (auto error = ModuleLayoutPass(*vstate, &instruction)) return error;
281
230k
    if (auto error = CfgPass(*vstate, &instruction)) return error;
282
230k
    if (auto error = InstructionPass(*vstate, &instruction)) return error;
283
284
    // Now that all of the checks are done, update the state.
285
230k
    {
286
230k
      Instruction* inst = const_cast<Instruction*>(&instruction);
287
230k
      vstate->RegisterInstruction(inst);
288
230k
      if (inst->opcode() == spv::Op::OpTypeForwardPointer) {
289
128
        vstate->RegisterForwardPointer(inst->GetOperandAs<uint32_t>(0));
290
128
      }
291
230k
    }
292
230k
  }
293
294
1.86k
  if (!vstate->has_memory_model_specified())
295
0
    return vstate->diag(SPV_ERROR_INVALID_LAYOUT, nullptr)
296
0
           << "Missing required OpMemoryModel instruction.";
297
298
1.86k
  if (vstate->in_function_body())
299
0
    return vstate->diag(SPV_ERROR_INVALID_LAYOUT, nullptr)
300
0
           << "Missing OpFunctionEnd at end of module.";
301
302
1.86k
  if (vstate->HasCapability(spv::Capability::BindlessTextureNV) &&
303
1.86k
      !vstate->has_samplerimage_variable_address_mode_specified())
304
0
    return vstate->diag(SPV_ERROR_INVALID_LAYOUT, nullptr)
305
0
           << "Missing required OpSamplerImageAddressingModeNV instruction.";
306
307
1.86k
  if (has_mask_task_ext && has_mask_task_nv)
308
0
    return vstate->diag(SPV_ERROR_INVALID_LAYOUT, nullptr)
309
0
           << vstate->VkErrorID(7102)
310
0
           << "Module can't mix MeshEXT/TaskEXT with MeshNV/TaskNV Execution "
311
0
              "Model.";
312
313
  // Catch undefined forward references before performing further checks.
314
1.86k
  if (auto error = ValidateForwardDecls(*vstate)) return error;
315
316
  // Calculate reachability after all the blocks are parsed, but early that it
317
  // can be relied on in subsequent pases.
318
1.86k
  ReachabilityPass(*vstate);
319
320
  // ID usage needs be handled in its own iteration of the instructions,
321
  // between the two others. It depends on the first loop to have been
322
  // finished, so that all instructions have been registered. And the following
323
  // loop depends on all of the usage data being populated. Thus it cannot live
324
  // in either of those iterations.
325
  // It should also live after the forward declaration check, since it will
326
  // have problems with missing forward declarations, but give less useful error
327
  // messages.
328
231k
  for (size_t i = 0; i < vstate->ordered_instructions().size(); ++i) {
329
229k
    auto& instruction = vstate->ordered_instructions()[i];
330
229k
    if (auto error = UpdateIdUse(*vstate, &instruction)) return error;
331
229k
  }
332
333
  // Validate individual opcodes.
334
227k
  for (size_t i = 0; i < vstate->ordered_instructions().size(); ++i) {
335
225k
    auto& instruction = vstate->ordered_instructions()[i];
336
337
    // Keep these passes in the order they appear in the SPIR-V specification
338
    // sections to maintain test consistency.
339
225k
    if (auto error = MiscPass(*vstate, &instruction)) return error;
340
225k
    if (auto error = DebugPass(*vstate, &instruction)) return error;
341
225k
    if (auto error = AnnotationPass(*vstate, &instruction)) return error;
342
225k
    if (auto error = ExtensionPass(*vstate, &instruction)) return error;
343
225k
    if (auto error = ModeSettingPass(*vstate, &instruction)) return error;
344
225k
    if (auto error = TypePass(*vstate, &instruction)) return error;
345
225k
    if (auto error = ConstantPass(*vstate, &instruction)) return error;
346
225k
    if (auto error = MemoryPass(*vstate, &instruction)) return error;
347
225k
    if (auto error = FunctionPass(*vstate, &instruction)) return error;
348
225k
    if (auto error = ImagePass(*vstate, &instruction)) return error;
349
225k
    if (auto error = ConversionPass(*vstate, &instruction)) return error;
350
225k
    if (auto error = CompositesPass(*vstate, &instruction)) return error;
351
225k
    if (auto error = ArithmeticsPass(*vstate, &instruction)) return error;
352
225k
    if (auto error = BitwisePass(*vstate, &instruction)) return error;
353
225k
    if (auto error = LogicalsPass(*vstate, &instruction)) return error;
354
225k
    if (auto error = ControlFlowPass(*vstate, &instruction)) return error;
355
225k
    if (auto error = DerivativesPass(*vstate, &instruction)) return error;
356
225k
    if (auto error = AtomicsPass(*vstate, &instruction)) return error;
357
225k
    if (auto error = PrimitivesPass(*vstate, &instruction)) return error;
358
225k
    if (auto error = BarriersPass(*vstate, &instruction)) return error;
359
    // Group
360
    // Device-Side Enqueue
361
    // Pipe
362
225k
    if (auto error = NonUniformPass(*vstate, &instruction)) return error;
363
364
225k
    if (auto error = LiteralsPass(*vstate, &instruction)) return error;
365
225k
    if (auto error = RayQueryPass(*vstate, &instruction)) return error;
366
225k
    if (auto error = RayTracingPass(*vstate, &instruction)) return error;
367
225k
    if (auto error = RayReorderNVPass(*vstate, &instruction)) return error;
368
225k
    if (auto error = MeshShadingPass(*vstate, &instruction)) return error;
369
225k
    if (auto error = TensorLayoutPass(*vstate, &instruction)) return error;
370
225k
    if (auto error = TensorPass(*vstate, &instruction)) return error;
371
225k
    if (auto error = InvalidTypePass(*vstate, &instruction)) return error;
372
225k
  }
373
374
  // Validate the preconditions involving adjacent instructions. e.g.
375
  // spv::Op::OpPhi must only be preceded by spv::Op::OpLabel, spv::Op::OpPhi,
376
  // or spv::Op::OpLine.
377
1.80k
  if (auto error = ValidateAdjacency(*vstate)) return error;
378
379
1.80k
  if (auto error = ValidateEntryPoints(*vstate)) return error;
380
  // CFG checks are performed after the binary has been parsed
381
  // and the CFGPass has collected information about the control flow
382
1.80k
  if (auto error = PerformCfgChecks(*vstate)) return error;
383
1.80k
  if (auto error = CheckIdDefinitionDominateUse(*vstate)) return error;
384
1.80k
  if (auto error = ValidateDecorations(*vstate)) return error;
385
1.80k
  if (auto error = ValidateInterfaces(*vstate)) return error;
386
  // TODO(dsinclair): Restructure ValidateBuiltins so we can move into the
387
  // for() above as it loops over all ordered_instructions internally.
388
1.80k
  if (auto error = ValidateBuiltIns(*vstate)) return error;
389
  // These checks must be performed after individual opcode checks because
390
  // those checks register the limitation checked here.
391
223k
  for (const auto& inst : vstate->ordered_instructions()) {
392
223k
    if (auto error = ValidateExecutionLimitations(*vstate, &inst)) return error;
393
223k
    if (auto error = ValidateSmallTypeUses(*vstate, &inst)) return error;
394
223k
    if (auto error = ValidateQCOMImageProcessingTextureUsages(*vstate, &inst))
395
0
      return error;
396
223k
  }
397
398
1.80k
  return SPV_SUCCESS;
399
1.80k
}
400
401
}  // namespace
402
403
spv_result_t ValidateBinaryAndKeepValidationState(
404
    const spv_const_context context, spv_const_validator_options options,
405
    const uint32_t* words, const size_t num_words, spv_diagnostic* pDiagnostic,
406
0
    std::unique_ptr<ValidationState_t>* vstate) {
407
0
  spv_context_t hijack_context = *context;
408
0
  if (pDiagnostic) {
409
0
    *pDiagnostic = nullptr;
410
0
    UseDiagnosticAsMessageConsumer(&hijack_context, pDiagnostic);
411
0
  }
412
413
0
  vstate->reset(new ValidationState_t(&hijack_context, options, words,
414
0
                                      num_words, kDefaultMaxNumOfWarnings));
415
416
0
  return ValidateBinaryUsingContextAndValidationState(
417
0
      hijack_context, words, num_words, pDiagnostic, vstate->get());
418
0
}
419
420
}  // namespace val
421
}  // namespace spvtools
422
423
spv_result_t spvValidate(const spv_const_context context,
424
                         const spv_const_binary binary,
425
0
                         spv_diagnostic* pDiagnostic) {
426
0
  return spvValidateBinary(context, binary->code, binary->wordCount,
427
0
                           pDiagnostic);
428
0
}
429
430
spv_result_t spvValidateBinary(const spv_const_context context,
431
                               const uint32_t* words, const size_t num_words,
432
0
                               spv_diagnostic* pDiagnostic) {
433
0
  spv_context_t hijack_context = *context;
434
0
  if (pDiagnostic) {
435
0
    *pDiagnostic = nullptr;
436
0
    spvtools::UseDiagnosticAsMessageConsumer(&hijack_context, pDiagnostic);
437
0
  }
438
439
  // This interface is used for default command line options.
440
0
  spv_validator_options default_options = spvValidatorOptionsCreate();
441
442
  // Create the ValidationState using the context and default options.
443
0
  spvtools::val::ValidationState_t vstate(&hijack_context, default_options,
444
0
                                          words, num_words,
445
0
                                          kDefaultMaxNumOfWarnings);
446
447
0
  spv_result_t result =
448
0
      spvtools::val::ValidateBinaryUsingContextAndValidationState(
449
0
          hijack_context, words, num_words, pDiagnostic, &vstate);
450
451
0
  spvValidatorOptionsDestroy(default_options);
452
0
  return result;
453
0
}
454
455
spv_result_t spvValidateWithOptions(const spv_const_context context,
456
                                    spv_const_validator_options options,
457
                                    const spv_const_binary binary,
458
1.92k
                                    spv_diagnostic* pDiagnostic) {
459
1.92k
  spv_context_t hijack_context = *context;
460
1.92k
  if (pDiagnostic) {
461
1.92k
    *pDiagnostic = nullptr;
462
1.92k
    spvtools::UseDiagnosticAsMessageConsumer(&hijack_context, pDiagnostic);
463
1.92k
  }
464
465
  // Create the ValidationState using the context.
466
1.92k
  spvtools::val::ValidationState_t vstate(&hijack_context, options,
467
1.92k
                                          binary->code, binary->wordCount,
468
1.92k
                                          kDefaultMaxNumOfWarnings);
469
470
1.92k
  return spvtools::val::ValidateBinaryUsingContextAndValidationState(
471
1.92k
      hijack_context, binary->code, binary->wordCount, pDiagnostic, &vstate);
472
1.92k
}