Coverage Report

Created: 2025-02-05 06:34

/src/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/enum_string_mapping.h"
26
#include "source/extensions.h"
27
#include "source/opcode.h"
28
#include "source/spirv_constant.h"
29
#include "source/spirv_endian.h"
30
#include "source/spirv_target_env.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
10.0k
                       const spv_parsed_instruction_t* inst) {
49
10.0k
  const std::string extension_str = spvtools::GetExtensionString(inst);
50
10.0k
  Extension extension;
51
10.0k
  if (!GetExtensionFromString(extension_str.c_str(), &extension)) {
52
    // The error will be logged in the ProcessInstruction pass.
53
7.44k
    return;
54
7.44k
  }
55
56
2.60k
  _.RegisterExtension(extension);
57
2.60k
}
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
87.3k
                               const spv_parsed_instruction_t* inst) {
66
87.3k
  const spv::Op opcode = static_cast<spv::Op>(inst->opcode);
67
87.3k
  if (opcode == spv::Op::OpCapability) return SPV_SUCCESS;
68
69
44.9k
  if (opcode == spv::Op::OpExtension) {
70
10.0k
    ValidationState_t& _ = *(reinterpret_cast<ValidationState_t*>(user_data));
71
10.0k
    RegisterExtension(_, inst);
72
10.0k
    return SPV_SUCCESS;
73
10.0k
  }
74
75
  // OpExtension block is finished, requesting termination.
76
34.8k
  return SPV_REQUESTED_TERMINATION;
77
44.9k
}
78
79
spv_result_t ProcessInstruction(void* user_data,
80
11.6M
                                const spv_parsed_instruction_t* inst) {
81
11.6M
  ValidationState_t& _ = *(reinterpret_cast<ValidationState_t*>(user_data));
82
83
11.6M
  auto* instruction = _.AddOrderedInstruction(inst);
84
11.6M
  _.RegisterDebugInstruction(instruction);
85
86
11.6M
  return SPV_SUCCESS;
87
11.6M
}
88
89
26.4k
spv_result_t ValidateForwardDecls(ValidationState_t& _) {
90
26.4k
  if (_.unresolved_forward_id_count() == 0) return SPV_SUCCESS;
91
92
2.20k
  std::stringstream ss;
93
2.20k
  std::vector<uint32_t> ids = _.UnresolvedForwardIds();
94
95
2.20k
  std::transform(
96
2.20k
      std::begin(ids), std::end(ids),
97
2.20k
      std::ostream_iterator<std::string>(ss, " "),
98
2.20k
      bind(&ValidationState_t::getIdName, std::ref(_), std::placeholders::_1));
99
100
2.20k
  auto id_str = ss.str();
101
2.20k
  return _.diag(SPV_ERROR_INVALID_ID, nullptr)
102
2.20k
         << "The following forward referenced IDs have not been defined:\n"
103
2.20k
         << id_str.substr(0, id_str.size() - 1);
104
26.4k
}
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
18.2k
spv_result_t ValidateEntryPoints(ValidationState_t& _) {
115
18.2k
  _.ComputeFunctionToEntryPointMapping();
116
18.2k
  _.ComputeRecursiveEntryPoints();
117
118
18.2k
  if (_.entry_points().empty() && !_.HasCapability(spv::Capability::Linkage)) {
119
2.78k
    return _.diag(SPV_ERROR_INVALID_BINARY, nullptr)
120
2.78k
           << "No OpEntryPoint instruction was found. This is only allowed if "
121
2.78k
              "the Linkage capability is being used.";
122
2.78k
  }
123
124
15.4k
  for (const auto& entry_point : _.entry_points()) {
125
12.1k
    if (_.IsFunctionCallTarget(entry_point)) {
126
43
      return _.diag(SPV_ERROR_INVALID_BINARY, _.FindDef(entry_point))
127
43
             << "A function (" << entry_point
128
43
             << ") may not be targeted by both an OpEntryPoint instruction and "
129
43
                "an OpFunctionCall instruction.";
130
43
    }
131
132
    // For Vulkan, the static function-call graph for an entry point
133
    // must not contain cycles.
134
12.0k
    if (spvIsVulkanEnv(_.context()->target_env)) {
135
0
      if (_.recursive_entry_points().find(entry_point) !=
136
0
          _.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
0
    }
142
12.0k
  }
143
144
15.4k
  if (auto error = ValidateFloatControls2(_)) {
145
0
    return error;
146
0
  }
147
15.4k
  if (auto error = ValidateDuplicateExecutionModes(_)) {
148
223
    return error;
149
223
  }
150
151
15.2k
  return SPV_SUCCESS;
152
15.4k
}
153
154
spv_result_t ValidateBinaryUsingContextAndValidationState(
155
    const spv_context_t& context, const uint32_t* words, const size_t num_words,
156
38.3k
    spv_diagnostic* pDiagnostic, ValidationState_t* vstate) {
157
38.3k
  auto binary = std::unique_ptr<spv_const_binary_t>(
158
38.3k
      new spv_const_binary_t{words, num_words});
159
160
38.3k
  spv_endianness_t endian;
161
38.3k
  spv_position_t position = {};
162
38.3k
  if (spvBinaryEndianness(binary.get(), &endian)) {
163
86
    return DiagnosticStream(position, context.consumer, "",
164
86
                            SPV_ERROR_INVALID_BINARY)
165
86
           << "Invalid SPIR-V magic number.";
166
86
  }
167
168
38.2k
  spv_header_t header;
169
38.2k
  if (spvBinaryHeaderGet(binary.get(), endian, &header)) {
170
51
    return DiagnosticStream(position, context.consumer, "",
171
51
                            SPV_ERROR_INVALID_BINARY)
172
51
           << "Invalid SPIR-V header.";
173
51
  }
174
175
38.2k
  if (header.version > spvVersionForTargetEnv(context.target_env)) {
176
652
    return DiagnosticStream(position, context.consumer, "",
177
652
                            SPV_ERROR_WRONG_VERSION)
178
652
           << "Invalid SPIR-V binary version "
179
652
           << SPV_SPIRV_VERSION_MAJOR_PART(header.version) << "."
180
652
           << SPV_SPIRV_VERSION_MINOR_PART(header.version)
181
652
           << " for target environment "
182
652
           << spvTargetEnvDescription(context.target_env) << ".";
183
652
  }
184
185
37.5k
  if (header.bound > vstate->options()->universal_limits_.max_id_bound) {
186
1.11k
    return DiagnosticStream(position, context.consumer, "",
187
1.11k
                            SPV_ERROR_INVALID_BINARY)
188
1.11k
           << "Invalid SPIR-V.  The id bound is larger than the max id bound "
189
1.11k
           << vstate->options()->universal_limits_.max_id_bound << ".";
190
1.11k
  }
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
36.4k
  spv_context_t hijacked_context = context;
197
36.4k
  hijacked_context.consumer = [](spv_message_level_t, const char*,
198
36.4k
                                 const spv_position_t&, const char*) {};
199
36.4k
  spvBinaryParse(&hijacked_context, vstate, words, num_words,
200
36.4k
                 /* parsed_header = */ nullptr, ProcessExtensions,
201
36.4k
                 /* 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
36.4k
  if (auto error = spvBinaryParse(&context, vstate, words, num_words,
206
36.4k
                                  /*parsed_header =*/nullptr,
207
36.4k
                                  ProcessInstruction, pDiagnostic)) {
208
1.13k
    return error;
209
1.13k
  }
210
211
35.3k
  bool has_mask_task_nv = false;
212
35.3k
  bool has_mask_task_ext = false;
213
35.3k
  std::vector<Instruction*> visited_entry_points;
214
11.1M
  for (auto& instruction : vstate->ordered_instructions()) {
215
11.1M
    {
216
      // In order to do this work outside of Process Instruction we need to be
217
      // able to, briefly, de-const the instruction.
218
11.1M
      Instruction* inst = const_cast<Instruction*>(&instruction);
219
220
11.1M
      if (inst->opcode() == spv::Op::OpEntryPoint) {
221
19.2k
        const auto entry_point = inst->GetOperandAs<uint32_t>(1);
222
19.2k
        const auto execution_model = inst->GetOperandAs<spv::ExecutionModel>(0);
223
19.2k
        const std::string desc_name = inst->GetOperandAs<std::string>(2);
224
225
19.2k
        ValidationState_t::EntryPointDescription desc;
226
19.2k
        desc.name = desc_name;
227
228
19.2k
        std::vector<uint32_t> interfaces;
229
1.90M
        for (size_t j = 3; j < inst->operands().size(); ++j)
230
1.88M
          desc.interfaces.push_back(inst->word(inst->operand(j).offset));
231
232
19.2k
        vstate->RegisterEntryPoint(entry_point, execution_model,
233
19.2k
                                   std::move(desc));
234
235
19.2k
        if (visited_entry_points.size() > 0) {
236
13.6k
          for (const Instruction* check_inst : visited_entry_points) {
237
13.6k
            const auto check_execution_model =
238
13.6k
                check_inst->GetOperandAs<spv::ExecutionModel>(0);
239
13.6k
            const std::string check_name =
240
13.6k
                check_inst->GetOperandAs<std::string>(2);
241
242
13.6k
            if (desc_name == check_name &&
243
13.6k
                execution_model == check_execution_model) {
244
105
              return vstate->diag(SPV_ERROR_INVALID_DATA, inst)
245
105
                     << "2 Entry points cannot share the same name and "
246
105
                        "ExecutionMode.";
247
105
            }
248
13.6k
          }
249
3.35k
        }
250
19.1k
        visited_entry_points.push_back(inst);
251
252
19.1k
        has_mask_task_nv |= (execution_model == spv::ExecutionModel::TaskNV ||
253
19.1k
                             execution_model == spv::ExecutionModel::MeshNV);
254
19.1k
        has_mask_task_ext |= (execution_model == spv::ExecutionModel::TaskEXT ||
255
19.1k
                              execution_model == spv::ExecutionModel::MeshEXT);
256
19.1k
      }
257
11.1M
      if (inst->opcode() == spv::Op::OpFunctionCall) {
258
17.0k
        if (!vstate->in_function_body()) {
259
1
          return vstate->diag(SPV_ERROR_INVALID_LAYOUT, &instruction)
260
1
                 << "A FunctionCall must happen within a function body.";
261
1
        }
262
263
17.0k
        const auto called_id = inst->GetOperandAs<uint32_t>(2);
264
17.0k
        vstate->AddFunctionCallTarget(called_id);
265
17.0k
      }
266
267
11.1M
      if (vstate->in_function_body()) {
268
1.83M
        inst->set_function(&(vstate->current_function()));
269
1.83M
        inst->set_block(vstate->current_function().current_block());
270
271
1.83M
        if (vstate->in_block() && spvOpcodeIsBlockTerminator(inst->opcode())) {
272
319k
          vstate->current_function().current_block()->set_terminator(inst);
273
319k
        }
274
1.83M
      }
275
276
11.1M
      if (auto error = IdPass(*vstate, inst)) return error;
277
11.1M
    }
278
279
11.1M
    if (auto error = CapabilityPass(*vstate, &instruction)) return error;
280
11.1M
    if (auto error = ModuleLayoutPass(*vstate, &instruction)) return error;
281
11.1M
    if (auto error = CfgPass(*vstate, &instruction)) return error;
282
11.1M
    if (auto error = InstructionPass(*vstate, &instruction)) return error;
283
284
    // Now that all of the checks are done, update the state.
285
11.1M
    {
286
11.1M
      Instruction* inst = const_cast<Instruction*>(&instruction);
287
11.1M
      vstate->RegisterInstruction(inst);
288
11.1M
      if (inst->opcode() == spv::Op::OpTypeForwardPointer) {
289
765
        vstate->RegisterForwardPointer(inst->GetOperandAs<uint32_t>(0));
290
765
      }
291
11.1M
    }
292
11.1M
  }
293
294
28.6k
  if (!vstate->has_memory_model_specified())
295
666
    return vstate->diag(SPV_ERROR_INVALID_LAYOUT, nullptr)
296
666
           << "Missing required OpMemoryModel instruction.";
297
298
27.9k
  if (vstate->in_function_body())
299
1.50k
    return vstate->diag(SPV_ERROR_INVALID_LAYOUT, nullptr)
300
1.50k
           << "Missing OpFunctionEnd at end of module.";
301
302
26.4k
  if (vstate->HasCapability(spv::Capability::BindlessTextureNV) &&
303
26.4k
      !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
26.4k
  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
26.4k
  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
24.2k
  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
10.6M
  for (size_t i = 0; i < vstate->ordered_instructions().size(); ++i) {
329
10.6M
    auto& instruction = vstate->ordered_instructions()[i];
330
10.6M
    if (auto error = UpdateIdUse(*vstate, &instruction)) return error;
331
10.6M
  }
332
333
  // Validate individual opcodes.
334
10.5M
  for (size_t i = 0; i < vstate->ordered_instructions().size(); ++i) {
335
10.4M
    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
10.4M
    if (auto error = MiscPass(*vstate, &instruction)) return error;
340
10.4M
    if (auto error = DebugPass(*vstate, &instruction)) return error;
341
10.4M
    if (auto error = AnnotationPass(*vstate, &instruction)) return error;
342
10.4M
    if (auto error = ExtensionPass(*vstate, &instruction)) return error;
343
10.4M
    if (auto error = ModeSettingPass(*vstate, &instruction)) return error;
344
10.4M
    if (auto error = TypePass(*vstate, &instruction)) return error;
345
10.4M
    if (auto error = ConstantPass(*vstate, &instruction)) return error;
346
10.4M
    if (auto error = MemoryPass(*vstate, &instruction)) return error;
347
10.4M
    if (auto error = FunctionPass(*vstate, &instruction)) return error;
348
10.4M
    if (auto error = ImagePass(*vstate, &instruction)) return error;
349
10.4M
    if (auto error = ConversionPass(*vstate, &instruction)) return error;
350
10.4M
    if (auto error = CompositesPass(*vstate, &instruction)) return error;
351
10.4M
    if (auto error = ArithmeticsPass(*vstate, &instruction)) return error;
352
10.4M
    if (auto error = BitwisePass(*vstate, &instruction)) return error;
353
10.4M
    if (auto error = LogicalsPass(*vstate, &instruction)) return error;
354
10.4M
    if (auto error = ControlFlowPass(*vstate, &instruction)) return error;
355
10.4M
    if (auto error = DerivativesPass(*vstate, &instruction)) return error;
356
10.4M
    if (auto error = AtomicsPass(*vstate, &instruction)) return error;
357
10.4M
    if (auto error = PrimitivesPass(*vstate, &instruction)) return error;
358
10.4M
    if (auto error = BarriersPass(*vstate, &instruction)) return error;
359
    // Group
360
    // Device-Side Enqueue
361
    // Pipe
362
10.4M
    if (auto error = NonUniformPass(*vstate, &instruction)) return error;
363
364
10.4M
    if (auto error = LiteralsPass(*vstate, &instruction)) return error;
365
10.4M
    if (auto error = RayQueryPass(*vstate, &instruction)) return error;
366
10.4M
    if (auto error = RayTracingPass(*vstate, &instruction)) return error;
367
10.4M
    if (auto error = RayReorderNVPass(*vstate, &instruction)) return error;
368
10.4M
    if (auto error = MeshShadingPass(*vstate, &instruction)) return error;
369
10.4M
    if (auto error = TensorLayoutPass(*vstate, &instruction)) return error;
370
10.4M
  }
371
372
  // Validate the preconditions involving adjacent instructions. e.g.
373
  // spv::Op::OpPhi must only be preceded by spv::Op::OpLabel, spv::Op::OpPhi,
374
  // or spv::Op::OpLine.
375
18.3k
  if (auto error = ValidateAdjacency(*vstate)) return error;
376
377
18.2k
  if (auto error = ValidateEntryPoints(*vstate)) return error;
378
  // CFG checks are performed after the binary has been parsed
379
  // and the CFGPass has collected information about the control flow
380
15.2k
  if (auto error = PerformCfgChecks(*vstate)) return error;
381
13.9k
  if (auto error = CheckIdDefinitionDominateUse(*vstate)) return error;
382
13.8k
  if (auto error = ValidateDecorations(*vstate)) return error;
383
12.4k
  if (auto error = ValidateInterfaces(*vstate)) return error;
384
  // TODO(dsinclair): Restructure ValidateBuiltins so we can move into the
385
  // for() above as it loops over all ordered_instructions internally.
386
12.2k
  if (auto error = ValidateBuiltIns(*vstate)) return error;
387
  // These checks must be performed after individual opcode checks because
388
  // those checks register the limitation checked here.
389
8.99M
  for (const auto& inst : vstate->ordered_instructions()) {
390
8.99M
    if (auto error = ValidateExecutionLimitations(*vstate, &inst)) return error;
391
8.99M
    if (auto error = ValidateSmallTypeUses(*vstate, &inst)) return error;
392
8.99M
    if (auto error = ValidateQCOMImageProcessingTextureUsages(*vstate, &inst))
393
0
      return error;
394
8.99M
  }
395
396
12.1k
  return SPV_SUCCESS;
397
12.2k
}
398
399
}  // namespace
400
401
spv_result_t ValidateBinaryAndKeepValidationState(
402
    const spv_const_context context, spv_const_validator_options options,
403
    const uint32_t* words, const size_t num_words, spv_diagnostic* pDiagnostic,
404
0
    std::unique_ptr<ValidationState_t>* vstate) {
405
0
  spv_context_t hijack_context = *context;
406
0
  if (pDiagnostic) {
407
0
    *pDiagnostic = nullptr;
408
0
    UseDiagnosticAsMessageConsumer(&hijack_context, pDiagnostic);
409
0
  }
410
411
0
  vstate->reset(new ValidationState_t(&hijack_context, options, words,
412
0
                                      num_words, kDefaultMaxNumOfWarnings));
413
414
0
  return ValidateBinaryUsingContextAndValidationState(
415
0
      hijack_context, words, num_words, pDiagnostic, vstate->get());
416
0
}
417
418
}  // namespace val
419
}  // namespace spvtools
420
421
spv_result_t spvValidate(const spv_const_context context,
422
                         const spv_const_binary binary,
423
0
                         spv_diagnostic* pDiagnostic) {
424
0
  return spvValidateBinary(context, binary->code, binary->wordCount,
425
0
                           pDiagnostic);
426
0
}
427
428
spv_result_t spvValidateBinary(const spv_const_context context,
429
                               const uint32_t* words, const size_t num_words,
430
17.2k
                               spv_diagnostic* pDiagnostic) {
431
17.2k
  spv_context_t hijack_context = *context;
432
17.2k
  if (pDiagnostic) {
433
0
    *pDiagnostic = nullptr;
434
0
    spvtools::UseDiagnosticAsMessageConsumer(&hijack_context, pDiagnostic);
435
0
  }
436
437
  // This interface is used for default command line options.
438
17.2k
  spv_validator_options default_options = spvValidatorOptionsCreate();
439
440
  // Create the ValidationState using the context and default options.
441
17.2k
  spvtools::val::ValidationState_t vstate(&hijack_context, default_options,
442
17.2k
                                          words, num_words,
443
17.2k
                                          kDefaultMaxNumOfWarnings);
444
445
17.2k
  spv_result_t result =
446
17.2k
      spvtools::val::ValidateBinaryUsingContextAndValidationState(
447
17.2k
          hijack_context, words, num_words, pDiagnostic, &vstate);
448
449
17.2k
  spvValidatorOptionsDestroy(default_options);
450
17.2k
  return result;
451
17.2k
}
452
453
spv_result_t spvValidateWithOptions(const spv_const_context context,
454
                                    spv_const_validator_options options,
455
                                    const spv_const_binary binary,
456
21.1k
                                    spv_diagnostic* pDiagnostic) {
457
21.1k
  spv_context_t hijack_context = *context;
458
21.1k
  if (pDiagnostic) {
459
21.1k
    *pDiagnostic = nullptr;
460
21.1k
    spvtools::UseDiagnosticAsMessageConsumer(&hijack_context, pDiagnostic);
461
21.1k
  }
462
463
  // Create the ValidationState using the context.
464
21.1k
  spvtools::val::ValidationState_t vstate(&hijack_context, options,
465
21.1k
                                          binary->code, binary->wordCount,
466
21.1k
                                          kDefaultMaxNumOfWarnings);
467
468
21.1k
  return spvtools::val::ValidateBinaryUsingContextAndValidationState(
469
21.1k
      hijack_context, binary->code, binary->wordCount, pDiagnostic, &vstate);
470
21.1k
}