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