graphics_robust_access_pass.cpp 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054
  1. // Copyright (c) 2019 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // This pass injects code in a graphics shader to implement guarantees
  15. // satisfying Vulkan's robustBufferAccess rules. Robust access rules permit
  16. // an out-of-bounds access to be redirected to an access of the same type
  17. // (load, store, etc.) but within the same root object.
  18. //
  19. // We assume baseline functionality in Vulkan, i.e. the module uses
  20. // logical addressing mode, without VK_KHR_variable_pointers.
  21. //
  22. // - Logical addressing mode implies:
  23. // - Each root pointer (a pointer that exists other than by the
  24. // execution of a shader instruction) is the result of an OpVariable.
  25. //
  26. // - Instructions that result in pointers are:
  27. // OpVariable
  28. // OpAccessChain
  29. // OpInBoundsAccessChain
  30. // OpFunctionParameter
  31. // OpImageTexelPointer
  32. // OpCopyObject
  33. //
  34. // - Instructions that use a pointer are:
  35. // OpLoad
  36. // OpStore
  37. // OpAccessChain
  38. // OpInBoundsAccessChain
  39. // OpFunctionCall
  40. // OpImageTexelPointer
  41. // OpCopyMemory
  42. // OpCopyObject
  43. // all OpAtomic* instructions
  44. //
  45. // We classify pointer-users into:
  46. // - Accesses:
  47. // - OpLoad
  48. // - OpStore
  49. // - OpAtomic*
  50. // - OpCopyMemory
  51. //
  52. // - Address calculations:
  53. // - OpAccessChain
  54. // - OpInBoundsAccessChain
  55. //
  56. // - Pass-through:
  57. // - OpFunctionCall
  58. // - OpFunctionParameter
  59. // - OpCopyObject
  60. //
  61. // The strategy is:
  62. //
  63. // - Handle only logical addressing mode. In particular, don't handle a module
  64. // if it uses one of the variable-pointers capabilities.
  65. //
  66. // - Don't handle modules using capability RuntimeDescriptorArrayEXT. So the
  67. // only runtime arrays are those that are the last member in a
  68. // Block-decorated struct. This allows us to feasibly/easily compute the
  69. // length of the runtime array. See below.
  70. //
  71. // - The memory locations accessed by OpLoad, OpStore, OpCopyMemory, and
  72. // OpAtomic* are determined by their pointer parameter or parameters.
  73. // Pointers are always (correctly) typed and so the address and number of
  74. // consecutive locations are fully determined by the pointer.
  75. //
  76. // - A pointer value originates as one of few cases:
  77. //
  78. // - OpVariable for an interface object or an array of them: image,
  79. // buffer (UBO or SSBO), sampler, sampled-image, push-constant, input
  80. // variable, output variable. The execution environment is responsible for
  81. // allocating the correct amount of storage for these, and for ensuring
  82. // each resource bound to such a variable is big enough to contain the
  83. // SPIR-V pointee type of the variable.
  84. //
  85. // - OpVariable for a non-interface object. These are variables in
  86. // Workgroup, Private, and Function storage classes. The compiler ensures
  87. // the underlying allocation is big enough to store the entire SPIR-V
  88. // pointee type of the variable.
  89. //
  90. // - An OpFunctionParameter. This always maps to a pointer parameter to an
  91. // OpFunctionCall.
  92. //
  93. // - In logical addressing mode, these are severely limited:
  94. // "Any pointer operand to an OpFunctionCall must be:
  95. // - a memory object declaration, or
  96. // - a pointer to an element in an array that is a memory object
  97. // declaration, where the element type is OpTypeSampler or OpTypeImage"
  98. //
  99. // - This has an important simplifying consequence:
  100. //
  101. // - When looking for a pointer to the structure containing a runtime
  102. // array, you begin with a pointer to the runtime array and trace
  103. // backward in the function. You never have to trace back beyond
  104. // your function call boundary. So you can't take a partial access
  105. // chain into an SSBO, then pass that pointer into a function. So
  106. // we don't resort to using fat pointers to compute array length.
  107. // We can trace back to a pointer to the containing structure,
  108. // and use that in an OpArrayLength instruction. (The structure type
  109. // gives us the member index of the runtime array.)
  110. //
  111. // - Otherwise, the pointer type fully encodes the range of valid
  112. // addresses. In particular, the type of a pointer to an aggregate
  113. // value fully encodes the range of indices when indexing into
  114. // that aggregate.
  115. //
  116. // - The pointer is the result of an access chain instruction. We clamp
  117. // indices contributing to address calculations. As noted above, the
  118. // valid ranges are either bound by the length of a runtime array, or
  119. // by the type of the base pointer. The length of a runtime array is
  120. // the result of an OpArrayLength instruction acting on the pointer of
  121. // the containing structure as noted above.
  122. //
  123. // - Access chain indices are always treated as signed, so:
  124. // - Clamp the upper bound at the signed integer maximum.
  125. // - Use SClamp for all clamping.
  126. //
  127. // - TODO(dneto): OpImageTexelPointer:
  128. // - Clamp coordinate to the image size returned by OpImageQuerySize
  129. // - If multi-sampled, clamp the sample index to the count returned by
  130. // OpImageQuerySamples.
  131. // - If not multi-sampled, set the sample index to 0.
  132. //
  133. // - Rely on the external validator to check that pointers are only
  134. // used by the instructions as above.
  135. //
  136. // - Handles OpTypeRuntimeArray
  137. // Track pointer back to original resource (pointer to struct), so we can
  138. // query the runtime array size.
  139. //
  140. #include "graphics_robust_access_pass.h"
  141. #include <functional>
  142. #include <initializer_list>
  143. #include <utility>
  144. #include "function.h"
  145. #include "ir_context.h"
  146. #include "pass.h"
  147. #include "source/diagnostic.h"
  148. #include "source/util/make_unique.h"
  149. #include "spirv-tools/libspirv.h"
  150. #include "spirv/unified1/GLSL.std.450.h"
  151. #include "type_manager.h"
  152. #include "types.h"
  153. namespace spvtools {
  154. namespace opt {
  155. using opt::Instruction;
  156. using opt::Operand;
  157. using spvtools::MakeUnique;
  158. GraphicsRobustAccessPass::GraphicsRobustAccessPass() : module_status_() {}
  159. Pass::Status GraphicsRobustAccessPass::Process() {
  160. module_status_ = PerModuleState();
  161. ProcessCurrentModule();
  162. auto result = module_status_.failed
  163. ? Status::Failure
  164. : (module_status_.modified ? Status::SuccessWithChange
  165. : Status::SuccessWithoutChange);
  166. return result;
  167. }
  168. spvtools::DiagnosticStream GraphicsRobustAccessPass::Fail() {
  169. module_status_.failed = true;
  170. // We don't really have a position, and we'll ignore the result.
  171. return std::move(
  172. spvtools::DiagnosticStream({}, consumer(), "", SPV_ERROR_INVALID_BINARY)
  173. << name() << ": ");
  174. }
  175. spv_result_t GraphicsRobustAccessPass::IsCompatibleModule() {
  176. auto* feature_mgr = context()->get_feature_mgr();
  177. if (!feature_mgr->HasCapability(spv::Capability::Shader))
  178. return Fail() << "Can only process Shader modules";
  179. if (feature_mgr->HasCapability(spv::Capability::VariablePointers))
  180. return Fail() << "Can't process modules with VariablePointers capability";
  181. if (feature_mgr->HasCapability(
  182. spv::Capability::VariablePointersStorageBuffer))
  183. return Fail() << "Can't process modules with VariablePointersStorageBuffer "
  184. "capability";
  185. if (feature_mgr->HasCapability(spv::Capability::RuntimeDescriptorArrayEXT)) {
  186. // These have a RuntimeArray outside of Block-decorated struct. There
  187. // is no way to compute the array length from within SPIR-V.
  188. return Fail() << "Can't process modules with RuntimeDescriptorArrayEXT "
  189. "capability";
  190. }
  191. {
  192. auto* inst = context()->module()->GetMemoryModel();
  193. const auto addressing_model =
  194. spv::AddressingModel(inst->GetSingleWordOperand(0));
  195. if (addressing_model != spv::AddressingModel::Logical)
  196. return Fail() << "Addressing model must be Logical. Found "
  197. << inst->PrettyPrint();
  198. }
  199. return SPV_SUCCESS;
  200. }
  201. spv_result_t GraphicsRobustAccessPass::ProcessCurrentModule() {
  202. auto err = IsCompatibleModule();
  203. if (err != SPV_SUCCESS) return err;
  204. ProcessFunction fn = [this](opt::Function* f) { return ProcessAFunction(f); };
  205. module_status_.modified |= context()->ProcessReachableCallTree(fn);
  206. // Need something here. It's the price we pay for easier failure paths.
  207. return SPV_SUCCESS;
  208. }
  209. bool GraphicsRobustAccessPass::ProcessAFunction(opt::Function* function) {
  210. // Ensure that all pointers computed inside a function are within bounds.
  211. // Find the access chains in this block before trying to modify them.
  212. std::vector<Instruction*> access_chains;
  213. std::vector<Instruction*> image_texel_pointers;
  214. for (auto& block : *function) {
  215. for (auto& inst : block) {
  216. switch (inst.opcode()) {
  217. case spv::Op::OpAccessChain:
  218. case spv::Op::OpInBoundsAccessChain:
  219. access_chains.push_back(&inst);
  220. break;
  221. case spv::Op::OpImageTexelPointer:
  222. image_texel_pointers.push_back(&inst);
  223. break;
  224. default:
  225. break;
  226. }
  227. }
  228. }
  229. for (auto* inst : access_chains) {
  230. ClampIndicesForAccessChain(inst);
  231. if (module_status_.failed) return module_status_.modified;
  232. }
  233. for (auto* inst : image_texel_pointers) {
  234. if (SPV_SUCCESS != ClampCoordinateForImageTexelPointer(inst)) break;
  235. }
  236. return module_status_.modified;
  237. }
  238. void GraphicsRobustAccessPass::ClampIndicesForAccessChain(
  239. Instruction* access_chain) {
  240. Instruction& inst = *access_chain;
  241. auto* constant_mgr = context()->get_constant_mgr();
  242. auto* def_use_mgr = context()->get_def_use_mgr();
  243. auto* type_mgr = context()->get_type_mgr();
  244. const bool have_int64_cap =
  245. context()->get_feature_mgr()->HasCapability(spv::Capability::Int64);
  246. // Replaces one of the OpAccessChain index operands with a new value.
  247. // Updates def-use analysis.
  248. auto replace_index = [this, &inst, def_use_mgr](uint32_t operand_index,
  249. Instruction* new_value) {
  250. inst.SetOperand(operand_index, {new_value->result_id()});
  251. def_use_mgr->AnalyzeInstUse(&inst);
  252. module_status_.modified = true;
  253. return SPV_SUCCESS;
  254. };
  255. // Replaces one of the OpAccesssChain index operands with a clamped value.
  256. // Replace the operand at |operand_index| with the value computed from
  257. // signed_clamp(%old_value, %min_value, %max_value). It also analyzes
  258. // the new instruction and records that them module is modified.
  259. // Assumes %min_value is signed-less-or-equal than %max_value. (All callees
  260. // use 0 for %min_value).
  261. auto clamp_index = [&inst, type_mgr, this, &replace_index](
  262. uint32_t operand_index, Instruction* old_value,
  263. Instruction* min_value, Instruction* max_value) {
  264. auto* clamp_inst =
  265. MakeSClampInst(*type_mgr, old_value, min_value, max_value, &inst);
  266. return replace_index(operand_index, clamp_inst);
  267. };
  268. // Ensures the specified index of access chain |inst| has a value that is
  269. // at most |count| - 1. If the index is already a constant value less than
  270. // |count| then no change is made.
  271. auto clamp_to_literal_count =
  272. [&inst, this, &constant_mgr, &type_mgr, have_int64_cap, &replace_index,
  273. &clamp_index](uint32_t operand_index, uint64_t count) -> spv_result_t {
  274. Instruction* index_inst =
  275. this->GetDef(inst.GetSingleWordOperand(operand_index));
  276. const auto* index_type =
  277. type_mgr->GetType(index_inst->type_id())->AsInteger();
  278. assert(index_type);
  279. const auto index_width = index_type->width();
  280. if (count <= 1) {
  281. // Replace the index with 0.
  282. return replace_index(operand_index, GetValueForType(0, index_type));
  283. }
  284. uint64_t maxval = count - 1;
  285. // Compute the bit width of a viable type to hold |maxval|.
  286. // Look for a bit width, up to 64 bits wide, to fit maxval.
  287. uint32_t maxval_width = index_width;
  288. while ((maxval_width < 64) && (0 != (maxval >> maxval_width))) {
  289. maxval_width *= 2;
  290. }
  291. // Determine the type for |maxval|.
  292. uint32_t next_id = context()->module()->IdBound();
  293. analysis::Integer signed_type_for_query(maxval_width, true);
  294. auto* maxval_type =
  295. type_mgr->GetRegisteredType(&signed_type_for_query)->AsInteger();
  296. if (next_id != context()->module()->IdBound()) {
  297. module_status_.modified = true;
  298. }
  299. // Access chain indices are treated as signed, so limit the maximum value
  300. // of the index so it will always be positive for a signed clamp operation.
  301. maxval = std::min(maxval, ((uint64_t(1) << (maxval_width - 1)) - 1));
  302. if (index_width > 64) {
  303. return this->Fail() << "Can't handle indices wider than 64 bits, found "
  304. "constant index with "
  305. << index_width << " bits as index number "
  306. << operand_index << " of access chain "
  307. << inst.PrettyPrint();
  308. }
  309. // Split into two cases: the current index is a constant, or not.
  310. // If the index is a constant then |index_constant| will not be a null
  311. // pointer. (If index is an |OpConstantNull| then it |index_constant| will
  312. // not be a null pointer.) Since access chain indices must be scalar
  313. // integers, this can't be a spec constant.
  314. if (auto* index_constant = constant_mgr->GetConstantFromInst(index_inst)) {
  315. auto* int_index_constant = index_constant->AsIntConstant();
  316. int64_t value = 0;
  317. // OpAccessChain indices are treated as signed. So get the signed
  318. // constant value here.
  319. if (index_width <= 32) {
  320. value = int64_t(int_index_constant->GetS32BitValue());
  321. } else if (index_width <= 64) {
  322. value = int_index_constant->GetS64BitValue();
  323. }
  324. if (value < 0) {
  325. return replace_index(operand_index, GetValueForType(0, index_type));
  326. } else if (uint64_t(value) <= maxval) {
  327. // Nothing to do.
  328. return SPV_SUCCESS;
  329. } else {
  330. // Replace with maxval.
  331. assert(count > 0); // Already took care of this case above.
  332. return replace_index(operand_index,
  333. GetValueForType(maxval, maxval_type));
  334. }
  335. } else {
  336. // Generate a clamp instruction.
  337. assert(maxval >= 1);
  338. assert(index_width <= 64); // Otherwise, already returned above.
  339. if (index_width >= 64 && !have_int64_cap) {
  340. // An inconsistent module.
  341. return Fail() << "Access chain index is wider than 64 bits, but Int64 "
  342. "is not declared: "
  343. << index_inst->PrettyPrint();
  344. }
  345. // Widen the index value if necessary
  346. if (maxval_width > index_width) {
  347. // Find the wider type. We only need this case if a constant array
  348. // bound is too big.
  349. // From how we calculated maxval_width, widening won't require adding
  350. // the Int64 capability.
  351. assert(have_int64_cap || maxval_width <= 32);
  352. if (!have_int64_cap && maxval_width >= 64) {
  353. // Be defensive, but this shouldn't happen.
  354. return this->Fail()
  355. << "Clamping index would require adding Int64 capability. "
  356. << "Can't clamp 32-bit index " << operand_index
  357. << " of access chain " << inst.PrettyPrint();
  358. }
  359. index_inst = WidenInteger(index_type->IsSigned(), maxval_width,
  360. index_inst, &inst);
  361. }
  362. // Finally, clamp the index.
  363. return clamp_index(operand_index, index_inst,
  364. GetValueForType(0, maxval_type),
  365. GetValueForType(maxval, maxval_type));
  366. }
  367. return SPV_SUCCESS;
  368. };
  369. // Ensures the specified index of access chain |inst| has a value that is at
  370. // most the value of |count_inst| minus 1, where |count_inst| is treated as an
  371. // unsigned integer. This can log a failure.
  372. auto clamp_to_count = [&inst, this, &constant_mgr, &clamp_to_literal_count,
  373. &clamp_index,
  374. &type_mgr](uint32_t operand_index,
  375. Instruction* count_inst) -> spv_result_t {
  376. Instruction* index_inst =
  377. this->GetDef(inst.GetSingleWordOperand(operand_index));
  378. const auto* index_type =
  379. type_mgr->GetType(index_inst->type_id())->AsInteger();
  380. const auto* count_type =
  381. type_mgr->GetType(count_inst->type_id())->AsInteger();
  382. assert(index_type);
  383. if (const auto* count_constant =
  384. constant_mgr->GetConstantFromInst(count_inst)) {
  385. uint64_t value = 0;
  386. const auto width = count_constant->type()->AsInteger()->width();
  387. if (width <= 32) {
  388. value = count_constant->AsIntConstant()->GetU32BitValue();
  389. } else if (width <= 64) {
  390. value = count_constant->AsIntConstant()->GetU64BitValue();
  391. } else {
  392. return this->Fail() << "Can't handle indices wider than 64 bits, found "
  393. "constant index with "
  394. << index_type->width() << "bits";
  395. }
  396. return clamp_to_literal_count(operand_index, value);
  397. } else {
  398. // Widen them to the same width.
  399. const auto index_width = index_type->width();
  400. const auto count_width = count_type->width();
  401. const auto target_width = std::max(index_width, count_width);
  402. // UConvert requires the result type to have 0 signedness. So enforce
  403. // that here.
  404. auto* wider_type = index_width < count_width ? count_type : index_type;
  405. if (index_type->width() < target_width) {
  406. // Access chain indices are treated as signed integers.
  407. index_inst = WidenInteger(true, target_width, index_inst, &inst);
  408. } else if (count_type->width() < target_width) {
  409. // Assume type sizes are treated as unsigned.
  410. count_inst = WidenInteger(false, target_width, count_inst, &inst);
  411. }
  412. // Compute count - 1.
  413. // It doesn't matter if 1 is signed or unsigned.
  414. auto* one = GetValueForType(1, wider_type);
  415. auto* count_minus_1 = InsertInst(
  416. &inst, spv::Op::OpISub, type_mgr->GetId(wider_type), TakeNextId(),
  417. {{SPV_OPERAND_TYPE_ID, {count_inst->result_id()}},
  418. {SPV_OPERAND_TYPE_ID, {one->result_id()}}});
  419. auto* zero = GetValueForType(0, wider_type);
  420. // Make sure we clamp to an upper bound that is at most the signed max
  421. // for the target type.
  422. const uint64_t max_signed_value =
  423. ((uint64_t(1) << (target_width - 1)) - 1);
  424. // Use unsigned-min to ensure that the result is always non-negative.
  425. // That ensures we satisfy the invariant for SClamp, where the "min"
  426. // argument we give it (zero), is no larger than the third argument.
  427. auto* upper_bound =
  428. MakeUMinInst(*type_mgr, count_minus_1,
  429. GetValueForType(max_signed_value, wider_type), &inst);
  430. // Now clamp the index to this upper bound.
  431. return clamp_index(operand_index, index_inst, zero, upper_bound);
  432. }
  433. return SPV_SUCCESS;
  434. };
  435. const Instruction* base_inst = GetDef(inst.GetSingleWordInOperand(0));
  436. const Instruction* base_type = GetDef(base_inst->type_id());
  437. Instruction* pointee_type = GetDef(base_type->GetSingleWordInOperand(1));
  438. // Walk the indices from earliest to latest, replacing indices with a
  439. // clamped value, and updating the pointee_type. The order matters for
  440. // the case when we have to compute the length of a runtime array. In
  441. // that the algorithm relies on the fact that that the earlier indices
  442. // have already been clamped.
  443. const uint32_t num_operands = inst.NumOperands();
  444. for (uint32_t idx = 3; !module_status_.failed && idx < num_operands; ++idx) {
  445. const uint32_t index_id = inst.GetSingleWordOperand(idx);
  446. Instruction* index_inst = GetDef(index_id);
  447. switch (pointee_type->opcode()) {
  448. case spv::Op::OpTypeMatrix: // Use column count
  449. case spv::Op::OpTypeVector: // Use component count
  450. {
  451. const uint32_t count = pointee_type->GetSingleWordOperand(2);
  452. clamp_to_literal_count(idx, count);
  453. pointee_type = GetDef(pointee_type->GetSingleWordOperand(1));
  454. } break;
  455. case spv::Op::OpTypeArray: {
  456. // The array length can be a spec constant, so go through the general
  457. // case.
  458. Instruction* array_len = GetDef(pointee_type->GetSingleWordOperand(2));
  459. clamp_to_count(idx, array_len);
  460. pointee_type = GetDef(pointee_type->GetSingleWordOperand(1));
  461. } break;
  462. case spv::Op::OpTypeStruct: {
  463. // SPIR-V requires the index to be an OpConstant.
  464. // We need to know the index literal value so we can compute the next
  465. // pointee type.
  466. if (index_inst->opcode() != spv::Op::OpConstant ||
  467. !constant_mgr->GetConstantFromInst(index_inst)
  468. ->type()
  469. ->AsInteger()) {
  470. Fail() << "Member index into struct is not a constant integer: "
  471. << index_inst->PrettyPrint(
  472. SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES)
  473. << "\nin access chain: "
  474. << inst.PrettyPrint(SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES);
  475. return;
  476. }
  477. const auto num_members = pointee_type->NumInOperands();
  478. const auto* index_constant =
  479. constant_mgr->GetConstantFromInst(index_inst);
  480. // Get the sign-extended value, since access index is always treated as
  481. // signed.
  482. const auto index_value = index_constant->GetSignExtendedValue();
  483. if (index_value < 0 || index_value >= num_members) {
  484. Fail() << "Member index " << index_value
  485. << " is out of bounds for struct type: "
  486. << pointee_type->PrettyPrint(
  487. SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES)
  488. << "\nin access chain: "
  489. << inst.PrettyPrint(SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES);
  490. return;
  491. }
  492. pointee_type = GetDef(pointee_type->GetSingleWordInOperand(
  493. static_cast<uint32_t>(index_value)));
  494. // No need to clamp this index. We just checked that it's valid.
  495. } break;
  496. case spv::Op::OpTypeRuntimeArray: {
  497. auto* array_len = MakeRuntimeArrayLengthInst(&inst, idx);
  498. if (!array_len) { // We've already signaled an error.
  499. return;
  500. }
  501. clamp_to_count(idx, array_len);
  502. if (module_status_.failed) return;
  503. pointee_type = GetDef(pointee_type->GetSingleWordOperand(1));
  504. } break;
  505. default:
  506. Fail() << " Unhandled pointee type for access chain "
  507. << pointee_type->PrettyPrint(
  508. SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES);
  509. }
  510. }
  511. }
  512. uint32_t GraphicsRobustAccessPass::GetGlslInsts() {
  513. if (module_status_.glsl_insts_id == 0) {
  514. // This string serves double-duty as raw data for a string and for a vector
  515. // of 32-bit words
  516. const char glsl[] = "GLSL.std.450";
  517. // Use an existing import if we can.
  518. for (auto& inst : context()->module()->ext_inst_imports()) {
  519. if (inst.GetInOperand(0).AsString() == glsl) {
  520. module_status_.glsl_insts_id = inst.result_id();
  521. }
  522. }
  523. if (module_status_.glsl_insts_id == 0) {
  524. // Make a new import instruction.
  525. module_status_.glsl_insts_id = TakeNextId();
  526. std::vector<uint32_t> words = spvtools::utils::MakeVector(glsl);
  527. auto import_inst = MakeUnique<Instruction>(
  528. context(), spv::Op::OpExtInstImport, 0, module_status_.glsl_insts_id,
  529. std::initializer_list<Operand>{
  530. Operand{SPV_OPERAND_TYPE_LITERAL_STRING, std::move(words)}});
  531. Instruction* inst = import_inst.get();
  532. context()->module()->AddExtInstImport(std::move(import_inst));
  533. module_status_.modified = true;
  534. context()->AnalyzeDefUse(inst);
  535. // Invalidates the feature manager, since we added an extended instruction
  536. // set import.
  537. context()->ResetFeatureManager();
  538. }
  539. }
  540. return module_status_.glsl_insts_id;
  541. }
  542. opt::Instruction* opt::GraphicsRobustAccessPass::GetValueForType(
  543. uint64_t value, const analysis::Integer* type) {
  544. auto* mgr = context()->get_constant_mgr();
  545. assert(type->width() <= 64);
  546. std::vector<uint32_t> words;
  547. words.push_back(uint32_t(value));
  548. if (type->width() > 32) {
  549. words.push_back(uint32_t(value >> 32u));
  550. }
  551. const auto* constant = mgr->GetConstant(type, words);
  552. return mgr->GetDefiningInstruction(
  553. constant, context()->get_type_mgr()->GetTypeInstruction(type));
  554. }
  555. opt::Instruction* opt::GraphicsRobustAccessPass::WidenInteger(
  556. bool sign_extend, uint32_t bit_width, Instruction* value,
  557. Instruction* before_inst) {
  558. analysis::Integer unsigned_type_for_query(bit_width, false);
  559. auto* type_mgr = context()->get_type_mgr();
  560. auto* unsigned_type = type_mgr->GetRegisteredType(&unsigned_type_for_query);
  561. auto type_id = context()->get_type_mgr()->GetId(unsigned_type);
  562. auto conversion_id = TakeNextId();
  563. auto* conversion = InsertInst(
  564. before_inst, (sign_extend ? spv::Op::OpSConvert : spv::Op::OpUConvert),
  565. type_id, conversion_id, {{SPV_OPERAND_TYPE_ID, {value->result_id()}}});
  566. return conversion;
  567. }
  568. Instruction* GraphicsRobustAccessPass::MakeUMinInst(
  569. const analysis::TypeManager& tm, Instruction* x, Instruction* y,
  570. Instruction* where) {
  571. // Get IDs of instructions we'll be referencing. Evaluate them before calling
  572. // the function so we force a deterministic ordering in case both of them need
  573. // to take a new ID.
  574. const uint32_t glsl_insts_id = GetGlslInsts();
  575. uint32_t smin_id = TakeNextId();
  576. const auto xwidth = tm.GetType(x->type_id())->AsInteger()->width();
  577. const auto ywidth = tm.GetType(y->type_id())->AsInteger()->width();
  578. assert(xwidth == ywidth);
  579. (void)xwidth;
  580. (void)ywidth;
  581. auto* smin_inst = InsertInst(
  582. where, spv::Op::OpExtInst, x->type_id(), smin_id,
  583. {
  584. {SPV_OPERAND_TYPE_ID, {glsl_insts_id}},
  585. {SPV_OPERAND_TYPE_EXTENSION_INSTRUCTION_NUMBER, {GLSLstd450UMin}},
  586. {SPV_OPERAND_TYPE_ID, {x->result_id()}},
  587. {SPV_OPERAND_TYPE_ID, {y->result_id()}},
  588. });
  589. return smin_inst;
  590. }
  591. Instruction* GraphicsRobustAccessPass::MakeSClampInst(
  592. const analysis::TypeManager& tm, Instruction* x, Instruction* min,
  593. Instruction* max, Instruction* where) {
  594. // Get IDs of instructions we'll be referencing. Evaluate them before calling
  595. // the function so we force a deterministic ordering in case both of them need
  596. // to take a new ID.
  597. const uint32_t glsl_insts_id = GetGlslInsts();
  598. uint32_t clamp_id = TakeNextId();
  599. const auto xwidth = tm.GetType(x->type_id())->AsInteger()->width();
  600. const auto minwidth = tm.GetType(min->type_id())->AsInteger()->width();
  601. const auto maxwidth = tm.GetType(max->type_id())->AsInteger()->width();
  602. assert(xwidth == minwidth);
  603. assert(xwidth == maxwidth);
  604. (void)xwidth;
  605. (void)minwidth;
  606. (void)maxwidth;
  607. auto* clamp_inst = InsertInst(
  608. where, spv::Op::OpExtInst, x->type_id(), clamp_id,
  609. {
  610. {SPV_OPERAND_TYPE_ID, {glsl_insts_id}},
  611. {SPV_OPERAND_TYPE_EXTENSION_INSTRUCTION_NUMBER, {GLSLstd450SClamp}},
  612. {SPV_OPERAND_TYPE_ID, {x->result_id()}},
  613. {SPV_OPERAND_TYPE_ID, {min->result_id()}},
  614. {SPV_OPERAND_TYPE_ID, {max->result_id()}},
  615. });
  616. return clamp_inst;
  617. }
  618. Instruction* GraphicsRobustAccessPass::MakeRuntimeArrayLengthInst(
  619. Instruction* access_chain, uint32_t operand_index) {
  620. // The Index parameter to the access chain at |operand_index| is indexing
  621. // *into* the runtime-array. To get the number of elements in the runtime
  622. // array we need a pointer to the Block-decorated struct that contains the
  623. // runtime array. So conceptually we have to go 2 steps backward in the
  624. // access chain. The two steps backward might forces us to traverse backward
  625. // across multiple dominating instructions.
  626. auto* type_mgr = context()->get_type_mgr();
  627. // How many access chain indices do we have to unwind to find the pointer
  628. // to the struct containing the runtime array?
  629. uint32_t steps_remaining = 2;
  630. // Find or create an instruction computing the pointer to the structure
  631. // containing the runtime array.
  632. // Walk backward through pointer address calculations until we either get
  633. // to exactly the right base pointer, or to an access chain instruction
  634. // that we can replicate but truncate to compute the address of the right
  635. // struct.
  636. Instruction* current_access_chain = access_chain;
  637. Instruction* pointer_to_containing_struct = nullptr;
  638. while (steps_remaining > 0) {
  639. switch (current_access_chain->opcode()) {
  640. case spv::Op::OpCopyObject:
  641. // Whoops. Walk right through this one.
  642. current_access_chain =
  643. GetDef(current_access_chain->GetSingleWordInOperand(0));
  644. break;
  645. case spv::Op::OpAccessChain:
  646. case spv::Op::OpInBoundsAccessChain: {
  647. const int first_index_operand = 3;
  648. // How many indices in this access chain contribute to getting us
  649. // to an element in the runtime array?
  650. const auto num_contributing_indices =
  651. current_access_chain == access_chain
  652. ? operand_index - (first_index_operand - 1)
  653. : current_access_chain->NumInOperands() - 1 /* skip the base */;
  654. Instruction* base =
  655. GetDef(current_access_chain->GetSingleWordInOperand(0));
  656. if (num_contributing_indices == steps_remaining) {
  657. // The base pointer points to the structure.
  658. pointer_to_containing_struct = base;
  659. steps_remaining = 0;
  660. break;
  661. } else if (num_contributing_indices < steps_remaining) {
  662. // Peel off the index and keep going backward.
  663. steps_remaining -= num_contributing_indices;
  664. current_access_chain = base;
  665. } else {
  666. // This access chain has more indices than needed. Generate a new
  667. // access chain instruction, but truncating the list of indices.
  668. const int base_operand = 2;
  669. // We'll use the base pointer and the indices up to but not including
  670. // the one indexing into the runtime array.
  671. Instruction::OperandList ops;
  672. // Use the base pointer
  673. ops.push_back(current_access_chain->GetOperand(base_operand));
  674. const uint32_t num_indices_to_keep =
  675. num_contributing_indices - steps_remaining - 1;
  676. for (uint32_t i = 0; i <= num_indices_to_keep; i++) {
  677. ops.push_back(
  678. current_access_chain->GetOperand(first_index_operand + i));
  679. }
  680. // Compute the type of the result of the new access chain. Start at
  681. // the base and walk the indices in a forward direction.
  682. auto* constant_mgr = context()->get_constant_mgr();
  683. std::vector<uint32_t> indices_for_type;
  684. for (uint32_t i = 0; i < ops.size() - 1; i++) {
  685. uint32_t index_for_type_calculation = 0;
  686. Instruction* index =
  687. GetDef(current_access_chain->GetSingleWordOperand(
  688. first_index_operand + i));
  689. if (auto* index_constant =
  690. constant_mgr->GetConstantFromInst(index)) {
  691. // We only need 32 bits. For the type calculation, it's sufficient
  692. // to take the zero-extended value. It only matters for the struct
  693. // case, and struct member indices are unsigned.
  694. index_for_type_calculation =
  695. uint32_t(index_constant->GetZeroExtendedValue());
  696. } else {
  697. // Indexing into a variably-sized thing like an array. Use 0.
  698. index_for_type_calculation = 0;
  699. }
  700. indices_for_type.push_back(index_for_type_calculation);
  701. }
  702. auto* base_ptr_type = type_mgr->GetType(base->type_id())->AsPointer();
  703. auto* base_pointee_type = base_ptr_type->pointee_type();
  704. auto* new_access_chain_result_pointee_type =
  705. type_mgr->GetMemberType(base_pointee_type, indices_for_type);
  706. const uint32_t new_access_chain_type_id = type_mgr->FindPointerToType(
  707. type_mgr->GetId(new_access_chain_result_pointee_type),
  708. base_ptr_type->storage_class());
  709. // Create the instruction and insert it.
  710. const auto new_access_chain_id = TakeNextId();
  711. auto* new_access_chain =
  712. InsertInst(current_access_chain, current_access_chain->opcode(),
  713. new_access_chain_type_id, new_access_chain_id, ops);
  714. pointer_to_containing_struct = new_access_chain;
  715. steps_remaining = 0;
  716. break;
  717. }
  718. } break;
  719. default:
  720. Fail() << "Unhandled access chain in logical addressing mode passes "
  721. "through "
  722. << current_access_chain->PrettyPrint(
  723. SPV_BINARY_TO_TEXT_OPTION_SHOW_BYTE_OFFSET |
  724. SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES);
  725. return nullptr;
  726. }
  727. }
  728. assert(pointer_to_containing_struct);
  729. auto* pointee_type =
  730. type_mgr->GetType(pointer_to_containing_struct->type_id())
  731. ->AsPointer()
  732. ->pointee_type();
  733. auto* struct_type = pointee_type->AsStruct();
  734. const uint32_t member_index_of_runtime_array =
  735. uint32_t(struct_type->element_types().size() - 1);
  736. // Create the length-of-array instruction before the original access chain,
  737. // but after the generation of the pointer to the struct.
  738. const auto array_len_id = TakeNextId();
  739. analysis::Integer uint_type_for_query(32, false);
  740. auto* uint_type = type_mgr->GetRegisteredType(&uint_type_for_query);
  741. auto* array_len = InsertInst(
  742. access_chain, spv::Op::OpArrayLength, type_mgr->GetId(uint_type),
  743. array_len_id,
  744. {{SPV_OPERAND_TYPE_ID, {pointer_to_containing_struct->result_id()}},
  745. {SPV_OPERAND_TYPE_LITERAL_INTEGER, {member_index_of_runtime_array}}});
  746. return array_len;
  747. }
  748. spv_result_t GraphicsRobustAccessPass::ClampCoordinateForImageTexelPointer(
  749. opt::Instruction* image_texel_pointer) {
  750. // TODO(dneto): Write tests for this code.
  751. // TODO(dneto): Use signed-clamp
  752. (void)(image_texel_pointer);
  753. return SPV_SUCCESS;
  754. // Do not compile this code until it is ready to be used.
  755. #if 0
  756. // Example:
  757. // %texel_ptr = OpImageTexelPointer %texel_ptr_type %image_ptr %coord
  758. // %sample
  759. //
  760. // We want to clamp %coord components between vector-0 and the result
  761. // of OpImageQuerySize acting on the underlying image. So insert:
  762. // %image = OpLoad %image_type %image_ptr
  763. // %query_size = OpImageQuerySize %query_size_type %image
  764. //
  765. // For a multi-sampled image, %sample is the sample index, and we need
  766. // to clamp it between zero and the number of samples in the image.
  767. // %sample_count = OpImageQuerySamples %uint %image
  768. // %max_sample_index = OpISub %uint %sample_count %uint_1
  769. // For non-multi-sampled images, the sample index must be constant zero.
  770. auto* def_use_mgr = context()->get_def_use_mgr();
  771. auto* type_mgr = context()->get_type_mgr();
  772. auto* constant_mgr = context()->get_constant_mgr();
  773. auto* image_ptr = GetDef(image_texel_pointer->GetSingleWordInOperand(0));
  774. auto* image_ptr_type = GetDef(image_ptr->type_id());
  775. auto image_type_id = image_ptr_type->GetSingleWordInOperand(1);
  776. auto* image_type = GetDef(image_type_id);
  777. auto* coord = GetDef(image_texel_pointer->GetSingleWordInOperand(1));
  778. auto* samples = GetDef(image_texel_pointer->GetSingleWordInOperand(2));
  779. // We will modify the module, at least by adding image query instructions.
  780. module_status_.modified = true;
  781. // Declare the ImageQuery capability if the module doesn't already have it.
  782. auto* feature_mgr = context()->get_feature_mgr();
  783. if (!feature_mgr->HasCapability(spv::Capability::ImageQuery)) {
  784. auto cap = MakeUnique<Instruction>(
  785. context(), spv::Op::OpCapability, 0, 0,
  786. std::initializer_list<Operand>{
  787. {SPV_OPERAND_TYPE_CAPABILITY, {spv::Capability::ImageQuery}}});
  788. def_use_mgr->AnalyzeInstDefUse(cap.get());
  789. context()->AddCapability(std::move(cap));
  790. feature_mgr->Analyze(context()->module());
  791. }
  792. // OpImageTexelPointer is used to translate a coordinate and sample index
  793. // into an address for use with an atomic operation. That is, it may only
  794. // used with what Vulkan calls a "storage image"
  795. // (OpTypeImage parameter Sampled=2).
  796. // Note: A storage image never has a level-of-detail associated with it.
  797. // Constraints on the sample id:
  798. // - Only 2D images can be multi-sampled: OpTypeImage parameter MS=1
  799. // only if Dim=2D.
  800. // - Non-multi-sampled images (OpTypeImage parameter MS=0) must use
  801. // sample ID to a constant 0.
  802. // The coordinate is treated as unsigned, and should be clamped against the
  803. // image "size", returned by OpImageQuerySize. (Note: OpImageQuerySizeLod
  804. // is only usable with a sampled image, i.e. its image type has Sampled=1).
  805. // Determine the result type for the OpImageQuerySize.
  806. // For non-arrayed images:
  807. // non-Cube:
  808. // - Always the same as the coordinate type
  809. // Cube:
  810. // - Use all but the last component of the coordinate (which is the face
  811. // index from 0 to 5).
  812. // For arrayed images (in Vulkan the Dim is 1D, 2D, or Cube):
  813. // non-Cube:
  814. // - A vector with the components in the coordinate, and one more for
  815. // the layer index.
  816. // Cube:
  817. // - The same as the coordinate type: 3-element integer vector.
  818. // - The third component from the size query is the layer count.
  819. // - The third component in the texel pointer calculation is
  820. // 6 * layer + face, where 0 <= face < 6.
  821. // Cube: Use all but the last component of the coordinate (which is the face
  822. // index from 0 to 5).
  823. const auto dim = SpvDim(image_type->GetSingleWordInOperand(1));
  824. const bool arrayed = image_type->GetSingleWordInOperand(3) == 1;
  825. const bool multisampled = image_type->GetSingleWordInOperand(4) != 0;
  826. const auto query_num_components = [dim, arrayed, this]() -> int {
  827. const int arrayness_bonus = arrayed ? 1 : 0;
  828. int num_coords = 0;
  829. switch (dim) {
  830. case spv::Dim::Buffer:
  831. case SpvDim1D:
  832. num_coords = 1;
  833. break;
  834. case spv::Dim::Cube:
  835. // For cube, we need bounds for x, y, but not face.
  836. case spv::Dim::Rect:
  837. case SpvDim2D:
  838. num_coords = 2;
  839. break;
  840. case SpvDim3D:
  841. num_coords = 3;
  842. break;
  843. case spv::Dim::SubpassData:
  844. case spv::Dim::Max:
  845. return Fail() << "Invalid image dimension for OpImageTexelPointer: "
  846. << int(dim);
  847. break;
  848. }
  849. return num_coords + arrayness_bonus;
  850. }();
  851. const auto* coord_component_type = [type_mgr, coord]() {
  852. const analysis::Type* coord_type = type_mgr->GetType(coord->type_id());
  853. if (auto* vector_type = coord_type->AsVector()) {
  854. return vector_type->element_type()->AsInteger();
  855. }
  856. return coord_type->AsInteger();
  857. }();
  858. // For now, only handle 32-bit case for coordinates.
  859. if (!coord_component_type) {
  860. return Fail() << " Coordinates for OpImageTexelPointer are not integral: "
  861. << image_texel_pointer->PrettyPrint(
  862. SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES);
  863. }
  864. if (coord_component_type->width() != 32) {
  865. return Fail() << " Expected OpImageTexelPointer coordinate components to "
  866. "be 32-bits wide. They are "
  867. << coord_component_type->width() << " bits. "
  868. << image_texel_pointer->PrettyPrint(
  869. SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES);
  870. }
  871. const auto* query_size_type =
  872. [type_mgr, coord_component_type,
  873. query_num_components]() -> const analysis::Type* {
  874. if (query_num_components == 1) return coord_component_type;
  875. analysis::Vector proposed(coord_component_type, query_num_components);
  876. return type_mgr->GetRegisteredType(&proposed);
  877. }();
  878. const uint32_t image_id = TakeNextId();
  879. auto* image =
  880. InsertInst(image_texel_pointer, spv::Op::OpLoad, image_type_id, image_id,
  881. {{SPV_OPERAND_TYPE_ID, {image_ptr->result_id()}}});
  882. const uint32_t query_size_id = TakeNextId();
  883. auto* query_size =
  884. InsertInst(image_texel_pointer, spv::Op::OpImageQuerySize,
  885. type_mgr->GetTypeInstruction(query_size_type), query_size_id,
  886. {{SPV_OPERAND_TYPE_ID, {image->result_id()}}});
  887. auto* component_1 = constant_mgr->GetConstant(coord_component_type, {1});
  888. const uint32_t component_1_id =
  889. constant_mgr->GetDefiningInstruction(component_1)->result_id();
  890. auto* component_0 = constant_mgr->GetConstant(coord_component_type, {0});
  891. const uint32_t component_0_id =
  892. constant_mgr->GetDefiningInstruction(component_0)->result_id();
  893. // If the image is a cube array, then the last component of the queried
  894. // size is the layer count. In the query, we have to accommodate folding
  895. // in the face index ranging from 0 through 5. The inclusive upper bound
  896. // on the third coordinate therefore is multiplied by 6.
  897. auto* query_size_including_faces = query_size;
  898. if (arrayed && (dim == spv::Dim::Cube)) {
  899. // Multiply the last coordinate by 6.
  900. auto* component_6 = constant_mgr->GetConstant(coord_component_type, {6});
  901. const uint32_t component_6_id =
  902. constant_mgr->GetDefiningInstruction(component_6)->result_id();
  903. assert(query_num_components == 3);
  904. auto* multiplicand = constant_mgr->GetConstant(
  905. query_size_type, {component_1_id, component_1_id, component_6_id});
  906. auto* multiplicand_inst =
  907. constant_mgr->GetDefiningInstruction(multiplicand);
  908. const auto query_size_including_faces_id = TakeNextId();
  909. query_size_including_faces = InsertInst(
  910. image_texel_pointer, spv::Op::OpIMul,
  911. type_mgr->GetTypeInstruction(query_size_type),
  912. query_size_including_faces_id,
  913. {{SPV_OPERAND_TYPE_ID, {query_size_including_faces->result_id()}},
  914. {SPV_OPERAND_TYPE_ID, {multiplicand_inst->result_id()}}});
  915. }
  916. // Make a coordinate-type with all 1 components.
  917. auto* coordinate_1 =
  918. query_num_components == 1
  919. ? component_1
  920. : constant_mgr->GetConstant(
  921. query_size_type,
  922. std::vector<uint32_t>(query_num_components, component_1_id));
  923. // Make a coordinate-type with all 1 components.
  924. auto* coordinate_0 =
  925. query_num_components == 0
  926. ? component_0
  927. : constant_mgr->GetConstant(
  928. query_size_type,
  929. std::vector<uint32_t>(query_num_components, component_0_id));
  930. const uint32_t query_max_including_faces_id = TakeNextId();
  931. auto* query_max_including_faces = InsertInst(
  932. image_texel_pointer, spv::Op::OpISub,
  933. type_mgr->GetTypeInstruction(query_size_type),
  934. query_max_including_faces_id,
  935. {{SPV_OPERAND_TYPE_ID, {query_size_including_faces->result_id()}},
  936. {SPV_OPERAND_TYPE_ID,
  937. {constant_mgr->GetDefiningInstruction(coordinate_1)->result_id()}}});
  938. // Clamp the coordinate
  939. auto* clamp_coord = MakeSClampInst(
  940. *type_mgr, coord, constant_mgr->GetDefiningInstruction(coordinate_0),
  941. query_max_including_faces, image_texel_pointer);
  942. image_texel_pointer->SetInOperand(1, {clamp_coord->result_id()});
  943. // Clamp the sample index
  944. if (multisampled) {
  945. // Get the sample count via OpImageQuerySamples
  946. const auto query_samples_id = TakeNextId();
  947. auto* query_samples = InsertInst(
  948. image_texel_pointer, spv::Op::OpImageQuerySamples,
  949. constant_mgr->GetDefiningInstruction(component_0)->type_id(),
  950. query_samples_id, {{SPV_OPERAND_TYPE_ID, {image->result_id()}}});
  951. const auto max_samples_id = TakeNextId();
  952. auto* max_samples = InsertInst(image_texel_pointer, spv::Op::OpImageQuerySamples,
  953. query_samples->type_id(), max_samples_id,
  954. {{SPV_OPERAND_TYPE_ID, {query_samples_id}},
  955. {SPV_OPERAND_TYPE_ID, {component_1_id}}});
  956. auto* clamp_samples = MakeSClampInst(
  957. *type_mgr, samples, constant_mgr->GetDefiningInstruction(coordinate_0),
  958. max_samples, image_texel_pointer);
  959. image_texel_pointer->SetInOperand(2, {clamp_samples->result_id()});
  960. } else {
  961. // Just replace it with 0. Don't even check what was there before.
  962. image_texel_pointer->SetInOperand(2, {component_0_id});
  963. }
  964. def_use_mgr->AnalyzeInstUse(image_texel_pointer);
  965. return SPV_SUCCESS;
  966. #endif
  967. }
  968. opt::Instruction* GraphicsRobustAccessPass::InsertInst(
  969. opt::Instruction* where_inst, spv::Op opcode, uint32_t type_id,
  970. uint32_t result_id, const Instruction::OperandList& operands) {
  971. module_status_.modified = true;
  972. auto* result = where_inst->InsertBefore(
  973. MakeUnique<Instruction>(context(), opcode, type_id, result_id, operands));
  974. context()->get_def_use_mgr()->AnalyzeInstDefUse(result);
  975. auto* basic_block = context()->get_instr_block(where_inst);
  976. context()->set_instr_block(result, basic_block);
  977. return result;
  978. }
  979. } // namespace opt
  980. } // namespace spvtools