blob: 246cdbb4e61a9ee115410f22ebc6c64cfe887499 [file] [log] [blame]
Chris Forbescc5697f2019-01-30 11:54:08 -08001// Copyright (c) 2018 The Khronos Group Inc.
2// Copyright (c) 2018 Valve Corporation
3// Copyright (c) 2018 LunarG Inc.
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
17#include "instrument_pass.h"
18
19#include "source/cfa.h"
Ben Claytonb73b7602019-07-29 13:56:13 +010020#include "source/spirv_constant.h"
Chris Forbescc5697f2019-01-30 11:54:08 -080021
22namespace {
23
24// Common Parameter Positions
25static const int kInstCommonParamInstIdx = 0;
26static const int kInstCommonParamCnt = 1;
27
28// Indices of operands in SPIR-V instructions
29static const int kEntryPointExecutionModelInIdx = 0;
30static const int kEntryPointFunctionIdInIdx = 1;
31
32} // anonymous namespace
33
34namespace spvtools {
35namespace opt {
36
37void InstrumentPass::MovePreludeCode(
38 BasicBlock::iterator ref_inst_itr,
39 UptrVectorIterator<BasicBlock> ref_block_itr,
40 std::unique_ptr<BasicBlock>* new_blk_ptr) {
41 same_block_pre_.clear();
42 same_block_post_.clear();
43 // Initialize new block. Reuse label from original block.
44 new_blk_ptr->reset(new BasicBlock(std::move(ref_block_itr->GetLabel())));
45 // Move contents of original ref block up to ref instruction.
46 for (auto cii = ref_block_itr->begin(); cii != ref_inst_itr;
47 cii = ref_block_itr->begin()) {
48 Instruction* inst = &*cii;
49 inst->RemoveFromList();
50 std::unique_ptr<Instruction> mv_ptr(inst);
51 // Remember same-block ops for possible regeneration.
52 if (IsSameBlockOp(&*mv_ptr)) {
53 auto* sb_inst_ptr = mv_ptr.get();
54 same_block_pre_[mv_ptr->result_id()] = sb_inst_ptr;
55 }
56 (*new_blk_ptr)->AddInstruction(std::move(mv_ptr));
57 }
58}
59
60void InstrumentPass::MovePostludeCode(
Ben Claytonb73b7602019-07-29 13:56:13 +010061 UptrVectorIterator<BasicBlock> ref_block_itr, BasicBlock* new_blk_ptr) {
Chris Forbescc5697f2019-01-30 11:54:08 -080062 // new_blk_ptr->reset(new BasicBlock(NewLabel(ref_block_itr->id())));
63 // Move contents of original ref block.
64 for (auto cii = ref_block_itr->begin(); cii != ref_block_itr->end();
65 cii = ref_block_itr->begin()) {
66 Instruction* inst = &*cii;
67 inst->RemoveFromList();
68 std::unique_ptr<Instruction> mv_inst(inst);
69 // Regenerate any same-block instruction that has not been seen in the
70 // current block.
71 if (same_block_pre_.size() > 0) {
72 CloneSameBlockOps(&mv_inst, &same_block_post_, &same_block_pre_,
73 new_blk_ptr);
74 // Remember same-block ops in this block.
75 if (IsSameBlockOp(&*mv_inst)) {
76 const uint32_t rid = mv_inst->result_id();
77 same_block_post_[rid] = rid;
78 }
79 }
Ben Claytonb73b7602019-07-29 13:56:13 +010080 new_blk_ptr->AddInstruction(std::move(mv_inst));
Chris Forbescc5697f2019-01-30 11:54:08 -080081 }
82}
83
84std::unique_ptr<Instruction> InstrumentPass::NewLabel(uint32_t label_id) {
85 std::unique_ptr<Instruction> newLabel(
86 new Instruction(context(), SpvOpLabel, 0, label_id, {}));
87 get_def_use_mgr()->AnalyzeInstDefUse(&*newLabel);
88 return newLabel;
89}
90
91uint32_t InstrumentPass::GenUintCastCode(uint32_t val_id,
92 InstructionBuilder* builder) {
93 // Cast value to 32-bit unsigned if necessary
94 if (get_def_use_mgr()->GetDef(val_id)->type_id() == GetUintId())
95 return val_id;
96 return builder->AddUnaryOp(GetUintId(), SpvOpBitcast, val_id)->result_id();
97}
98
99void InstrumentPass::GenDebugOutputFieldCode(uint32_t base_offset_id,
100 uint32_t field_offset,
101 uint32_t field_value_id,
102 InstructionBuilder* builder) {
103 // Cast value to 32-bit unsigned if necessary
104 uint32_t val_id = GenUintCastCode(field_value_id, builder);
105 // Store value
106 Instruction* data_idx_inst =
107 builder->AddBinaryOp(GetUintId(), SpvOpIAdd, base_offset_id,
108 builder->GetUintConstantId(field_offset));
109 uint32_t buf_id = GetOutputBufferId();
Ben Claytond0f684e2019-08-30 22:36:08 +0100110 uint32_t buf_uint_ptr_id = GetOutputBufferPtrId();
Chris Forbescc5697f2019-01-30 11:54:08 -0800111 Instruction* achain_inst =
112 builder->AddTernaryOp(buf_uint_ptr_id, SpvOpAccessChain, buf_id,
113 builder->GetUintConstantId(kDebugOutputDataOffset),
114 data_idx_inst->result_id());
115 (void)builder->AddBinaryOp(0, SpvOpStore, achain_inst->result_id(), val_id);
116}
117
118void InstrumentPass::GenCommonStreamWriteCode(uint32_t record_sz,
119 uint32_t inst_id,
120 uint32_t stage_idx,
121 uint32_t base_offset_id,
122 InstructionBuilder* builder) {
123 // Store record size
124 GenDebugOutputFieldCode(base_offset_id, kInstCommonOutSize,
125 builder->GetUintConstantId(record_sz), builder);
126 // Store Shader Id
127 GenDebugOutputFieldCode(base_offset_id, kInstCommonOutShaderId,
128 builder->GetUintConstantId(shader_id_), builder);
129 // Store Instruction Idx
130 GenDebugOutputFieldCode(base_offset_id, kInstCommonOutInstructionIdx, inst_id,
131 builder);
132 // Store Stage Idx
133 GenDebugOutputFieldCode(base_offset_id, kInstCommonOutStageIdx,
134 builder->GetUintConstantId(stage_idx), builder);
135}
136
137void InstrumentPass::GenFragCoordEltDebugOutputCode(
138 uint32_t base_offset_id, uint32_t uint_frag_coord_id, uint32_t element,
139 InstructionBuilder* builder) {
140 Instruction* element_val_inst = builder->AddIdLiteralOp(
141 GetUintId(), SpvOpCompositeExtract, uint_frag_coord_id, element);
142 GenDebugOutputFieldCode(base_offset_id, kInstFragOutFragCoordX + element,
143 element_val_inst->result_id(), builder);
144}
145
Ben Claytonb73b7602019-07-29 13:56:13 +0100146uint32_t InstrumentPass::GenVarLoad(uint32_t var_id,
147 InstructionBuilder* builder) {
148 Instruction* var_inst = get_def_use_mgr()->GetDef(var_id);
149 uint32_t type_id = GetPointeeTypeId(var_inst);
150 Instruction* load_inst = builder->AddUnaryOp(type_id, SpvOpLoad, var_id);
151 return load_inst->result_id();
152}
153
Chris Forbescc5697f2019-01-30 11:54:08 -0800154void InstrumentPass::GenBuiltinOutputCode(uint32_t builtin_id,
155 uint32_t builtin_off,
156 uint32_t base_offset_id,
157 InstructionBuilder* builder) {
158 // Load and store builtin
Ben Claytonb73b7602019-07-29 13:56:13 +0100159 uint32_t load_id = GenVarLoad(builtin_id, builder);
160 GenDebugOutputFieldCode(base_offset_id, builtin_off, load_id, builder);
Chris Forbescc5697f2019-01-30 11:54:08 -0800161}
162
163void InstrumentPass::GenStageStreamWriteCode(uint32_t stage_idx,
164 uint32_t base_offset_id,
165 InstructionBuilder* builder) {
166 // TODO(greg-lunarg): Add support for all stages
167 switch (stage_idx) {
168 case SpvExecutionModelVertex: {
169 // Load and store VertexId and InstanceId
Ben Claytonb73b7602019-07-29 13:56:13 +0100170 GenBuiltinOutputCode(
171 context()->GetBuiltinInputVarId(SpvBuiltInVertexIndex),
172 kInstVertOutVertexIndex, base_offset_id, builder);
173 GenBuiltinOutputCode(
174 context()->GetBuiltinInputVarId(SpvBuiltInInstanceIndex),
175 kInstVertOutInstanceIndex, base_offset_id, builder);
Chris Forbescc5697f2019-01-30 11:54:08 -0800176 } break;
177 case SpvExecutionModelGLCompute: {
Ben Claytonb73b7602019-07-29 13:56:13 +0100178 // Load and store GlobalInvocationId.
179 uint32_t load_id = GenVarLoad(
180 context()->GetBuiltinInputVarId(SpvBuiltInGlobalInvocationId),
181 builder);
182 Instruction* x_inst = builder->AddIdLiteralOp(
183 GetUintId(), SpvOpCompositeExtract, load_id, 0);
184 Instruction* y_inst = builder->AddIdLiteralOp(
185 GetUintId(), SpvOpCompositeExtract, load_id, 1);
186 Instruction* z_inst = builder->AddIdLiteralOp(
187 GetUintId(), SpvOpCompositeExtract, load_id, 2);
188 if (version_ == 1) {
189 // For version 1 format, as a stopgap, pack uvec3 into first word:
190 // x << 21 | y << 10 | z. Second word is unused. (DEPRECATED)
191 Instruction* x_shft_inst = builder->AddBinaryOp(
192 GetUintId(), SpvOpShiftLeftLogical, x_inst->result_id(),
193 builder->GetUintConstantId(21));
194 Instruction* y_shft_inst = builder->AddBinaryOp(
195 GetUintId(), SpvOpShiftLeftLogical, y_inst->result_id(),
196 builder->GetUintConstantId(10));
197 Instruction* x_or_y_inst = builder->AddBinaryOp(
198 GetUintId(), SpvOpBitwiseOr, x_shft_inst->result_id(),
199 y_shft_inst->result_id());
200 Instruction* x_or_y_or_z_inst =
201 builder->AddBinaryOp(GetUintId(), SpvOpBitwiseOr,
202 x_or_y_inst->result_id(), z_inst->result_id());
203 GenDebugOutputFieldCode(base_offset_id, kInstCompOutGlobalInvocationId,
204 x_or_y_or_z_inst->result_id(), builder);
205 } else {
206 // For version 2 format, write all three words
207 GenDebugOutputFieldCode(base_offset_id, kInstCompOutGlobalInvocationIdX,
208 x_inst->result_id(), builder);
209 GenDebugOutputFieldCode(base_offset_id, kInstCompOutGlobalInvocationIdY,
210 y_inst->result_id(), builder);
211 GenDebugOutputFieldCode(base_offset_id, kInstCompOutGlobalInvocationIdZ,
212 z_inst->result_id(), builder);
213 }
Chris Forbescc5697f2019-01-30 11:54:08 -0800214 } break;
215 case SpvExecutionModelGeometry: {
216 // Load and store PrimitiveId and InvocationId.
Ben Claytonb73b7602019-07-29 13:56:13 +0100217 GenBuiltinOutputCode(
218 context()->GetBuiltinInputVarId(SpvBuiltInPrimitiveId),
219 kInstGeomOutPrimitiveId, base_offset_id, builder);
220 GenBuiltinOutputCode(
221 context()->GetBuiltinInputVarId(SpvBuiltInInvocationId),
222 kInstGeomOutInvocationId, base_offset_id, builder);
Chris Forbescc5697f2019-01-30 11:54:08 -0800223 } break;
Ben Claytonb73b7602019-07-29 13:56:13 +0100224 case SpvExecutionModelTessellationControl: {
225 // Load and store InvocationId and PrimitiveId
226 GenBuiltinOutputCode(
227 context()->GetBuiltinInputVarId(SpvBuiltInInvocationId),
228 kInstTessCtlOutInvocationId, base_offset_id, builder);
229 GenBuiltinOutputCode(
230 context()->GetBuiltinInputVarId(SpvBuiltInPrimitiveId),
231 kInstTessCtlOutPrimitiveId, base_offset_id, builder);
232 } break;
Chris Forbescc5697f2019-01-30 11:54:08 -0800233 case SpvExecutionModelTessellationEvaluation: {
Ben Claytonb73b7602019-07-29 13:56:13 +0100234 if (version_ == 1) {
235 // For format version 1, load and store InvocationId.
236 GenBuiltinOutputCode(
237 context()->GetBuiltinInputVarId(SpvBuiltInInvocationId),
238 kInstTessOutInvocationId, base_offset_id, builder);
239 } else {
240 // For format version 2, load and store PrimitiveId and TessCoord.uv
241 GenBuiltinOutputCode(
242 context()->GetBuiltinInputVarId(SpvBuiltInPrimitiveId),
243 kInstTessEvalOutPrimitiveId, base_offset_id, builder);
244 uint32_t load_id = GenVarLoad(
245 context()->GetBuiltinInputVarId(SpvBuiltInTessCoord), builder);
Ben Claytond0f684e2019-08-30 22:36:08 +0100246 Instruction* uvec3_cast_inst =
247 builder->AddUnaryOp(GetVec3UintId(), SpvOpBitcast, load_id);
248 uint32_t uvec3_cast_id = uvec3_cast_inst->result_id();
Ben Claytonb73b7602019-07-29 13:56:13 +0100249 Instruction* u_inst = builder->AddIdLiteralOp(
Ben Claytond0f684e2019-08-30 22:36:08 +0100250 GetUintId(), SpvOpCompositeExtract, uvec3_cast_id, 0);
Ben Claytonb73b7602019-07-29 13:56:13 +0100251 Instruction* v_inst = builder->AddIdLiteralOp(
Ben Claytond0f684e2019-08-30 22:36:08 +0100252 GetUintId(), SpvOpCompositeExtract, uvec3_cast_id, 1);
Ben Claytonb73b7602019-07-29 13:56:13 +0100253 GenDebugOutputFieldCode(base_offset_id, kInstTessEvalOutTessCoordU,
254 u_inst->result_id(), builder);
255 GenDebugOutputFieldCode(base_offset_id, kInstTessEvalOutTessCoordV,
256 v_inst->result_id(), builder);
257 }
Chris Forbescc5697f2019-01-30 11:54:08 -0800258 } break;
259 case SpvExecutionModelFragment: {
260 // Load FragCoord and convert to Uint
Ben Claytonb73b7602019-07-29 13:56:13 +0100261 Instruction* frag_coord_inst = builder->AddUnaryOp(
262 GetVec4FloatId(), SpvOpLoad,
263 context()->GetBuiltinInputVarId(SpvBuiltInFragCoord));
Chris Forbescc5697f2019-01-30 11:54:08 -0800264 Instruction* uint_frag_coord_inst = builder->AddUnaryOp(
265 GetVec4UintId(), SpvOpBitcast, frag_coord_inst->result_id());
266 for (uint32_t u = 0; u < 2u; ++u)
267 GenFragCoordEltDebugOutputCode(
268 base_offset_id, uint_frag_coord_inst->result_id(), u, builder);
269 } break;
Ben Claytonb73b7602019-07-29 13:56:13 +0100270 case SpvExecutionModelRayGenerationNV:
271 case SpvExecutionModelIntersectionNV:
272 case SpvExecutionModelAnyHitNV:
273 case SpvExecutionModelClosestHitNV:
274 case SpvExecutionModelMissNV:
275 case SpvExecutionModelCallableNV: {
276 // Load and store LaunchIdNV.
277 uint32_t launch_id = GenVarLoad(
278 context()->GetBuiltinInputVarId(SpvBuiltInLaunchIdNV), builder);
279 Instruction* x_launch_inst = builder->AddIdLiteralOp(
280 GetUintId(), SpvOpCompositeExtract, launch_id, 0);
281 Instruction* y_launch_inst = builder->AddIdLiteralOp(
282 GetUintId(), SpvOpCompositeExtract, launch_id, 1);
283 Instruction* z_launch_inst = builder->AddIdLiteralOp(
284 GetUintId(), SpvOpCompositeExtract, launch_id, 2);
285 GenDebugOutputFieldCode(base_offset_id, kInstRayTracingOutLaunchIdX,
286 x_launch_inst->result_id(), builder);
287 GenDebugOutputFieldCode(base_offset_id, kInstRayTracingOutLaunchIdY,
288 y_launch_inst->result_id(), builder);
289 GenDebugOutputFieldCode(base_offset_id, kInstRayTracingOutLaunchIdZ,
290 z_launch_inst->result_id(), builder);
291 } break;
Chris Forbescc5697f2019-01-30 11:54:08 -0800292 default: { assert(false && "unsupported stage"); } break;
293 }
294}
295
296void InstrumentPass::GenDebugStreamWrite(
297 uint32_t instruction_idx, uint32_t stage_idx,
298 const std::vector<uint32_t>& validation_ids, InstructionBuilder* builder) {
299 // Call debug output function. Pass func_idx, instruction_idx and
300 // validation ids as args.
301 uint32_t val_id_cnt = static_cast<uint32_t>(validation_ids.size());
302 uint32_t output_func_id = GetStreamWriteFunctionId(stage_idx, val_id_cnt);
303 std::vector<uint32_t> args = {output_func_id,
304 builder->GetUintConstantId(instruction_idx)};
305 (void)args.insert(args.end(), validation_ids.begin(), validation_ids.end());
306 (void)builder->AddNaryOp(GetVoidId(), SpvOpFunctionCall, args);
307}
308
Ben Claytonb73b7602019-07-29 13:56:13 +0100309uint32_t InstrumentPass::GenDebugDirectRead(
310 const std::vector<uint32_t>& offset_ids, InstructionBuilder* builder) {
311 // Call debug input function. Pass func_idx and offset ids as args.
312 uint32_t off_id_cnt = static_cast<uint32_t>(offset_ids.size());
313 uint32_t input_func_id = GetDirectReadFunctionId(off_id_cnt);
314 std::vector<uint32_t> args = {input_func_id};
315 (void)args.insert(args.end(), offset_ids.begin(), offset_ids.end());
316 return builder->AddNaryOp(GetUintId(), SpvOpFunctionCall, args)->result_id();
317}
318
Chris Forbescc5697f2019-01-30 11:54:08 -0800319bool InstrumentPass::IsSameBlockOp(const Instruction* inst) const {
320 return inst->opcode() == SpvOpSampledImage || inst->opcode() == SpvOpImage;
321}
322
323void InstrumentPass::CloneSameBlockOps(
324 std::unique_ptr<Instruction>* inst,
325 std::unordered_map<uint32_t, uint32_t>* same_blk_post,
326 std::unordered_map<uint32_t, Instruction*>* same_blk_pre,
Ben Claytonb73b7602019-07-29 13:56:13 +0100327 BasicBlock* block_ptr) {
Chris Forbescc5697f2019-01-30 11:54:08 -0800328 (*inst)->ForEachInId(
329 [&same_blk_post, &same_blk_pre, &block_ptr, this](uint32_t* iid) {
330 const auto map_itr = (*same_blk_post).find(*iid);
331 if (map_itr == (*same_blk_post).end()) {
332 const auto map_itr2 = (*same_blk_pre).find(*iid);
333 if (map_itr2 != (*same_blk_pre).end()) {
334 // Clone pre-call same-block ops, map result id.
335 const Instruction* in_inst = map_itr2->second;
336 std::unique_ptr<Instruction> sb_inst(in_inst->Clone(context()));
337 CloneSameBlockOps(&sb_inst, same_blk_post, same_blk_pre, block_ptr);
338 const uint32_t rid = sb_inst->result_id();
339 const uint32_t nid = this->TakeNextId();
340 get_decoration_mgr()->CloneDecorations(rid, nid);
341 sb_inst->SetResultId(nid);
342 (*same_blk_post)[rid] = nid;
343 *iid = nid;
Ben Claytonb73b7602019-07-29 13:56:13 +0100344 block_ptr->AddInstruction(std::move(sb_inst));
Chris Forbescc5697f2019-01-30 11:54:08 -0800345 }
346 } else {
347 // Reset same-block op operand.
348 *iid = map_itr->second;
349 }
350 });
351}
352
353void InstrumentPass::UpdateSucceedingPhis(
354 std::vector<std::unique_ptr<BasicBlock>>& new_blocks) {
355 const auto first_blk = new_blocks.begin();
356 const auto last_blk = new_blocks.end() - 1;
357 const uint32_t first_id = (*first_blk)->id();
358 const uint32_t last_id = (*last_blk)->id();
359 const BasicBlock& const_last_block = *last_blk->get();
360 const_last_block.ForEachSuccessorLabel(
361 [&first_id, &last_id, this](const uint32_t succ) {
362 BasicBlock* sbp = this->id2block_[succ];
363 sbp->ForEachPhiInst([&first_id, &last_id, this](Instruction* phi) {
364 bool changed = false;
365 phi->ForEachInId([&first_id, &last_id, &changed](uint32_t* id) {
366 if (*id == first_id) {
367 *id = last_id;
368 changed = true;
369 }
370 });
371 if (changed) get_def_use_mgr()->AnalyzeInstUse(phi);
372 });
373 });
374}
375
Ben Claytond0f684e2019-08-30 22:36:08 +0100376uint32_t InstrumentPass::GetOutputBufferPtrId() {
377 if (output_buffer_ptr_id_ == 0) {
378 output_buffer_ptr_id_ = context()->get_type_mgr()->FindPointerToType(
Chris Forbescc5697f2019-01-30 11:54:08 -0800379 GetUintId(), SpvStorageClassStorageBuffer);
380 }
Ben Claytond0f684e2019-08-30 22:36:08 +0100381 return output_buffer_ptr_id_;
382}
383
384uint32_t InstrumentPass::GetInputBufferTypeId() {
385 return (validation_id_ == kInstValidationIdBuffAddr) ? GetUint64Id()
386 : GetUintId();
387}
388
389uint32_t InstrumentPass::GetInputBufferPtrId() {
390 if (input_buffer_ptr_id_ == 0) {
391 input_buffer_ptr_id_ = context()->get_type_mgr()->FindPointerToType(
392 GetInputBufferTypeId(), SpvStorageClassStorageBuffer);
393 }
394 return input_buffer_ptr_id_;
Chris Forbescc5697f2019-01-30 11:54:08 -0800395}
396
397uint32_t InstrumentPass::GetOutputBufferBinding() {
398 switch (validation_id_) {
399 case kInstValidationIdBindless:
400 return kDebugOutputBindingStream;
Ben Claytond0f684e2019-08-30 22:36:08 +0100401 case kInstValidationIdBuffAddr:
402 return kDebugOutputBindingStream;
Chris Forbescc5697f2019-01-30 11:54:08 -0800403 default:
404 assert(false && "unexpected validation id");
405 }
406 return 0;
407}
408
Ben Claytonb73b7602019-07-29 13:56:13 +0100409uint32_t InstrumentPass::GetInputBufferBinding() {
410 switch (validation_id_) {
411 case kInstValidationIdBindless:
412 return kDebugInputBindingBindless;
Ben Claytond0f684e2019-08-30 22:36:08 +0100413 case kInstValidationIdBuffAddr:
414 return kDebugInputBindingBuffAddr;
Ben Claytonb73b7602019-07-29 13:56:13 +0100415 default:
416 assert(false && "unexpected validation id");
417 }
418 return 0;
419}
420
Ben Claytond0f684e2019-08-30 22:36:08 +0100421analysis::Type* InstrumentPass::GetUintXRuntimeArrayType(
422 uint32_t width, analysis::Type** rarr_ty) {
423 if (*rarr_ty == nullptr) {
424 analysis::DecorationManager* deco_mgr = get_decoration_mgr();
425 analysis::TypeManager* type_mgr = context()->get_type_mgr();
426 analysis::Integer uint_ty(width, false);
Ben Claytonb73b7602019-07-29 13:56:13 +0100427 analysis::Type* reg_uint_ty = type_mgr->GetRegisteredType(&uint_ty);
428 analysis::RuntimeArray uint_rarr_ty_tmp(reg_uint_ty);
Ben Claytond0f684e2019-08-30 22:36:08 +0100429 *rarr_ty = type_mgr->GetRegisteredType(&uint_rarr_ty_tmp);
430 uint32_t uint_arr_ty_id = type_mgr->GetTypeInstruction(*rarr_ty);
Ben Claytonb73b7602019-07-29 13:56:13 +0100431 // By the Vulkan spec, a pre-existing RuntimeArray of uint must be part of
432 // a block, and will therefore be decorated with an ArrayStride. Therefore
433 // the undecorated type returned here will not be pre-existing and can
434 // safely be decorated. Since this type is now decorated, it is out of
435 // sync with the TypeManager and therefore the TypeManager must be
436 // invalidated after this pass.
437 assert(context()->get_def_use_mgr()->NumUses(uint_arr_ty_id) == 0 &&
438 "used RuntimeArray type returned");
Ben Claytond0f684e2019-08-30 22:36:08 +0100439 deco_mgr->AddDecorationVal(uint_arr_ty_id, SpvDecorationArrayStride,
440 width / 8u);
Ben Claytonb73b7602019-07-29 13:56:13 +0100441 }
Ben Claytond0f684e2019-08-30 22:36:08 +0100442 return *rarr_ty;
443}
444
445analysis::Type* InstrumentPass::GetUintRuntimeArrayType(uint32_t width) {
446 analysis::Type** rarr_ty =
447 (width == 64) ? &uint64_rarr_ty_ : &uint32_rarr_ty_;
448 return GetUintXRuntimeArrayType(width, rarr_ty);
Ben Claytonb73b7602019-07-29 13:56:13 +0100449}
450
451void InstrumentPass::AddStorageBufferExt() {
452 if (storage_buffer_ext_defined_) return;
453 if (!get_feature_mgr()->HasExtension(kSPV_KHR_storage_buffer_storage_class)) {
Ben Claytond0f684e2019-08-30 22:36:08 +0100454 context()->AddExtension("SPV_KHR_storage_buffer_storage_class");
Ben Claytonb73b7602019-07-29 13:56:13 +0100455 }
456 storage_buffer_ext_defined_ = true;
457}
458
Chris Forbescc5697f2019-01-30 11:54:08 -0800459// Return id for output buffer
460uint32_t InstrumentPass::GetOutputBufferId() {
461 if (output_buffer_id_ == 0) {
462 // If not created yet, create one
463 analysis::DecorationManager* deco_mgr = get_decoration_mgr();
464 analysis::TypeManager* type_mgr = context()->get_type_mgr();
Ben Claytond0f684e2019-08-30 22:36:08 +0100465 analysis::Type* reg_uint_rarr_ty = GetUintRuntimeArrayType(32);
Chris Forbescc5697f2019-01-30 11:54:08 -0800466 analysis::Integer uint_ty(32, false);
467 analysis::Type* reg_uint_ty = type_mgr->GetRegisteredType(&uint_ty);
Ben Claytonb73b7602019-07-29 13:56:13 +0100468 analysis::Struct buf_ty({reg_uint_ty, reg_uint_rarr_ty});
469 analysis::Type* reg_buf_ty = type_mgr->GetRegisteredType(&buf_ty);
470 uint32_t obufTyId = type_mgr->GetTypeInstruction(reg_buf_ty);
471 // By the Vulkan spec, a pre-existing struct containing a RuntimeArray
472 // must be a block, and will therefore be decorated with Block. Therefore
473 // the undecorated type returned here will not be pre-existing and can
474 // safely be decorated. Since this type is now decorated, it is out of
475 // sync with the TypeManager and therefore the TypeManager must be
476 // invalidated after this pass.
477 assert(context()->get_def_use_mgr()->NumUses(obufTyId) == 0 &&
478 "used struct type returned");
Chris Forbescc5697f2019-01-30 11:54:08 -0800479 deco_mgr->AddDecoration(obufTyId, SpvDecorationBlock);
480 deco_mgr->AddMemberDecoration(obufTyId, kDebugOutputSizeOffset,
481 SpvDecorationOffset, 0);
482 deco_mgr->AddMemberDecoration(obufTyId, kDebugOutputDataOffset,
483 SpvDecorationOffset, 4);
484 uint32_t obufTyPtrId_ =
485 type_mgr->FindPointerToType(obufTyId, SpvStorageClassStorageBuffer);
486 output_buffer_id_ = TakeNextId();
487 std::unique_ptr<Instruction> newVarOp(new Instruction(
488 context(), SpvOpVariable, obufTyPtrId_, output_buffer_id_,
489 {{spv_operand_type_t::SPV_OPERAND_TYPE_LITERAL_INTEGER,
490 {SpvStorageClassStorageBuffer}}}));
491 context()->AddGlobalValue(std::move(newVarOp));
492 deco_mgr->AddDecorationVal(output_buffer_id_, SpvDecorationDescriptorSet,
493 desc_set_);
494 deco_mgr->AddDecorationVal(output_buffer_id_, SpvDecorationBinding,
495 GetOutputBufferBinding());
Ben Claytonb73b7602019-07-29 13:56:13 +0100496 AddStorageBufferExt();
497 if (get_module()->version() >= SPV_SPIRV_VERSION_WORD(1, 4)) {
498 // Add the new buffer to all entry points.
499 for (auto& entry : get_module()->entry_points()) {
500 entry.AddOperand({SPV_OPERAND_TYPE_ID, {output_buffer_id_}});
501 context()->AnalyzeUses(&entry);
502 }
Chris Forbescc5697f2019-01-30 11:54:08 -0800503 }
504 }
505 return output_buffer_id_;
506}
507
Ben Claytonb73b7602019-07-29 13:56:13 +0100508uint32_t InstrumentPass::GetInputBufferId() {
509 if (input_buffer_id_ == 0) {
510 // If not created yet, create one
511 analysis::DecorationManager* deco_mgr = get_decoration_mgr();
512 analysis::TypeManager* type_mgr = context()->get_type_mgr();
Ben Claytond0f684e2019-08-30 22:36:08 +0100513 uint32_t width = (validation_id_ == kInstValidationIdBuffAddr) ? 64u : 32u;
514 analysis::Type* reg_uint_rarr_ty = GetUintRuntimeArrayType(width);
Ben Claytonb73b7602019-07-29 13:56:13 +0100515 analysis::Struct buf_ty({reg_uint_rarr_ty});
516 analysis::Type* reg_buf_ty = type_mgr->GetRegisteredType(&buf_ty);
517 uint32_t ibufTyId = type_mgr->GetTypeInstruction(reg_buf_ty);
518 // By the Vulkan spec, a pre-existing struct containing a RuntimeArray
519 // must be a block, and will therefore be decorated with Block. Therefore
520 // the undecorated type returned here will not be pre-existing and can
521 // safely be decorated. Since this type is now decorated, it is out of
522 // sync with the TypeManager and therefore the TypeManager must be
523 // invalidated after this pass.
524 assert(context()->get_def_use_mgr()->NumUses(ibufTyId) == 0 &&
525 "used struct type returned");
526 deco_mgr->AddDecoration(ibufTyId, SpvDecorationBlock);
527 deco_mgr->AddMemberDecoration(ibufTyId, 0, SpvDecorationOffset, 0);
528 uint32_t ibufTyPtrId_ =
529 type_mgr->FindPointerToType(ibufTyId, SpvStorageClassStorageBuffer);
530 input_buffer_id_ = TakeNextId();
531 std::unique_ptr<Instruction> newVarOp(new Instruction(
532 context(), SpvOpVariable, ibufTyPtrId_, input_buffer_id_,
533 {{spv_operand_type_t::SPV_OPERAND_TYPE_LITERAL_INTEGER,
534 {SpvStorageClassStorageBuffer}}}));
535 context()->AddGlobalValue(std::move(newVarOp));
536 deco_mgr->AddDecorationVal(input_buffer_id_, SpvDecorationDescriptorSet,
537 desc_set_);
538 deco_mgr->AddDecorationVal(input_buffer_id_, SpvDecorationBinding,
539 GetInputBufferBinding());
540 AddStorageBufferExt();
541 if (get_module()->version() >= SPV_SPIRV_VERSION_WORD(1, 4)) {
542 // Add the new buffer to all entry points.
543 for (auto& entry : get_module()->entry_points()) {
544 entry.AddOperand({SPV_OPERAND_TYPE_ID, {input_buffer_id_}});
545 context()->AnalyzeUses(&entry);
546 }
547 }
548 }
549 return input_buffer_id_;
550}
551
Chris Forbescc5697f2019-01-30 11:54:08 -0800552uint32_t InstrumentPass::GetVec4FloatId() {
553 if (v4float_id_ == 0) {
554 analysis::TypeManager* type_mgr = context()->get_type_mgr();
555 analysis::Float float_ty(32);
556 analysis::Type* reg_float_ty = type_mgr->GetRegisteredType(&float_ty);
557 analysis::Vector v4float_ty(reg_float_ty, 4);
558 analysis::Type* reg_v4float_ty = type_mgr->GetRegisteredType(&v4float_ty);
559 v4float_id_ = type_mgr->GetTypeInstruction(reg_v4float_ty);
560 }
561 return v4float_id_;
562}
563
564uint32_t InstrumentPass::GetUintId() {
565 if (uint_id_ == 0) {
566 analysis::TypeManager* type_mgr = context()->get_type_mgr();
567 analysis::Integer uint_ty(32, false);
568 analysis::Type* reg_uint_ty = type_mgr->GetRegisteredType(&uint_ty);
569 uint_id_ = type_mgr->GetTypeInstruction(reg_uint_ty);
570 }
571 return uint_id_;
572}
573
Ben Claytond0f684e2019-08-30 22:36:08 +0100574uint32_t InstrumentPass::GetUint64Id() {
575 if (uint64_id_ == 0) {
Chris Forbescc5697f2019-01-30 11:54:08 -0800576 analysis::TypeManager* type_mgr = context()->get_type_mgr();
Ben Claytond0f684e2019-08-30 22:36:08 +0100577 analysis::Integer uint64_ty(64, false);
578 analysis::Type* reg_uint64_ty = type_mgr->GetRegisteredType(&uint64_ty);
579 uint64_id_ = type_mgr->GetTypeInstruction(reg_uint64_ty);
Chris Forbescc5697f2019-01-30 11:54:08 -0800580 }
Ben Claytond0f684e2019-08-30 22:36:08 +0100581 return uint64_id_;
582}
583
584uint32_t InstrumentPass::GetVecUintId(uint32_t len) {
585 analysis::TypeManager* type_mgr = context()->get_type_mgr();
586 analysis::Integer uint_ty(32, false);
587 analysis::Type* reg_uint_ty = type_mgr->GetRegisteredType(&uint_ty);
588 analysis::Vector v_uint_ty(reg_uint_ty, len);
589 analysis::Type* reg_v_uint_ty = type_mgr->GetRegisteredType(&v_uint_ty);
590 uint32_t v_uint_id = type_mgr->GetTypeInstruction(reg_v_uint_ty);
591 return v_uint_id;
592}
593
594uint32_t InstrumentPass::GetVec4UintId() {
595 if (v4uint_id_ == 0) v4uint_id_ = GetVecUintId(4u);
Chris Forbescc5697f2019-01-30 11:54:08 -0800596 return v4uint_id_;
597}
598
Ben Claytond0f684e2019-08-30 22:36:08 +0100599uint32_t InstrumentPass::GetVec3UintId() {
600 if (v3uint_id_ == 0) v3uint_id_ = GetVecUintId(3u);
601 return v3uint_id_;
602}
603
Chris Forbescc5697f2019-01-30 11:54:08 -0800604uint32_t InstrumentPass::GetBoolId() {
605 if (bool_id_ == 0) {
606 analysis::TypeManager* type_mgr = context()->get_type_mgr();
607 analysis::Bool bool_ty;
608 analysis::Type* reg_bool_ty = type_mgr->GetRegisteredType(&bool_ty);
609 bool_id_ = type_mgr->GetTypeInstruction(reg_bool_ty);
610 }
611 return bool_id_;
612}
613
614uint32_t InstrumentPass::GetVoidId() {
615 if (void_id_ == 0) {
616 analysis::TypeManager* type_mgr = context()->get_type_mgr();
617 analysis::Void void_ty;
618 analysis::Type* reg_void_ty = type_mgr->GetRegisteredType(&void_ty);
619 void_id_ = type_mgr->GetTypeInstruction(reg_void_ty);
620 }
621 return void_id_;
622}
623
624uint32_t InstrumentPass::GetStreamWriteFunctionId(uint32_t stage_idx,
625 uint32_t val_spec_param_cnt) {
626 // Total param count is common params plus validation-specific
627 // params
628 uint32_t param_cnt = kInstCommonParamCnt + val_spec_param_cnt;
629 if (output_func_id_ == 0) {
630 // Create function
631 output_func_id_ = TakeNextId();
632 analysis::TypeManager* type_mgr = context()->get_type_mgr();
633 std::vector<const analysis::Type*> param_types;
634 for (uint32_t c = 0; c < param_cnt; ++c)
635 param_types.push_back(type_mgr->GetType(GetUintId()));
636 analysis::Function func_ty(type_mgr->GetType(GetVoidId()), param_types);
637 analysis::Type* reg_func_ty = type_mgr->GetRegisteredType(&func_ty);
638 std::unique_ptr<Instruction> func_inst(new Instruction(
639 get_module()->context(), SpvOpFunction, GetVoidId(), output_func_id_,
640 {{spv_operand_type_t::SPV_OPERAND_TYPE_LITERAL_INTEGER,
641 {SpvFunctionControlMaskNone}},
642 {spv_operand_type_t::SPV_OPERAND_TYPE_ID,
643 {type_mgr->GetTypeInstruction(reg_func_ty)}}}));
644 get_def_use_mgr()->AnalyzeInstDefUse(&*func_inst);
645 std::unique_ptr<Function> output_func =
646 MakeUnique<Function>(std::move(func_inst));
647 // Add parameters
648 std::vector<uint32_t> param_vec;
649 for (uint32_t c = 0; c < param_cnt; ++c) {
650 uint32_t pid = TakeNextId();
651 param_vec.push_back(pid);
652 std::unique_ptr<Instruction> param_inst(
653 new Instruction(get_module()->context(), SpvOpFunctionParameter,
654 GetUintId(), pid, {}));
655 get_def_use_mgr()->AnalyzeInstDefUse(&*param_inst);
656 output_func->AddParameter(std::move(param_inst));
657 }
658 // Create first block
659 uint32_t test_blk_id = TakeNextId();
660 std::unique_ptr<Instruction> test_label(NewLabel(test_blk_id));
661 std::unique_ptr<BasicBlock> new_blk_ptr =
662 MakeUnique<BasicBlock>(std::move(test_label));
663 InstructionBuilder builder(
664 context(), &*new_blk_ptr,
665 IRContext::kAnalysisDefUse | IRContext::kAnalysisInstrToBlockMapping);
666 // Gen test if debug output buffer size will not be exceeded.
Ben Claytonb73b7602019-07-29 13:56:13 +0100667 uint32_t val_spec_offset =
668 (version_ == 1) ? kInstStageOutCnt : kInst2StageOutCnt;
669 uint32_t obuf_record_sz = val_spec_offset + val_spec_param_cnt;
Chris Forbescc5697f2019-01-30 11:54:08 -0800670 uint32_t buf_id = GetOutputBufferId();
Ben Claytond0f684e2019-08-30 22:36:08 +0100671 uint32_t buf_uint_ptr_id = GetOutputBufferPtrId();
Chris Forbescc5697f2019-01-30 11:54:08 -0800672 Instruction* obuf_curr_sz_ac_inst =
673 builder.AddBinaryOp(buf_uint_ptr_id, SpvOpAccessChain, buf_id,
674 builder.GetUintConstantId(kDebugOutputSizeOffset));
675 // Fetch the current debug buffer written size atomically, adding the
676 // size of the record to be written.
677 uint32_t obuf_record_sz_id = builder.GetUintConstantId(obuf_record_sz);
678 uint32_t mask_none_id = builder.GetUintConstantId(SpvMemoryAccessMaskNone);
679 uint32_t scope_invok_id = builder.GetUintConstantId(SpvScopeInvocation);
680 Instruction* obuf_curr_sz_inst = builder.AddQuadOp(
681 GetUintId(), SpvOpAtomicIAdd, obuf_curr_sz_ac_inst->result_id(),
682 scope_invok_id, mask_none_id, obuf_record_sz_id);
683 uint32_t obuf_curr_sz_id = obuf_curr_sz_inst->result_id();
684 // Compute new written size
685 Instruction* obuf_new_sz_inst =
686 builder.AddBinaryOp(GetUintId(), SpvOpIAdd, obuf_curr_sz_id,
687 builder.GetUintConstantId(obuf_record_sz));
688 // Fetch the data bound
689 Instruction* obuf_bnd_inst =
690 builder.AddIdLiteralOp(GetUintId(), SpvOpArrayLength,
691 GetOutputBufferId(), kDebugOutputDataOffset);
692 // Test that new written size is less than or equal to debug output
693 // data bound
694 Instruction* obuf_safe_inst = builder.AddBinaryOp(
695 GetBoolId(), SpvOpULessThanEqual, obuf_new_sz_inst->result_id(),
696 obuf_bnd_inst->result_id());
697 uint32_t merge_blk_id = TakeNextId();
698 uint32_t write_blk_id = TakeNextId();
699 std::unique_ptr<Instruction> merge_label(NewLabel(merge_blk_id));
700 std::unique_ptr<Instruction> write_label(NewLabel(write_blk_id));
701 (void)builder.AddConditionalBranch(obuf_safe_inst->result_id(),
702 write_blk_id, merge_blk_id, merge_blk_id,
703 SpvSelectionControlMaskNone);
704 // Close safety test block and gen write block
705 new_blk_ptr->SetParent(&*output_func);
706 output_func->AddBasicBlock(std::move(new_blk_ptr));
707 new_blk_ptr = MakeUnique<BasicBlock>(std::move(write_label));
708 builder.SetInsertPoint(&*new_blk_ptr);
709 // Generate common and stage-specific debug record members
710 GenCommonStreamWriteCode(obuf_record_sz, param_vec[kInstCommonParamInstIdx],
711 stage_idx, obuf_curr_sz_id, &builder);
712 GenStageStreamWriteCode(stage_idx, obuf_curr_sz_id, &builder);
713 // Gen writes of validation specific data
714 for (uint32_t i = 0; i < val_spec_param_cnt; ++i) {
Ben Claytonb73b7602019-07-29 13:56:13 +0100715 GenDebugOutputFieldCode(obuf_curr_sz_id, val_spec_offset + i,
Chris Forbescc5697f2019-01-30 11:54:08 -0800716 param_vec[kInstCommonParamCnt + i], &builder);
717 }
718 // Close write block and gen merge block
719 (void)builder.AddBranch(merge_blk_id);
720 new_blk_ptr->SetParent(&*output_func);
721 output_func->AddBasicBlock(std::move(new_blk_ptr));
722 new_blk_ptr = MakeUnique<BasicBlock>(std::move(merge_label));
723 builder.SetInsertPoint(&*new_blk_ptr);
724 // Close merge block and function and add function to module
725 (void)builder.AddNullaryOp(0, SpvOpReturn);
726 new_blk_ptr->SetParent(&*output_func);
727 output_func->AddBasicBlock(std::move(new_blk_ptr));
728 std::unique_ptr<Instruction> func_end_inst(
729 new Instruction(get_module()->context(), SpvOpFunctionEnd, 0, 0, {}));
730 get_def_use_mgr()->AnalyzeInstDefUse(&*func_end_inst);
731 output_func->SetFunctionEnd(std::move(func_end_inst));
732 context()->AddFunction(std::move(output_func));
733 output_func_param_cnt_ = param_cnt;
734 }
735 assert(param_cnt == output_func_param_cnt_ && "bad arg count");
736 return output_func_id_;
737}
738
Ben Claytonb73b7602019-07-29 13:56:13 +0100739uint32_t InstrumentPass::GetDirectReadFunctionId(uint32_t param_cnt) {
740 uint32_t func_id = param2input_func_id_[param_cnt];
741 if (func_id != 0) return func_id;
Ben Claytond0f684e2019-08-30 22:36:08 +0100742 // Create input function for param_cnt.
Ben Claytonb73b7602019-07-29 13:56:13 +0100743 func_id = TakeNextId();
744 analysis::TypeManager* type_mgr = context()->get_type_mgr();
745 std::vector<const analysis::Type*> param_types;
746 for (uint32_t c = 0; c < param_cnt; ++c)
747 param_types.push_back(type_mgr->GetType(GetUintId()));
Ben Claytond0f684e2019-08-30 22:36:08 +0100748 uint32_t ibuf_type_id = GetInputBufferTypeId();
749 analysis::Function func_ty(type_mgr->GetType(ibuf_type_id), param_types);
Ben Claytonb73b7602019-07-29 13:56:13 +0100750 analysis::Type* reg_func_ty = type_mgr->GetRegisteredType(&func_ty);
751 std::unique_ptr<Instruction> func_inst(new Instruction(
Ben Claytond0f684e2019-08-30 22:36:08 +0100752 get_module()->context(), SpvOpFunction, ibuf_type_id, func_id,
Ben Claytonb73b7602019-07-29 13:56:13 +0100753 {{spv_operand_type_t::SPV_OPERAND_TYPE_LITERAL_INTEGER,
754 {SpvFunctionControlMaskNone}},
755 {spv_operand_type_t::SPV_OPERAND_TYPE_ID,
756 {type_mgr->GetTypeInstruction(reg_func_ty)}}}));
757 get_def_use_mgr()->AnalyzeInstDefUse(&*func_inst);
758 std::unique_ptr<Function> input_func =
759 MakeUnique<Function>(std::move(func_inst));
760 // Add parameters
761 std::vector<uint32_t> param_vec;
762 for (uint32_t c = 0; c < param_cnt; ++c) {
763 uint32_t pid = TakeNextId();
764 param_vec.push_back(pid);
765 std::unique_ptr<Instruction> param_inst(new Instruction(
766 get_module()->context(), SpvOpFunctionParameter, GetUintId(), pid, {}));
767 get_def_use_mgr()->AnalyzeInstDefUse(&*param_inst);
768 input_func->AddParameter(std::move(param_inst));
769 }
770 // Create block
771 uint32_t blk_id = TakeNextId();
772 std::unique_ptr<Instruction> blk_label(NewLabel(blk_id));
773 std::unique_ptr<BasicBlock> new_blk_ptr =
774 MakeUnique<BasicBlock>(std::move(blk_label));
775 InstructionBuilder builder(
776 context(), &*new_blk_ptr,
777 IRContext::kAnalysisDefUse | IRContext::kAnalysisInstrToBlockMapping);
778 // For each offset parameter, generate new offset with parameter, adding last
779 // loaded value if it exists, and load value from input buffer at new offset.
780 // Return last loaded value.
781 uint32_t buf_id = GetInputBufferId();
Ben Claytond0f684e2019-08-30 22:36:08 +0100782 uint32_t buf_ptr_id = GetInputBufferPtrId();
Ben Claytonb73b7602019-07-29 13:56:13 +0100783 uint32_t last_value_id = 0;
784 for (uint32_t p = 0; p < param_cnt; ++p) {
785 uint32_t offset_id;
786 if (p == 0) {
787 offset_id = param_vec[0];
788 } else {
Ben Claytond0f684e2019-08-30 22:36:08 +0100789 if (ibuf_type_id != GetUintId()) {
790 Instruction* ucvt_inst =
791 builder.AddUnaryOp(GetUintId(), SpvOpUConvert, last_value_id);
792 last_value_id = ucvt_inst->result_id();
793 }
Ben Claytonb73b7602019-07-29 13:56:13 +0100794 Instruction* offset_inst = builder.AddBinaryOp(
795 GetUintId(), SpvOpIAdd, last_value_id, param_vec[p]);
796 offset_id = offset_inst->result_id();
797 }
798 Instruction* ac_inst = builder.AddTernaryOp(
Ben Claytond0f684e2019-08-30 22:36:08 +0100799 buf_ptr_id, SpvOpAccessChain, buf_id,
Ben Claytonb73b7602019-07-29 13:56:13 +0100800 builder.GetUintConstantId(kDebugInputDataOffset), offset_id);
801 Instruction* load_inst =
Ben Claytond0f684e2019-08-30 22:36:08 +0100802 builder.AddUnaryOp(ibuf_type_id, SpvOpLoad, ac_inst->result_id());
Ben Claytonb73b7602019-07-29 13:56:13 +0100803 last_value_id = load_inst->result_id();
804 }
805 (void)builder.AddInstruction(MakeUnique<Instruction>(
806 context(), SpvOpReturnValue, 0, 0,
807 std::initializer_list<Operand>{{SPV_OPERAND_TYPE_ID, {last_value_id}}}));
808 // Close block and function and add function to module
809 new_blk_ptr->SetParent(&*input_func);
810 input_func->AddBasicBlock(std::move(new_blk_ptr));
811 std::unique_ptr<Instruction> func_end_inst(
812 new Instruction(get_module()->context(), SpvOpFunctionEnd, 0, 0, {}));
813 get_def_use_mgr()->AnalyzeInstDefUse(&*func_end_inst);
814 input_func->SetFunctionEnd(std::move(func_end_inst));
815 context()->AddFunction(std::move(input_func));
816 param2input_func_id_[param_cnt] = func_id;
817 return func_id;
818}
819
Chris Forbescc5697f2019-01-30 11:54:08 -0800820bool InstrumentPass::InstrumentFunction(Function* func, uint32_t stage_idx,
821 InstProcessFunction& pfn) {
822 bool modified = false;
823 // Compute function index
824 uint32_t function_idx = 0;
825 for (auto fii = get_module()->begin(); fii != get_module()->end(); ++fii) {
826 if (&*fii == func) break;
827 ++function_idx;
828 }
829 std::vector<std::unique_ptr<BasicBlock>> new_blks;
Chris Forbescc5697f2019-01-30 11:54:08 -0800830 // Using block iterators here because of block erasures and insertions.
831 for (auto bi = func->begin(); bi != func->end(); ++bi) {
Ben Claytonb73b7602019-07-29 13:56:13 +0100832 for (auto ii = bi->begin(); ii != bi->end();) {
Chris Forbescc5697f2019-01-30 11:54:08 -0800833 // Generate instrumentation if warranted
Ben Claytonb73b7602019-07-29 13:56:13 +0100834 pfn(ii, bi, stage_idx, &new_blks);
Chris Forbescc5697f2019-01-30 11:54:08 -0800835 if (new_blks.size() == 0) {
836 ++ii;
837 continue;
838 }
Ben Claytonb73b7602019-07-29 13:56:13 +0100839 // Add new blocks to label id map
840 for (auto& blk : new_blks) id2block_[blk->id()] = &*blk;
Chris Forbescc5697f2019-01-30 11:54:08 -0800841 // If there are new blocks we know there will always be two or
842 // more, so update succeeding phis with label of new last block.
843 size_t newBlocksSize = new_blks.size();
844 assert(newBlocksSize > 1);
845 UpdateSucceedingPhis(new_blks);
846 // Replace original block with new block(s)
847 bi = bi.Erase();
848 for (auto& bb : new_blks) {
849 bb->SetParent(func);
850 }
851 bi = bi.InsertBefore(&new_blks);
852 // Reset block iterator to last new block
853 for (size_t i = 0; i < newBlocksSize - 1; i++) ++bi;
854 modified = true;
855 // Restart instrumenting at beginning of last new block,
856 // but skip over any new phi or copy instruction.
857 ii = bi->begin();
858 if (ii->opcode() == SpvOpPhi || ii->opcode() == SpvOpCopyObject) ++ii;
859 new_blks.clear();
860 }
861 }
862 return modified;
863}
864
865bool InstrumentPass::InstProcessCallTreeFromRoots(InstProcessFunction& pfn,
866 std::queue<uint32_t>* roots,
867 uint32_t stage_idx) {
868 bool modified = false;
869 std::unordered_set<uint32_t> done;
Ben Claytonb73b7602019-07-29 13:56:13 +0100870 // Don't process input and output functions
871 for (auto& ifn : param2input_func_id_) done.insert(ifn.second);
872 if (output_func_id_ != 0) done.insert(output_func_id_);
Chris Forbescc5697f2019-01-30 11:54:08 -0800873 // Process all functions from roots
874 while (!roots->empty()) {
875 const uint32_t fi = roots->front();
876 roots->pop();
877 if (done.insert(fi).second) {
878 Function* fn = id2function_.at(fi);
879 // Add calls first so we don't add new output function
880 context()->AddCalls(fn, roots);
881 modified = InstrumentFunction(fn, stage_idx, pfn) || modified;
882 }
883 }
884 return modified;
885}
886
887bool InstrumentPass::InstProcessEntryPointCallTree(InstProcessFunction& pfn) {
888 // Make sure all entry points have the same execution model. Do not
889 // instrument if they do not.
890 // TODO(greg-lunarg): Handle mixed stages. Technically, a shader module
891 // can contain entry points with different execution models, although
892 // such modules will likely be rare as GLSL and HLSL are geared toward
893 // one model per module. In such cases we will need
894 // to clone any functions which are in the call trees of entrypoints
895 // with differing execution models.
896 uint32_t ecnt = 0;
897 uint32_t stage = SpvExecutionModelMax;
898 for (auto& e : get_module()->entry_points()) {
899 if (ecnt == 0)
900 stage = e.GetSingleWordInOperand(kEntryPointExecutionModelInIdx);
901 else if (e.GetSingleWordInOperand(kEntryPointExecutionModelInIdx) != stage)
902 return false;
903 ++ecnt;
904 }
905 // Only supporting vertex, fragment and compute shaders at the moment.
906 // TODO(greg-lunarg): Handle all stages.
907 if (stage != SpvExecutionModelVertex && stage != SpvExecutionModelFragment &&
908 stage != SpvExecutionModelGeometry &&
909 stage != SpvExecutionModelGLCompute &&
910 stage != SpvExecutionModelTessellationControl &&
Ben Claytonb73b7602019-07-29 13:56:13 +0100911 stage != SpvExecutionModelTessellationEvaluation &&
912 stage != SpvExecutionModelRayGenerationNV &&
913 stage != SpvExecutionModelIntersectionNV &&
914 stage != SpvExecutionModelAnyHitNV &&
915 stage != SpvExecutionModelClosestHitNV &&
916 stage != SpvExecutionModelMissNV && stage != SpvExecutionModelCallableNV)
Chris Forbescc5697f2019-01-30 11:54:08 -0800917 return false;
918 // Add together the roots of all entry points
919 std::queue<uint32_t> roots;
920 for (auto& e : get_module()->entry_points()) {
921 roots.push(e.GetSingleWordInOperand(kEntryPointFunctionIdInIdx));
922 }
923 bool modified = InstProcessCallTreeFromRoots(pfn, &roots, stage);
924 return modified;
925}
926
927void InstrumentPass::InitializeInstrument() {
928 output_buffer_id_ = 0;
Ben Claytond0f684e2019-08-30 22:36:08 +0100929 output_buffer_ptr_id_ = 0;
930 input_buffer_ptr_id_ = 0;
Chris Forbescc5697f2019-01-30 11:54:08 -0800931 output_func_id_ = 0;
932 output_func_param_cnt_ = 0;
Ben Claytonb73b7602019-07-29 13:56:13 +0100933 input_buffer_id_ = 0;
Chris Forbescc5697f2019-01-30 11:54:08 -0800934 v4float_id_ = 0;
935 uint_id_ = 0;
Ben Claytond0f684e2019-08-30 22:36:08 +0100936 uint64_id_ = 0;
Chris Forbescc5697f2019-01-30 11:54:08 -0800937 v4uint_id_ = 0;
Ben Claytond0f684e2019-08-30 22:36:08 +0100938 v3uint_id_ = 0;
Chris Forbescc5697f2019-01-30 11:54:08 -0800939 bool_id_ = 0;
940 void_id_ = 0;
Ben Claytonb73b7602019-07-29 13:56:13 +0100941 storage_buffer_ext_defined_ = false;
Ben Claytond0f684e2019-08-30 22:36:08 +0100942 uint32_rarr_ty_ = nullptr;
943 uint64_rarr_ty_ = nullptr;
Chris Forbescc5697f2019-01-30 11:54:08 -0800944
945 // clear collections
946 id2function_.clear();
947 id2block_.clear();
948
949 // Initialize function and block maps.
950 for (auto& fn : *get_module()) {
951 id2function_[fn.result_id()] = &fn;
952 for (auto& blk : fn) {
953 id2block_[blk.id()] = &blk;
954 }
955 }
956
Ben Claytonb73b7602019-07-29 13:56:13 +0100957 // Remember original instruction offsets
958 uint32_t module_offset = 0;
Chris Forbescc5697f2019-01-30 11:54:08 -0800959 Module* module = get_module();
960 for (auto& i : context()->capabilities()) {
961 (void)i;
Ben Claytonb73b7602019-07-29 13:56:13 +0100962 ++module_offset;
Chris Forbescc5697f2019-01-30 11:54:08 -0800963 }
964 for (auto& i : module->extensions()) {
965 (void)i;
Ben Claytonb73b7602019-07-29 13:56:13 +0100966 ++module_offset;
Chris Forbescc5697f2019-01-30 11:54:08 -0800967 }
968 for (auto& i : module->ext_inst_imports()) {
969 (void)i;
Ben Claytonb73b7602019-07-29 13:56:13 +0100970 ++module_offset;
Chris Forbescc5697f2019-01-30 11:54:08 -0800971 }
Ben Claytonb73b7602019-07-29 13:56:13 +0100972 ++module_offset; // memory_model
Chris Forbescc5697f2019-01-30 11:54:08 -0800973 for (auto& i : module->entry_points()) {
974 (void)i;
Ben Claytonb73b7602019-07-29 13:56:13 +0100975 ++module_offset;
Chris Forbescc5697f2019-01-30 11:54:08 -0800976 }
977 for (auto& i : module->execution_modes()) {
978 (void)i;
Ben Claytonb73b7602019-07-29 13:56:13 +0100979 ++module_offset;
Chris Forbescc5697f2019-01-30 11:54:08 -0800980 }
981 for (auto& i : module->debugs1()) {
982 (void)i;
Ben Claytonb73b7602019-07-29 13:56:13 +0100983 ++module_offset;
Chris Forbescc5697f2019-01-30 11:54:08 -0800984 }
985 for (auto& i : module->debugs2()) {
986 (void)i;
Ben Claytonb73b7602019-07-29 13:56:13 +0100987 ++module_offset;
Chris Forbescc5697f2019-01-30 11:54:08 -0800988 }
989 for (auto& i : module->debugs3()) {
990 (void)i;
Ben Claytonb73b7602019-07-29 13:56:13 +0100991 ++module_offset;
Chris Forbescc5697f2019-01-30 11:54:08 -0800992 }
993 for (auto& i : module->annotations()) {
994 (void)i;
Ben Claytonb73b7602019-07-29 13:56:13 +0100995 ++module_offset;
Chris Forbescc5697f2019-01-30 11:54:08 -0800996 }
997 for (auto& i : module->types_values()) {
Ben Claytonb73b7602019-07-29 13:56:13 +0100998 module_offset += 1;
999 module_offset += static_cast<uint32_t>(i.dbg_line_insts().size());
Chris Forbescc5697f2019-01-30 11:54:08 -08001000 }
Chris Forbescc5697f2019-01-30 11:54:08 -08001001
Ben Claytonb73b7602019-07-29 13:56:13 +01001002 auto curr_fn = get_module()->begin();
1003 for (; curr_fn != get_module()->end(); ++curr_fn) {
1004 // Count function instruction
1005 module_offset += 1;
1006 curr_fn->ForEachParam(
1007 [&module_offset](const Instruction*) { module_offset += 1; }, true);
1008 for (auto& blk : *curr_fn) {
Chris Forbescc5697f2019-01-30 11:54:08 -08001009 // Count label
Ben Claytonb73b7602019-07-29 13:56:13 +01001010 module_offset += 1;
Chris Forbescc5697f2019-01-30 11:54:08 -08001011 for (auto& inst : blk) {
Ben Claytonb73b7602019-07-29 13:56:13 +01001012 module_offset += static_cast<uint32_t>(inst.dbg_line_insts().size());
1013 uid2offset_[inst.unique_id()] = module_offset;
1014 module_offset += 1;
Chris Forbescc5697f2019-01-30 11:54:08 -08001015 }
1016 }
Ben Claytonb73b7602019-07-29 13:56:13 +01001017 // Count function end instruction
1018 module_offset += 1;
Chris Forbescc5697f2019-01-30 11:54:08 -08001019 }
1020}
1021
1022} // namespace opt
1023} // namespace spvtools