Coverage Report

Created: 2026-09-28 07:06

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/spirv-tools/source/val/validate_memory.cpp
Line
Count
Source
1
// Copyright (c) 2018 Google LLC.
2
// Modifications Copyright (C) 2020-2024 Advanced Micro Devices, Inc. All
3
// rights reserved.
4
// Copyright (C) 2026 Qualcomm Technologies, Inc.
5
//
6
// Licensed under the Apache License, Version 2.0 (the "License");
7
// you may not use this file except in compliance with the License.
8
// You may obtain a copy of the License at
9
//
10
//     http://www.apache.org/licenses/LICENSE-2.0
11
//
12
// Unless required by applicable law or agreed to in writing, software
13
// distributed under the License is distributed on an "AS IS" BASIS,
14
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
// See the License for the specific language governing permissions and
16
// limitations under the License.
17
18
#include <algorithm>
19
#include <cstdint>
20
#include <string>
21
#include <vector>
22
23
#include "source/opcode.h"
24
#include "source/spirv_target_env.h"
25
#include "source/table2.h"
26
#include "source/val/instruction.h"
27
#include "source/val/validate.h"
28
#include "source/val/validate_scopes.h"
29
#include "source/val/validation_state.h"
30
31
namespace spvtools {
32
namespace val {
33
namespace {
34
35
bool AreLayoutCompatibleStructs(ValidationState_t&, const Instruction*,
36
                                const Instruction*);
37
bool HaveLayoutCompatibleMembers(ValidationState_t&, const Instruction*,
38
                                 const Instruction*);
39
bool HaveSameLayoutDecorations(ValidationState_t&, const Instruction*,
40
                               const Instruction*);
41
bool HasConflictingMemberOffsets(const std::set<Decoration>&,
42
                                 const std::set<Decoration>&);
43
44
bool IsAllowedTypeOrArrayOfSame(ValidationState_t& _, const Instruction& type,
45
0
                                std::initializer_list<spv::Op> allowed) {
46
0
  if (std::find(allowed.begin(), allowed.end(), type.opcode()) !=
47
0
      allowed.end()) {
48
0
    return true;
49
0
  }
50
0
  if (type.opcode() == spv::Op::OpTypeArray ||
51
0
      type.opcode() == spv::Op::OpTypeRuntimeArray) {
52
0
    auto elem_type = _.FindDef(type.word(2));
53
0
    return std::find(allowed.begin(), allowed.end(), elem_type->opcode()) !=
54
0
           allowed.end();
55
0
  }
56
0
  return false;
57
0
}
58
59
// Returns true if the two instructions represent structs that, as far as the
60
// validator can tell, have the exact same data layout.
61
bool AreLayoutCompatibleStructs(ValidationState_t& _, const Instruction* type1,
62
0
                                const Instruction* type2) {
63
0
  if (type1->opcode() != spv::Op::OpTypeStruct) {
64
0
    return false;
65
0
  }
66
0
  if (type2->opcode() != spv::Op::OpTypeStruct) {
67
0
    return false;
68
0
  }
69
70
0
  if (!HaveLayoutCompatibleMembers(_, type1, type2)) return false;
71
72
0
  return HaveSameLayoutDecorations(_, type1, type2);
73
0
}
74
75
// Returns true if the operands to the OpTypeStruct instruction defining the
76
// types are the same or are layout compatible types. |type1| and |type2| must
77
// be OpTypeStruct instructions.
78
bool HaveLayoutCompatibleMembers(ValidationState_t& _, const Instruction* type1,
79
0
                                 const Instruction* type2) {
80
0
  assert(type1->opcode() == spv::Op::OpTypeStruct &&
81
0
         "type1 must be an OpTypeStruct instruction.");
82
0
  assert(type2->opcode() == spv::Op::OpTypeStruct &&
83
0
         "type2 must be an OpTypeStruct instruction.");
84
0
  const auto& type1_operands = type1->operands();
85
0
  const auto& type2_operands = type2->operands();
86
0
  if (type1_operands.size() != type2_operands.size()) {
87
0
    return false;
88
0
  }
89
90
0
  for (size_t operand = 2; operand < type1_operands.size(); ++operand) {
91
0
    if (type1->word(operand) != type2->word(operand)) {
92
0
      auto def1 = _.FindDef(type1->word(operand));
93
0
      auto def2 = _.FindDef(type2->word(operand));
94
0
      if (!AreLayoutCompatibleStructs(_, def1, def2)) {
95
0
        return false;
96
0
      }
97
0
    }
98
0
  }
99
0
  return true;
100
0
}
101
102
// Returns true if all decorations that affect the data layout of the struct
103
// (like Offset), are the same for the two types. |type1| and |type2| must be
104
// OpTypeStruct instructions.
105
bool HaveSameLayoutDecorations(ValidationState_t& _, const Instruction* type1,
106
0
                               const Instruction* type2) {
107
0
  assert(type1->opcode() == spv::Op::OpTypeStruct &&
108
0
         "type1 must be an OpTypeStruct instruction.");
109
0
  assert(type2->opcode() == spv::Op::OpTypeStruct &&
110
0
         "type2 must be an OpTypeStruct instruction.");
111
0
  const std::set<Decoration>& type1_decorations = _.id_decorations(type1->id());
112
0
  const std::set<Decoration>& type2_decorations = _.id_decorations(type2->id());
113
114
  // TODO: Will have to add other check for arrays an matricies if we want to
115
  // handle them.
116
0
  if (HasConflictingMemberOffsets(type1_decorations, type2_decorations)) {
117
0
    return false;
118
0
  }
119
120
0
  return true;
121
0
}
122
123
bool HasConflictingMemberOffsets(
124
    const std::set<Decoration>& type1_decorations,
125
0
    const std::set<Decoration>& type2_decorations) {
126
0
  {
127
    // We are interested in conflicting decoration.  If a decoration is in one
128
    // list but not the other, then we will assume the code is correct.  We are
129
    // looking for things we know to be wrong.
130
    //
131
    // We do not have to traverse type2_decoration because, after traversing
132
    // type1_decorations, anything new will not be found in
133
    // type1_decoration.  Therefore, it cannot lead to a conflict.
134
0
    for (const Decoration& decoration : type1_decorations) {
135
0
      switch (decoration.dec_type()) {
136
0
        case spv::Decoration::Offset: {
137
          // Since these affect the layout of the struct, they must be present
138
          // in both structs.
139
0
          auto compare = [&decoration](const Decoration& rhs) {
140
0
            if (rhs.dec_type() != spv::Decoration::Offset) return false;
141
0
            return decoration.struct_member_index() ==
142
0
                   rhs.struct_member_index();
143
0
          };
144
0
          auto i = std::find_if(type2_decorations.begin(),
145
0
                                type2_decorations.end(), compare);
146
0
          if (i != type2_decorations.end() &&
147
0
              decoration.params().front() != i->params().front()) {
148
0
            return true;
149
0
          }
150
0
        } break;
151
0
        default:
152
          // This decoration does not affect the layout of the structure, so
153
          // just moving on.
154
0
          break;
155
0
      }
156
0
    }
157
0
  }
158
0
  return false;
159
0
}
160
161
// If |skip_builtin| is true, returns true if |storage| contains bool within
162
// it and no storage that contains the bool is builtin.
163
// If |skip_builtin| is false, returns true if |storage| contains bool within
164
// it.
165
bool ContainsInvalidBool(ValidationState_t& _, const Instruction* storage,
166
86.8k
                         bool skip_builtin) {
167
86.8k
  if (skip_builtin) {
168
50.1k
    for (const Decoration& decoration : _.id_decorations(storage->id())) {
169
22.6k
      if (decoration.dec_type() == spv::Decoration::BuiltIn) return false;
170
22.6k
    }
171
50.1k
  }
172
173
86.7k
  const size_t elem_type_index = 1;
174
86.7k
  uint32_t elem_type_id;
175
86.7k
  Instruction* elem_type;
176
177
86.7k
  switch (storage->opcode()) {
178
14
    case spv::Op::OpTypeBool:
179
14
      return true;
180
31.9k
    case spv::Op::OpTypeVector:
181
32.2k
    case spv::Op::OpTypeMatrix:
182
33.9k
    case spv::Op::OpTypeArray:
183
34.6k
    case spv::Op::OpTypeRuntimeArray:
184
34.6k
      elem_type_id = storage->GetOperandAs<uint32_t>(elem_type_index);
185
34.6k
      elem_type = _.FindDef(elem_type_id);
186
34.6k
      return ContainsInvalidBool(_, elem_type, skip_builtin);
187
13.7k
    case spv::Op::OpTypeStruct:
188
13.7k
      for (size_t member_type_index = 1;
189
29.0k
           member_type_index < storage->operands().size();
190
15.3k
           ++member_type_index) {
191
15.3k
        auto member_type_id =
192
15.3k
            storage->GetOperandAs<uint32_t>(member_type_index);
193
15.3k
        auto member_type = _.FindDef(member_type_id);
194
15.3k
        if (ContainsInvalidBool(_, member_type, skip_builtin)) return true;
195
15.3k
      }
196
52.0k
    default:
197
52.0k
      break;
198
86.7k
  }
199
52.0k
  return false;
200
86.7k
}
201
202
std::pair<Instruction*, Instruction*> GetPointerTypes(ValidationState_t& _,
203
729k
                                                      const Instruction* inst) {
204
729k
  Instruction* dst_pointer_type = nullptr;
205
729k
  Instruction* src_pointer_type = nullptr;
206
729k
  switch (inst->opcode()) {
207
0
    case spv::Op::OpCooperativeMatrixLoadNV:
208
0
    case spv::Op::OpCooperativeMatrixLoadTensorNV:
209
0
    case spv::Op::OpCooperativeMatrixLoadKHR:
210
0
    case spv::Op::OpCooperativeVectorLoadNV:
211
320k
    case spv::Op::OpLoad:
212
320k
    case spv::Op::OpPredicatedLoadINTEL: {
213
320k
      auto load_pointer = _.FindDef(inst->GetOperandAs<uint32_t>(2));
214
320k
      dst_pointer_type = _.FindDef(load_pointer->type_id());
215
320k
      break;
216
320k
    }
217
0
    case spv::Op::OpCooperativeMatrixStoreNV:
218
0
    case spv::Op::OpCooperativeMatrixStoreTensorNV:
219
0
    case spv::Op::OpCooperativeMatrixStoreKHR:
220
0
    case spv::Op::OpCooperativeVectorStoreNV:
221
258k
    case spv::Op::OpStore:
222
258k
    case spv::Op::OpPredicatedStoreINTEL: {
223
258k
      auto store_pointer = _.FindDef(inst->GetOperandAs<uint32_t>(0));
224
258k
      dst_pointer_type = _.FindDef(store_pointer->type_id());
225
258k
      break;
226
258k
    }
227
    // Spec: "Matching Storage Class is not required"
228
150k
    case spv::Op::OpCopyMemory:
229
150k
    case spv::Op::OpCopyMemorySized: {
230
150k
      auto dst_pointer = _.FindDef(inst->GetOperandAs<uint32_t>(0));
231
150k
      dst_pointer_type = _.FindDef(dst_pointer->type_id());
232
150k
      auto src_pointer = _.FindDef(inst->GetOperandAs<uint32_t>(1));
233
150k
      src_pointer_type = _.FindDef(src_pointer->type_id());
234
150k
      break;
235
150k
    }
236
0
    default:
237
0
      break;
238
729k
  }
239
240
729k
  return std::make_pair(dst_pointer_type, src_pointer_type);
241
729k
}
242
243
// Returns the number of instruction words taken up by a memory access
244
// argument and its implied operands.
245
73.1k
int MemoryAccessNumWords(uint32_t mask) {
246
73.1k
  int result = 1;  // Count the mask
247
73.1k
  if (mask & uint32_t(spv::MemoryAccessMask::Aligned)) ++result;
248
73.1k
  if (mask & uint32_t(spv::MemoryAccessMask::MakePointerAvailableKHR)) ++result;
249
73.1k
  if (mask & uint32_t(spv::MemoryAccessMask::MakePointerVisibleKHR)) ++result;
250
73.1k
  if (mask & uint32_t(spv::MemoryAccessMask::AliasScopeINTELMask)) ++result;
251
73.1k
  if (mask & uint32_t(spv::MemoryAccessMask::NoAliasINTELMask)) ++result;
252
73.1k
  return result;
253
73.1k
}
254
255
// Returns the scope ID operand for MakeAvailable memory access with mask
256
// at the given operand index.
257
// This function is only called for OpLoad, OpStore, OpCopyMemory and
258
// OpCopyMemorySized, OpCooperativeMatrixLoadNV,
259
// OpCooperativeMatrixStoreNV, OpCooperativeVectorLoadNV,
260
// OpCooperativeVectorStoreNV.
261
uint32_t GetMakeAvailableScope(const Instruction* inst, uint32_t mask,
262
0
                               uint32_t mask_index) {
263
0
  assert(mask & uint32_t(spv::MemoryAccessMask::MakePointerAvailableKHR));
264
0
  uint32_t this_bit = uint32_t(spv::MemoryAccessMask::MakePointerAvailableKHR);
265
0
  uint32_t index =
266
0
      mask_index - 1 + MemoryAccessNumWords(mask & (this_bit | (this_bit - 1)));
267
0
  return inst->GetOperandAs<uint32_t>(index);
268
0
}
269
270
// This function is only called for OpLoad, OpStore, OpCopyMemory,
271
// OpCopyMemorySized, OpCooperativeMatrixLoadNV,
272
// OpCooperativeMatrixStoreNV, OpCooperativeVectorLoadNV,
273
// OpCooperativeVectorStoreNV.
274
uint32_t GetMakeVisibleScope(const Instruction* inst, uint32_t mask,
275
0
                             uint32_t mask_index) {
276
0
  assert(mask & uint32_t(spv::MemoryAccessMask::MakePointerVisibleKHR));
277
0
  uint32_t this_bit = uint32_t(spv::MemoryAccessMask::MakePointerVisibleKHR);
278
0
  uint32_t index =
279
0
      mask_index - 1 + MemoryAccessNumWords(mask & (this_bit | (this_bit - 1)));
280
0
  return inst->GetOperandAs<uint32_t>(index);
281
0
}
282
283
0
bool DoesStructContainRTA(const ValidationState_t& _, const Instruction* inst) {
284
0
  for (size_t member_index = 1; member_index < inst->operands().size();
285
0
       ++member_index) {
286
0
    const auto member_id = inst->GetOperandAs<uint32_t>(member_index);
287
0
    const auto member_type = _.FindDef(member_id);
288
0
    if (member_type->opcode() == spv::Op::OpTypeRuntimeArray) return true;
289
0
  }
290
0
  return false;
291
0
}
292
293
spv_result_t CheckMemoryAccess(ValidationState_t& _, const Instruction* inst,
294
729k
                               uint32_t index) {
295
729k
  Instruction* dst_pointer_type = nullptr;
296
729k
  Instruction* src_pointer_type = nullptr;  // only used for OpCopyMemory
297
729k
  std::tie(dst_pointer_type, src_pointer_type) = GetPointerTypes(_, inst);
298
299
729k
  const spv::StorageClass dst_sc =
300
729k
      dst_pointer_type ? dst_pointer_type->GetOperandAs<spv::StorageClass>(1)
301
729k
                       : spv::StorageClass::Max;
302
729k
  const spv::StorageClass src_sc =
303
729k
      src_pointer_type ? src_pointer_type->GetOperandAs<spv::StorageClass>(1)
304
729k
                       : spv::StorageClass::Max;
305
306
729k
  if (inst->operands().size() <= index) {
307
    // Cases where lack of some operand is invalid
308
569k
    if (src_sc == spv::StorageClass::PhysicalStorageBuffer ||
309
569k
        dst_sc == spv::StorageClass::PhysicalStorageBuffer) {
310
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
311
0
             << _.VkErrorID(4708)
312
0
             << "Memory accesses with PhysicalStorageBuffer must use Aligned.";
313
0
    }
314
569k
    return SPV_SUCCESS;
315
569k
  }
316
317
160k
  const uint32_t mask = inst->GetOperandAs<uint32_t>(index);
318
160k
  if (mask & uint32_t(spv::MemoryAccessMask::MakePointerAvailableKHR)) {
319
0
    if (inst->opcode() == spv::Op::OpLoad ||
320
0
        inst->opcode() == spv::Op::OpCooperativeMatrixLoadNV ||
321
0
        inst->opcode() == spv::Op::OpCooperativeMatrixLoadTensorNV ||
322
0
        inst->opcode() == spv::Op::OpCooperativeMatrixLoadKHR ||
323
0
        inst->opcode() == spv::Op::OpCooperativeVectorLoadNV ||
324
0
        inst->opcode() == spv::Op::OpPredicatedLoadINTEL) {
325
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
326
0
             << "MakePointerAvailableKHR cannot be used with OpLoad.";
327
0
    }
328
329
0
    if (!(mask & uint32_t(spv::MemoryAccessMask::NonPrivatePointerKHR))) {
330
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
331
0
             << "NonPrivatePointerKHR must be specified if "
332
0
                "MakePointerAvailableKHR is specified.";
333
0
    }
334
335
    // Check the associated scope for MakeAvailableKHR.
336
0
    const auto available_scope = GetMakeAvailableScope(inst, mask, index);
337
0
    if (auto error = ValidateMemoryScope(_, inst, available_scope))
338
0
      return error;
339
0
  }
340
341
160k
  if (mask & uint32_t(spv::MemoryAccessMask::MakePointerVisibleKHR)) {
342
0
    if (inst->opcode() == spv::Op::OpStore ||
343
0
        inst->opcode() == spv::Op::OpCooperativeMatrixStoreNV ||
344
0
        inst->opcode() == spv::Op::OpCooperativeMatrixStoreKHR ||
345
0
        inst->opcode() == spv::Op::OpCooperativeMatrixStoreTensorNV ||
346
0
        inst->opcode() == spv::Op::OpCooperativeVectorStoreNV ||
347
0
        inst->opcode() == spv::Op::OpPredicatedStoreINTEL) {
348
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
349
0
             << "MakePointerVisibleKHR cannot be used with OpStore.";
350
0
    }
351
352
0
    if (!(mask & uint32_t(spv::MemoryAccessMask::NonPrivatePointerKHR))) {
353
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
354
0
             << "NonPrivatePointerKHR must be specified if "
355
0
             << "MakePointerVisibleKHR is specified.";
356
0
    }
357
358
    // Check the associated scope for MakeVisibleKHR.
359
0
    const auto visible_scope = GetMakeVisibleScope(inst, mask, index);
360
0
    if (auto error = ValidateMemoryScope(_, inst, visible_scope)) return error;
361
0
  }
362
363
160k
  if (mask & uint32_t(spv::MemoryAccessMask::NonPrivatePointerKHR)) {
364
0
    if (dst_sc != spv::StorageClass::Uniform &&
365
0
        dst_sc != spv::StorageClass::Workgroup &&
366
0
        dst_sc != spv::StorageClass::CrossWorkgroup &&
367
0
        dst_sc != spv::StorageClass::Generic &&
368
0
        dst_sc != spv::StorageClass::Image &&
369
0
        dst_sc != spv::StorageClass::StorageBuffer &&
370
0
        dst_sc != spv::StorageClass::PhysicalStorageBuffer) {
371
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
372
0
             << "NonPrivatePointerKHR requires a pointer in Uniform, "
373
0
             << "Workgroup, CrossWorkgroup, Generic, Image or StorageBuffer "
374
0
             << "storage classes.";
375
0
    }
376
0
    if (src_sc != spv::StorageClass::Max &&
377
0
        src_sc != spv::StorageClass::Uniform &&
378
0
        src_sc != spv::StorageClass::Workgroup &&
379
0
        src_sc != spv::StorageClass::CrossWorkgroup &&
380
0
        src_sc != spv::StorageClass::Generic &&
381
0
        src_sc != spv::StorageClass::Image &&
382
0
        src_sc != spv::StorageClass::StorageBuffer &&
383
0
        src_sc != spv::StorageClass::PhysicalStorageBuffer) {
384
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
385
0
             << "NonPrivatePointerKHR requires a pointer in Uniform, "
386
0
             << "Workgroup, CrossWorkgroup, Generic, Image or StorageBuffer "
387
0
             << "storage classes.";
388
0
    }
389
0
  }
390
391
160k
  if (!(mask & uint32_t(spv::MemoryAccessMask::Aligned))) {
392
160k
    if (src_sc == spv::StorageClass::PhysicalStorageBuffer ||
393
160k
        dst_sc == spv::StorageClass::PhysicalStorageBuffer) {
394
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
395
0
             << _.VkErrorID(4708)
396
0
             << "Memory accesses with PhysicalStorageBuffer must use Aligned.";
397
0
    }
398
160k
  } else {
399
    // even if there are other masks, the Aligned operand will be next
400
89
    const uint32_t aligned_value = inst->GetOperandAs<uint32_t>(index + 1);
401
89
    const bool is_power_of_two =
402
89
        aligned_value && !(aligned_value & (aligned_value - 1));
403
89
    if (!is_power_of_two) {
404
10
      return _.diag(SPV_ERROR_INVALID_ID, inst)
405
10
             << "Memory accesses Aligned operand value " << aligned_value
406
10
             << " is not a power of two.";
407
10
    }
408
409
79
    uint32_t largest_scalar = 0;
410
79
    if (dst_sc == spv::StorageClass::PhysicalStorageBuffer) {
411
0
      if (dst_pointer_type->opcode() != spv::Op::OpTypeUntypedPointerKHR) {
412
0
        largest_scalar =
413
0
            _.GetLargestScalarType(dst_pointer_type->GetOperandAs<uint32_t>(2));
414
0
      } else if (inst->type_id() != 0) {
415
0
        largest_scalar = _.GetLargestScalarType(inst->type_id());
416
0
      } else {
417
        // TODO need to handle cases like OpStore and OpCopyMemorySized which
418
        // don't have a result type
419
0
      }
420
0
    }
421
    // TODO - Handle Untyped in OpCopyMemory
422
79
    if (src_sc == spv::StorageClass::PhysicalStorageBuffer &&
423
0
        src_pointer_type->opcode() != spv::Op::OpTypeUntypedPointerKHR) {
424
0
      largest_scalar = std::max(
425
0
          largest_scalar,
426
0
          _.GetLargestScalarType(src_pointer_type->GetOperandAs<uint32_t>(2)));
427
0
    }
428
79
    if (aligned_value < largest_scalar) {
429
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
430
0
             << _.VkErrorID(6314) << "Memory accesses Aligned operand value "
431
0
             << aligned_value << " is too small, the largest scalar type is "
432
0
             << largest_scalar << " bytes.";
433
0
    }
434
79
  }
435
436
160k
  return SPV_SUCCESS;
437
160k
}
438
439
spv_result_t ValidateVariableInitializer(ValidationState_t& _,
440
                                         const Instruction* inst,
441
                                         spv::StorageClass storage_class,
442
203k
                                         uint32_t value_id) {
443
203k
  const bool untyped_pointer = inst->opcode() == spv::Op::OpUntypedVariableKHR;
444
203k
  const uint32_t initializer_index = untyped_pointer ? 4u : 3u;
445
203k
  if (initializer_index < inst->operands().size()) {
446
6.89k
    const uint32_t initializer_id =
447
6.89k
        inst->GetOperandAs<uint32_t>(initializer_index);
448
6.89k
    const Instruction* initializer = _.FindDef(initializer_id);
449
6.89k
    const uint32_t storage_class_index = 2u;
450
6.89k
    const bool is_module_scope_var =
451
6.89k
        initializer &&
452
6.89k
        (initializer->opcode() == spv::Op::OpVariable ||
453
6.88k
         initializer->opcode() == spv::Op::OpUntypedVariableKHR) &&
454
4
        (initializer->GetOperandAs<spv::StorageClass>(storage_class_index) !=
455
4
         spv::StorageClass::Function);
456
6.89k
    const bool is_constant =
457
6.89k
        initializer && spvOpcodeIsConstant(initializer->opcode());
458
6.89k
    if (!initializer || !(is_constant || is_module_scope_var)) {
459
7
      return _.diag(SPV_ERROR_INVALID_ID, inst)
460
7
             << "Variable Initializer <id> " << _.getIdName(initializer_id)
461
7
             << " is not a constant or module-scope variable.";
462
7
    }
463
6.88k
    if (initializer->type_id() != value_id) {
464
5
      return _.diag(SPV_ERROR_INVALID_ID, inst)
465
5
             << "Initializer type must match the data type";
466
5
    }
467
6.88k
  }
468
469
  // Vulkan Appendix A: Check that if contains initializer, then
470
  // storage class is Output, Private, or Function.
471
203k
  if (inst->operands().size() > initializer_index &&
472
6.88k
      storage_class != spv::StorageClass::Output &&
473
6.75k
      storage_class != spv::StorageClass::Private &&
474
1.78k
      storage_class != spv::StorageClass::Function) {
475
20
    if (spvIsVulkanEnv(_.context()->target_env)) {
476
0
      if (storage_class == spv::StorageClass::Workgroup) {
477
0
        auto init_id = inst->GetOperandAs<uint32_t>(initializer_index);
478
0
        auto init = _.FindDef(init_id);
479
0
        if (init->opcode() != spv::Op::OpConstantNull) {
480
0
          return _.diag(SPV_ERROR_INVALID_ID, inst)
481
0
                 << _.VkErrorID(4734) << "OpVariable, <id> "
482
0
                 << _.getIdName(inst->id())
483
0
                 << ", initializers are limited to OpConstantNull in "
484
0
                    "Workgroup "
485
0
                    "storage class";
486
0
        }
487
0
      } else if (storage_class != spv::StorageClass::Output &&
488
0
                 storage_class != spv::StorageClass::Private &&
489
0
                 storage_class != spv::StorageClass::Function) {
490
0
        return _.diag(SPV_ERROR_INVALID_ID, inst)
491
0
               << _.VkErrorID(4651) << "OpVariable, <id> "
492
0
               << _.getIdName(inst->id())
493
0
               << ", has a disallowed initializer & storage class "
494
0
               << "combination.\n"
495
0
               << "From " << spvLogStringForEnv(_.context()->target_env)
496
0
               << " spec:\n"
497
0
               << "Variable declarations that include initializers must have "
498
0
               << "one of the following storage classes: Output, Private, "
499
0
               << "Function or Workgroup";
500
0
      }
501
0
    }
502
20
  }
503
504
203k
  if (initializer_index < inst->operands().size()) {
505
6.88k
    if (storage_class == spv::StorageClass::TaskPayloadWorkgroupEXT) {
506
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
507
0
             << "OpVariable, <id> " << _.getIdName(inst->id())
508
0
             << ", initializer are not allowed for TaskPayloadWorkgroupEXT";
509
0
    }
510
6.88k
    if (storage_class == spv::StorageClass::Input) {
511
5
      return _.diag(SPV_ERROR_INVALID_ID, inst)
512
5
             << "OpVariable, <id> " << _.getIdName(inst->id())
513
5
             << ", initializer are not allowed for Input";
514
5
    }
515
6.87k
    if (storage_class == spv::StorageClass::HitObjectAttributeNV) {
516
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
517
0
             << "OpVariable, <id> " << _.getIdName(inst->id())
518
0
             << ", initializer are not allowed for HitObjectAttributeNV";
519
0
    }
520
6.87k
    if (storage_class == spv::StorageClass::HitObjectAttributeEXT) {
521
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
522
0
             << "OpVariable, <id> " << _.getIdName(inst->id())
523
0
             << ", initializer are not allowed for HitObjectAttributeEXT";
524
0
    }
525
6.87k
  }
526
527
203k
  return SPV_SUCCESS;
528
203k
}
529
530
spv_result_t ValidateVariableStorageClass(ValidationState_t& _,
531
                                          const Instruction* inst,
532
                                          spv::StorageClass storage_class,
533
203k
                                          const Instruction* value_type) {
534
203k
  if (storage_class != spv::StorageClass::Workgroup &&
535
202k
      storage_class != spv::StorageClass::CrossWorkgroup &&
536
202k
      storage_class != spv::StorageClass::Private &&
537
189k
      storage_class != spv::StorageClass::Function &&
538
43.5k
      storage_class != spv::StorageClass::UniformConstant &&
539
40.3k
      storage_class != spv::StorageClass::RayPayloadKHR &&
540
40.3k
      storage_class != spv::StorageClass::IncomingRayPayloadKHR &&
541
40.3k
      storage_class != spv::StorageClass::HitAttributeKHR &&
542
40.3k
      storage_class != spv::StorageClass::CallableDataKHR &&
543
40.3k
      storage_class != spv::StorageClass::IncomingCallableDataKHR &&
544
40.3k
      storage_class != spv::StorageClass::TaskPayloadWorkgroupEXT &&
545
40.3k
      storage_class != spv::StorageClass::HitObjectAttributeNV &&
546
40.3k
      storage_class != spv::StorageClass::HitObjectAttributeEXT &&
547
40.3k
      storage_class != spv::StorageClass::NodePayloadAMDX) {
548
40.3k
    bool storage_input_or_output = storage_class == spv::StorageClass::Input ||
549
28.6k
                                   storage_class == spv::StorageClass::Output;
550
40.3k
    bool builtin = false;
551
40.3k
    if (storage_input_or_output) {
552
27.8k
      for (const Decoration& decoration : _.id_decorations(inst->id())) {
553
15.4k
        if (decoration.dec_type() == spv::Decoration::BuiltIn) {
554
3.45k
          builtin = true;
555
3.45k
          break;
556
3.45k
        }
557
15.4k
      }
558
27.8k
    }
559
40.3k
    if (!builtin && value_type &&
560
36.9k
        ContainsInvalidBool(_, value_type, storage_input_or_output)) {
561
14
      if (storage_input_or_output) {
562
6
        return _.diag(SPV_ERROR_INVALID_ID, inst)
563
6
               << _.VkErrorID(7290)
564
6
               << "If OpTypeBool is stored in conjunction with OpVariable "
565
6
                  "using Input or Output Storage Classes it requires a BuiltIn "
566
6
                  "decoration";
567
568
8
      } else {
569
8
        return _.diag(SPV_ERROR_INVALID_ID, inst)
570
8
               << "If OpTypeBool is stored in conjunction with OpVariable, it "
571
8
                  "can only be used with non-externally visible shader Storage "
572
8
                  "Classes: Workgroup, CrossWorkgroup, Private, Function, "
573
8
                  "Input, Output, RayPayloadKHR, IncomingRayPayloadKHR, "
574
8
                  "HitAttributeKHR, CallableDataKHR, "
575
8
                  "IncomingCallableDataKHR, NodePayloadAMDX, or "
576
8
                  "UniformConstant";
577
8
      }
578
14
    }
579
40.3k
  }
580
581
202k
  if (!_.IsValidStorageClass(storage_class)) {
582
0
    return _.diag(SPV_ERROR_INVALID_BINARY, inst)
583
0
           << _.VkErrorID(4643)
584
0
           << "Invalid storage class for target environment";
585
0
  }
586
587
202k
  if (storage_class == spv::StorageClass::Generic) {
588
3
    return _.diag(SPV_ERROR_INVALID_BINARY, inst)
589
3
           << "Variable storage class cannot be Generic";
590
3
  }
591
592
202k
  if (inst->function() && storage_class != spv::StorageClass::Function) {
593
30
    return _.diag(SPV_ERROR_INVALID_LAYOUT, inst)
594
30
           << "Variables must have a function[7] storage class inside"
595
30
              " of a function";
596
30
  }
597
598
202k
  if (!inst->function() && storage_class == spv::StorageClass::Function) {
599
10
    return _.diag(SPV_ERROR_INVALID_LAYOUT, inst)
600
10
           << "Variables can not have a function[7] storage class "
601
10
              "outside of a function";
602
10
  }
603
604
  // SPIR-V 3.32.8: Check that pointer type and variable type have the same
605
  // storage class.
606
202k
  auto result_type = _.FindDef(inst->type_id());
607
202k
  const auto result_storage_class_index = 1;
608
202k
  const auto result_storage_class =
609
202k
      result_type->GetOperandAs<spv::StorageClass>(result_storage_class_index);
610
202k
  if (storage_class != result_storage_class) {
611
127
    return _.diag(SPV_ERROR_INVALID_ID, inst)
612
127
           << "Storage class must match result type storage class";
613
127
  }
614
615
202k
  if (storage_class == spv::StorageClass::PhysicalStorageBuffer) {
616
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
617
0
           << "PhysicalStorageBuffer must not be used with OpVariable.";
618
0
  }
619
620
202k
  if (storage_class == spv::StorageClass::TileAttachmentQCOM &&
621
0
      !_.HasCapability(spv::Capability::TileShadingQCOM)) {
622
0
    return _.diag(SPV_ERROR_INVALID_CAPABILITY, inst)
623
0
           << _.VkErrorID(10689)
624
0
           << "the TileAttachmentQCOM storage class variable requires "
625
0
              "TileShadingQCOM capability enabled.";
626
0
  }
627
628
202k
  return SPV_SUCCESS;
629
202k
}
630
631
spv_result_t ValidateVariablePointer(ValidationState_t& _,
632
                                     const Instruction* inst,
633
                                     spv::StorageClass storage_class,
634
202k
                                     const Instruction& pointee) {
635
202k
  if ((_.addressing_model() == spv::AddressingModel::Logical ||
636
160
       _.addressing_model() == spv::AddressingModel::PhysicalStorageBuffer64) &&
637
202k
      !_.options()->relax_logical_pointer) {
638
202k
    spv_result_t error = SPV_SUCCESS;
639
202k
    bool contains_logical_pointer = _.ContainsType(
640
202k
        pointee.id(),
641
359k
        [&_, inst, &error](const Instruction* type) {
642
359k
          if (type->opcode() == spv::Op::OpTypePointer ||
643
359k
              type->opcode() == spv::Op::OpTypeUntypedPointerKHR) {
644
26
            const auto sc = type->GetOperandAs<spv::StorageClass>(1u);
645
26
            if (sc != spv::StorageClass::PhysicalStorageBuffer) {
646
26
              if (sc != spv::StorageClass::StorageBuffer &&
647
26
                  sc != spv::StorageClass::Workgroup) {
648
22
                error =
649
22
                    _.diag(SPV_ERROR_INVALID_ID, inst)
650
22
                    << "In Logical addressing, variables can only allocate a "
651
22
                       "pointer to the StorageBuffer or Workgroup storage "
652
22
                       "classes";
653
22
              } else if (!_.HasCapability(
654
4
                             spv::Capability::VariablePointersStorageBuffer) &&
655
4
                         sc == spv::StorageClass::StorageBuffer) {
656
0
                error =
657
0
                    _.diag(SPV_ERROR_INVALID_ID, inst)
658
0
                    << "In Logical addressing, variables can only allocate a "
659
0
                       "storage buffer pointer if the "
660
0
                       "VariablePointersStorageBuffer capability is declared";
661
4
              } else if (!_.HasCapability(spv::Capability::VariablePointers) &&
662
4
                         sc == spv::StorageClass::Workgroup) {
663
4
                error =
664
4
                    _.diag(SPV_ERROR_INVALID_ID, inst)
665
4
                    << "In Logical addressing, variables can only allocate a "
666
4
                       "workgroup pointer if the VariablePointers capability "
667
4
                       "is "
668
4
                       "declared";
669
4
              }
670
26
              return true;
671
26
            }
672
26
          }
673
359k
          return false;
674
359k
        },
675
202k
        /* traverse_all_types = */ false);
676
677
202k
    if (error != SPV_SUCCESS) return error;
678
679
202k
    if (contains_logical_pointer) {
680
0
      if (storage_class != spv::StorageClass::Function &&
681
0
          storage_class != spv::StorageClass::Private) {
682
0
        return _.diag(SPV_ERROR_INVALID_ID, inst)
683
0
               << "In Logical addressing with variable pointers, variables "
684
0
               << "that allocate pointers must be in Function or Private "
685
0
               << "storage classes";
686
0
      }
687
0
    }
688
202k
  }
689
690
202k
  return SPV_SUCCESS;
691
202k
}
692
693
spv_result_t ValidateVariableVulkanDescriptor(ValidationState_t& _,
694
                                              const Instruction* inst,
695
                                              spv::StorageClass storage_class,
696
0
                                              const Instruction& pointee) {
697
  // Vulkan Push Constant Interface section: Check type of PushConstant
698
  // variables.
699
0
  if (storage_class == spv::StorageClass::PushConstant) {
700
0
    if (pointee.opcode() != spv::Op::OpTypeStruct) {
701
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
702
0
             << _.VkErrorID(6808) << "PushConstant OpVariable <id> "
703
0
             << _.getIdName(inst->id()) << " has illegal type.\n"
704
0
             << "From Vulkan spec, Push Constant Interface section:\n"
705
0
             << "Such variables must be typed as OpTypeStruct";
706
0
    }
707
0
  }
708
709
  // Vulkan Descriptor Set Interface: Check type of UniformConstant and
710
  // Uniform variables.
711
0
  if (storage_class == spv::StorageClass::UniformConstant) {
712
0
    if (!IsAllowedTypeOrArrayOfSame(
713
0
            _, pointee,
714
0
            {spv::Op::OpTypeImage, spv::Op::OpTypeSampler,
715
0
             spv::Op::OpTypeSampledImage, spv::Op::OpTypeTensorARM,
716
0
             spv::Op::OpTypeAccelerationStructureKHR})) {
717
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
718
0
             << _.VkErrorID(4655) << "UniformConstant OpVariable <id> "
719
0
             << _.getIdName(inst->id()) << " has illegal type.\n"
720
0
             << "Variables identified with the UniformConstant storage class "
721
0
             << "are used only as handles to refer to opaque resources. Such "
722
0
             << "variables must be typed as OpTypeImage, OpTypeSampler, "
723
0
             << "OpTypeSampledImage, OpTypeAccelerationStructureKHR, "
724
0
             << "or an array of one of these types.";
725
0
    }
726
0
  }
727
728
0
  if (storage_class == spv::StorageClass::Uniform) {
729
0
    if (!IsAllowedTypeOrArrayOfSame(_, pointee, {spv::Op::OpTypeStruct})) {
730
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
731
0
             << _.VkErrorID(6807) << "Uniform OpVariable <id> "
732
0
             << _.getIdName(inst->id()) << " has illegal type.\n"
733
0
             << "From Vulkan spec:\n"
734
0
             << "Variables identified with the Uniform storage class are "
735
0
             << "used to access transparent buffer backed resources. Such "
736
0
             << "variables must be typed as OpTypeStruct, or an array of "
737
0
             << "this type";
738
0
    }
739
0
  }
740
741
0
  if (storage_class == spv::StorageClass::StorageBuffer) {
742
0
    if (!IsAllowedTypeOrArrayOfSame(_, pointee, {spv::Op::OpTypeStruct})) {
743
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
744
0
             << _.VkErrorID(6807) << "StorageBuffer OpVariable <id> "
745
0
             << _.getIdName(inst->id()) << " has illegal type.\n"
746
0
             << "From Vulkan spec:\n"
747
0
             << "Variables identified with the StorageBuffer storage class "
748
0
                "are used to access transparent buffer backed resources. "
749
0
                "Such variables must be typed as OpTypeStruct, or an array "
750
0
                "of this type";
751
0
    }
752
0
  }
753
754
0
  return SPV_SUCCESS;
755
0
}
756
757
spv_result_t ValidateVariableVulkanInterface(ValidationState_t& _,
758
                                             const Instruction* inst,
759
                                             spv::StorageClass storage_class,
760
                                             const Instruction* value_type,
761
0
                                             uint32_t value_id) {
762
  // Check for invalid use of Invariant
763
0
  if (storage_class != spv::StorageClass::Input &&
764
0
      storage_class != spv::StorageClass::Output) {
765
0
    if (_.HasDecoration(inst->id(), spv::Decoration::Invariant)) {
766
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
767
0
             << _.VkErrorID(4677)
768
0
             << "Variable decorated with Invariant must only be identified "
769
0
                "with the Input or Output storage class in Vulkan "
770
0
                "environment.";
771
0
    }
772
    // Need to check if only the members in a struct are decorated
773
0
    if (value_type && value_type->opcode() == spv::Op::OpTypeStruct) {
774
0
      if (_.HasDecoration(value_id, spv::Decoration::Invariant)) {
775
0
        return _.diag(SPV_ERROR_INVALID_ID, inst)
776
0
               << _.VkErrorID(4677)
777
0
               << "Variable struct member decorated with Invariant must only "
778
0
                  "be identified with the Input or Output storage class in "
779
0
                  "Vulkan environment.";
780
0
      }
781
0
    }
782
0
  }
783
784
0
  return SPV_SUCCESS;
785
0
}
786
787
spv_result_t ValidateVariableCoopMat(ValidationState_t& _,
788
                                     const Instruction* inst,
789
                                     spv::StorageClass storage_class,
790
202k
                                     const Instruction& pointee) {
791
  // Cooperative matrix types can only be allocated in Function or Private
792
202k
  if ((storage_class != spv::StorageClass::Function &&
793
56.6k
       storage_class != spv::StorageClass::Private) &&
794
102k
      _.ContainsType(pointee.id(), [](const Instruction* type_inst) {
795
102k
        auto opcode = type_inst->opcode();
796
102k
        return opcode == spv::Op::OpTypeCooperativeMatrixNV ||
797
102k
               opcode == spv::Op::OpTypeCooperativeMatrixKHR;
798
102k
      })) {
799
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
800
0
           << "Cooperative matrix types (or types containing them) can only be "
801
0
              "allocated "
802
0
           << "in Function or Private storage classes or as function "
803
0
              "parameters";
804
0
  }
805
806
202k
  return SPV_SUCCESS;
807
202k
}
808
809
// Vulkan specific validation rules for OpTypeRuntimeArray
810
spv_result_t ValidateVariableVulkanArray(ValidationState_t& _,
811
                                         const Instruction* inst,
812
                                         spv::StorageClass storage_class,
813
                                         const Instruction& value_type,
814
0
                                         uint32_t value_id) {
815
  // OpTypeRuntimeArray should only ever be in a container like OpTypeStruct,
816
  // so should never appear as a bare variable.
817
  // Unless the module has the RuntimeDescriptorArray capability.
818
0
  if (value_type.opcode() == spv::Op::OpTypeRuntimeArray) {
819
0
    if (!_.HasCapability(spv::Capability::RuntimeDescriptorArray)) {
820
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
821
0
             << _.VkErrorID(4680) << "OpVariable, <id> "
822
0
             << _.getIdName(inst->id())
823
0
             << ", is attempting to create memory for an illegal type, "
824
0
             << "OpTypeRuntimeArray.\nFor Vulkan OpTypeRuntimeArray can only "
825
0
             << "appear as the final member of an OpTypeStruct, thus cannot "
826
0
             << "be instantiated via OpVariable, unless the "
827
0
                "RuntimeDescriptorArray Capability is declared";
828
0
    } else {
829
      // A bare variable OpTypeRuntimeArray is allowed in this context, but
830
      // still need to check the storage class.
831
0
      if (storage_class != spv::StorageClass::StorageBuffer &&
832
0
          storage_class != spv::StorageClass::Uniform &&
833
0
          storage_class != spv::StorageClass::UniformConstant) {
834
0
        return _.diag(SPV_ERROR_INVALID_ID, inst)
835
0
               << _.VkErrorID(4680)
836
0
               << "For Vulkan with RuntimeDescriptorArray, a variable "
837
0
               << "containing OpTypeRuntimeArray must have storage class of "
838
0
               << "StorageBuffer, Uniform, or UniformConstant.";
839
0
      }
840
0
    }
841
0
  }
842
843
  // If an OpStruct has an OpTypeRuntimeArray somewhere within it, then it
844
  // must either have the storage class StorageBuffer and be decorated
845
  // with Block, or it must be in the Uniform storage class
846
0
  if (value_type.opcode() == spv::Op::OpTypeStruct) {
847
0
    if (DoesStructContainRTA(_, &value_type)) {
848
0
      if (storage_class == spv::StorageClass::StorageBuffer ||
849
0
          storage_class == spv::StorageClass::PhysicalStorageBuffer) {
850
0
        if (!_.HasDecoration(value_id, spv::Decoration::Block)) {
851
0
          return _.diag(SPV_ERROR_INVALID_ID, inst)
852
0
                 << _.VkErrorID(4680)
853
0
                 << "For Vulkan, an OpTypeStruct variable containing an "
854
0
                 << "OpTypeRuntimeArray must be decorated with Block if it "
855
0
                 << "has storage class StorageBuffer or "
856
0
                    "PhysicalStorageBuffer.";
857
0
        }
858
0
      } else if (storage_class == spv::StorageClass::Uniform) {
859
        // BufferBlock Uniform were always allowed.
860
        //
861
        // Block Uniform use to be invalid, but Vulkan added
862
        // VK_EXT_shader_uniform_buffer_unsized_array and now this is
863
        // validated at runtime
864
        //
865
        // The uniform must have either the Block or BufferBlock decoration
866
        // (see VUID-StandaloneSpirv-Uniform-06676)
867
0
      } else {
868
0
        return _.diag(SPV_ERROR_INVALID_ID, inst)
869
0
               << _.VkErrorID(4680)
870
0
               << "For Vulkan, OpTypeStruct variables containing "
871
0
               << "OpTypeRuntimeArray must have storage class of "
872
0
               << "StorageBuffer, PhysicalStorageBuffer, or Uniform.";
873
0
      }
874
0
    }
875
0
  }
876
877
0
  return SPV_SUCCESS;
878
0
}
879
880
// Vulkan-specific validation for long vectors
881
spv_result_t ValidateVariableVulkanLongVector(ValidationState_t& _,
882
                                              const Instruction* inst,
883
                                              spv::StorageClass storage_class,
884
0
                                              const Instruction& pointee) {
885
0
  if (_.HasCapability(spv::Capability::LongVectorEXT)) {
886
0
    if ((storage_class != spv::StorageClass::Function &&
887
0
         storage_class != spv::StorageClass::Private &&
888
0
         storage_class != spv::StorageClass::StorageBuffer &&
889
0
         storage_class != spv::StorageClass::PhysicalStorageBuffer &&
890
0
         storage_class != spv::StorageClass::Workgroup &&
891
0
         storage_class != spv::StorageClass::Uniform &&
892
0
         storage_class != spv::StorageClass::PushConstant &&
893
0
         storage_class != spv::StorageClass::ShaderRecordBufferKHR) &&
894
0
        _.ContainsType(pointee.id(), [&](const Instruction* type_inst) {
895
0
          auto opcode = type_inst->opcode();
896
0
          if (opcode == spv::Op::OpTypeVector ||
897
0
              opcode == spv::Op::OpTypeVectorIdEXT) {
898
0
            uint32_t dim = _.GetDimension(type_inst->id());
899
0
            return dim > 4;
900
0
          }
901
0
          return false;
902
0
        })) {
903
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
904
0
             << _.VkErrorID(12297)
905
0
             << "Long vector types with more than 4 components (or types "
906
0
                "containing them) not supported in storage class "
907
0
             << StorageClassToString(storage_class);
908
0
    }
909
910
0
    if ((storage_class == spv::StorageClass::StorageBuffer ||
911
0
         storage_class == spv::StorageClass::PhysicalStorageBuffer ||
912
0
         storage_class == spv::StorageClass::Uniform ||
913
0
         storage_class == spv::StorageClass::PushConstant ||
914
0
         storage_class == spv::StorageClass::ShaderRecordBufferKHR ||
915
0
         (storage_class == spv::StorageClass::Workgroup &&
916
0
          _.HasDecoration(pointee.id(), spv::Decoration::Block))) &&
917
0
        _.ContainsType(pointee.id(), [&](const Instruction* type_inst) {
918
0
          auto opcode = type_inst->opcode();
919
0
          if (opcode == spv::Op::OpTypeVectorIdEXT) {
920
0
            auto component_count =
921
0
                _.FindDef(type_inst->GetOperandAs<uint32_t>(2u));
922
0
            return (bool)spvOpcodeIsSpecConstant(component_count->opcode());
923
0
          }
924
0
          return false;
925
0
        })) {
926
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
927
0
             << _.VkErrorID(12294)
928
0
             << "Long vector types with spec constant component count "
929
0
                "not supported in storage class with explicit layout "
930
0
             << StorageClassToString(storage_class);
931
0
    }
932
0
  } else {
933
0
    if ((storage_class != spv::StorageClass::Function &&
934
0
         storage_class != spv::StorageClass::Private) &&
935
0
        _.ContainsType(pointee.id(), [](const Instruction* type_inst) {
936
0
          auto opcode = type_inst->opcode();
937
0
          return opcode == spv::Op::OpTypeVectorIdEXT;
938
0
        })) {
939
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
940
0
             << "Cooperative vector types (or types containing them) can "
941
0
                "only be "
942
0
                "allocated "
943
0
             << "in Function or Private storage classes or as function "
944
0
                "parameters";
945
0
    }
946
0
  }
947
948
0
  return SPV_SUCCESS;
949
0
}
950
951
spv_result_t ValidateVariableShader(ValidationState_t& _,
952
                                    const Instruction* inst,
953
                                    spv::StorageClass storage_class,
954
                                    const Instruction* value_type,
955
202k
                                    uint32_t value_id) {
956
  // Don't allow variables containing 16-bit elements without the appropriate
957
  // capabilities.
958
202k
  if ((!_.HasCapability(spv::Capability::Int16) &&
959
201k
       _.ContainsSizedIntOrFloatType(value_id, spv::Op::OpTypeInt, 16)) ||
960
202k
      (!_.HasCapability(spv::Capability::Float16) &&
961
202k
       _.ContainsSizedIntOrFloatType(value_id, spv::Op::OpTypeFloat, 16))) {
962
9
    auto underlying_type = value_type;
963
9
    while (underlying_type &&
964
9
           underlying_type->opcode() == spv::Op::OpTypePointer) {
965
0
      storage_class = underlying_type->GetOperandAs<spv::StorageClass>(1u);
966
0
      underlying_type = _.FindDef(underlying_type->GetOperandAs<uint32_t>(2u));
967
0
    }
968
9
    bool storage_class_ok = true;
969
9
    std::string sc_name = _.grammar().lookupOperandName(
970
9
        SPV_OPERAND_TYPE_STORAGE_CLASS, uint32_t(storage_class));
971
9
    switch (storage_class) {
972
0
      case spv::StorageClass::StorageBuffer:
973
0
      case spv::StorageClass::PhysicalStorageBuffer:
974
0
        if (!_.HasCapability(spv::Capability::StorageBuffer16BitAccess)) {
975
0
          storage_class_ok = false;
976
0
        }
977
0
        break;
978
1
      case spv::StorageClass::Uniform:
979
1
        if (underlying_type &&
980
1
            !_.HasCapability(
981
1
                spv::Capability::UniformAndStorageBuffer16BitAccess)) {
982
1
          if (underlying_type->opcode() == spv::Op::OpTypeArray ||
983
1
              underlying_type->opcode() == spv::Op::OpTypeRuntimeArray) {
984
0
            underlying_type =
985
0
                _.FindDef(underlying_type->GetOperandAs<uint32_t>(1u));
986
0
          }
987
1
          if (!_.HasCapability(spv::Capability::StorageBuffer16BitAccess) ||
988
0
              !_.HasDecoration(underlying_type->id(),
989
1
                               spv::Decoration::BufferBlock)) {
990
1
            storage_class_ok = false;
991
1
          }
992
1
        }
993
1
        break;
994
2
      case spv::StorageClass::PushConstant:
995
2
        if (!_.HasCapability(spv::Capability::StoragePushConstant16)) {
996
2
          storage_class_ok = false;
997
2
        }
998
2
        break;
999
1
      case spv::StorageClass::Input:
1000
2
      case spv::StorageClass::Output:
1001
2
        if (!_.HasCapability(spv::Capability::StorageInputOutput16)) {
1002
2
          storage_class_ok = false;
1003
2
        }
1004
2
        break;
1005
1
      case spv::StorageClass::Workgroup:
1006
1
        if (!_.HasCapability(
1007
1
                spv::Capability::WorkgroupMemoryExplicitLayout16BitAccessKHR)) {
1008
1
          storage_class_ok = false;
1009
1
        }
1010
1
        break;
1011
3
      default:
1012
3
        return _.diag(SPV_ERROR_INVALID_ID, inst)
1013
3
               << "Cannot allocate a variable containing a 16-bit type in "
1014
3
               << sc_name << " storage class";
1015
9
    }
1016
6
    if (!storage_class_ok) {
1017
6
      return _.diag(SPV_ERROR_INVALID_ID, inst)
1018
6
             << "Allocating a variable containing a 16-bit element in "
1019
6
             << sc_name << " storage class requires an additional capability";
1020
6
    }
1021
6
  }
1022
  // Don't allow variables containing 8-bit elements without the appropriate
1023
  // capabilities.
1024
202k
  if (!_.HasCapability(spv::Capability::Int8) &&
1025
202k
      _.ContainsSizedIntOrFloatType(value_id, spv::Op::OpTypeInt, 8)) {
1026
0
    auto underlying_type = value_type;
1027
0
    while (underlying_type &&
1028
0
           underlying_type->opcode() == spv::Op::OpTypePointer) {
1029
0
      storage_class = underlying_type->GetOperandAs<spv::StorageClass>(1u);
1030
0
      underlying_type = _.FindDef(underlying_type->GetOperandAs<uint32_t>(2u));
1031
0
    }
1032
0
    bool storage_class_ok = true;
1033
0
    std::string sc_name = _.grammar().lookupOperandName(
1034
0
        SPV_OPERAND_TYPE_STORAGE_CLASS, uint32_t(storage_class));
1035
0
    switch (storage_class) {
1036
0
      case spv::StorageClass::StorageBuffer:
1037
0
      case spv::StorageClass::PhysicalStorageBuffer:
1038
0
        if (!_.HasCapability(spv::Capability::StorageBuffer8BitAccess)) {
1039
0
          storage_class_ok = false;
1040
0
        }
1041
0
        break;
1042
0
      case spv::StorageClass::Uniform:
1043
0
        if (underlying_type &&
1044
0
            !_.HasCapability(
1045
0
                spv::Capability::UniformAndStorageBuffer8BitAccess)) {
1046
0
          if (underlying_type->opcode() == spv::Op::OpTypeArray ||
1047
0
              underlying_type->opcode() == spv::Op::OpTypeRuntimeArray) {
1048
0
            underlying_type =
1049
0
                _.FindDef(underlying_type->GetOperandAs<uint32_t>(1u));
1050
0
          }
1051
0
          if (!_.HasCapability(spv::Capability::StorageBuffer8BitAccess) ||
1052
0
              !_.HasDecoration(underlying_type->id(),
1053
0
                               spv::Decoration::BufferBlock)) {
1054
0
            storage_class_ok = false;
1055
0
          }
1056
0
        }
1057
0
        break;
1058
0
      case spv::StorageClass::PushConstant:
1059
0
        if (!_.HasCapability(spv::Capability::StoragePushConstant8)) {
1060
0
          storage_class_ok = false;
1061
0
        }
1062
0
        break;
1063
0
      case spv::StorageClass::Workgroup:
1064
0
        if (!_.HasCapability(
1065
0
                spv::Capability::WorkgroupMemoryExplicitLayout8BitAccessKHR)) {
1066
0
          storage_class_ok = false;
1067
0
        }
1068
0
        break;
1069
0
      default:
1070
0
        return _.diag(SPV_ERROR_INVALID_ID, inst)
1071
0
               << "Cannot allocate a variable containing a 8-bit type in "
1072
0
               << sc_name << " storage class";
1073
0
    }
1074
0
    if (!storage_class_ok) {
1075
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
1076
0
             << "Allocating a variable containing a 8-bit element in "
1077
0
             << sc_name << " storage class requires an additional capability";
1078
0
    }
1079
0
  }
1080
1081
202k
  if (_.ContainsOCPMicroscalingNonByteType(value_id)) {
1082
0
    auto underlying_type = value_type;
1083
0
    auto sc = storage_class;
1084
0
    while (underlying_type &&
1085
0
           underlying_type->opcode() == spv::Op::OpTypePointer) {
1086
0
      sc = underlying_type->GetOperandAs<spv::StorageClass>(1u);
1087
0
      underlying_type = _.FindDef(underlying_type->GetOperandAs<uint32_t>(2u));
1088
0
    }
1089
0
    if (sc != spv::StorageClass::Function && sc != spv::StorageClass::Private) {
1090
0
      std::string sc_name = _.grammar().lookupOperandName(
1091
0
          SPV_OPERAND_TYPE_STORAGE_CLASS, uint32_t(sc));
1092
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
1093
0
             << "Cannot allocate a variable containing a Float4EXT or "
1094
0
                "Float6EXT type in "
1095
0
             << sc_name << " storage class";
1096
0
    }
1097
0
  }
1098
1099
202k
  return SPV_SUCCESS;
1100
202k
}
1101
1102
spv_result_t ValidateVariableTileShadingQCOM(ValidationState_t& _,
1103
0
                                             const Instruction* inst) {
1104
0
  auto result_type = _.FindDef(inst->type_id());
1105
0
  if (result_type->opcode() == spv::Op::OpTypePointer) {
1106
0
    const auto pointee_type = _.FindDef(result_type->GetOperandAs<uint32_t>(2));
1107
0
    if (pointee_type && pointee_type->opcode() == spv::Op::OpTypeImage) {
1108
0
      spv::Dim dim = static_cast<spv::Dim>(pointee_type->word(3));
1109
0
      if (dim != spv::Dim::Dim2D) {
1110
0
        return _.diag(SPV_ERROR_INVALID_DATA, inst)
1111
0
               << _.VkErrorID(10693)
1112
0
               << "Any OpTypeImage variable in the TileAttachmentQCOM "
1113
0
                  "Storage Class must "
1114
0
                  "have 2D as its dimension";
1115
0
      }
1116
0
      unsigned sampled = pointee_type->word(7);
1117
0
      if (sampled != 1 && sampled != 2) {
1118
0
        return _.diag(SPV_ERROR_INVALID_DATA, inst)
1119
0
               << _.VkErrorID(10694)
1120
0
               << "Any OpTypeImage variable in the TileAttachmentQCOM "
1121
0
                  "Storage Class must "
1122
0
                  "have 1 or 2 as Image 'Sampled' parameter";
1123
0
      }
1124
0
      for (const auto& pair_o : inst->uses()) {
1125
0
        const auto* use_inst_o = pair_o.first;
1126
0
        if (use_inst_o->opcode() == spv::Op::OpLoad) {
1127
0
          for (const auto& pair_i : use_inst_o->uses()) {
1128
0
            const auto* use_inst_i = pair_i.first;
1129
0
            switch (use_inst_i->opcode()) {
1130
0
              case spv::Op::OpImageQueryFormat:
1131
0
              case spv::Op::OpImageQueryOrder:
1132
0
              case spv::Op::OpImageQuerySizeLod:
1133
0
              case spv::Op::OpImageQuerySize:
1134
0
              case spv::Op::OpImageQueryLod:
1135
0
              case spv::Op::OpImageQueryLevels:
1136
0
              case spv::Op::OpImageQuerySamples:
1137
0
                return _.diag(SPV_ERROR_INVALID_DATA, inst)
1138
0
                       << _.VkErrorID(10697)
1139
0
                       << "Any variable in the TileAttachmentQCOM Storage "
1140
0
                          "Class must "
1141
0
                          "not be consumed by an OpImageQuery* instruction";
1142
0
              default:
1143
0
                break;
1144
0
            }
1145
0
          }
1146
0
        }
1147
0
      }
1148
0
    }
1149
0
  }
1150
1151
0
  if (!(_.HasDecoration(inst->id(), spv::Decoration::DescriptorSet) &&
1152
0
        _.HasDecoration(inst->id(), spv::Decoration::Binding))) {
1153
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
1154
0
           << _.VkErrorID(10695)
1155
0
           << "Any variable in the TileAttachmentQCOM Storage Class must "
1156
0
              "be decorated with DescriptorSet and Binding";
1157
0
  }
1158
0
  if (_.HasDecoration(inst->id(), spv::Decoration::Component)) {
1159
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
1160
0
           << _.VkErrorID(10696)
1161
0
           << "Any variable in the TileAttachmentQCOM Storage Class must "
1162
0
              "not be decorated with Component decoration";
1163
0
  }
1164
1165
0
  return SPV_SUCCESS;
1166
0
}
1167
1168
spv_result_t ValidateVariableTileImageEXT(ValidationState_t& _,
1169
0
                                          const Instruction* inst) {
1170
0
  bool is_valid_decl = true;
1171
1172
0
  auto result_type = _.FindDef(inst->type_id());
1173
0
  if (result_type->opcode() == spv::Op::OpTypePointer) {
1174
0
    auto pointee_type = _.FindDef(result_type->GetOperandAs<uint32_t>(2));
1175
1176
0
    while (pointee_type && pointee_type->opcode() == spv::Op::OpTypeArray) {
1177
0
      pointee_type = _.FindDef(pointee_type->GetOperandAs<uint32_t>(1));
1178
0
    }
1179
1180
0
    if (pointee_type && pointee_type->opcode() == spv::Op::OpTypeImage) {
1181
0
      spv::Dim dim = static_cast<spv::Dim>(pointee_type->word(3));
1182
0
      if (dim != spv::Dim::TileImageDataEXT) {
1183
0
        is_valid_decl = false;
1184
0
      }
1185
0
    } else {
1186
0
      is_valid_decl = false;
1187
0
    }
1188
0
  }
1189
1190
0
  if (!is_valid_decl) {
1191
0
    return _.diag(SPV_ERROR_INVALID_DATA, inst)
1192
0
           << _.VkErrorID(8724)
1193
0
           << "The TileImageEXT Storage Class must only be used for declaring "
1194
0
              "tile image variables";
1195
0
  } else {
1196
0
    return SPV_SUCCESS;
1197
0
  }
1198
0
}
1199
1200
203k
spv_result_t ValidateVariable(ValidationState_t& _, const Instruction* inst) {
1201
203k
  const bool untyped_pointer = inst->opcode() == spv::Op::OpUntypedVariableKHR;
1202
1203
203k
  auto result_type = _.FindDef(inst->type_id());
1204
203k
  if (untyped_pointer) {
1205
0
    if (!result_type ||
1206
0
        result_type->opcode() != spv::Op::OpTypeUntypedPointerKHR)
1207
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
1208
0
             << "Result type must be an untyped pointer";
1209
203k
  } else {
1210
203k
    if (!result_type || result_type->opcode() != spv::Op::OpTypePointer) {
1211
30
      return _.diag(SPV_ERROR_INVALID_ID, inst)
1212
30
             << "OpVariable Result Type <id> " << _.getIdName(inst->type_id())
1213
30
             << " is not a pointer type.";
1214
30
    }
1215
203k
  }
1216
1217
203k
  const auto storage_class_index = 2u;
1218
203k
  auto storage_class =
1219
203k
      inst->GetOperandAs<spv::StorageClass>(storage_class_index);
1220
203k
  uint32_t value_id = 0;
1221
203k
  if (untyped_pointer) {
1222
0
    const bool has_data_type = 3u < inst->operands().size();
1223
0
    if (has_data_type) {
1224
0
      value_id = inst->GetOperandAs<uint32_t>(3u);
1225
0
      auto data_type = _.FindDef(value_id);
1226
0
      if (!data_type || !spvOpcodeGeneratesType(data_type->opcode())) {
1227
0
        return _.diag(SPV_ERROR_INVALID_ID, inst)
1228
0
               << "Data type must be a type instruction";
1229
0
      }
1230
0
    } else {
1231
0
      if (storage_class == spv::StorageClass::Function ||
1232
0
          storage_class == spv::StorageClass::Private ||
1233
0
          storage_class == spv::StorageClass::Workgroup) {
1234
0
        return _.diag(SPV_ERROR_INVALID_ID, inst)
1235
0
               << "Data type must be specified for Function, Private, and "
1236
0
                  "Workgroup storage classes";
1237
0
      }
1238
      // Added from SPV_EXT_descriptor_heap
1239
      // Vulkan allows untyped pointer without |Data Type| but only for heap
1240
      // decorated variable that are in UniformConstant
1241
0
      if (spvIsVulkanEnv(_.context()->target_env)) {
1242
0
        if (storage_class != spv::StorageClass::UniformConstant) {
1243
0
          return _.diag(SPV_ERROR_INVALID_ID, inst)
1244
0
                 << _.VkErrorID(11167) << "Storage class is "
1245
0
                 << StorageClassToString(storage_class)
1246
0
                 << ", but Vulkan requires that Data Type be specified when "
1247
0
                    "not using UniformConstant storage class";
1248
0
        } else if (!(_.IsDescriptorHeapBaseVariable(inst))) {
1249
0
          return _.diag(SPV_ERROR_INVALID_ID, inst)
1250
0
                 << _.VkErrorID(11347)
1251
0
                 << "Storage class is UniformConstant, but Vulkan requires "
1252
0
                    "that Data Type be specified if the variable is not "
1253
0
                    "decorated with SamplerHeapEXT or ResourceHeapEXT";
1254
0
        }
1255
0
      }
1256
0
    }
1257
0
  }
1258
1259
  // For OpVariable the data type comes from pointee type of the result type,
1260
  // while for OpUntypedVariableKHR the data type comes from the operand.
1261
203k
  if (!untyped_pointer) {
1262
203k
    value_id = result_type->GetOperandAs<uint32_t>(2);
1263
203k
  }
1264
203k
  const Instruction* value_type = value_id == 0 ? nullptr : _.FindDef(value_id);
1265
1266
203k
  if (auto error =
1267
203k
          ValidateVariableInitializer(_, inst, storage_class, value_id))
1268
17
    return error;
1269
1270
203k
  if (auto error =
1271
203k
          ValidateVariableStorageClass(_, inst, storage_class, value_type))
1272
184
    return error;
1273
1274
  // Variable pointer related restrictions.
1275
202k
  const Instruction* pointee =
1276
202k
      untyped_pointer ? value_id == 0 ? nullptr : _.FindDef(value_id)
1277
202k
                      : _.FindDef(result_type->word(3));
1278
1279
202k
  if (pointee) {
1280
202k
    if (auto error = ValidateVariablePointer(_, inst, storage_class, *pointee))
1281
26
      return error;
1282
202k
    if (auto error = ValidateVariableCoopMat(_, inst, storage_class, *pointee))
1283
0
      return error;
1284
202k
  }
1285
1286
202k
  if (spvIsVulkanEnv(_.context()->target_env)) {
1287
0
    if (pointee) {
1288
0
      if (auto error = ValidateVariableVulkanDescriptor(_, inst, storage_class,
1289
0
                                                        *pointee))
1290
0
        return error;
1291
0
      if (auto error = ValidateVariableVulkanLongVector(_, inst, storage_class,
1292
0
                                                        *pointee))
1293
0
        return error;
1294
0
    }
1295
1296
0
    if (auto error = ValidateVariableVulkanInterface(_, inst, storage_class,
1297
0
                                                     value_type, value_id))
1298
0
      return error;
1299
1300
0
    if (value_type) {
1301
0
      if (auto error = ValidateVariableVulkanArray(_, inst, storage_class,
1302
0
                                                   *value_type, value_id))
1303
0
        return error;
1304
0
    }
1305
0
  }
1306
1307
202k
  if (_.HasCapability(spv::Capability::Shader)) {
1308
202k
    if (auto error = ValidateVariableShader(_, inst, storage_class, value_type,
1309
202k
                                            value_id))
1310
9
      return error;
1311
202k
  }
1312
1313
202k
  if (_.HasCapability(spv::Capability::TileShadingQCOM) &&
1314
0
      storage_class == spv::StorageClass::TileAttachmentQCOM) {
1315
0
    if (auto error = ValidateVariableTileShadingQCOM(_, inst)) return error;
1316
0
  }
1317
1318
202k
  if (_.HasCapability(spv::Capability::TileImageColorReadAccessEXT) &&
1319
0
      storage_class == spv::StorageClass::TileImageEXT) {
1320
0
    if (auto error = ValidateVariableTileImageEXT(_, inst)) return error;
1321
0
  }
1322
1323
202k
  return SPV_SUCCESS;
1324
202k
}
1325
1326
321k
spv_result_t ValidateLoad(ValidationState_t& _, const Instruction* inst) {
1327
321k
  const auto result_type = _.FindDef(inst->type_id());
1328
321k
  if (!result_type) {
1329
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
1330
0
           << "OpLoad Result Type <id> " << _.getIdName(inst->type_id())
1331
0
           << " is not defined.";
1332
0
  }
1333
1334
321k
  const auto pointer_index = 2;
1335
321k
  const auto pointer_id = inst->GetOperandAs<uint32_t>(pointer_index);
1336
321k
  const auto pointer = _.FindDef(pointer_id);
1337
321k
  if (!pointer ||
1338
321k
      ((_.addressing_model() == spv::AddressingModel::Logical) &&
1339
321k
       ((!_.features().variable_pointers &&
1340
321k
         !spvOpcodeReturnsLogicalPointer(pointer->opcode())) ||
1341
320k
        (_.features().variable_pointers &&
1342
21
         !spvOpcodeReturnsLogicalVariablePointer(pointer->opcode()))))) {
1343
21
    return _.diag(SPV_ERROR_INVALID_ID, inst)
1344
21
           << "OpLoad Pointer <id> " << _.getIdName(pointer_id)
1345
21
           << " is not a logical pointer.";
1346
21
  }
1347
1348
321k
  const auto pointer_type = _.FindDef(pointer->type_id());
1349
321k
  if (!pointer_type ||
1350
321k
      (pointer_type->opcode() != spv::Op::OpTypePointer &&
1351
6
       pointer_type->opcode() != spv::Op::OpTypeUntypedPointerKHR)) {
1352
6
    return _.diag(SPV_ERROR_INVALID_ID, inst)
1353
6
           << "OpLoad type for pointer <id> " << _.getIdName(pointer_id)
1354
6
           << " is not a pointer type.";
1355
6
  }
1356
1357
321k
  if (pointer_type->opcode() == spv::Op::OpTypePointer) {
1358
321k
    const auto pointee_type =
1359
321k
        _.FindDef(pointer_type->GetOperandAs<uint32_t>(2));
1360
321k
    if (!pointee_type || result_type->id() != pointee_type->id()) {
1361
38
      return _.diag(SPV_ERROR_INVALID_ID, inst)
1362
38
             << "OpLoad Result Type <id> " << _.getIdName(inst->type_id())
1363
38
             << " does not match Pointer <id> " << _.getIdName(pointer->id())
1364
38
             << "s type.";
1365
38
    }
1366
321k
  }
1367
1368
320k
  if (!_.options()->before_hlsl_legalization &&
1369
320k
      _.ContainsRuntimeArray(inst->type_id())) {
1370
3
    return _.diag(SPV_ERROR_INVALID_ID, inst)
1371
3
           << "Cannot load a runtime-sized array";
1372
3
  }
1373
1374
320k
  if (auto error = CheckMemoryAccess(_, inst, 3)) return error;
1375
1376
320k
  if (_.HasCapability(spv::Capability::Shader) &&
1377
320k
      _.ContainsLimitedUseIntOrFloatType(inst->type_id()) &&
1378
0
      result_type->opcode() != spv::Op::OpTypePointer) {
1379
0
    if (result_type->opcode() != spv::Op::OpTypeInt &&
1380
0
        result_type->opcode() != spv::Op::OpTypeFloat &&
1381
0
        result_type->opcode() != spv::Op::OpTypeVector &&
1382
0
        result_type->opcode() != spv::Op::OpTypeMatrix) {
1383
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
1384
0
             << "8- or 16-bit loads must be a scalar, vector or matrix type";
1385
0
    }
1386
0
  }
1387
1388
  // Skip checking if there is zero chance for this having a mesh shader
1389
  // entrypoint
1390
320k
  if (_.HasCapability(spv::Capability::MeshShadingEXT) &&
1391
0
      pointer_type->GetOperandAs<spv::StorageClass>(1) ==
1392
0
          spv::StorageClass::Output) {
1393
0
    std::string errorVUID = _.VkErrorID(7107);
1394
0
    _.function(inst->function()->id())
1395
0
        ->RegisterExecutionModelLimitation(
1396
0
            [errorVUID](spv::ExecutionModel model, std::string* message) {
1397
              // Seems the NV Mesh extension was less strict and allowed
1398
              // writting to outputs
1399
0
              if (model == spv::ExecutionModel::MeshEXT) {
1400
0
                if (message) {
1401
0
                  *message = errorVUID +
1402
0
                             "The Output Storage Class in a Mesh Execution "
1403
0
                             "Model must not be read from";
1404
0
                }
1405
0
                return false;
1406
0
              }
1407
0
              return true;
1408
0
            });
1409
0
  }
1410
1411
320k
  _.RegisterQCOMImageProcessingTextureConsumer(pointer_id, inst, nullptr);
1412
1413
  // EXT_descriptor_heap
1414
320k
  if (spvIsVulkanEnv(_.context()->target_env) &&
1415
0
      (result_type->opcode() == spv::Op::OpTypeSampler ||
1416
0
       result_type->opcode() == spv::Op::OpTypeImage ||
1417
0
       result_type->opcode() == spv::Op::OpTypeAccelerationStructureKHR)) {
1418
0
    if (_.IsDescriptorHeapBaseVariable(_.FindDef(pointer_id))) {
1419
0
      if (auto descBaseVariable =
1420
0
              _.FindUntypedBaseVariable(_.FindDef(pointer_id))) {
1421
0
        auto descBaseVariableId = descBaseVariable->id();
1422
0
        if (!_.HasDecoration(descBaseVariableId,
1423
0
                             spv::Decoration::DescriptorSet) &&
1424
0
            !_.HasDecoration(descBaseVariableId, spv::Decoration::Binding)) {
1425
0
          switch (result_type->opcode()) {
1426
0
            case spv::Op::OpTypeSampler:
1427
0
              if (!_.IsBuiltin(descBaseVariableId,
1428
0
                               spv::BuiltIn::SamplerHeapEXT)) {
1429
0
                return _.diag(SPV_ERROR_INVALID_ID, inst)
1430
0
                       << _.VkErrorID(11336)
1431
0
                       << "OpTypeSampler pointer instruction has no descriptor "
1432
0
                          "set "
1433
0
                       << "or binding and is not derived from a variable "
1434
0
                          "decorated "
1435
0
                          "with "
1436
0
                          "SamplerHeapEXT";
1437
0
              }
1438
0
              break;
1439
0
            case spv::Op::OpTypeImage:
1440
0
              if (!_.IsBuiltin(descBaseVariableId,
1441
0
                               spv::BuiltIn::ResourceHeapEXT)) {
1442
0
                return _.diag(SPV_ERROR_INVALID_ID, inst)
1443
0
                       << _.VkErrorID(11337)
1444
0
                       << "OpTypeImage pointer instruction has no descriptor "
1445
0
                          "set "
1446
0
                       << "or binding and is not derived from a variable "
1447
0
                          "decorated "
1448
0
                          "with "
1449
0
                          "ResourceHeapEXT";
1450
0
              }
1451
0
              break;
1452
0
            case spv::Op::OpTypeAccelerationStructureKHR:
1453
0
              uint32_t data_type;
1454
0
              spv::StorageClass sc;
1455
0
              if (_.GetPointerTypeInfo(descBaseVariable->type_id(), &data_type,
1456
0
                                       &sc) &&
1457
0
                  sc != spv::StorageClass::Private &&
1458
0
                  sc != spv::StorageClass::Function &&
1459
0
                  !_.IsBuiltin(descBaseVariableId,
1460
0
                               spv::BuiltIn::ResourceHeapEXT)) {
1461
0
                return _.diag(SPV_ERROR_INVALID_ID, inst)
1462
0
                       << _.VkErrorID(11339)
1463
0
                       << "OpTypeAccelerationStructureKHR pointer instruction "
1464
0
                          "has "
1465
0
                          "no "
1466
0
                       << "descriptor set or binding and is not derived from a "
1467
0
                          "variable decorated with ResourceHeapEXT";
1468
0
              }
1469
0
              break;
1470
0
            default:
1471
0
              break;
1472
0
          }
1473
0
        }
1474
0
      }
1475
0
    }
1476
0
  }
1477
1478
320k
  return SPV_SUCCESS;
1479
320k
}
1480
1481
258k
spv_result_t ValidateStore(ValidationState_t& _, const Instruction* inst) {
1482
258k
  const auto pointer_index = 0;
1483
258k
  const auto pointer_id = inst->GetOperandAs<uint32_t>(pointer_index);
1484
258k
  const auto pointer = _.FindDef(pointer_id);
1485
258k
  if (!pointer ||
1486
258k
      (_.addressing_model() == spv::AddressingModel::Logical &&
1487
258k
       ((!_.features().variable_pointers &&
1488
258k
         !spvOpcodeReturnsLogicalPointer(pointer->opcode())) ||
1489
258k
        (_.features().variable_pointers &&
1490
10
         !spvOpcodeReturnsLogicalVariablePointer(pointer->opcode()))))) {
1491
10
    return _.diag(SPV_ERROR_INVALID_ID, inst)
1492
10
           << "OpStore Pointer <id> " << _.getIdName(pointer_id)
1493
10
           << " is not a logical pointer.";
1494
10
  }
1495
258k
  const auto pointer_type = _.FindDef(pointer->type_id());
1496
258k
  if (!pointer_type ||
1497
258k
      (pointer_type->opcode() != spv::Op::OpTypePointer &&
1498
5
       pointer_type->opcode() != spv::Op::OpTypeUntypedPointerKHR)) {
1499
5
    return _.diag(SPV_ERROR_INVALID_ID, inst)
1500
5
           << "OpStore type for pointer <id> " << _.getIdName(pointer_id)
1501
5
           << " is not a pointer type.";
1502
5
  }
1503
1504
258k
  Instruction* type = nullptr;
1505
258k
  if (pointer_type->opcode() == spv::Op::OpTypePointer) {
1506
258k
    const auto type_id = pointer_type->GetOperandAs<uint32_t>(2);
1507
258k
    type = _.FindDef(type_id);
1508
258k
    if (!type || spv::Op::OpTypeVoid == type->opcode()) {
1509
6
      return _.diag(SPV_ERROR_INVALID_ID, inst)
1510
6
             << "OpStore Pointer <id> " << _.getIdName(pointer_id)
1511
6
             << "s type is void.";
1512
6
    }
1513
258k
  }
1514
1515
  // validate storage class
1516
258k
  {
1517
258k
    uint32_t data_type;
1518
258k
    spv::StorageClass storage_class;
1519
258k
    if (!_.GetPointerTypeInfo(pointer_type->id(), &data_type, &storage_class)) {
1520
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
1521
0
             << "OpStore Pointer <id> " << _.getIdName(pointer_id)
1522
0
             << " is not pointer type";
1523
0
    }
1524
1525
258k
    if (storage_class == spv::StorageClass::UniformConstant ||
1526
258k
        storage_class == spv::StorageClass::Input ||
1527
258k
        storage_class == spv::StorageClass::PushConstant) {
1528
14
      return _.diag(SPV_ERROR_INVALID_ID, inst)
1529
14
             << "OpStore Pointer <id> " << _.getIdName(pointer_id)
1530
14
             << " storage class is read-only";
1531
258k
    } else if (storage_class == spv::StorageClass::ShaderRecordBufferKHR) {
1532
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
1533
0
             << "ShaderRecordBufferKHR Storage Class variables are read only";
1534
258k
    } else if (storage_class == spv::StorageClass::HitAttributeKHR) {
1535
0
      std::string errorVUID = _.VkErrorID(4703);
1536
0
      _.function(inst->function()->id())
1537
0
          ->RegisterExecutionModelLimitation(
1538
0
              [errorVUID](spv::ExecutionModel model, std::string* message) {
1539
0
                if (model == spv::ExecutionModel::AnyHitKHR ||
1540
0
                    model == spv::ExecutionModel::ClosestHitKHR) {
1541
0
                  if (message) {
1542
0
                    *message =
1543
0
                        errorVUID +
1544
0
                        "HitAttributeKHR Storage Class variables are read only "
1545
0
                        "with AnyHitKHR and ClosestHitKHR";
1546
0
                  }
1547
0
                  return false;
1548
0
                }
1549
0
                return true;
1550
0
              });
1551
0
    }
1552
1553
258k
    if (spvIsVulkanEnv(_.context()->target_env) &&
1554
0
        storage_class == spv::StorageClass::Uniform) {
1555
0
      auto base_ptr = _.TracePointer(pointer);
1556
0
      if (base_ptr->opcode() == spv::Op::OpVariable) {
1557
        // If it's not a variable a different check should catch the problem.
1558
0
        auto base_type = _.FindDef(base_ptr->GetOperandAs<uint32_t>(0));
1559
        // Get the pointed-to type.
1560
0
        base_type = _.FindDef(base_type->GetOperandAs<uint32_t>(2u));
1561
0
        if (base_type->opcode() == spv::Op::OpTypeArray ||
1562
0
            base_type->opcode() == spv::Op::OpTypeRuntimeArray) {
1563
0
          base_type = _.FindDef(base_type->GetOperandAs<uint32_t>(1u));
1564
0
        }
1565
0
        if (_.HasDecoration(base_type->id(), spv::Decoration::Block)) {
1566
0
          return _.diag(SPV_ERROR_INVALID_ID, inst)
1567
0
                 << _.VkErrorID(6925)
1568
0
                 << "In the Vulkan environment, cannot store to Uniform Blocks";
1569
0
        }
1570
0
      }
1571
0
    }
1572
258k
  }
1573
1574
258k
  const auto object_index = 1;
1575
258k
  const auto object_id = inst->GetOperandAs<uint32_t>(object_index);
1576
258k
  const auto object = _.FindDef(object_id);
1577
258k
  if (!object || !object->type_id()) {
1578
5
    return _.diag(SPV_ERROR_INVALID_ID, inst)
1579
5
           << "OpStore Object <id> " << _.getIdName(object_id)
1580
5
           << " is not an object.";
1581
5
  }
1582
258k
  const auto object_type = _.FindDef(object->type_id());
1583
258k
  if (!object_type || spv::Op::OpTypeVoid == object_type->opcode()) {
1584
5
    return _.diag(SPV_ERROR_INVALID_ID, inst)
1585
5
           << "OpStore Object <id> " << _.getIdName(object_id)
1586
5
           << "s type is void.";
1587
5
  }
1588
1589
258k
  if (type && (type->id() != object_type->id())) {
1590
31
    if (!_.options()->relax_struct_store ||
1591
0
        type->opcode() != spv::Op::OpTypeStruct ||
1592
31
        object_type->opcode() != spv::Op::OpTypeStruct) {
1593
31
      return _.diag(SPV_ERROR_INVALID_ID, inst)
1594
31
             << "OpStore Pointer <id> " << _.getIdName(pointer_id)
1595
31
             << "s type does not match Object <id> "
1596
31
             << _.getIdName(object->id()) << "s type.";
1597
31
    }
1598
1599
    // TODO: Check for layout compatible matricies and arrays as well.
1600
0
    if (!AreLayoutCompatibleStructs(_, type, object_type)) {
1601
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
1602
0
             << "OpStore Pointer <id> " << _.getIdName(pointer_id)
1603
0
             << "s layout does not match Object <id> "
1604
0
             << _.getIdName(object->id()) << "s layout.";
1605
0
    }
1606
0
  }
1607
1608
258k
  if (auto error = CheckMemoryAccess(_, inst, 2)) return error;
1609
1610
258k
  if (_.HasCapability(spv::Capability::Shader) &&
1611
258k
      _.ContainsLimitedUseIntOrFloatType(inst->type_id()) &&
1612
0
      object_type->opcode() != spv::Op::OpTypePointer) {
1613
0
    if (object_type->opcode() != spv::Op::OpTypeInt &&
1614
0
        object_type->opcode() != spv::Op::OpTypeFloat &&
1615
0
        object_type->opcode() != spv::Op::OpTypeVector &&
1616
0
        object_type->opcode() != spv::Op::OpTypeMatrix) {
1617
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
1618
0
             << "8- or 16-bit stores must be a scalar, vector or matrix type";
1619
0
    }
1620
0
  }
1621
1622
258k
  if (spvIsVulkanEnv(_.context()->target_env) &&
1623
0
      !_.options()->before_hlsl_legalization) {
1624
0
    const auto isForbiddenType = [](const Instruction* type_inst) {
1625
0
      auto opcode = type_inst->opcode();
1626
0
      return opcode == spv::Op::OpTypeImage ||
1627
0
             opcode == spv::Op::OpTypeSampler ||
1628
0
             opcode == spv::Op::OpTypeSampledImage ||
1629
0
             opcode == spv::Op::OpTypeAccelerationStructureKHR;
1630
0
    };
1631
0
    if (_.ContainsType(object_type->id(), isForbiddenType)) {
1632
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
1633
0
             << _.VkErrorID(6924)
1634
0
             << "Cannot store to OpTypeImage, OpTypeSampler, "
1635
0
                "OpTypeSampledImage, or OpTypeAccelerationStructureKHR objects";
1636
0
    }
1637
0
  }
1638
1639
258k
  return SPV_SUCCESS;
1640
258k
}
1641
1642
spv_result_t ValidateCopyMemoryMemoryAccess(ValidationState_t& _,
1643
77.4k
                                            const Instruction* inst) {
1644
77.4k
  assert(inst->opcode() == spv::Op::OpCopyMemory ||
1645
77.4k
         inst->opcode() == spv::Op::OpCopyMemorySized);
1646
77.4k
  const uint32_t first_access_index =
1647
77.4k
      inst->opcode() == spv::Op::OpCopyMemory ? 2 : 3;
1648
77.4k
  if (inst->operands().size() > first_access_index) {
1649
73.1k
    if (auto error = CheckMemoryAccess(_, inst, first_access_index))
1650
0
      return error;
1651
1652
73.1k
    const auto first_access = inst->GetOperandAs<uint32_t>(first_access_index);
1653
73.1k
    const uint32_t second_access_index =
1654
73.1k
        first_access_index + MemoryAccessNumWords(first_access);
1655
73.1k
    if (inst->operands().size() > second_access_index) {
1656
3
      if (_.features().copy_memory_permits_two_memory_accesses) {
1657
0
        if (auto error = CheckMemoryAccess(_, inst, second_access_index))
1658
0
          return error;
1659
1660
        // In the two-access form in SPIR-V 1.4 and later:
1661
        //  - the first is the target (write) access and it can't have
1662
        //  make-visible.
1663
        //  - the second is the source (read) access and it can't have
1664
        //  make-available.
1665
0
        if (first_access &
1666
0
            uint32_t(spv::MemoryAccessMask::MakePointerVisibleKHR)) {
1667
0
          return _.diag(SPV_ERROR_INVALID_DATA, inst)
1668
0
                 << "Target memory access must not include "
1669
0
                    "MakePointerVisibleKHR";
1670
0
        }
1671
0
        const auto second_access =
1672
0
            inst->GetOperandAs<uint32_t>(second_access_index);
1673
0
        if (second_access &
1674
0
            uint32_t(spv::MemoryAccessMask::MakePointerAvailableKHR)) {
1675
0
          return _.diag(SPV_ERROR_INVALID_DATA, inst)
1676
0
                 << "Source memory access must not include "
1677
0
                    "MakePointerAvailableKHR";
1678
0
        }
1679
3
      } else {
1680
3
        return _.diag(SPV_ERROR_INVALID_DATA, inst)
1681
3
               << spvOpcodeString(inst->opcode())
1682
3
               << " with two memory access operands requires SPIR-V 1.4 or "
1683
3
                  "later";
1684
3
      }
1685
3
    }
1686
73.1k
  }
1687
77.4k
  return SPV_SUCCESS;
1688
77.4k
}
1689
1690
77.4k
spv_result_t ValidateCopyMemory(ValidationState_t& _, const Instruction* inst) {
1691
77.4k
  const auto target_index = 0;
1692
77.4k
  const auto target_id = inst->GetOperandAs<uint32_t>(target_index);
1693
77.4k
  const auto target = _.FindDef(target_id);
1694
77.4k
  if (!target) {
1695
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
1696
0
           << "Target operand <id> " << _.getIdName(target_id)
1697
0
           << " is not defined.";
1698
0
  }
1699
1700
77.4k
  const auto source_index = 1;
1701
77.4k
  const auto source_id = inst->GetOperandAs<uint32_t>(source_index);
1702
77.4k
  const auto source = _.FindDef(source_id);
1703
77.4k
  if (!source) {
1704
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
1705
0
           << "Source operand <id> " << _.getIdName(source_id)
1706
0
           << " is not defined.";
1707
0
  }
1708
1709
77.4k
  const auto target_pointer_type = _.FindDef(target->type_id());
1710
77.4k
  if (!target_pointer_type ||
1711
77.4k
      (target_pointer_type->opcode() != spv::Op::OpTypePointer &&
1712
7
       target_pointer_type->opcode() != spv::Op::OpTypeUntypedPointerKHR)) {
1713
7
    return _.diag(SPV_ERROR_INVALID_ID, inst)
1714
7
           << "Target operand <id> " << _.getIdName(target_id)
1715
7
           << " is not a pointer.";
1716
7
  }
1717
1718
77.4k
  const auto source_pointer_type = _.FindDef(source->type_id());
1719
77.4k
  if (!source_pointer_type ||
1720
77.4k
      (source_pointer_type->opcode() != spv::Op::OpTypePointer &&
1721
14
       source_pointer_type->opcode() != spv::Op::OpTypeUntypedPointerKHR)) {
1722
14
    return _.diag(SPV_ERROR_INVALID_ID, inst)
1723
14
           << "Source operand <id> " << _.getIdName(source_id)
1724
14
           << " is not a pointer.";
1725
14
  }
1726
1727
77.4k
  if (inst->opcode() == spv::Op::OpCopyMemory) {
1728
77.4k
    const bool target_typed =
1729
77.4k
        target_pointer_type->opcode() == spv::Op::OpTypePointer;
1730
77.4k
    const bool source_typed =
1731
77.4k
        source_pointer_type->opcode() == spv::Op::OpTypePointer;
1732
77.4k
    Instruction* target_type = nullptr;
1733
77.4k
    Instruction* source_type = nullptr;
1734
77.4k
    if (target_typed) {
1735
77.4k
      target_type = _.FindDef(target_pointer_type->GetOperandAs<uint32_t>(2));
1736
1737
77.4k
      if (!target_type || target_type->opcode() == spv::Op::OpTypeVoid) {
1738
4
        return _.diag(SPV_ERROR_INVALID_ID, inst)
1739
4
               << "Target operand <id> " << _.getIdName(target_id)
1740
4
               << " cannot be a void pointer.";
1741
4
      }
1742
77.4k
    }
1743
1744
77.4k
    if (source_typed) {
1745
77.4k
      source_type = _.FindDef(source_pointer_type->GetOperandAs<uint32_t>(2));
1746
77.4k
      if (!source_type || source_type->opcode() == spv::Op::OpTypeVoid) {
1747
4
        return _.diag(SPV_ERROR_INVALID_ID, inst)
1748
4
               << "Source operand <id> " << _.getIdName(source_id)
1749
4
               << " cannot be a void pointer.";
1750
4
      }
1751
77.4k
    }
1752
1753
77.4k
    if (target_type && source_type && target_type->id() != source_type->id()) {
1754
6
      return _.diag(SPV_ERROR_INVALID_ID, inst)
1755
6
             << "Target <id> " << _.getIdName(source_id)
1756
6
             << "s type does not match Source <id> "
1757
6
             << _.getIdName(source_type->id()) << "s type.";
1758
6
    }
1759
1760
77.4k
    if (!target_type && !source_type) {
1761
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
1762
0
             << "One of Source or Target must be a typed pointer";
1763
0
    }
1764
1765
77.4k
    if (auto error = CheckMemoryAccess(_, inst, 2)) return error;
1766
77.4k
  } else {
1767
0
    const auto size_id = inst->GetOperandAs<uint32_t>(2);
1768
0
    const auto size = _.FindDef(size_id);
1769
0
    if (!size) {
1770
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
1771
0
             << "Size operand <id> " << _.getIdName(size_id)
1772
0
             << " is not defined.";
1773
0
    }
1774
1775
0
    const auto size_type = _.FindDef(size->type_id());
1776
0
    if (!_.IsIntScalarType(size_type->id())) {
1777
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
1778
0
             << "Size operand <id> " << _.getIdName(size_id)
1779
0
             << " must be a scalar integer type.";
1780
0
    }
1781
0
    bool is_zero = true;
1782
0
    switch (size->opcode()) {
1783
0
      case spv::Op::OpConstantNull:
1784
0
        return _.diag(SPV_ERROR_INVALID_ID, inst)
1785
0
               << "Size operand <id> " << _.getIdName(size_id)
1786
0
               << " cannot be a constant zero.";
1787
0
      case spv::Op::OpConstant:
1788
0
        if (size_type->word(3) == 1 &&
1789
0
            size->word(size->words().size() - 1) & 0x80000000) {
1790
0
          return _.diag(SPV_ERROR_INVALID_ID, inst)
1791
0
                 << "Size operand <id> " << _.getIdName(size_id)
1792
0
                 << " cannot have the sign bit set to 1.";
1793
0
        }
1794
0
        for (size_t i = 3; is_zero && i < size->words().size(); ++i) {
1795
0
          is_zero &= (size->word(i) == 0);
1796
0
        }
1797
0
        if (is_zero) {
1798
0
          return _.diag(SPV_ERROR_INVALID_ID, inst)
1799
0
                 << "Size operand <id> " << _.getIdName(size_id)
1800
0
                 << " cannot be a constant zero.";
1801
0
        }
1802
0
        break;
1803
0
      default:
1804
        // Cannot infer any other opcodes.
1805
0
        break;
1806
0
    }
1807
1808
0
    if (_.HasCapability(spv::Capability::Shader)) {
1809
0
      bool is_int = false;
1810
0
      bool is_const = false;
1811
0
      uint32_t value = 0;
1812
0
      std::tie(is_int, is_const, value) = _.EvalInt32IfConst(size_id);
1813
0
      if (is_const) {
1814
0
        if (value % 4 != 0) {
1815
0
          const auto source_sc =
1816
0
              source_pointer_type->GetOperandAs<spv::StorageClass>(1);
1817
0
          const auto target_sc =
1818
0
              target_pointer_type->GetOperandAs<spv::StorageClass>(1);
1819
0
          const bool int8 = _.HasCapability(spv::Capability::Int8);
1820
0
          const bool ubo_int8 = _.HasCapability(
1821
0
              spv::Capability::UniformAndStorageBuffer8BitAccess);
1822
0
          const bool ssbo_int8 =
1823
0
              _.HasCapability(spv::Capability::StorageBuffer8BitAccess) ||
1824
0
              ubo_int8;
1825
0
          const bool pc_int8 =
1826
0
              _.HasCapability(spv::Capability::StoragePushConstant8);
1827
0
          const bool wg_int8 = _.HasCapability(
1828
0
              spv::Capability::WorkgroupMemoryExplicitLayout8BitAccessKHR);
1829
0
          const bool int16 = _.HasCapability(spv::Capability::Int16) || int8;
1830
0
          const bool ubo_int16 =
1831
0
              _.HasCapability(
1832
0
                  spv::Capability::UniformAndStorageBuffer16BitAccess) ||
1833
0
              ubo_int8;
1834
0
          const bool ssbo_int16 =
1835
0
              _.HasCapability(spv::Capability::StorageBuffer16BitAccess) ||
1836
0
              ubo_int16 || ssbo_int8;
1837
0
          const bool pc_int16 =
1838
0
              _.HasCapability(spv::Capability::StoragePushConstant16) ||
1839
0
              pc_int8;
1840
0
          const bool io_int16 =
1841
0
              _.HasCapability(spv::Capability::StorageInputOutput16);
1842
0
          const bool wg_int16 = _.HasCapability(
1843
0
              spv::Capability::WorkgroupMemoryExplicitLayout16BitAccessKHR);
1844
1845
0
          bool source_int16_match = false;
1846
0
          bool target_int16_match = false;
1847
0
          bool source_int8_match = false;
1848
0
          bool target_int8_match = false;
1849
0
          switch (source_sc) {
1850
0
            case spv::StorageClass::StorageBuffer:
1851
0
              source_int16_match = ssbo_int16;
1852
0
              source_int8_match = ssbo_int8;
1853
0
              break;
1854
0
            case spv::StorageClass::Uniform:
1855
0
              source_int16_match = ubo_int16;
1856
0
              source_int8_match = ubo_int8;
1857
0
              break;
1858
0
            case spv::StorageClass::PushConstant:
1859
0
              source_int16_match = pc_int16;
1860
0
              source_int8_match = pc_int8;
1861
0
              break;
1862
0
            case spv::StorageClass::Input:
1863
0
            case spv::StorageClass::Output:
1864
0
              source_int16_match = io_int16;
1865
0
              break;
1866
0
            case spv::StorageClass::Workgroup:
1867
0
              source_int16_match = wg_int16;
1868
0
              source_int8_match = wg_int8;
1869
0
              break;
1870
0
            default:
1871
0
              break;
1872
0
          }
1873
0
          switch (target_sc) {
1874
0
            case spv::StorageClass::StorageBuffer:
1875
0
              target_int16_match = ssbo_int16;
1876
0
              target_int8_match = ssbo_int8;
1877
0
              break;
1878
0
            case spv::StorageClass::Uniform:
1879
0
              target_int16_match = ubo_int16;
1880
0
              target_int8_match = ubo_int8;
1881
0
              break;
1882
0
            case spv::StorageClass::PushConstant:
1883
0
              target_int16_match = pc_int16;
1884
0
              target_int8_match = pc_int8;
1885
0
              break;
1886
            // Input is read-only so it cannot be the target pointer.
1887
0
            case spv::StorageClass::Output:
1888
0
              target_int16_match = io_int16;
1889
0
              break;
1890
0
            case spv::StorageClass::Workgroup:
1891
0
              target_int16_match = wg_int16;
1892
0
              target_int8_match = wg_int8;
1893
0
              break;
1894
0
            default:
1895
0
              break;
1896
0
          }
1897
0
          if (!int8 && !int16 && !(source_int16_match && target_int16_match)) {
1898
0
            return _.diag(SPV_ERROR_INVALID_ID, inst)
1899
0
                   << _.VkErrorID(11165)
1900
0
                   << "Size must be a multiple of 4. This is valid if Source ("
1901
0
                   << StorageClassToString(source_sc) << ") and Target ("
1902
0
                   << StorageClassToString(source_sc)
1903
0
                   << ") storage classes both support either 8-bit or 16-bit";
1904
0
          }
1905
0
          if (value % 2 != 0) {
1906
0
            if (!int8 && !(source_int8_match && target_int8_match)) {
1907
0
              return _.diag(SPV_ERROR_INVALID_ID, inst)
1908
0
                     << _.VkErrorID(11165)
1909
0
                     << "Size must be a multiple of 2. This is valid if Source "
1910
0
                        "("
1911
0
                     << StorageClassToString(source_sc) << ") and Target ("
1912
0
                     << StorageClassToString(source_sc)
1913
0
                     << ") storage classes both support 8-bit";
1914
0
            }
1915
0
          }
1916
0
        }
1917
0
      }
1918
0
    }
1919
1920
0
    if (auto error = CheckMemoryAccess(_, inst, 3)) return error;
1921
0
  }
1922
77.4k
  if (auto error = ValidateCopyMemoryMemoryAccess(_, inst)) return error;
1923
1924
  // Get past the pointers to avoid checking a pointer copy.
1925
77.4k
  if (target_pointer_type->opcode() == spv::Op::OpTypePointer) {
1926
77.4k
    auto sub_type = _.FindDef(target_pointer_type->GetOperandAs<uint32_t>(2));
1927
77.4k
    while (sub_type->opcode() == spv::Op::OpTypePointer) {
1928
0
      sub_type = _.FindDef(sub_type->GetOperandAs<uint32_t>(2));
1929
0
    }
1930
77.4k
    if (_.HasCapability(spv::Capability::Shader) &&
1931
77.4k
        _.ContainsLimitedUseIntOrFloatType(sub_type->id())) {
1932
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
1933
0
             << "Cannot copy memory of objects containing 8- or 16-bit types";
1934
0
    }
1935
77.4k
  }
1936
1937
77.4k
  return SPV_SUCCESS;
1938
77.4k
}
1939
1940
spv_result_t ValidateAccessChain(ValidationState_t& _,
1941
149k
                                 const Instruction* inst) {
1942
149k
  const spv::Op opcode = inst->opcode();
1943
149k
  const bool untyped_pointer = spvOpcodeGeneratesUntypedPointer(inst->opcode());
1944
1945
  // The result type must be OpTypePointer for regular access chains and an
1946
  // OpTypeUntypedPointerKHR for untyped access chains.
1947
149k
  auto result_type = _.FindDef(inst->type_id());
1948
149k
  if (untyped_pointer) {
1949
0
    if (!result_type ||
1950
0
        spv::Op::OpTypeUntypedPointerKHR != result_type->opcode()) {
1951
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
1952
0
             << "The Result Type of Op" << spvOpcodeString(opcode) << " <id> "
1953
0
             << _.getIdName(inst->id())
1954
0
             << " must be OpTypeUntypedPointerKHR. Found Op"
1955
0
             << spvOpcodeString(result_type->opcode()) << ".";
1956
0
    }
1957
149k
  } else {
1958
149k
    if (!result_type || spv::Op::OpTypePointer != result_type->opcode()) {
1959
18
      return _.diag(SPV_ERROR_INVALID_ID, inst)
1960
18
             << "The Result Type of Op" << spvOpcodeString(opcode) << " <id> "
1961
18
             << _.getIdName(inst->id()) << " must be OpTypePointer. Found Op"
1962
18
             << spvOpcodeString(result_type->opcode()) << ".";
1963
18
    }
1964
149k
  }
1965
1966
149k
  if (untyped_pointer) {
1967
    // Base type must be a non-pointer type.
1968
0
    const auto base_type = _.FindDef(inst->GetOperandAs<uint32_t>(2));
1969
0
    if (!base_type || !spvOpcodeGeneratesType(base_type->opcode()) ||
1970
0
        base_type->opcode() == spv::Op::OpTypePointer ||
1971
0
        base_type->opcode() == spv::Op::OpTypeUntypedPointerKHR) {
1972
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
1973
0
             << "Base type must be a non-pointer type";
1974
0
    }
1975
1976
0
    const auto ContainsBlock = [&_](const Instruction* type_inst) {
1977
0
      if (type_inst->opcode() == spv::Op::OpTypeStruct) {
1978
0
        if (_.HasDecoration(type_inst->id(), spv::Decoration::Block) ||
1979
0
            _.HasDecoration(type_inst->id(), spv::Decoration::BufferBlock)) {
1980
0
          return true;
1981
0
        }
1982
0
      }
1983
0
      return false;
1984
0
    };
1985
1986
    // Block (and BufferBlock) arrays cannot be reinterpreted via untyped access
1987
    // chains.
1988
0
    const bool base_type_block_array =
1989
0
        base_type->opcode() == spv::Op::OpTypeArray &&
1990
0
        _.ContainsType(base_type->id(), ContainsBlock,
1991
0
                       /* traverse_all_types = */ false);
1992
1993
0
    const auto base_index = untyped_pointer ? 3 : 2;
1994
0
    const auto base_id = inst->GetOperandAs<uint32_t>(base_index);
1995
0
    auto base = _.FindDef(base_id);
1996
    // Strictly speaking this misses trivial access chains and function
1997
    // parameter chasing, but that would be a significant complication in the
1998
    // traversal.
1999
0
    while (base->opcode() == spv::Op::OpCopyObject) {
2000
0
      base = _.FindDef(base->GetOperandAs<uint32_t>(2));
2001
0
    }
2002
0
    const Instruction* base_data_type = nullptr;
2003
0
    if (base->opcode() == spv::Op::OpVariable) {
2004
0
      const auto ptr_type = _.FindDef(base->type_id());
2005
0
      base_data_type = _.FindDef(ptr_type->GetOperandAs<uint32_t>(2));
2006
0
    } else if (base->opcode() == spv::Op::OpUntypedVariableKHR) {
2007
0
      if (base->operands().size() > 3) {
2008
0
        base_data_type = _.FindDef(base->GetOperandAs<uint32_t>(3));
2009
0
      }
2010
0
    }
2011
2012
0
    if (base_data_type) {
2013
0
      const bool base_block_array =
2014
0
          base_data_type->opcode() == spv::Op::OpTypeArray &&
2015
0
          _.ContainsType(base_data_type->id(), ContainsBlock,
2016
0
                         /* traverse_all_types = */ false);
2017
2018
0
      if (base_type_block_array != base_block_array) {
2019
0
        return _.diag(SPV_ERROR_INVALID_ID, inst)
2020
0
               << "Both Base Type and Base must be Block or BufferBlock arrays "
2021
0
                  "or neither can be";
2022
0
      } else if (base_type_block_array && base_block_array &&
2023
0
                 base_type->id() != base_data_type->id()) {
2024
0
        return _.diag(SPV_ERROR_INVALID_ID, inst)
2025
0
               << "If Base or Base Type is a Block or BufferBlock array, the "
2026
0
                  "other must also be the same array";
2027
0
      }
2028
0
    }
2029
0
  }
2030
2031
  // Base must be a pointer, pointing to the base of a composite object.
2032
149k
  const auto base_index = untyped_pointer ? 3 : 2;
2033
149k
  const auto base_id = inst->GetOperandAs<uint32_t>(base_index);
2034
149k
  const auto base = _.FindDef(base_id);
2035
149k
  const auto base_type = _.FindDef(base->type_id());
2036
149k
  if (!base_type || !(spv::Op::OpTypePointer == base_type->opcode() ||
2037
12
                      (untyped_pointer && spv::Op::OpTypeUntypedPointerKHR ==
2038
16
                                              base_type->opcode()))) {
2039
16
    return _.diag(SPV_ERROR_INVALID_ID, inst)
2040
16
           << "The Base <id> " << _.getIdName(base_id) << " in Op"
2041
16
           << spvOpcodeString(opcode) << " instruction must be a pointer.";
2042
16
  }
2043
2044
  // The result pointer storage class and base pointer storage class must match.
2045
  // Word 2 of OpTypePointer is the Storage Class.
2046
149k
  auto result_type_storage_class = result_type->word(2);
2047
149k
  auto base_type_storage_class = base_type->word(2);
2048
149k
  if (result_type_storage_class != base_type_storage_class) {
2049
12
    return _.diag(SPV_ERROR_INVALID_ID, inst)
2050
12
           << "The result pointer storage class and base "
2051
12
              "pointer storage class in Op"
2052
12
           << spvOpcodeString(opcode) << " do not match.";
2053
12
  }
2054
2055
  // The type pointed to by OpTypePointer (word 3) must be a composite type.
2056
149k
  auto type_pointee = untyped_pointer
2057
149k
                          ? _.FindDef(inst->GetOperandAs<uint32_t>(2))
2058
149k
                          : _.FindDef(base_type->word(3));
2059
2060
  // Check Universal Limit (SPIR-V Spec. Section 2.17).
2061
  // The number of indexes passed to OpAccessChain may not exceed 255
2062
  // The instruction includes 4 words + N words (for N indexes)
2063
149k
  size_t num_indexes = inst->words().size() - 4;
2064
149k
  if (inst->opcode() == spv::Op::OpPtrAccessChain ||
2065
149k
      inst->opcode() == spv::Op::OpInBoundsPtrAccessChain ||
2066
149k
      inst->opcode() == spv::Op::OpUntypedPtrAccessChainKHR ||
2067
149k
      inst->opcode() == spv::Op::OpUntypedInBoundsPtrAccessChainKHR) {
2068
    // In pointer access chains, the element operand is required, but not
2069
    // counted as an index.
2070
13
    --num_indexes;
2071
13
  }
2072
149k
  const size_t num_indexes_limit =
2073
149k
      _.options()->universal_limits_.max_access_chain_indexes;
2074
149k
  if (num_indexes > num_indexes_limit) {
2075
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
2076
0
           << "The number of indexes in Op" << spvOpcodeString(opcode)
2077
0
           << " may not exceed " << num_indexes_limit << ". Found "
2078
0
           << num_indexes << " indexes.";
2079
0
  }
2080
  // Indexes walk the type hierarchy to the desired depth, potentially down to
2081
  // scalar granularity. The first index in Indexes will select the top-level
2082
  // member/element/component/element of the base composite. All composite
2083
  // constituents use zero-based numbering, as described by their OpType...
2084
  // instruction. The second index will apply similarly to that result, and so
2085
  // on. Once any non-composite type is reached, there must be no remaining
2086
  // (unused) indexes.
2087
149k
  auto starting_index = untyped_pointer ? 5 : 4;
2088
149k
  if (inst->opcode() == spv::Op::OpPtrAccessChain ||
2089
149k
      inst->opcode() == spv::Op::OpInBoundsPtrAccessChain ||
2090
149k
      inst->opcode() == spv::Op::OpUntypedPtrAccessChainKHR ||
2091
149k
      inst->opcode() == spv::Op::OpUntypedInBoundsPtrAccessChainKHR) {
2092
13
    ++starting_index;
2093
13
  }
2094
339k
  for (size_t i = starting_index; i < inst->words().size(); ++i) {
2095
189k
    const uint32_t cur_word = inst->words()[i];
2096
    // Earlier ID checks ensure that cur_word definition exists.
2097
189k
    auto cur_word_instr = _.FindDef(cur_word);
2098
    // The index must be a scalar integer type (See OpAccessChain in the Spec.)
2099
189k
    auto index_type = _.FindDef(cur_word_instr->type_id());
2100
189k
    if (!index_type || spv::Op::OpTypeInt != index_type->opcode()) {
2101
10
      return _.diag(SPV_ERROR_INVALID_ID, inst)
2102
10
             << "Indexes passed to Op" << spvOpcodeString(opcode)
2103
10
             << " must be of type integer.";
2104
10
    }
2105
2106
    // Logical pointer restrictions: any constant index with a signed integer
2107
    // type must not have its sign bit set.
2108
189k
    if (!_.options()->relax_logical_pointer &&
2109
189k
        (_.addressing_model() == spv::AddressingModel::Logical ||
2110
22
         _.addressing_model() ==
2111
22
             spv::AddressingModel::PhysicalStorageBuffer64) &&
2112
189k
        result_type_storage_class !=
2113
189k
            static_cast<uint32_t>(spv::StorageClass::PhysicalStorageBuffer)) {
2114
189k
      if (index_type->GetOperandAs<uint32_t>(2) == 1) {
2115
125k
        int64_t val = 0;
2116
125k
        if (_.EvalConstantValInt64(cur_word, &val)) {
2117
73.7k
          if (val < 0) {
2118
59
            return _.diag(SPV_ERROR_INVALID_ID, inst)
2119
59
                   << "Index at word " << i << " may not have a negative value";
2120
59
          }
2121
73.7k
        }
2122
125k
      }
2123
189k
    }
2124
2125
189k
    switch (type_pointee->opcode()) {
2126
4.99k
      case spv::Op::OpTypeMatrix:
2127
75.3k
      case spv::Op::OpTypeVector:
2128
75.3k
      case spv::Op::OpTypeVectorIdEXT:
2129
75.3k
      case spv::Op::OpTypeCooperativeMatrixNV:
2130
75.3k
      case spv::Op::OpTypeCooperativeMatrixKHR:
2131
136k
      case spv::Op::OpTypeArray:
2132
137k
      case spv::Op::OpTypeRuntimeArray:
2133
137k
      case spv::Op::OpTypeNodePayloadArrayAMDX: {
2134
        // In OpTypeMatrix, OpTypeVector, spv::Op::OpTypeCooperativeMatrixNV,
2135
        // OpTypeVectorIdEXT, OpTypeArray, and OpTypeRuntimeArray, word
2136
        // 2 is the Element Type.
2137
137k
        type_pointee = _.FindDef(type_pointee->word(2));
2138
137k
        break;
2139
137k
      }
2140
52.4k
      case spv::Op::OpTypeStruct: {
2141
        // In case of structures, there is an additional constraint on the
2142
        // index: the index must be an OpConstant.
2143
52.4k
        int64_t cur_index;
2144
52.4k
        if (!_.EvalConstantValInt64(cur_word, &cur_index)) {
2145
5
          return _.diag(SPV_ERROR_INVALID_ID, inst)
2146
5
                 << "The <id> passed to Op" << spvOpcodeString(opcode)
2147
5
                 << " to index " << _.getIdName(cur_word)
2148
5
                 << " into a "
2149
5
                    "structure must be an OpConstant.";
2150
5
        }
2151
2152
        // The index points to the struct member we want, therefore, the index
2153
        // should be less than the number of struct members.
2154
52.4k
        const int64_t num_struct_members =
2155
52.4k
            static_cast<int64_t>(type_pointee->words().size() - 2);
2156
52.4k
        if (cur_index >= num_struct_members || cur_index < 0) {
2157
68
          return _.diag(SPV_ERROR_INVALID_ID, inst)
2158
68
                 << "Index " << _.getIdName(cur_word) << " is out of bounds: Op"
2159
68
                 << spvOpcodeString(opcode) << " cannot find index "
2160
68
                 << cur_index << " into the structure <id> "
2161
68
                 << _.getIdName(type_pointee->id()) << ". This structure has "
2162
68
                 << num_struct_members << " members. Largest valid index is "
2163
68
                 << num_struct_members - 1 << ".";
2164
68
        }
2165
        // Struct members IDs start at word 2 of OpTypeStruct.
2166
52.3k
        const size_t word_index = static_cast<size_t>(cur_index) + 2;
2167
52.3k
        auto structMemberId = type_pointee->word(word_index);
2168
52.3k
        type_pointee = _.FindDef(structMemberId);
2169
52.3k
        break;
2170
52.4k
      }
2171
21
      default: {
2172
        // Give an error. reached non-composite type while indexes still remain.
2173
21
        return _.diag(SPV_ERROR_INVALID_ID, inst)
2174
21
               << "Op" << spvOpcodeString(opcode)
2175
21
               << " reached non-composite type while indexes "
2176
21
                  "still remain to be traversed.";
2177
52.4k
      }
2178
189k
    }
2179
189k
  }
2180
2181
149k
  if (!untyped_pointer) {
2182
    // Result type is a pointer. Find out what it's pointing to.
2183
    // This will be used to make sure the indexing results in the same type.
2184
    // OpTypePointer word 3 is the type being pointed to.
2185
149k
    const auto result_type_pointee = _.FindDef(result_type->word(3));
2186
    // At this point, we have fully walked down from the base using the indeces.
2187
    // The type being pointed to should be the same as the result type.
2188
149k
    if (type_pointee->id() != result_type_pointee->id()) {
2189
19
      bool same_type = result_type_pointee->opcode() == type_pointee->opcode();
2190
19
      return _.diag(SPV_ERROR_INVALID_ID, inst)
2191
19
             << "Op" << spvOpcodeString(opcode) << " result type <id> "
2192
19
             << _.getIdName(result_type_pointee->id()) << " (Op"
2193
19
             << spvOpcodeString(result_type_pointee->opcode())
2194
19
             << ") does not match the type that results from indexing into the "
2195
19
                "base "
2196
19
                "<id> "
2197
19
             << _.getIdName(type_pointee->id()) << " (Op"
2198
19
             << spvOpcodeString(type_pointee->opcode()) << ")."
2199
19
             << (same_type ? " (The types must be the exact same Id, so the "
2200
3
                             "two types referenced are slighlty different)"
2201
19
                           : "");
2202
19
    }
2203
149k
  }
2204
2205
149k
  return SPV_SUCCESS;
2206
149k
}
2207
2208
spv_result_t ValidateRawAccessChain(ValidationState_t& _,
2209
0
                                    const Instruction* inst) {
2210
0
  const spv::Op opcode = inst->opcode();
2211
  // The result type must be OpTypePointer.
2212
0
  const auto result_type = _.FindDef(inst->type_id());
2213
0
  if (spv::Op::OpTypePointer != result_type->opcode()) {
2214
0
    return _.diag(SPV_ERROR_INVALID_DATA, inst)
2215
0
           << "The Result Type of Op" << spvOpcodeString(opcode) << " <id> "
2216
0
           << _.getIdName(inst->id()) << " must be OpTypePointer. Found Op"
2217
0
           << spvOpcodeString(result_type->opcode()) << '.';
2218
0
  }
2219
2220
  // The pointed storage class must be valid.
2221
0
  const auto storage_class = result_type->GetOperandAs<spv::StorageClass>(1);
2222
0
  if (storage_class != spv::StorageClass::StorageBuffer &&
2223
0
      storage_class != spv::StorageClass::PhysicalStorageBuffer &&
2224
0
      storage_class != spv::StorageClass::Uniform) {
2225
0
    return _.diag(SPV_ERROR_INVALID_DATA, inst)
2226
0
           << "The Result Type of Op" << spvOpcodeString(opcode) << " <id> "
2227
0
           << _.getIdName(inst->id())
2228
0
           << " must point to a storage class of "
2229
0
              "StorageBuffer, PhysicalStorageBuffer, or Uniform.";
2230
0
  }
2231
2232
  // The pointed type must not be one in the list below.
2233
0
  const auto result_type_pointee =
2234
0
      _.FindDef(result_type->GetOperandAs<uint32_t>(2));
2235
0
  if (result_type_pointee->opcode() == spv::Op::OpTypeArray ||
2236
0
      result_type_pointee->opcode() == spv::Op::OpTypeMatrix ||
2237
0
      result_type_pointee->opcode() == spv::Op::OpTypeStruct) {
2238
0
    return _.diag(SPV_ERROR_INVALID_DATA, inst)
2239
0
           << "The Result Type of Op" << spvOpcodeString(opcode) << " <id> "
2240
0
           << _.getIdName(inst->id())
2241
0
           << " must not point to "
2242
0
              "OpTypeArray, OpTypeMatrix, or OpTypeStruct.";
2243
0
  }
2244
2245
  // Validate Stride is a OpConstant.
2246
0
  const auto stride = _.FindDef(inst->GetOperandAs<uint32_t>(3));
2247
0
  if (stride->opcode() != spv::Op::OpConstant) {
2248
0
    return _.diag(SPV_ERROR_INVALID_DATA, inst)
2249
0
           << "The Stride of Op" << spvOpcodeString(opcode) << " <id> "
2250
0
           << _.getIdName(inst->id()) << " must be OpConstant. Found Op"
2251
0
           << spvOpcodeString(stride->opcode()) << '.';
2252
0
  }
2253
  // Stride type must be OpTypeInt
2254
0
  const auto stride_type = _.FindDef(stride->type_id());
2255
0
  if (stride_type->opcode() != spv::Op::OpTypeInt) {
2256
0
    return _.diag(SPV_ERROR_INVALID_DATA, inst)
2257
0
           << "The type of Stride of Op" << spvOpcodeString(opcode) << " <id> "
2258
0
           << _.getIdName(inst->id()) << " must be OpTypeInt. Found Op"
2259
0
           << spvOpcodeString(stride_type->opcode()) << '.';
2260
0
  }
2261
2262
  // Index and Offset type must be OpTypeInt with a width of 32
2263
0
  const auto ValidateType = [&](const char* name,
2264
0
                                int operandIndex) -> spv_result_t {
2265
0
    const auto value = _.FindDef(inst->GetOperandAs<uint32_t>(operandIndex));
2266
0
    const auto value_type = _.FindDef(value->type_id());
2267
0
    if (value_type->opcode() != spv::Op::OpTypeInt) {
2268
0
      return _.diag(SPV_ERROR_INVALID_DATA, inst)
2269
0
             << "The type of " << name << " of Op" << spvOpcodeString(opcode)
2270
0
             << " <id> " << _.getIdName(inst->id())
2271
0
             << " must be OpTypeInt. Found Op"
2272
0
             << spvOpcodeString(value_type->opcode()) << '.';
2273
0
    }
2274
0
    const auto width = value_type->GetOperandAs<uint32_t>(1);
2275
0
    if (width != 32) {
2276
0
      return _.diag(SPV_ERROR_INVALID_DATA, inst)
2277
0
             << "The integer width of " << name << " of Op"
2278
0
             << spvOpcodeString(opcode) << " <id> " << _.getIdName(inst->id())
2279
0
             << " must be 32. Found " << width << '.';
2280
0
    }
2281
0
    return SPV_SUCCESS;
2282
0
  };
2283
0
  spv_result_t result;
2284
0
  result = ValidateType("Index", 4);
2285
0
  if (result != SPV_SUCCESS) {
2286
0
    return result;
2287
0
  }
2288
0
  result = ValidateType("Offset", 5);
2289
0
  if (result != SPV_SUCCESS) {
2290
0
    return result;
2291
0
  }
2292
2293
0
  uint32_t access_operands = 0;
2294
0
  if (inst->operands().size() >= 7) {
2295
0
    access_operands = inst->GetOperandAs<uint32_t>(6);
2296
0
  }
2297
0
  if (access_operands &
2298
0
      uint32_t(spv::RawAccessChainOperandsMask::RobustnessPerElementNV)) {
2299
0
    uint64_t stride_value = 0;
2300
0
    if (_.EvalConstantValUint64(stride->id(), &stride_value) &&
2301
0
        stride_value == 0) {
2302
0
      return _.diag(SPV_ERROR_INVALID_DATA, inst)
2303
0
             << "Stride must not be zero when per-element robustness is used.";
2304
0
    }
2305
0
  }
2306
0
  if (access_operands &
2307
0
          uint32_t(spv::RawAccessChainOperandsMask::RobustnessPerComponentNV) ||
2308
0
      access_operands &
2309
0
          uint32_t(spv::RawAccessChainOperandsMask::RobustnessPerElementNV)) {
2310
0
    if (storage_class == spv::StorageClass::PhysicalStorageBuffer) {
2311
0
      return _.diag(SPV_ERROR_INVALID_DATA, inst)
2312
0
             << "Storage class cannot be PhysicalStorageBuffer when "
2313
0
                "raw access chain robustness is used.";
2314
0
    }
2315
0
  }
2316
0
  if (access_operands &
2317
0
          uint32_t(spv::RawAccessChainOperandsMask::RobustnessPerComponentNV) &&
2318
0
      access_operands &
2319
0
          uint32_t(spv::RawAccessChainOperandsMask::RobustnessPerElementNV)) {
2320
0
    return _.diag(SPV_ERROR_INVALID_DATA, inst)
2321
0
           << "Per-component robustness and per-element robustness are "
2322
0
              "mutually exclusive.";
2323
0
  }
2324
2325
0
  return SPV_SUCCESS;
2326
0
}
2327
2328
spv_result_t ValidatePtrAccessChain(ValidationState_t& _,
2329
7
                                    const Instruction* inst) {
2330
  // Need to call first, will make sure Base is a valid ID
2331
7
  if (auto error = ValidateAccessChain(_, inst)) return error;
2332
2333
3
  const bool untyped_pointer = spvOpcodeGeneratesUntypedPointer(inst->opcode());
2334
2335
3
  const auto base_idx = untyped_pointer ? 3 : 2;
2336
3
  const auto base = _.FindDef(inst->GetOperandAs<uint32_t>(base_idx));
2337
3
  const auto base_type = _.FindDef(base->type_id());
2338
3
  const auto base_type_storage_class =
2339
3
      base_type->GetOperandAs<spv::StorageClass>(1);
2340
2341
3
  const auto element_idx = untyped_pointer ? 4 : 3;
2342
3
  const auto element = _.FindDef(inst->GetOperandAs<uint32_t>(element_idx));
2343
3
  const auto element_type = _.FindDef(element->type_id());
2344
3
  if (!element_type || element_type->opcode() != spv::Op::OpTypeInt) {
2345
3
    return _.diag(SPV_ERROR_INVALID_DATA, inst) << "Element must be an integer";
2346
3
  }
2347
0
  uint64_t element_val = 0;
2348
0
  if (_.EvalConstantValUint64(element->id(), &element_val)) {
2349
0
    if (element_val != 0) {
2350
0
      const auto interp_type =
2351
0
          untyped_pointer ? _.FindDef(inst->GetOperandAs<uint32_t>(2))
2352
0
                          : _.FindDef(base_type->GetOperandAs<uint32_t>(2));
2353
0
      if (interp_type->opcode() == spv::Op::OpTypeStruct &&
2354
0
          (_.HasDecoration(interp_type->id(), spv::Decoration::Block) ||
2355
0
           _.HasDecoration(interp_type->id(), spv::Decoration::BufferBlock))) {
2356
0
        return _.diag(SPV_ERROR_INVALID_DATA, inst)
2357
0
               << "Element must be 0 if the interpretation type is a Block- or "
2358
0
                  "BufferBlock-decorated structure";
2359
0
      }
2360
0
    }
2361
0
  }
2362
2363
0
  if (_.HasCapability(spv::Capability::Shader) &&
2364
0
      (base_type_storage_class == spv::StorageClass::Uniform ||
2365
0
       base_type_storage_class == spv::StorageClass::StorageBuffer ||
2366
0
       base_type_storage_class == spv::StorageClass::PhysicalStorageBuffer ||
2367
0
       base_type_storage_class == spv::StorageClass::PushConstant ||
2368
0
       (_.HasCapability(spv::Capability::WorkgroupMemoryExplicitLayoutKHR) &&
2369
0
        base_type_storage_class == spv::StorageClass::Workgroup)) &&
2370
0
      (!_.HasDecoration(base_type->id(), spv::Decoration::ArrayStride) &&
2371
0
       !_.HasDecoration(base_type->id(), spv::Decoration::ArrayStrideIdEXT))) {
2372
0
    return _.diag(SPV_ERROR_INVALID_DATA, inst)
2373
0
           << "OpPtrAccessChain must have a Base whose type is decorated "
2374
0
              "with ArrayStride or ArrayStrideIdEXT";
2375
0
  }
2376
2377
0
  if (spvIsVulkanEnv(_.context()->target_env)) {
2378
0
    const auto untyped_cap =
2379
0
        untyped_pointer && _.HasCapability(spv::Capability::UntypedPointersKHR);
2380
0
    if (base_type_storage_class == spv::StorageClass::Workgroup) {
2381
0
      if (!_.HasCapability(spv::Capability::VariablePointers) && !untyped_cap) {
2382
0
        return _.diag(SPV_ERROR_INVALID_DATA, inst)
2383
0
               << _.VkErrorID(7651)
2384
0
               << "OpPtrAccessChain Base operand pointing to Workgroup "
2385
0
                  "storage class must use VariablePointers capability";
2386
0
      }
2387
0
    } else if (base_type_storage_class == spv::StorageClass::StorageBuffer) {
2388
0
      if (!_.features().variable_pointers && !untyped_cap) {
2389
0
        return _.diag(SPV_ERROR_INVALID_DATA, inst)
2390
0
               << _.VkErrorID(7652)
2391
0
               << "OpPtrAccessChain Base operand pointing to StorageBuffer "
2392
0
                  "storage class must use VariablePointers or "
2393
0
                  "VariablePointersStorageBuffer capability";
2394
0
      }
2395
0
    } else if (base_type_storage_class !=
2396
0
                   spv::StorageClass::PhysicalStorageBuffer &&
2397
0
               !untyped_cap) {
2398
0
      return _.diag(SPV_ERROR_INVALID_DATA, inst)
2399
0
             << _.VkErrorID(7650)
2400
0
             << "OpPtrAccessChain Base operand must point to Workgroup, "
2401
0
                "StorageBuffer, or PhysicalStorageBuffer storage class";
2402
0
    }
2403
0
  }
2404
2405
0
  return SPV_SUCCESS;
2406
0
}
2407
2408
spv_result_t ValidateArrayLength(ValidationState_t& state,
2409
32
                                 const Instruction* inst) {
2410
32
  const spv::Op opcode = inst->opcode();
2411
2412
  // Result type must be a 32- or 64-bit unsigned int.
2413
  // 64-bit requires CapabilityShader64BitIndexingEXT or a pipeline/shader
2414
  // flag and is validated in VVL.
2415
32
  const uint32_t result_type_id = inst->type_id();
2416
32
  if (!state.IsIntScalarTypeWithSignedness(result_type_id, 0)) {
2417
19
    return state.diag(SPV_ERROR_INVALID_ID, inst)
2418
19
           << "The Result Type of Op" << spvOpcodeString(opcode) << " <id> "
2419
19
           << state.getIdName(inst->id())
2420
19
           << " must be OpTypeInt with width 32 or 64 and signedness 0.";
2421
19
  }
2422
13
  const uint32_t result_type_width = state.GetBitWidth(inst->type_id());
2423
13
  if (result_type_width != 32 && result_type_width != 64) {
2424
0
    return state.diag(SPV_ERROR_INVALID_ID, inst)
2425
0
           << "The Result Type of Op" << spvOpcodeString(opcode) << " <id> "
2426
0
           << state.getIdName(inst->id())
2427
0
           << " must be OpTypeInt with width 32 or 64 and signedness 0.";
2428
0
  }
2429
2430
13
  const bool untyped = inst->opcode() == spv::Op::OpUntypedArrayLengthKHR;
2431
13
  auto pointer_ty_id = state.GetOperandTypeId(inst, (untyped ? 3 : 2));
2432
13
  auto pointer_ty = state.FindDef(pointer_ty_id);
2433
13
  if (untyped) {
2434
0
    if (!pointer_ty ||
2435
0
        pointer_ty->opcode() != spv::Op::OpTypeUntypedPointerKHR) {
2436
0
      return state.diag(SPV_ERROR_INVALID_ID, inst)
2437
0
             << "Pointer must be an untyped pointer object";
2438
0
    }
2439
13
  } else if (!pointer_ty || pointer_ty->opcode() != spv::Op::OpTypePointer) {
2440
8
    return state.diag(SPV_ERROR_INVALID_ID, inst)
2441
8
           << "The Structure's type in Op" << spvOpcodeString(opcode)
2442
8
           << " <id> " << state.getIdName(inst->id())
2443
8
           << " must be a pointer to an OpTypeStruct.";
2444
8
  }
2445
2446
5
  Instruction* structure_type = nullptr;
2447
5
  if (untyped) {
2448
0
    structure_type = state.FindDef(inst->GetOperandAs<uint32_t>(2));
2449
5
  } else {
2450
5
    structure_type = state.FindDef(pointer_ty->GetOperandAs<uint32_t>(2));
2451
5
  }
2452
2453
5
  if (structure_type->opcode() != spv::Op::OpTypeStruct) {
2454
4
    return state.diag(SPV_ERROR_INVALID_ID, inst)
2455
4
           << "The Structure's type in Op" << spvOpcodeString(opcode)
2456
4
           << " <id> " << state.getIdName(inst->id())
2457
4
           << " must be a pointer to an OpTypeStruct.";
2458
4
  }
2459
2460
1
  auto num_of_members = structure_type->operands().size() - 1;
2461
1
  auto last_member =
2462
1
      state.FindDef(structure_type->GetOperandAs<uint32_t>(num_of_members));
2463
1
  if (last_member->opcode() != spv::Op::OpTypeRuntimeArray) {
2464
1
    return state.diag(SPV_ERROR_INVALID_ID, inst)
2465
1
           << "The Structure's last member in Op" << spvOpcodeString(opcode)
2466
1
           << " <id> " << state.getIdName(inst->id())
2467
1
           << " must be an OpTypeRuntimeArray.";
2468
1
  }
2469
2470
  // The array member must the index of the last element (the run time
2471
  // array).
2472
0
  const auto index = untyped ? 4 : 3;
2473
0
  if (inst->GetOperandAs<uint32_t>(index) != num_of_members - 1) {
2474
0
    return state.diag(SPV_ERROR_INVALID_ID, inst)
2475
0
           << "The array member in Op" << spvOpcodeString(opcode) << " <id> "
2476
0
           << state.getIdName(inst->id())
2477
0
           << " must be the last member of the struct.";
2478
0
  }
2479
2480
0
  if (spvIsVulkanEnv(state.context()->target_env)) {
2481
0
    const auto storage_class = pointer_ty->GetOperandAs<spv::StorageClass>(1);
2482
0
    if (storage_class == spv::StorageClass::Uniform &&
2483
0
        state.HasDecoration(structure_type->id(), spv::Decoration::Block)) {
2484
0
      return state.diag(SPV_ERROR_INVALID_ID, inst)
2485
0
             << state.VkErrorID(11805) << "Op" << spvOpcodeString(opcode)
2486
0
             << " must not be used on the OpTypeRuntimeArray inside a Uniform "
2487
0
                "block";
2488
0
    }
2489
0
  }
2490
2491
0
  return SPV_SUCCESS;
2492
0
}
2493
2494
spv_result_t ValidateCooperativeMatrixLength(ValidationState_t& state,
2495
                                             const Instruction* inst,
2496
                                             bool is_khr,
2497
29
                                             uint32_t operand_index = 2) {
2498
29
  const spv::Op opcode = inst->opcode();
2499
  // Result type must be a 32-bit unsigned int.
2500
29
  const uint32_t result_type_id = inst->type_id();
2501
29
  if (!state.IsIntScalarTypeWithSignedness(result_type_id, 0) ||
2502
29
      state.GetBitWidth(inst->type_id()) != 32) {
2503
29
    return state.diag(SPV_ERROR_INVALID_ID, inst)
2504
29
           << "The Result Type of Op" << spvOpcodeString(opcode) << " <id> "
2505
29
           << state.getIdName(inst->id())
2506
29
           << " must be OpTypeInt with width 32 and signedness 0.";
2507
29
  }
2508
2509
0
  auto type_id = inst->GetOperandAs<uint32_t>(operand_index);
2510
0
  auto type = state.FindDef(type_id);
2511
0
  if (is_khr && type->opcode() != spv::Op::OpTypeCooperativeMatrixKHR) {
2512
0
    return state.diag(SPV_ERROR_INVALID_ID, inst)
2513
0
           << "The type in Op" << spvOpcodeString(opcode) << " <id> "
2514
0
           << state.getIdName(type_id)
2515
0
           << " must be OpTypeCooperativeMatrixKHR.";
2516
0
  } else if (!is_khr && type->opcode() != spv::Op::OpTypeCooperativeMatrixNV) {
2517
0
    return state.diag(SPV_ERROR_INVALID_ID, inst)
2518
0
           << "The type in Op" << spvOpcodeString(opcode) << " <id> "
2519
0
           << state.getIdName(type_id) << " must be OpTypeCooperativeMatrixNV.";
2520
0
  }
2521
0
  return SPV_SUCCESS;
2522
0
}
2523
2524
spv_result_t ValidateCooperativeMatrixGetCoordinateEXT(
2525
0
    ValidationState_t& state, const Instruction* inst) {
2526
0
  std::string instr_name = "OpCooperativeMatrixGetCoordinateEXT";
2527
2528
  // Result type must be a uvec2
2529
0
  if (!state.IsIntVectorType(inst->type_id(), 32, 2)) {
2530
0
    return state.diag(SPV_ERROR_INVALID_ID, inst)
2531
0
           << instr_name << " Result Type <id> "
2532
0
           << state.getIdName(inst->type_id())
2533
0
           << " must be OpTypeVector with two 32-bit integer components.";
2534
0
  }
2535
2536
  // Matrix operand must be a cooperative matrix
2537
0
  auto matrix_type_id =
2538
0
      state.FindDef(inst->GetOperandAs<uint32_t>(2))->type_id();
2539
0
  if (!state.IsCooperativeMatrixKHRType(matrix_type_id)) {
2540
0
    return state.diag(SPV_ERROR_INVALID_ID, inst)
2541
0
           << instr_name << " Matrix <id> "
2542
0
           << state.getIdName(inst->GetOperandAs<uint32_t>(2))
2543
0
           << " must be OpTypeCooperativeMatrixKHR.";
2544
0
  }
2545
2546
  // Index operand must be a 32-bit int.
2547
0
  auto index_type_id =
2548
0
      state.FindDef(inst->GetOperandAs<uint32_t>(3))->type_id();
2549
0
  if (!state.IsIntScalarType(index_type_id, 32)) {
2550
0
    return state.diag(SPV_ERROR_INVALID_ID, inst)
2551
0
           << instr_name << " Index <id> "
2552
0
           << state.getIdName(inst->GetOperandAs<uint32_t>(3))
2553
0
           << " must be OpTypeInt with width 32.";
2554
0
  }
2555
2556
0
  return SPV_SUCCESS;
2557
0
}
2558
2559
spv_result_t ValidateCooperativeMatrixLoadStoreNV(ValidationState_t& _,
2560
0
                                                  const Instruction* inst) {
2561
0
  uint32_t type_id;
2562
0
  const char* opname;
2563
0
  if (inst->opcode() == spv::Op::OpCooperativeMatrixLoadNV) {
2564
0
    type_id = inst->type_id();
2565
0
    opname = "spv::Op::OpCooperativeMatrixLoadNV";
2566
0
  } else {
2567
    // get Object operand's type
2568
0
    type_id = _.FindDef(inst->GetOperandAs<uint32_t>(1))->type_id();
2569
0
    opname = "spv::Op::OpCooperativeMatrixStoreNV";
2570
0
  }
2571
2572
0
  auto matrix_type = _.FindDef(type_id);
2573
2574
0
  if (matrix_type->opcode() != spv::Op::OpTypeCooperativeMatrixNV) {
2575
0
    if (inst->opcode() == spv::Op::OpCooperativeMatrixLoadNV) {
2576
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
2577
0
             << "spv::Op::OpCooperativeMatrixLoadNV Result Type <id> "
2578
0
             << _.getIdName(type_id) << " is not a cooperative matrix type.";
2579
0
    } else {
2580
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
2581
0
             << "spv::Op::OpCooperativeMatrixStoreNV Object type <id> "
2582
0
             << _.getIdName(type_id) << " is not a cooperative matrix type.";
2583
0
    }
2584
0
  }
2585
2586
0
  const auto pointer_index =
2587
0
      (inst->opcode() == spv::Op::OpCooperativeMatrixLoadNV) ? 2u : 0u;
2588
0
  const auto pointer_id = inst->GetOperandAs<uint32_t>(pointer_index);
2589
0
  const auto pointer = _.FindDef(pointer_id);
2590
0
  if (!pointer ||
2591
0
      ((_.addressing_model() == spv::AddressingModel::Logical) &&
2592
0
       ((!_.features().variable_pointers &&
2593
0
         !spvOpcodeReturnsLogicalPointer(pointer->opcode())) ||
2594
0
        (_.features().variable_pointers &&
2595
0
         !spvOpcodeReturnsLogicalVariablePointer(pointer->opcode()))))) {
2596
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
2597
0
           << opname << " Pointer <id> " << _.getIdName(pointer_id)
2598
0
           << " is not a logical pointer.";
2599
0
  }
2600
2601
0
  const auto pointer_type_id = pointer->type_id();
2602
0
  const auto pointer_type = _.FindDef(pointer_type_id);
2603
0
  if (!pointer_type || pointer_type->opcode() != spv::Op::OpTypePointer) {
2604
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
2605
0
           << opname << " type for pointer <id> " << _.getIdName(pointer_id)
2606
0
           << " is not a pointer type.";
2607
0
  }
2608
2609
0
  const auto storage_class_index = 1u;
2610
0
  const auto storage_class =
2611
0
      pointer_type->GetOperandAs<spv::StorageClass>(storage_class_index);
2612
2613
0
  if (storage_class != spv::StorageClass::Workgroup &&
2614
0
      storage_class != spv::StorageClass::StorageBuffer &&
2615
0
      storage_class != spv::StorageClass::PhysicalStorageBuffer) {
2616
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
2617
0
           << opname << " storage class for pointer type <id> "
2618
0
           << _.getIdName(pointer_type_id)
2619
0
           << " is not Workgroup or StorageBuffer.";
2620
0
  }
2621
2622
0
  const auto pointee_id = pointer_type->GetOperandAs<uint32_t>(2);
2623
0
  const auto pointee_type = _.FindDef(pointee_id);
2624
0
  if (!pointee_type || !(_.IsIntScalarOrVectorType(pointee_id) ||
2625
0
                         _.IsFloatScalarOrVectorType(pointee_id))) {
2626
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
2627
0
           << opname << " Pointer <id> " << _.getIdName(pointer->id())
2628
0
           << "s Type must be a scalar or vector type.";
2629
0
  }
2630
2631
0
  const auto stride_index =
2632
0
      (inst->opcode() == spv::Op::OpCooperativeMatrixLoadNV) ? 3u : 2u;
2633
0
  const auto stride_id = inst->GetOperandAs<uint32_t>(stride_index);
2634
0
  const auto stride = _.FindDef(stride_id);
2635
0
  if (!stride || !_.IsIntScalarType(stride->type_id())) {
2636
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
2637
0
           << "Stride operand <id> " << _.getIdName(stride_id)
2638
0
           << " must be a scalar integer type.";
2639
0
  }
2640
2641
0
  const auto colmajor_index =
2642
0
      (inst->opcode() == spv::Op::OpCooperativeMatrixLoadNV) ? 4u : 3u;
2643
0
  const auto colmajor_id = inst->GetOperandAs<uint32_t>(colmajor_index);
2644
0
  const auto colmajor = _.FindDef(colmajor_id);
2645
0
  if (!colmajor || !_.IsBoolScalarType(colmajor->type_id()) ||
2646
0
      !(spvOpcodeIsConstant(colmajor->opcode()) ||
2647
0
        spvOpcodeIsSpecConstant(colmajor->opcode()))) {
2648
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
2649
0
           << "Column Major operand <id> " << _.getIdName(colmajor_id)
2650
0
           << " must be a boolean constant instruction.";
2651
0
  }
2652
2653
0
  const auto memory_access_index =
2654
0
      (inst->opcode() == spv::Op::OpCooperativeMatrixLoadNV) ? 5u : 4u;
2655
0
  if (inst->operands().size() > memory_access_index) {
2656
0
    if (auto error = CheckMemoryAccess(_, inst, memory_access_index))
2657
0
      return error;
2658
0
  }
2659
2660
0
  return SPV_SUCCESS;
2661
0
}
2662
2663
spv_result_t ValidateCooperativeMatrixLoadStoreKHR(ValidationState_t& _,
2664
0
                                                   const Instruction* inst) {
2665
0
  uint32_t type_id;
2666
0
  const char* opname;
2667
0
  if (inst->opcode() == spv::Op::OpCooperativeMatrixLoadKHR) {
2668
0
    type_id = inst->type_id();
2669
0
    opname = "spv::Op::OpCooperativeMatrixLoadKHR";
2670
0
  } else {
2671
    // get Object operand's type
2672
0
    type_id = _.FindDef(inst->GetOperandAs<uint32_t>(1))->type_id();
2673
0
    opname = "spv::Op::OpCooperativeMatrixStoreKHR";
2674
0
  }
2675
2676
0
  auto matrix_type = _.FindDef(type_id);
2677
2678
0
  if (matrix_type->opcode() != spv::Op::OpTypeCooperativeMatrixKHR) {
2679
0
    if (inst->opcode() == spv::Op::OpCooperativeMatrixLoadKHR) {
2680
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
2681
0
             << "spv::Op::OpCooperativeMatrixLoadKHR Result Type <id> "
2682
0
             << _.getIdName(type_id) << " is not a cooperative matrix type.";
2683
0
    } else {
2684
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
2685
0
             << "spv::Op::OpCooperativeMatrixStoreKHR Object type <id> "
2686
0
             << _.getIdName(type_id) << " is not a cooperative matrix type.";
2687
0
    }
2688
0
  }
2689
2690
0
  const auto pointer_index =
2691
0
      (inst->opcode() == spv::Op::OpCooperativeMatrixLoadKHR) ? 2u : 0u;
2692
0
  const auto pointer_id = inst->GetOperandAs<uint32_t>(pointer_index);
2693
0
  const auto pointer = _.FindDef(pointer_id);
2694
0
  if (!pointer ||
2695
0
      ((_.addressing_model() == spv::AddressingModel::Logical) &&
2696
0
       ((!_.features().variable_pointers &&
2697
0
         !spvOpcodeReturnsLogicalPointer(pointer->opcode())) ||
2698
0
        (_.features().variable_pointers &&
2699
0
         !spvOpcodeReturnsLogicalVariablePointer(pointer->opcode()))))) {
2700
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
2701
0
           << opname << " Pointer <id> " << _.getIdName(pointer_id)
2702
0
           << " is not a logical pointer.";
2703
0
  }
2704
2705
0
  const auto pointer_type_id = pointer->type_id();
2706
0
  const auto pointer_type = _.FindDef(pointer_type_id);
2707
0
  if (!pointer_type ||
2708
0
      !(pointer_type->opcode() == spv::Op::OpTypePointer ||
2709
0
        pointer_type->opcode() == spv::Op::OpTypeUntypedPointerKHR)) {
2710
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
2711
0
           << opname << " type for pointer <id> " << _.getIdName(pointer_id)
2712
0
           << " is not a pointer type.";
2713
0
  }
2714
2715
0
  const bool untyped =
2716
0
      pointer_type->opcode() == spv::Op::OpTypeUntypedPointerKHR;
2717
0
  const auto storage_class_index = 1u;
2718
0
  const auto storage_class =
2719
0
      pointer_type->GetOperandAs<spv::StorageClass>(storage_class_index);
2720
2721
0
  if (spvIsVulkanEnv(_.context()->target_env)) {
2722
0
    if (storage_class != spv::StorageClass::Workgroup &&
2723
0
        storage_class != spv::StorageClass::StorageBuffer &&
2724
0
        storage_class != spv::StorageClass::PhysicalStorageBuffer) {
2725
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
2726
0
             << _.VkErrorID(8973) << opname
2727
0
             << " storage class for pointer type <id> "
2728
0
             << _.getIdName(pointer_type_id)
2729
0
             << " is not Workgroup, StorageBuffer, or PhysicalStorageBuffer.";
2730
0
    }
2731
0
  }
2732
2733
0
  if (!untyped) {
2734
0
    const auto pointee_id = pointer_type->GetOperandAs<uint32_t>(2);
2735
0
    const auto pointee_type = _.FindDef(pointee_id);
2736
0
    if (!pointee_type || !(_.IsIntScalarOrVectorType(pointee_id) ||
2737
0
                           _.IsFloatScalarOrVectorType(pointee_id))) {
2738
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
2739
0
             << opname << " Pointer <id> " << _.getIdName(pointer->id())
2740
0
             << "s Type must be a scalar or vector type.";
2741
0
    }
2742
0
  }
2743
2744
0
  const auto layout_index =
2745
0
      (inst->opcode() == spv::Op::OpCooperativeMatrixLoadKHR) ? 3u : 2u;
2746
0
  const auto layout_id = inst->GetOperandAs<uint32_t>(layout_index);
2747
0
  const auto layout_inst = _.FindDef(layout_id);
2748
0
  if (!layout_inst || !_.IsIntScalarType(layout_inst->type_id()) ||
2749
0
      !spvOpcodeIsConstant(layout_inst->opcode())) {
2750
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
2751
0
           << "MemoryLayout operand <id> " << _.getIdName(layout_id)
2752
0
           << " must be a 32-bit integer constant instruction.";
2753
0
  }
2754
2755
0
  bool stride_required = false;
2756
0
  bool layout_requires_constant_stride = false;
2757
0
  uint64_t layout;
2758
0
  if (_.EvalConstantValUint64(layout_id, &layout)) {
2759
0
    const bool is_arm_layout =
2760
0
        (layout ==
2761
0
         (uint64_t)spv::CooperativeMatrixLayout::RowBlockedInterleavedARM) ||
2762
0
        (layout ==
2763
0
         (uint64_t)spv::CooperativeMatrixLayout::ColumnBlockedInterleavedARM);
2764
2765
0
    if (is_arm_layout) {
2766
0
      if (!_.HasCapability(spv::Capability::CooperativeMatrixLayoutsARM)) {
2767
0
        return _.diag(SPV_ERROR_INVALID_ID, inst)
2768
0
               << "Using the RowBlockedInterleavedARM or "
2769
0
                  "ColumnBlockedInterleavedARM MemoryLayout requires the "
2770
0
                  "CooperativeMatrixLayoutsARM capability be declared";
2771
0
      }
2772
0
    }
2773
2774
0
    stride_required =
2775
0
        (layout == (uint64_t)spv::CooperativeMatrixLayout::RowMajorKHR) ||
2776
0
        (layout == (uint64_t)spv::CooperativeMatrixLayout::ColumnMajorKHR) ||
2777
0
        is_arm_layout;
2778
0
    layout_requires_constant_stride = is_arm_layout;
2779
0
  }
2780
2781
0
  const auto stride_index =
2782
0
      (inst->opcode() == spv::Op::OpCooperativeMatrixLoadKHR) ? 4u : 3u;
2783
0
  if (inst->operands().size() > stride_index) {
2784
0
    const auto stride_id = inst->GetOperandAs<uint32_t>(stride_index);
2785
0
    const auto stride_inst = _.FindDef(stride_id);
2786
0
    if (!stride_inst || !_.IsIntScalarType(stride_inst->type_id())) {
2787
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
2788
0
             << "Stride operand <id> " << _.getIdName(stride_id)
2789
0
             << " must be a scalar integer type.";
2790
0
    }
2791
    // Check SPV_ARM_cooperative_matrix_layouts constraints
2792
0
    if (layout_requires_constant_stride &&
2793
0
        !spvOpcodeIsConstant(stride_inst->opcode())) {
2794
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
2795
0
             << "MemoryLayout " << layout
2796
0
             << " requires Stride come from a constant instruction.";
2797
0
    }
2798
0
    if (layout_requires_constant_stride) {
2799
0
      uint64_t stride;
2800
0
      if (_.EvalConstantValUint64(stride_id, &stride)) {
2801
0
        if ((layout ==
2802
0
             (uint64_t)
2803
0
                 spv::CooperativeMatrixLayout::RowBlockedInterleavedARM) ||
2804
0
            (layout ==
2805
0
             (uint64_t)
2806
0
                 spv::CooperativeMatrixLayout::ColumnBlockedInterleavedARM)) {
2807
0
          if ((stride != 1) && (stride != 2) && (stride != 4)) {
2808
0
            return _.diag(SPV_ERROR_INVALID_ID, inst)
2809
0
                   << "MemoryLayout " << layout
2810
0
                   << " requires Stride be 1, 2, or 4.";
2811
0
          }
2812
0
        }
2813
0
        const uint32_t elty_id = matrix_type->GetOperandAs<uint32_t>(1);
2814
0
        const uint32_t rows_id = matrix_type->GetOperandAs<uint32_t>(3);
2815
0
        const uint32_t cols_id = matrix_type->GetOperandAs<uint32_t>(4);
2816
0
        uint64_t rows = 0, cols = 0;
2817
0
        _.EvalConstantValUint64(rows_id, &rows);
2818
0
        _.EvalConstantValUint64(cols_id, &cols);
2819
0
        uint32_t sizeof_component_in_bytes = _.GetBitWidth(elty_id) / 8;
2820
0
        uint64_t rows_required_multiple = 4;
2821
0
        uint64_t cols_required_multiple = 16 / sizeof_component_in_bytes;
2822
2823
0
        if (layout ==
2824
0
            (uint64_t)spv::CooperativeMatrixLayout::RowBlockedInterleavedARM) {
2825
0
          cols_required_multiple *= stride;
2826
0
        }
2827
0
        if (layout ==
2828
0
            (uint64_t)
2829
0
                spv::CooperativeMatrixLayout::ColumnBlockedInterleavedARM) {
2830
0
          rows_required_multiple *= stride;
2831
0
        }
2832
0
        if ((rows != 0) && (rows % rows_required_multiple != 0)) {
2833
0
          return _.diag(SPV_ERROR_INVALID_ID, inst)
2834
0
                 << "MemoryLayout " << layout << " with a Stride of " << stride
2835
0
                 << " requires that the number of rows be a multiple of "
2836
0
                 << rows_required_multiple;
2837
0
        }
2838
0
        if ((cols != 0) && (cols % cols_required_multiple != 0)) {
2839
0
          return _.diag(SPV_ERROR_INVALID_ID, inst)
2840
0
                 << "MemoryLayout " << layout << " with a Stride of " << stride
2841
0
                 << " requires that the number of columns be a multiple of "
2842
0
                 << cols_required_multiple;
2843
0
        }
2844
0
      }
2845
0
    }
2846
0
  } else if (stride_required) {
2847
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
2848
0
           << "MemoryLayout " << layout << " requires a Stride.";
2849
0
  }
2850
2851
0
  const auto memory_access_index =
2852
0
      (inst->opcode() == spv::Op::OpCooperativeMatrixLoadKHR) ? 5u : 4u;
2853
0
  if (inst->operands().size() > memory_access_index) {
2854
0
    if (auto error = CheckMemoryAccess(_, inst, memory_access_index))
2855
0
      return error;
2856
0
  }
2857
2858
0
  return SPV_SUCCESS;
2859
0
}
2860
2861
spv_result_t ValidateBufferPointerEXT(ValidationState_t& _,
2862
0
                                      const Instruction* inst) {
2863
0
  const auto storage_class_ptr = _.FindDef(inst->type_id());
2864
0
  if (storage_class_ptr->opcode() != spv::Op::OpTypeUntypedPointerKHR &&
2865
0
      storage_class_ptr->opcode() != spv::Op::OpTypePointer) {
2866
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
2867
0
           << "OpBufferPointerEXT's Result Type should be "
2868
0
           << "a pointer type.";
2869
0
  }
2870
2871
0
  auto sc = storage_class_ptr->GetOperandAs<spv::StorageClass>(1u);
2872
0
  if (sc != spv::StorageClass::StorageBuffer &&
2873
0
      sc != spv::StorageClass::Uniform) {
2874
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
2875
0
           << "OpBufferPointerEXT Result Type must be a pointer type "
2876
0
           << "with a Storage Class of Uniform or StorageBuffer.";
2877
0
  }
2878
2879
  // Buffer operand
2880
0
  auto buffer =
2881
0
      _.FindUntypedBaseVariable(_.FindDef(inst->GetOperandAs<uint32_t>(2)));
2882
0
  if (!buffer || !_.IsBuiltin(buffer->id(), spv::BuiltIn::ResourceHeapEXT)) {
2883
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
2884
0
           << "OpBufferPointerEXT's buffer must be an untyped pointer"
2885
0
           << " into a variable declared with the ResourceHeapEXT built-in";
2886
0
  }
2887
0
  return SPV_SUCCESS;
2888
0
}
2889
2890
// Returns the number of instruction words taken up by a tensor addressing
2891
// operands argument and its implied operands.
2892
0
int TensorAddressingOperandsNumWords(spv::TensorAddressingOperandsMask mask) {
2893
0
  int result = 1;  // Count the mask
2894
0
  if ((mask & spv::TensorAddressingOperandsMask::TensorView) !=
2895
0
      spv::TensorAddressingOperandsMask::MaskNone)
2896
0
    ++result;
2897
0
  if ((mask & spv::TensorAddressingOperandsMask::DecodeFunc) !=
2898
0
      spv::TensorAddressingOperandsMask::MaskNone)
2899
0
    ++result;
2900
0
  if ((mask & spv::TensorAddressingOperandsMask::DecodeVectorFunc) !=
2901
0
      spv::TensorAddressingOperandsMask::MaskNone)
2902
0
    ++result;
2903
0
  return result;
2904
0
}
2905
2906
spv_result_t ValidateCooperativeMatrixLoadStoreTensorNV(
2907
0
    ValidationState_t& _, const Instruction* inst) {
2908
0
  uint32_t type_id;
2909
0
  const char* opname;
2910
0
  if (inst->opcode() == spv::Op::OpCooperativeMatrixLoadTensorNV) {
2911
0
    type_id = inst->type_id();
2912
0
    opname = "spv::Op::OpCooperativeMatrixLoadTensorNV";
2913
0
  } else {
2914
    // get Object operand's type
2915
0
    type_id = _.FindDef(inst->GetOperandAs<uint32_t>(1))->type_id();
2916
0
    opname = "spv::Op::OpCooperativeMatrixStoreTensorNV";
2917
0
  }
2918
2919
0
  auto matrix_type = _.FindDef(type_id);
2920
2921
0
  if (matrix_type->opcode() != spv::Op::OpTypeCooperativeMatrixKHR) {
2922
0
    if (inst->opcode() == spv::Op::OpCooperativeMatrixLoadTensorNV) {
2923
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
2924
0
             << "spv::Op::OpCooperativeMatrixLoadTensorNV Result Type <id> "
2925
0
             << _.getIdName(type_id) << " is not a cooperative matrix type.";
2926
0
    } else {
2927
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
2928
0
             << "spv::Op::OpCooperativeMatrixStoreTensorNV Object type <id> "
2929
0
             << _.getIdName(type_id) << " is not a cooperative matrix type.";
2930
0
    }
2931
0
  }
2932
2933
0
  const auto pointer_index =
2934
0
      (inst->opcode() == spv::Op::OpCooperativeMatrixLoadTensorNV) ? 2u : 0u;
2935
0
  const auto pointer_id = inst->GetOperandAs<uint32_t>(pointer_index);
2936
0
  const auto pointer = _.FindDef(pointer_id);
2937
0
  if (!pointer ||
2938
0
      ((_.addressing_model() == spv::AddressingModel::Logical) &&
2939
0
       ((!_.features().variable_pointers &&
2940
0
         !spvOpcodeReturnsLogicalPointer(pointer->opcode())) ||
2941
0
        (_.features().variable_pointers &&
2942
0
         !spvOpcodeReturnsLogicalVariablePointer(pointer->opcode()))))) {
2943
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
2944
0
           << opname << " Pointer <id> " << _.getIdName(pointer_id)
2945
0
           << " is not a logical pointer.";
2946
0
  }
2947
2948
0
  const auto pointer_type_id = pointer->type_id();
2949
0
  const auto pointer_type = _.FindDef(pointer_type_id);
2950
0
  if (!pointer_type || pointer_type->opcode() != spv::Op::OpTypePointer) {
2951
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
2952
0
           << opname << " type for pointer <id> " << _.getIdName(pointer_id)
2953
0
           << " is not a pointer type.";
2954
0
  }
2955
2956
0
  const auto storage_class_index = 1u;
2957
0
  const auto storage_class =
2958
0
      pointer_type->GetOperandAs<spv::StorageClass>(storage_class_index);
2959
2960
0
  if (storage_class != spv::StorageClass::Workgroup &&
2961
0
      storage_class != spv::StorageClass::StorageBuffer &&
2962
0
      storage_class != spv::StorageClass::PhysicalStorageBuffer) {
2963
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
2964
0
           << _.VkErrorID(8973) << opname
2965
0
           << " storage class for pointer type <id> "
2966
0
           << _.getIdName(pointer_type_id)
2967
0
           << " is not Workgroup, StorageBuffer, or PhysicalStorageBuffer.";
2968
0
  }
2969
2970
0
  if (inst->opcode() == spv::Op::OpCooperativeMatrixLoadTensorNV) {
2971
0
    const auto object_index = 3;
2972
0
    const auto object_id = inst->GetOperandAs<uint32_t>(object_index);
2973
0
    const auto object = _.FindDef(object_id);
2974
0
    if (!object || object->type_id() != type_id) {
2975
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
2976
0
             << opname << " Object <id> " << _.getIdName(object_id)
2977
0
             << " type does not match Result Type.";
2978
0
    }
2979
0
  }
2980
2981
0
  const auto tensor_layout_index =
2982
0
      (inst->opcode() == spv::Op::OpCooperativeMatrixLoadTensorNV) ? 4u : 2u;
2983
0
  const auto tensor_layout_id =
2984
0
      inst->GetOperandAs<uint32_t>(tensor_layout_index);
2985
0
  const auto tensor_layout = _.FindDef(tensor_layout_id);
2986
0
  if (!tensor_layout || _.FindDef(tensor_layout->type_id())->opcode() !=
2987
0
                            spv::Op::OpTypeTensorLayoutNV) {
2988
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
2989
0
           << opname << " TensorLayout <id> " << _.getIdName(tensor_layout_id)
2990
0
           << " does not have a tensor layout type.";
2991
0
  }
2992
2993
0
  const auto memory_access_index =
2994
0
      (inst->opcode() == spv::Op::OpCooperativeMatrixLoadTensorNV) ? 5u : 3u;
2995
0
  if (inst->operands().size() > memory_access_index) {
2996
0
    if (auto error = CheckMemoryAccess(_, inst, memory_access_index))
2997
0
      return error;
2998
0
  }
2999
3000
0
  const auto memory_access_mask =
3001
0
      inst->GetOperandAs<uint32_t>(memory_access_index);
3002
0
  const auto tensor_operands_index =
3003
0
      memory_access_index + MemoryAccessNumWords(memory_access_mask);
3004
0
  const auto tensor_operands =
3005
0
      inst->GetOperandAs<spv::TensorAddressingOperandsMask>(
3006
0
          tensor_operands_index);
3007
3008
0
  if (inst->operands().size() <
3009
0
      tensor_operands_index +
3010
0
          TensorAddressingOperandsNumWords(tensor_operands)) {
3011
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
3012
0
           << opname << " not enough tensor addressing operands.";
3013
0
  }
3014
3015
0
  uint32_t tensor_operand_index = tensor_operands_index + 1;
3016
0
  if ((tensor_operands & spv::TensorAddressingOperandsMask::TensorView) !=
3017
0
      spv::TensorAddressingOperandsMask::MaskNone) {
3018
0
    const auto tensor_view_id =
3019
0
        inst->GetOperandAs<uint32_t>(tensor_operand_index);
3020
0
    const auto tensor_view = _.FindDef(tensor_view_id);
3021
0
    if (!tensor_view || _.FindDef(tensor_view->type_id())->opcode() !=
3022
0
                            spv::Op::OpTypeTensorViewNV) {
3023
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
3024
0
             << opname << " TensorView <id> " << _.getIdName(tensor_view_id)
3025
0
             << " does not have a tensor view type.";
3026
0
    }
3027
3028
0
    tensor_operand_index++;
3029
0
  }
3030
3031
0
  const bool has_decode_func =
3032
0
      (tensor_operands & spv::TensorAddressingOperandsMask::DecodeFunc) !=
3033
0
      spv::TensorAddressingOperandsMask::MaskNone;
3034
0
  const bool has_decode_vector_func =
3035
0
      (tensor_operands & spv::TensorAddressingOperandsMask::DecodeVectorFunc) !=
3036
0
      spv::TensorAddressingOperandsMask::MaskNone;
3037
3038
0
  if (has_decode_func || has_decode_vector_func) {
3039
0
    if (inst->opcode() == spv::Op::OpCooperativeMatrixStoreTensorNV) {
3040
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
3041
0
             << "OpCooperativeMatrixStoreTensorNV does not support DecodeFunc "
3042
0
                "or DecodeVectorFunc.";
3043
0
    }
3044
0
  }
3045
3046
0
  const auto component_type_index = 1;
3047
0
  const auto component_type_id =
3048
0
      matrix_type->GetOperandAs<uint32_t>(component_type_index);
3049
0
  const auto tensor_layout_type = _.FindDef(tensor_layout->type_id());
3050
3051
  // Validate one decode-function operand (scalar DecodeFunc or vector
3052
  // DecodeVectorFunc). `expect_vector` selects which return-type rule to
3053
  // enforce.
3054
0
  auto validate_decode_function = [&](uint32_t decode_func_id,
3055
0
                                      const char* operand_name,
3056
0
                                      bool expect_vector) -> spv_result_t {
3057
0
    const auto decode_func = _.FindDef(decode_func_id);
3058
3059
0
    if (!decode_func || decode_func->opcode() != spv::Op::OpFunction) {
3060
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
3061
0
             << opname << " " << operand_name << " <id> "
3062
0
             << _.getIdName(decode_func_id) << " is not a function.";
3063
0
    }
3064
3065
0
    const auto function_type =
3066
0
        _.FindDef(decode_func->GetOperandAs<uint32_t>(3));
3067
0
    const auto return_type_id = function_type->GetOperandAs<uint32_t>(1);
3068
0
    const auto return_type = _.FindDef(return_type_id);
3069
0
    const bool return_is_scalar_match = (return_type_id == component_type_id);
3070
0
    const bool return_is_vector = _.IsVectorType(return_type_id);
3071
0
    const uint32_t return_vec_component_type_id =
3072
0
        return_is_vector ? return_type->GetOperandAs<uint32_t>(1) : 0;
3073
3074
0
    if (!expect_vector) {
3075
0
      if (!return_is_scalar_match) {
3076
0
        return _.diag(SPV_ERROR_INVALID_ID, inst)
3077
0
               << opname << " " << operand_name << " <id> "
3078
0
               << _.getIdName(decode_func_id)
3079
0
               << " return type must match matrix component type.";
3080
0
      }
3081
0
    } else {
3082
0
      if (!return_is_vector ||
3083
0
          return_vec_component_type_id != component_type_id) {
3084
0
        return _.diag(SPV_ERROR_INVALID_ID, inst)
3085
0
               << opname << " " << operand_name << " <id> "
3086
0
               << _.getIdName(decode_func_id)
3087
0
               << " return type must be a vector of the matrix component "
3088
0
                  "type.";
3089
0
      }
3090
      // GetDimension returns 0 for OpTypeVectorIdEXT whose count is a
3091
      // spec constant; skip the static check in that case.
3092
0
      const uint32_t v = _.GetDimension(return_type_id);
3093
0
      if (v != 0 && v != 2 && v != 4 && v != 8) {
3094
0
        return _.diag(SPV_ERROR_INVALID_ID, inst)
3095
0
               << opname << " " << operand_name << " <id> "
3096
0
               << _.getIdName(decode_func_id)
3097
0
               << " return vector length must be 2, 4, or 8.";
3098
0
      }
3099
0
    }
3100
3101
0
    const auto decode_ptr_type_id = function_type->GetOperandAs<uint32_t>(2);
3102
0
    const auto decode_ptr_type = _.FindDef(decode_ptr_type_id);
3103
0
    auto decode_storage_class =
3104
0
        decode_ptr_type->GetOperandAs<spv::StorageClass>(storage_class_index);
3105
3106
0
    if (decode_storage_class != spv::StorageClass::PhysicalStorageBuffer) {
3107
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
3108
0
             << opname << " " << operand_name << " <id> "
3109
0
             << _.getIdName(decode_func_id)
3110
0
             << " first parameter must be pointer to PhysicalStorageBuffer.";
3111
0
    }
3112
3113
0
    for (uint32_t param = 3; param < 5; ++param) {
3114
0
      const auto param_type_id = function_type->GetOperandAs<uint32_t>(param);
3115
0
      const auto param_type = _.FindDef(param_type_id);
3116
0
      if (param_type->opcode() != spv::Op::OpTypeArray) {
3117
0
        return _.diag(SPV_ERROR_INVALID_ID, inst)
3118
0
               << opname << " " << operand_name << " <id> "
3119
0
               << _.getIdName(decode_func_id)
3120
0
               << " second/third parameter must be array of 32-bit integer "
3121
0
                  "with dimension equal to the tensor dimension.";
3122
0
      }
3123
0
      const auto length_index = 2u;
3124
0
      uint64_t array_length;
3125
0
      if (_.EvalConstantValUint64(
3126
0
              param_type->GetOperandAs<uint32_t>(length_index),
3127
0
              &array_length)) {
3128
0
        const auto tensor_layout_dim_id =
3129
0
            tensor_layout_type->GetOperandAs<uint32_t>(1);
3130
0
        uint64_t dim_value;
3131
0
        if (_.EvalConstantValUint64(tensor_layout_dim_id, &dim_value)) {
3132
0
          if (array_length != dim_value) {
3133
0
            return _.diag(SPV_ERROR_INVALID_ID, inst)
3134
0
                   << opname << " " << operand_name << " <id> "
3135
0
                   << _.getIdName(decode_func_id)
3136
0
                   << " second/third parameter must be array of 32-bit integer "
3137
0
                      "with dimension equal to the tensor dimension.";
3138
0
          }
3139
0
        }
3140
0
      }
3141
0
    }
3142
3143
0
    return SPV_SUCCESS;
3144
0
  };
3145
3146
0
  if (has_decode_func) {
3147
0
    const uint32_t decode_func_id =
3148
0
        inst->GetOperandAs<uint32_t>(tensor_operand_index);
3149
0
    if (auto error = validate_decode_function(decode_func_id, "DecodeFunc",
3150
0
                                              /*expect_vector=*/false)) {
3151
0
      return error;
3152
0
    }
3153
0
    tensor_operand_index++;
3154
0
  }
3155
3156
0
  if (has_decode_vector_func) {
3157
0
    if (!has_decode_func) {
3158
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
3159
0
             << opname
3160
0
             << " DecodeVectorFunc requires DecodeFunc to also be specified.";
3161
0
    }
3162
3163
0
    const uint32_t decode_vector_func_id =
3164
0
        inst->GetOperandAs<uint32_t>(tensor_operand_index);
3165
0
    if (auto error =
3166
0
            validate_decode_function(decode_vector_func_id, "DecodeVectorFunc",
3167
0
                                     /*expect_vector=*/true)) {
3168
0
      return error;
3169
0
    }
3170
3171
0
    tensor_operand_index++;
3172
0
  }
3173
3174
0
  return SPV_SUCCESS;
3175
0
}
3176
3177
spv_result_t ValidateInt32Operand(ValidationState_t& _, const Instruction* inst,
3178
                                  uint32_t operand_index,
3179
                                  const char* opcode_name,
3180
0
                                  const char* operand_name) {
3181
0
  const auto type_id =
3182
0
      _.FindDef(inst->GetOperandAs<uint32_t>(operand_index))->type_id();
3183
0
  if (!_.IsIntScalarType(type_id, 32)) {
3184
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
3185
0
           << opcode_name << " " << operand_name << " type <id> "
3186
0
           << _.getIdName(type_id) << " is not a 32 bit integer.";
3187
0
  }
3188
0
  return SPV_SUCCESS;
3189
0
}
3190
3191
spv_result_t ValidateInt32Or64Operand(ValidationState_t& _,
3192
                                      const Instruction* inst,
3193
                                      uint32_t operand_index,
3194
                                      const char* opcode_name,
3195
0
                                      const char* operand_name) {
3196
0
  const auto type_id =
3197
0
      _.FindDef(inst->GetOperandAs<uint32_t>(operand_index))->type_id();
3198
0
  if (!_.IsIntScalarType(type_id) ||
3199
0
      !(_.GetBitWidth(type_id) == 32 || _.GetBitWidth(type_id) == 64)) {
3200
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
3201
0
           << opcode_name << " " << operand_name << " type <id> "
3202
0
           << _.getIdName(type_id) << " is not a 32 or 64 bit integer.";
3203
0
  }
3204
3205
0
  return SPV_SUCCESS;
3206
0
}
3207
3208
spv_result_t ValidateCooperativeVectorPointer(ValidationState_t& _,
3209
                                              const Instruction* inst,
3210
                                              const char* opname,
3211
0
                                              uint32_t pointer_index) {
3212
0
  const auto pointer_id = inst->GetOperandAs<uint32_t>(pointer_index);
3213
0
  const auto pointer = _.FindDef(pointer_id);
3214
0
  if (!pointer ||
3215
0
      ((_.addressing_model() == spv::AddressingModel::Logical) &&
3216
0
       ((!_.features().variable_pointers &&
3217
0
         !spvOpcodeReturnsLogicalPointer(pointer->opcode())) ||
3218
0
        (_.features().variable_pointers &&
3219
0
         !spvOpcodeReturnsLogicalVariablePointer(pointer->opcode()))))) {
3220
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
3221
0
           << opname << " Pointer <id> " << _.getIdName(pointer_id)
3222
0
           << " is not a logical pointer.";
3223
0
  }
3224
3225
0
  const auto pointer_type_id = pointer->type_id();
3226
0
  const auto pointer_type = _.FindDef(pointer_type_id);
3227
0
  if (!pointer_type || pointer_type->opcode() != spv::Op::OpTypePointer) {
3228
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
3229
0
           << opname << " type for pointer <id> " << _.getIdName(pointer_id)
3230
0
           << " is not a pointer type.";
3231
0
  }
3232
3233
0
  const auto storage_class_index = 1u;
3234
0
  const auto storage_class =
3235
0
      pointer_type->GetOperandAs<spv::StorageClass>(storage_class_index);
3236
3237
0
  if (storage_class != spv::StorageClass::Workgroup &&
3238
0
      storage_class != spv::StorageClass::StorageBuffer &&
3239
0
      storage_class != spv::StorageClass::PhysicalStorageBuffer) {
3240
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
3241
0
           << opname << " storage class for pointer type <id> "
3242
0
           << _.getIdName(pointer_type_id)
3243
0
           << " is not Workgroup or StorageBuffer.";
3244
0
  }
3245
3246
0
  const auto pointee_id = pointer_type->GetOperandAs<uint32_t>(2);
3247
0
  const auto pointee_type = _.FindDef(pointee_id);
3248
0
  if (!pointee_type ||
3249
0
      (pointee_type->opcode() != spv::Op::OpTypeArray &&
3250
0
       pointee_type->opcode() != spv::Op::OpTypeRuntimeArray)) {
3251
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
3252
0
           << opname << " Pointer <id> " << _.getIdName(pointer->id())
3253
0
           << "s Type must be an array type.";
3254
0
  }
3255
3256
0
  const auto array_elem_type_id = pointee_type->GetOperandAs<uint32_t>(1);
3257
0
  auto array_elem_type = _.FindDef(array_elem_type_id);
3258
0
  if (!array_elem_type || !(_.IsIntScalarOrVectorType(array_elem_type_id) ||
3259
0
                            _.IsFloatScalarOrVectorType(array_elem_type_id))) {
3260
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
3261
0
           << opname << " Pointer <id> " << _.getIdName(pointer->id())
3262
0
           << "s Type must be an array of scalar or vector type.";
3263
0
  }
3264
3265
0
  return SPV_SUCCESS;
3266
0
}
3267
3268
spv_result_t ValidateCooperativeVectorLoadStoreNV(ValidationState_t& _,
3269
0
                                                  const Instruction* inst) {
3270
0
  uint32_t type_id;
3271
0
  const char* opname;
3272
0
  if (inst->opcode() == spv::Op::OpCooperativeVectorLoadNV) {
3273
0
    type_id = inst->type_id();
3274
0
    opname = "spv::Op::OpCooperativeVectorLoadNV";
3275
0
  } else {
3276
    // get Object operand's type
3277
0
    type_id = _.FindDef(inst->GetOperandAs<uint32_t>(2))->type_id();
3278
0
    opname = "spv::Op::OpCooperativeVectorStoreNV";
3279
0
  }
3280
3281
0
  auto vector_type = _.FindDef(type_id);
3282
3283
0
  if (vector_type->opcode() != spv::Op::OpTypeVectorIdEXT) {
3284
0
    if (inst->opcode() == spv::Op::OpCooperativeVectorLoadNV) {
3285
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
3286
0
             << "spv::Op::OpCooperativeVectorLoadNV Result Type <id> "
3287
0
             << _.getIdName(type_id) << " is not a cooperative vector type.";
3288
0
    } else {
3289
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
3290
0
             << "spv::Op::OpCooperativeVectorStoreNV Object type <id> "
3291
0
             << _.getIdName(type_id) << " is not a cooperative vector type.";
3292
0
    }
3293
0
  }
3294
3295
0
  const auto pointer_index =
3296
0
      (inst->opcode() == spv::Op::OpCooperativeVectorLoadNV) ? 2u : 0u;
3297
3298
0
  const auto offset_index =
3299
0
      (inst->opcode() == spv::Op::OpCooperativeVectorLoadNV) ? 3u : 1u;
3300
3301
0
  if (auto error =
3302
0
          ValidateCooperativeVectorPointer(_, inst, opname, pointer_index)) {
3303
0
    return error;
3304
0
  }
3305
3306
0
  if (auto error =
3307
0
          ValidateInt32Or64Operand(_, inst, offset_index, opname, "Offset")) {
3308
0
    return error;
3309
0
  }
3310
3311
0
  const auto memory_access_index =
3312
0
      (inst->opcode() == spv::Op::OpCooperativeVectorLoadNV) ? 4u : 3u;
3313
0
  if (inst->operands().size() > memory_access_index) {
3314
0
    if (auto error = CheckMemoryAccess(_, inst, memory_access_index))
3315
0
      return error;
3316
0
  }
3317
3318
0
  return SPV_SUCCESS;
3319
0
}
3320
3321
spv_result_t ValidateCooperativeVectorOuterProductNV(ValidationState_t& _,
3322
0
                                                     const Instruction* inst) {
3323
0
  const auto pointer_index = 0u;
3324
0
  const auto opcode_name =
3325
0
      "spv::Op::OpCooperativeVectorOuterProductAccumulateNV";
3326
3327
0
  if (auto error = ValidateCooperativeVectorPointer(_, inst, opcode_name,
3328
0
                                                    pointer_index)) {
3329
0
    return error;
3330
0
  }
3331
3332
0
  auto type_id = _.FindDef(inst->GetOperandAs<uint32_t>(2))->type_id();
3333
0
  auto a_type = _.FindDef(type_id);
3334
3335
0
  if (a_type->opcode() != spv::Op::OpTypeVectorIdEXT) {
3336
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
3337
0
           << opcode_name << " A type <id> " << _.getIdName(type_id)
3338
0
           << " is not a cooperative vector type.";
3339
0
  }
3340
3341
0
  type_id = _.FindDef(inst->GetOperandAs<uint32_t>(3))->type_id();
3342
0
  auto b_type = _.FindDef(type_id);
3343
3344
0
  if (b_type->opcode() != spv::Op::OpTypeVectorIdEXT) {
3345
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
3346
0
           << opcode_name << " B type <id> " << _.getIdName(type_id)
3347
0
           << " is not a cooperative vector type.";
3348
0
  }
3349
3350
0
  const auto a_component_type_id = a_type->GetOperandAs<uint32_t>(1);
3351
0
  const auto b_component_type_id = b_type->GetOperandAs<uint32_t>(1);
3352
3353
0
  if (a_component_type_id != b_component_type_id) {
3354
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
3355
0
           << opcode_name << " A and B component types "
3356
0
           << _.getIdName(a_component_type_id) << " and "
3357
0
           << _.getIdName(b_component_type_id) << " do not match.";
3358
0
  }
3359
3360
0
  if (auto error =
3361
0
          ValidateInt32Or64Operand(_, inst, 1, opcode_name, "Offset")) {
3362
0
    return error;
3363
0
  }
3364
3365
0
  if (auto error =
3366
0
          ValidateInt32Operand(_, inst, 4, opcode_name, "MemoryLayout")) {
3367
0
    return error;
3368
0
  }
3369
3370
0
  if (auto error = ValidateInt32Operand(_, inst, 5, opcode_name,
3371
0
                                        "MatrixInterpretation")) {
3372
0
    return error;
3373
0
  }
3374
3375
0
  if (inst->operands().size() > 6) {
3376
0
    if (auto error =
3377
0
            ValidateInt32Operand(_, inst, 6, opcode_name, "MatrixStride")) {
3378
0
      return error;
3379
0
    }
3380
0
  }
3381
3382
0
  return SPV_SUCCESS;
3383
0
}
3384
3385
spv_result_t ValidateCooperativeVectorReduceSumNV(ValidationState_t& _,
3386
0
                                                  const Instruction* inst) {
3387
0
  const auto opcode_name = "spv::Op::OpCooperativeVectorReduceSumAccumulateNV";
3388
0
  const auto pointer_index = 0u;
3389
3390
0
  if (auto error = ValidateCooperativeVectorPointer(_, inst, opcode_name,
3391
0
                                                    pointer_index)) {
3392
0
    return error;
3393
0
  }
3394
3395
0
  auto type_id = _.FindDef(inst->GetOperandAs<uint32_t>(2))->type_id();
3396
0
  auto v_type = _.FindDef(type_id);
3397
3398
0
  if (v_type->opcode() != spv::Op::OpTypeVectorIdEXT) {
3399
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
3400
0
           << opcode_name << " V type <id> " << _.getIdName(type_id)
3401
0
           << " is not a cooperative vector type.";
3402
0
  }
3403
3404
0
  if (auto error =
3405
0
          ValidateInt32Or64Operand(_, inst, 1, opcode_name, "Offset")) {
3406
0
    return error;
3407
0
  }
3408
3409
0
  return SPV_SUCCESS;
3410
0
}
3411
3412
0
bool InterpretationIsPacked(spv::ComponentType interp) {
3413
0
  switch (interp) {
3414
0
    case spv::ComponentType::SignedInt8PackedNV:
3415
0
    case spv::ComponentType::UnsignedInt8PackedNV:
3416
0
      return true;
3417
0
    default:
3418
0
      return false;
3419
0
  }
3420
0
}
3421
3422
using std::get;
3423
3424
spv_result_t ValidateCooperativeVectorMatrixMulNV(ValidationState_t& _,
3425
0
                                                  const Instruction* inst) {
3426
0
  const bool has_bias =
3427
0
      inst->opcode() == spv::Op::OpCooperativeVectorMatrixMulAddNV;
3428
0
  const auto opcode_name = has_bias
3429
0
                               ? "spv::Op::OpCooperativeVectorMatrixMulAddNV"
3430
0
                               : "spv::Op::OpCooperativeVectorMatrixMulNV";
3431
3432
0
  const auto bias_offset = has_bias ? 3 : 0;
3433
3434
0
  const auto result_type_index = 0u;
3435
0
  const auto input_index = 2u;
3436
0
  const auto input_interpretation_index = 3u;
3437
0
  const auto matrix_index = 4u;
3438
0
  const auto matrix_offset_index = 5u;
3439
0
  const auto matrix_interpretation_index = 6u;
3440
0
  const auto bias_index = 7u;
3441
0
  const auto bias_offset_index = 8u;
3442
0
  const auto bias_interpretation_index = 9u;
3443
0
  const auto m_index = 7u + bias_offset;
3444
0
  const auto k_index = 8u + bias_offset;
3445
0
  const auto memory_layout_index = 9u + bias_offset;
3446
0
  const auto transpose_index = 10u + bias_offset;
3447
3448
0
  const auto result_type_id = inst->GetOperandAs<uint32_t>(result_type_index);
3449
0
  const auto input_id = inst->GetOperandAs<uint32_t>(input_index);
3450
0
  const auto input_interpretation_id =
3451
0
      inst->GetOperandAs<uint32_t>(input_interpretation_index);
3452
0
  const auto matrix_interpretation_id =
3453
0
      inst->GetOperandAs<uint32_t>(matrix_interpretation_index);
3454
0
  const auto bias_interpretation_id =
3455
0
      inst->GetOperandAs<uint32_t>(bias_interpretation_index);
3456
0
  const auto m_id = inst->GetOperandAs<uint32_t>(m_index);
3457
0
  const auto k_id = inst->GetOperandAs<uint32_t>(k_index);
3458
0
  const auto memory_layout_id =
3459
0
      inst->GetOperandAs<uint32_t>(memory_layout_index);
3460
0
  const auto transpose_id = inst->GetOperandAs<uint32_t>(transpose_index);
3461
3462
0
  if (auto error = ValidateCooperativeVectorPointer(_, inst, opcode_name,
3463
0
                                                    matrix_index)) {
3464
0
    return error;
3465
0
  }
3466
3467
0
  if (inst->opcode() == spv::Op::OpCooperativeVectorMatrixMulAddNV) {
3468
0
    if (auto error = ValidateCooperativeVectorPointer(_, inst, opcode_name,
3469
0
                                                      bias_index)) {
3470
0
      return error;
3471
0
    }
3472
0
  }
3473
3474
0
  const auto result_type = _.FindDef(result_type_id);
3475
3476
0
  if (result_type->opcode() != spv::Op::OpTypeVectorIdEXT) {
3477
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
3478
0
           << opcode_name << " result type <id> " << _.getIdName(result_type_id)
3479
0
           << " is not a cooperative vector type.";
3480
0
  }
3481
3482
0
  const auto result_component_type_id = result_type->GetOperandAs<uint32_t>(1u);
3483
0
  if (!_.IsIntScalarType(result_component_type_id, 32) &&
3484
0
      !_.IsFloatScalarType(result_component_type_id, 32) &&
3485
0
      !_.IsFloatScalarType(result_component_type_id, 16)) {
3486
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
3487
0
           << opcode_name << " result component type <id> "
3488
0
           << _.getIdName(result_component_type_id)
3489
0
           << " is not a 32 bit int or 16/32 bit float.";
3490
0
  }
3491
3492
0
  const auto m_eval = _.EvalInt32IfConst(m_id);
3493
0
  const auto rc_eval =
3494
0
      _.EvalInt32IfConst(result_type->GetOperandAs<uint32_t>(2u));
3495
0
  if (get<1>(m_eval) && get<1>(rc_eval) && get<2>(m_eval) != get<2>(rc_eval)) {
3496
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
3497
0
           << opcode_name << " result type number of components "
3498
0
           << get<2>(rc_eval) << " does not match M " << get<2>(m_eval);
3499
0
  }
3500
3501
0
  const auto k_eval = _.EvalInt32IfConst(k_id);
3502
3503
0
  const auto input = _.FindDef(input_id);
3504
0
  const auto input_type = _.FindDef(input->type_id());
3505
0
  const auto input_num_components_id = input_type->GetOperandAs<uint32_t>(2u);
3506
3507
0
  auto input_interp_eval = _.EvalInt32IfConst(input_interpretation_id);
3508
0
  if (get<1>(input_interp_eval) &&
3509
0
      !InterpretationIsPacked(spv::ComponentType{get<2>(input_interp_eval)})) {
3510
0
    const auto inc_eval = _.EvalInt32IfConst(input_num_components_id);
3511
0
    if (get<1>(inc_eval) && get<1>(k_eval) &&
3512
0
        get<2>(inc_eval) != get<2>(k_eval)) {
3513
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
3514
0
             << opcode_name << " input number of components "
3515
0
             << get<2>(inc_eval) << " does not match K " << get<2>(k_eval);
3516
0
    }
3517
0
  }
3518
3519
0
  if (!_.IsBoolScalarType(_.FindDef(transpose_id)->type_id())) {
3520
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
3521
0
           << opcode_name << " Transpose <id> " << _.getIdName(transpose_id)
3522
0
           << " is not a scalar boolean.";
3523
0
  }
3524
3525
0
  const auto check_constant = [&](uint32_t id,
3526
0
                                  const char* operand_name) -> spv_result_t {
3527
0
    if (!spvOpcodeIsConstant(_.GetIdOpcode(id))) {
3528
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
3529
0
             << opcode_name << " " << operand_name << " <id> "
3530
0
             << _.getIdName(id) << " is not a constant instruction.";
3531
0
    }
3532
0
    return SPV_SUCCESS;
3533
0
  };
3534
3535
0
  if (auto error =
3536
0
          check_constant(input_interpretation_id, "InputInterpretation")) {
3537
0
    return error;
3538
0
  }
3539
0
  if (auto error =
3540
0
          check_constant(matrix_interpretation_id, "MatrixInterpretation")) {
3541
0
    return error;
3542
0
  }
3543
0
  if (has_bias) {
3544
0
    if (auto error =
3545
0
            check_constant(bias_interpretation_id, "BiasInterpretation")) {
3546
0
      return error;
3547
0
    }
3548
0
  }
3549
0
  if (auto error = check_constant(m_id, "M")) {
3550
0
    return error;
3551
0
  }
3552
0
  if (auto error = check_constant(k_id, "K")) {
3553
0
    return error;
3554
0
  }
3555
0
  if (auto error = check_constant(memory_layout_id, "MemoryLayout")) {
3556
0
    return error;
3557
0
  }
3558
0
  if (auto error = check_constant(transpose_id, "Transpose")) {
3559
0
    return error;
3560
0
  }
3561
3562
0
  if (auto error = ValidateInt32Operand(_, inst, input_interpretation_index,
3563
0
                                        opcode_name, "InputInterpretation")) {
3564
0
    return error;
3565
0
  }
3566
0
  if (auto error = ValidateInt32Operand(_, inst, matrix_interpretation_index,
3567
0
                                        opcode_name, "MatrixInterpretation")) {
3568
0
    return error;
3569
0
  }
3570
0
  if (has_bias) {
3571
0
    if (auto error = ValidateInt32Operand(_, inst, bias_interpretation_index,
3572
0
                                          opcode_name, "BiasInterpretation")) {
3573
0
      return error;
3574
0
    }
3575
0
  }
3576
0
  if (auto error = ValidateInt32Operand(_, inst, m_index, opcode_name, "M")) {
3577
0
    return error;
3578
0
  }
3579
0
  if (auto error = ValidateInt32Operand(_, inst, k_index, opcode_name, "K")) {
3580
0
    return error;
3581
0
  }
3582
0
  if (auto error = ValidateInt32Operand(_, inst, memory_layout_index,
3583
0
                                        opcode_name, "MemoryLayout")) {
3584
0
    return error;
3585
0
  }
3586
3587
0
  if (auto error = ValidateInt32Or64Operand(_, inst, matrix_offset_index,
3588
0
                                            opcode_name, "MatrixOffset")) {
3589
0
    return error;
3590
0
  }
3591
0
  if (has_bias) {
3592
0
    if (auto error = ValidateInt32Or64Operand(_, inst, bias_offset_index,
3593
0
                                              opcode_name, "BiasOffset")) {
3594
0
      return error;
3595
0
    }
3596
0
  }
3597
3598
0
  return SPV_SUCCESS;
3599
0
}
3600
3601
spv_result_t ValidatePtrComparison(ValidationState_t& _,
3602
2
                                   const Instruction* inst) {
3603
2
  const auto op1 = _.FindDef(inst->GetOperandAs<uint32_t>(2u));
3604
2
  const auto op2 = _.FindDef(inst->GetOperandAs<uint32_t>(3u));
3605
2
  const auto op1_type = _.FindDef(op1->type_id());
3606
2
  const auto op2_type = _.FindDef(op2->type_id());
3607
2
  spv::StorageClass sc = op1_type->GetOperandAs<spv::StorageClass>(1u);
3608
2
  if ((_.addressing_model() == spv::AddressingModel::Logical ||
3609
1
       _.addressing_model() == spv::AddressingModel::PhysicalStorageBuffer64) &&
3610
1
      sc != spv::StorageClass::PhysicalStorageBuffer &&
3611
1
      !_.features().variable_pointers) {
3612
1
    return _.diag(SPV_ERROR_INVALID_ID, inst)
3613
1
           << "Instruction on logical pointers cannot be used without "
3614
1
              "a variable pointers capability";
3615
1
  }
3616
3617
1
  const auto result_type = _.FindDef(inst->type_id());
3618
1
  if (inst->opcode() == spv::Op::OpPtrDiff) {
3619
1
    if (!result_type || result_type->opcode() != spv::Op::OpTypeInt) {
3620
1
      return _.diag(SPV_ERROR_INVALID_ID, inst)
3621
1
             << "Result Type must be an integer scalar";
3622
1
    }
3623
1
  } else {
3624
0
    if (!result_type || result_type->opcode() != spv::Op::OpTypeBool) {
3625
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
3626
0
             << "Result Type must be OpTypeBool";
3627
0
    }
3628
0
  }
3629
3630
0
  if (!op1_type || (op1_type->opcode() != spv::Op::OpTypePointer &&
3631
0
                    op1_type->opcode() != spv::Op::OpTypeUntypedPointerKHR)) {
3632
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
3633
0
           << "Operand type must be a pointer";
3634
0
  }
3635
3636
0
  if (!op2_type || (op2_type->opcode() != spv::Op::OpTypePointer &&
3637
0
                    op2_type->opcode() != spv::Op::OpTypeUntypedPointerKHR)) {
3638
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
3639
0
           << "Operand type must be a pointer";
3640
0
  }
3641
3642
0
  if (inst->opcode() == spv::Op::OpPtrDiff) {
3643
0
    if (op1->type_id() != op2->type_id()) {
3644
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
3645
0
             << "The types of Operand 1 and Operand 2 must match";
3646
0
    }
3647
0
  } else {
3648
0
    const auto either_untyped =
3649
0
        op1_type->opcode() == spv::Op::OpTypeUntypedPointerKHR ||
3650
0
        op2_type->opcode() == spv::Op::OpTypeUntypedPointerKHR;
3651
0
    if (either_untyped) {
3652
0
      const auto sc1 = op1_type->GetOperandAs<spv::StorageClass>(1);
3653
0
      const auto sc2 = op2_type->GetOperandAs<spv::StorageClass>(1);
3654
0
      if (sc1 != sc2) {
3655
0
        return _.diag(SPV_ERROR_INVALID_ID, inst)
3656
0
               << "Pointer storage classes must match";
3657
0
      }
3658
0
    } else if (op1->type_id() != op2->type_id()) {
3659
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
3660
0
             << "The types of Operand 1 and Operand 2 must match";
3661
0
    }
3662
0
  }
3663
3664
0
  if (_.addressing_model() == spv::AddressingModel::Logical) {
3665
0
    if (sc != spv::StorageClass::Workgroup &&
3666
0
        sc != spv::StorageClass::StorageBuffer) {
3667
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
3668
0
             << "Invalid pointer storage class";
3669
0
    }
3670
3671
0
    if (sc == spv::StorageClass::Workgroup &&
3672
0
        !_.HasCapability(spv::Capability::VariablePointers)) {
3673
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
3674
0
             << "Workgroup storage class pointer requires VariablePointers "
3675
0
                "capability to be specified";
3676
0
    }
3677
0
  } else if (sc == spv::StorageClass::PhysicalStorageBuffer) {
3678
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
3679
0
           << "Cannot use a pointer in the PhysicalStorageBuffer storage class";
3680
0
  }
3681
3682
0
  return SPV_SUCCESS;
3683
0
}
3684
3685
spv_result_t ValidatePredicatedLoadINTEL(ValidationState_t& _,
3686
0
                                         const Instruction* inst) {
3687
0
  const auto result_type_id = inst->type_id();
3688
0
  if (!_.IsIntScalarOrVectorType(result_type_id) &&
3689
0
      !_.IsFloatScalarOrVectorType(result_type_id)) {
3690
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
3691
0
           << "OpPredicatedLoadINTEL Result Type <id> "
3692
0
           << _.getIdName(result_type_id)
3693
0
           << " must be a scalar or vector of numerical type.";
3694
0
  }
3695
3696
0
  const auto pointer_id = inst->GetOperandAs<uint32_t>(2);
3697
0
  const auto pointer = _.FindDef(pointer_id);
3698
0
  if (!pointer ||
3699
0
      ((_.addressing_model() == spv::AddressingModel::Logical) &&
3700
0
       ((!_.features().variable_pointers &&
3701
0
         !spvOpcodeReturnsLogicalPointer(pointer->opcode())) ||
3702
0
        (_.features().variable_pointers &&
3703
0
         !spvOpcodeReturnsLogicalVariablePointer(pointer->opcode()))))) {
3704
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
3705
0
           << "OpPredicatedLoadINTEL Pointer <id> " << _.getIdName(pointer_id)
3706
0
           << " is not a logical pointer.";
3707
0
  }
3708
3709
0
  const auto pointer_type = _.FindDef(pointer->type_id());
3710
0
  if (!pointer_type ||
3711
0
      (pointer_type->opcode() != spv::Op::OpTypePointer &&
3712
0
       pointer_type->opcode() != spv::Op::OpTypeUntypedPointerKHR)) {
3713
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
3714
0
           << "OpPredicatedLoadINTEL type for pointer <id> "
3715
0
           << _.getIdName(pointer_id) << " is not a pointer type.";
3716
0
  }
3717
3718
0
  if (pointer_type->opcode() == spv::Op::OpTypePointer) {
3719
0
    const auto pointee_type =
3720
0
        _.FindDef(pointer_type->GetOperandAs<uint32_t>(2));
3721
0
    if (!pointee_type || result_type_id != pointee_type->id()) {
3722
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
3723
0
             << "OpPredicatedLoadINTEL Result Type <id> "
3724
0
             << _.getIdName(result_type_id) << " does not match Pointer <id> "
3725
0
             << _.getIdName(pointer->id()) << "s type.";
3726
0
    }
3727
0
  }
3728
3729
0
  const auto predicate_id = inst->GetOperandAs<uint32_t>(3);
3730
0
  const auto predicate = _.FindDef(predicate_id);
3731
0
  if (!predicate || !_.IsBoolScalarType(predicate->type_id())) {
3732
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
3733
0
           << "OpPredicatedLoadINTEL Predicate <id> "
3734
0
           << _.getIdName(predicate_id) << " must be a Boolean scalar.";
3735
0
  }
3736
3737
0
  const auto default_value_id = inst->GetOperandAs<uint32_t>(4);
3738
0
  const auto default_value = _.FindDef(default_value_id);
3739
0
  if (!default_value || default_value->type_id() != result_type_id) {
3740
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
3741
0
           << "OpPredicatedLoadINTEL Default Value <id> "
3742
0
           << _.getIdName(default_value_id)
3743
0
           << " type does not match Result Type.";
3744
0
  }
3745
3746
0
  if (inst->operands().size() > 5) {
3747
0
    const auto mask = inst->GetOperandAs<uint32_t>(5);
3748
0
    if (mask & uint32_t(spv::MemoryAccessMask::Volatile)) {
3749
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
3750
0
             << "OpPredicatedLoadINTEL does not allow the Volatile memory "
3751
0
                "operand.";
3752
0
    }
3753
0
  }
3754
3755
0
  if (auto error = CheckMemoryAccess(_, inst, 5)) return error;
3756
3757
0
  return SPV_SUCCESS;
3758
0
}
3759
3760
spv_result_t ValidatePredicatedStoreINTEL(ValidationState_t& _,
3761
0
                                          const Instruction* inst) {
3762
0
  const auto pointer_id = inst->GetOperandAs<uint32_t>(0);
3763
0
  const auto pointer = _.FindDef(pointer_id);
3764
0
  if (!pointer ||
3765
0
      (_.addressing_model() == spv::AddressingModel::Logical &&
3766
0
       ((!_.features().variable_pointers &&
3767
0
         !spvOpcodeReturnsLogicalPointer(pointer->opcode())) ||
3768
0
        (_.features().variable_pointers &&
3769
0
         !spvOpcodeReturnsLogicalVariablePointer(pointer->opcode()))))) {
3770
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
3771
0
           << "OpPredicatedStoreINTEL Pointer <id> " << _.getIdName(pointer_id)
3772
0
           << " is not a logical pointer.";
3773
0
  }
3774
3775
0
  const auto pointer_type = _.FindDef(pointer->type_id());
3776
0
  if (!pointer_type ||
3777
0
      (pointer_type->opcode() != spv::Op::OpTypePointer &&
3778
0
       pointer_type->opcode() != spv::Op::OpTypeUntypedPointerKHR)) {
3779
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
3780
0
           << "OpPredicatedStoreINTEL type for pointer <id> "
3781
0
           << _.getIdName(pointer_id) << " is not a pointer type.";
3782
0
  }
3783
3784
0
  const auto object_id = inst->GetOperandAs<uint32_t>(1);
3785
0
  const auto object = _.FindDef(object_id);
3786
0
  if (!object || !object->type_id()) {
3787
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
3788
0
           << "OpPredicatedStoreINTEL Object <id> " << _.getIdName(object_id)
3789
0
           << " is not an object.";
3790
0
  }
3791
3792
0
  const auto object_type_id = object->type_id();
3793
0
  if (!_.IsIntScalarOrVectorType(object_type_id) &&
3794
0
      !_.IsFloatScalarOrVectorType(object_type_id)) {
3795
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
3796
0
           << "OpPredicatedStoreINTEL Object <id> " << _.getIdName(object_id)
3797
0
           << " type must be a scalar or vector of numerical type.";
3798
0
  }
3799
3800
0
  if (pointer_type->opcode() == spv::Op::OpTypePointer) {
3801
0
    const auto pointee_type =
3802
0
        _.FindDef(pointer_type->GetOperandAs<uint32_t>(2));
3803
0
    if (!pointee_type || pointee_type->id() != object_type_id) {
3804
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
3805
0
             << "OpPredicatedStoreINTEL Pointer <id> "
3806
0
             << _.getIdName(pointer_id) << "s type does not match Object <id> "
3807
0
             << _.getIdName(object->id()) << "s type.";
3808
0
    }
3809
0
  }
3810
3811
0
  const auto predicate_id = inst->GetOperandAs<uint32_t>(2);
3812
0
  const auto predicate = _.FindDef(predicate_id);
3813
0
  if (!predicate || !_.IsBoolScalarType(predicate->type_id())) {
3814
0
    return _.diag(SPV_ERROR_INVALID_ID, inst)
3815
0
           << "OpPredicatedStoreINTEL Predicate <id> "
3816
0
           << _.getIdName(predicate_id) << " must be a Boolean scalar.";
3817
0
  }
3818
3819
0
  if (inst->operands().size() > 3) {
3820
0
    const auto mask = inst->GetOperandAs<uint32_t>(3);
3821
0
    if (mask & uint32_t(spv::MemoryAccessMask::Volatile)) {
3822
0
      return _.diag(SPV_ERROR_INVALID_ID, inst)
3823
0
             << "OpPredicatedStoreINTEL does not allow the Volatile memory "
3824
0
                "operand.";
3825
0
    }
3826
0
  }
3827
3828
0
  if (auto error = CheckMemoryAccess(_, inst, 3)) return error;
3829
3830
0
  return SPV_SUCCESS;
3831
0
}
3832
3833
}  // namespace
3834
3835
14.3M
spv_result_t MemoryPass(ValidationState_t& _, const Instruction* inst) {
3836
14.3M
  switch (inst->opcode()) {
3837
203k
    case spv::Op::OpVariable:
3838
203k
    case spv::Op::OpUntypedVariableKHR:
3839
203k
      return ValidateVariable(_, inst);
3840
0
    case spv::Op::OpBufferPointerEXT:
3841
0
      return ValidateBufferPointerEXT(_, inst);
3842
321k
    case spv::Op::OpLoad:
3843
321k
      return ValidateLoad(_, inst);
3844
258k
    case spv::Op::OpStore:
3845
258k
      return ValidateStore(_, inst);
3846
77.4k
    case spv::Op::OpCopyMemory:
3847
77.4k
    case spv::Op::OpCopyMemorySized:
3848
77.4k
      return ValidateCopyMemory(_, inst);
3849
7
    case spv::Op::OpPtrAccessChain:
3850
7
    case spv::Op::OpUntypedPtrAccessChainKHR:
3851
7
    case spv::Op::OpUntypedInBoundsPtrAccessChainKHR:
3852
7
      return ValidatePtrAccessChain(_, inst);
3853
147k
    case spv::Op::OpAccessChain:
3854
149k
    case spv::Op::OpInBoundsAccessChain:
3855
149k
    case spv::Op::OpInBoundsPtrAccessChain:
3856
149k
    case spv::Op::OpUntypedAccessChainKHR:
3857
149k
    case spv::Op::OpUntypedInBoundsAccessChainKHR:
3858
149k
      return ValidateAccessChain(_, inst);
3859
0
    case spv::Op::OpRawAccessChainNV:
3860
0
      return ValidateRawAccessChain(_, inst);
3861
32
    case spv::Op::OpArrayLength:
3862
32
    case spv::Op::OpUntypedArrayLengthKHR:
3863
32
      return ValidateArrayLength(_, inst);
3864
0
    case spv::Op::OpCooperativeMatrixLoadNV:
3865
0
    case spv::Op::OpCooperativeMatrixStoreNV:
3866
0
      return ValidateCooperativeMatrixLoadStoreNV(_, inst);
3867
0
    case spv::Op::OpCooperativeMatrixLengthKHR:
3868
0
      return ValidateCooperativeMatrixLength(_, inst, true);
3869
0
    case spv::Op::OpCooperativeMatrixLengthNV:
3870
0
      return ValidateCooperativeMatrixLength(_, inst, false);
3871
0
    case spv::Op::OpCooperativeMatrixGetCoordinateEXT:
3872
0
      return ValidateCooperativeMatrixGetCoordinateEXT(_, inst);
3873
0
    case spv::Op::OpCooperativeMatrixLoadKHR:
3874
0
    case spv::Op::OpCooperativeMatrixStoreKHR:
3875
0
      return ValidateCooperativeMatrixLoadStoreKHR(_, inst);
3876
0
    case spv::Op::OpCooperativeMatrixLoadTensorNV:
3877
0
    case spv::Op::OpCooperativeMatrixStoreTensorNV:
3878
0
      return ValidateCooperativeMatrixLoadStoreTensorNV(_, inst);
3879
0
    case spv::Op::OpCooperativeVectorLoadNV:
3880
0
    case spv::Op::OpCooperativeVectorStoreNV:
3881
0
      return ValidateCooperativeVectorLoadStoreNV(_, inst);
3882
0
    case spv::Op::OpCooperativeVectorOuterProductAccumulateNV:
3883
0
      return ValidateCooperativeVectorOuterProductNV(_, inst);
3884
0
    case spv::Op::OpCooperativeVectorReduceSumAccumulateNV:
3885
0
      return ValidateCooperativeVectorReduceSumNV(_, inst);
3886
0
    case spv::Op::OpCooperativeVectorMatrixMulNV:
3887
0
    case spv::Op::OpCooperativeVectorMatrixMulAddNV:
3888
0
      return ValidateCooperativeVectorMatrixMulNV(_, inst);
3889
0
    case spv::Op::OpPredicatedLoadINTEL:
3890
0
      return ValidatePredicatedLoadINTEL(_, inst);
3891
0
    case spv::Op::OpPredicatedStoreINTEL:
3892
0
      return ValidatePredicatedStoreINTEL(_, inst);
3893
0
    case spv::Op::OpPtrEqual:
3894
0
    case spv::Op::OpPtrNotEqual:
3895
2
    case spv::Op::OpPtrDiff:
3896
2
      return ValidatePtrComparison(_, inst);
3897
21
    case spv::Op::OpImageTexelPointer:
3898
21
    case spv::Op::OpGenericPtrMemSemantics:
3899
21
      break;  // no validation currently
3900
556
    case spv::Op::OpSpecConstantOp: {
3901
556
      switch (inst->GetOperandAs<spv::Op>(2u)) {
3902
9
        case spv::Op::OpCooperativeMatrixLengthKHR:
3903
9
          return ValidateCooperativeMatrixLength(_, inst, true, 3);
3904
20
        case spv::Op::OpCooperativeMatrixLengthNV:
3905
20
          return ValidateCooperativeMatrixLength(_, inst, false, 3);
3906
        // TODO - Add AccesChains
3907
527
        default:
3908
527
          break;
3909
556
      }
3910
556
    }
3911
3912
13.3M
    default:
3913
13.3M
      break;
3914
14.3M
  }
3915
3916
13.3M
  return SPV_SUCCESS;
3917
14.3M
}
3918
}  // namespace val
3919
}  // namespace spvtools