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
15 #include "source/opt/desc_sroa.h"
16
17 #include "source/opt/desc_sroa_util.h"
18 #include "source/util/string_utils.h"
19
20 namespace spvtools {
21 namespace opt {
22 namespace {
23
IsDecorationBinding(Instruction * inst)24 bool IsDecorationBinding(Instruction* inst) {
25 if (inst->opcode() != spv::Op::OpDecorate) return false;
26 return spv::Decoration(inst->GetSingleWordInOperand(1u)) ==
27 spv::Decoration::Binding;
28 }
29
30 } // namespace
31
Process()32 Pass::Status DescriptorScalarReplacement::Process() {
33 bool modified = false;
34
35 std::vector<Instruction*> vars_to_kill;
36
37 for (Instruction& var : context()->types_values()) {
38 if (descsroautil::IsDescriptorArray(context(), &var)) {
39 modified = true;
40 if (!ReplaceCandidate(&var)) {
41 return Status::Failure;
42 }
43 vars_to_kill.push_back(&var);
44 }
45 }
46
47 for (Instruction* var : vars_to_kill) {
48 context()->KillInst(var);
49 }
50
51 return (modified ? Status::SuccessWithChange : Status::SuccessWithoutChange);
52 }
53
ReplaceCandidate(Instruction * var)54 bool DescriptorScalarReplacement::ReplaceCandidate(Instruction* var) {
55 std::vector<Instruction*> access_chain_work_list;
56 std::vector<Instruction*> load_work_list;
57 std::vector<Instruction*> entry_point_work_list;
58 bool failed = !get_def_use_mgr()->WhileEachUser(
59 var->result_id(), [this, &access_chain_work_list, &load_work_list,
60 &entry_point_work_list](Instruction* use) {
61 if (use->opcode() == spv::Op::OpName) {
62 return true;
63 }
64
65 if (use->IsDecoration()) {
66 return true;
67 }
68
69 switch (use->opcode()) {
70 case spv::Op::OpAccessChain:
71 case spv::Op::OpInBoundsAccessChain:
72 access_chain_work_list.push_back(use);
73 return true;
74 case spv::Op::OpLoad:
75 load_work_list.push_back(use);
76 return true;
77 case spv::Op::OpEntryPoint:
78 entry_point_work_list.push_back(use);
79 return true;
80 default:
81 context()->EmitErrorMessage(
82 "Variable cannot be replaced: invalid instruction", use);
83 return false;
84 }
85 return true;
86 });
87
88 if (failed) {
89 return false;
90 }
91
92 for (Instruction* use : access_chain_work_list) {
93 if (!ReplaceAccessChain(var, use)) {
94 return false;
95 }
96 }
97 for (Instruction* use : load_work_list) {
98 if (!ReplaceLoadedValue(var, use)) {
99 return false;
100 }
101 }
102 for (Instruction* use : entry_point_work_list) {
103 if (!ReplaceEntryPoint(var, use)) {
104 return false;
105 }
106 }
107 return true;
108 }
109
ReplaceAccessChain(Instruction * var,Instruction * use)110 bool DescriptorScalarReplacement::ReplaceAccessChain(Instruction* var,
111 Instruction* use) {
112 if (use->NumInOperands() <= 1) {
113 context()->EmitErrorMessage(
114 "Variable cannot be replaced: invalid instruction", use);
115 return false;
116 }
117
118 const analysis::Constant* const_index =
119 descsroautil::GetAccessChainIndexAsConst(context(), use);
120 if (const_index == nullptr) {
121 context()->EmitErrorMessage("Variable cannot be replaced: invalid index",
122 use);
123 return false;
124 }
125
126 uint32_t idx = const_index->GetU32();
127 uint32_t replacement_var = GetReplacementVariable(var, idx);
128
129 if (use->NumInOperands() == 2) {
130 // We are not indexing into the replacement variable. We can replaces the
131 // access chain with the replacement variable itself.
132 context()->ReplaceAllUsesWith(use->result_id(), replacement_var);
133 context()->KillInst(use);
134 return true;
135 }
136
137 // We need to build a new access chain with the replacement variable as the
138 // base address.
139 Instruction::OperandList new_operands;
140
141 // Same result id and result type.
142 new_operands.emplace_back(use->GetOperand(0));
143 new_operands.emplace_back(use->GetOperand(1));
144
145 // Use the replacement variable as the base address.
146 new_operands.push_back({SPV_OPERAND_TYPE_ID, {replacement_var}});
147
148 // Drop the first index because it is consumed by the replacement, and copy
149 // the rest.
150 for (uint32_t i = 4; i < use->NumOperands(); i++) {
151 new_operands.emplace_back(use->GetOperand(i));
152 }
153
154 use->ReplaceOperands(new_operands);
155 context()->UpdateDefUse(use);
156 return true;
157 }
158
ReplaceEntryPoint(Instruction * var,Instruction * use)159 bool DescriptorScalarReplacement::ReplaceEntryPoint(Instruction* var,
160 Instruction* use) {
161 // Build a new |OperandList| for |use| that removes |var| and adds its
162 // replacement variables.
163 Instruction::OperandList new_operands;
164
165 // Copy all operands except |var|.
166 bool found = false;
167 for (uint32_t idx = 0; idx < use->NumOperands(); idx++) {
168 Operand& op = use->GetOperand(idx);
169 if (op.type == SPV_OPERAND_TYPE_ID && op.words[0] == var->result_id()) {
170 found = true;
171 } else {
172 new_operands.emplace_back(op);
173 }
174 }
175
176 if (!found) {
177 context()->EmitErrorMessage(
178 "Variable cannot be replaced: invalid instruction", use);
179 return false;
180 }
181
182 // Add all new replacement variables.
183 uint32_t num_replacement_vars =
184 descsroautil::GetNumberOfElementsForArrayOrStruct(context(), var);
185 for (uint32_t i = 0; i < num_replacement_vars; i++) {
186 new_operands.push_back(
187 {SPV_OPERAND_TYPE_ID, {GetReplacementVariable(var, i)}});
188 }
189
190 use->ReplaceOperands(new_operands);
191 context()->UpdateDefUse(use);
192 return true;
193 }
194
GetReplacementVariable(Instruction * var,uint32_t idx)195 uint32_t DescriptorScalarReplacement::GetReplacementVariable(Instruction* var,
196 uint32_t idx) {
197 auto replacement_vars = replacement_variables_.find(var);
198 if (replacement_vars == replacement_variables_.end()) {
199 uint32_t number_of_elements =
200 descsroautil::GetNumberOfElementsForArrayOrStruct(context(), var);
201 replacement_vars =
202 replacement_variables_
203 .insert({var, std::vector<uint32_t>(number_of_elements, 0)})
204 .first;
205 }
206
207 if (replacement_vars->second[idx] == 0) {
208 replacement_vars->second[idx] = CreateReplacementVariable(var, idx);
209 }
210
211 return replacement_vars->second[idx];
212 }
213
CopyDecorationsForNewVariable(Instruction * old_var,uint32_t index,uint32_t new_var_id,uint32_t new_var_ptr_type_id,const bool is_old_var_array,const bool is_old_var_struct,Instruction * old_var_type)214 void DescriptorScalarReplacement::CopyDecorationsForNewVariable(
215 Instruction* old_var, uint32_t index, uint32_t new_var_id,
216 uint32_t new_var_ptr_type_id, const bool is_old_var_array,
217 const bool is_old_var_struct, Instruction* old_var_type) {
218 // Handle OpDecorate and OpDecorateString instructions.
219 for (auto old_decoration :
220 get_decoration_mgr()->GetDecorationsFor(old_var->result_id(), true)) {
221 uint32_t new_binding = 0;
222 if (IsDecorationBinding(old_decoration)) {
223 new_binding = GetNewBindingForElement(
224 old_decoration->GetSingleWordInOperand(2), index, new_var_ptr_type_id,
225 is_old_var_array, is_old_var_struct, old_var_type);
226 }
227 CreateNewDecorationForNewVariable(old_decoration, new_var_id, new_binding);
228 }
229
230 // Handle OpMemberDecorate instructions.
231 for (auto old_decoration : get_decoration_mgr()->GetDecorationsFor(
232 old_var_type->result_id(), true)) {
233 assert(old_decoration->opcode() == spv::Op::OpMemberDecorate);
234 if (old_decoration->GetSingleWordInOperand(1u) != index) continue;
235 CreateNewDecorationForMemberDecorate(old_decoration, new_var_id);
236 }
237 }
238
GetNewBindingForElement(uint32_t old_binding,uint32_t index,uint32_t new_var_ptr_type_id,const bool is_old_var_array,const bool is_old_var_struct,Instruction * old_var_type)239 uint32_t DescriptorScalarReplacement::GetNewBindingForElement(
240 uint32_t old_binding, uint32_t index, uint32_t new_var_ptr_type_id,
241 const bool is_old_var_array, const bool is_old_var_struct,
242 Instruction* old_var_type) {
243 if (is_old_var_array) {
244 return old_binding + index * GetNumBindingsUsedByType(new_var_ptr_type_id);
245 }
246 if (is_old_var_struct) {
247 // The binding offset that should be added is the sum of binding
248 // numbers used by previous members of the current struct.
249 uint32_t new_binding = old_binding;
250 for (uint32_t i = 0; i < index; ++i) {
251 new_binding +=
252 GetNumBindingsUsedByType(old_var_type->GetSingleWordInOperand(i));
253 }
254 return new_binding;
255 }
256 return old_binding;
257 }
258
CreateNewDecorationForNewVariable(Instruction * old_decoration,uint32_t new_var_id,uint32_t new_binding)259 void DescriptorScalarReplacement::CreateNewDecorationForNewVariable(
260 Instruction* old_decoration, uint32_t new_var_id, uint32_t new_binding) {
261 assert(old_decoration->opcode() == spv::Op::OpDecorate ||
262 old_decoration->opcode() == spv::Op::OpDecorateString);
263 std::unique_ptr<Instruction> new_decoration(old_decoration->Clone(context()));
264 new_decoration->SetInOperand(0, {new_var_id});
265
266 if (IsDecorationBinding(new_decoration.get())) {
267 new_decoration->SetInOperand(2, {new_binding});
268 }
269 context()->AddAnnotationInst(std::move(new_decoration));
270 }
271
CreateNewDecorationForMemberDecorate(Instruction * old_member_decoration,uint32_t new_var_id)272 void DescriptorScalarReplacement::CreateNewDecorationForMemberDecorate(
273 Instruction* old_member_decoration, uint32_t new_var_id) {
274 std::vector<Operand> operands(
275 {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {new_var_id}}});
276 auto new_decorate_operand_begin = old_member_decoration->begin() + 2u;
277 auto new_decorate_operand_end = old_member_decoration->end();
278 operands.insert(operands.end(), new_decorate_operand_begin,
279 new_decorate_operand_end);
280 get_decoration_mgr()->AddDecoration(spv::Op::OpDecorate, std::move(operands));
281 }
282
CreateReplacementVariable(Instruction * var,uint32_t idx)283 uint32_t DescriptorScalarReplacement::CreateReplacementVariable(
284 Instruction* var, uint32_t idx) {
285 // The storage class for the new variable is the same as the original.
286 spv::StorageClass storage_class =
287 static_cast<spv::StorageClass>(var->GetSingleWordInOperand(0));
288
289 // The type for the new variable will be a pointer to type of the elements of
290 // the array.
291 uint32_t ptr_type_id = var->type_id();
292 Instruction* ptr_type_inst = get_def_use_mgr()->GetDef(ptr_type_id);
293 assert(ptr_type_inst->opcode() == spv::Op::OpTypePointer &&
294 "Variable should be a pointer to an array or structure.");
295 uint32_t pointee_type_id = ptr_type_inst->GetSingleWordInOperand(1);
296 Instruction* pointee_type_inst = get_def_use_mgr()->GetDef(pointee_type_id);
297 const bool is_array = pointee_type_inst->opcode() == spv::Op::OpTypeArray;
298 const bool is_struct = pointee_type_inst->opcode() == spv::Op::OpTypeStruct;
299 assert((is_array || is_struct) &&
300 "Variable should be a pointer to an array or structure.");
301
302 uint32_t element_type_id =
303 is_array ? pointee_type_inst->GetSingleWordInOperand(0)
304 : pointee_type_inst->GetSingleWordInOperand(idx);
305
306 uint32_t ptr_element_type_id = context()->get_type_mgr()->FindPointerToType(
307 element_type_id, storage_class);
308
309 // Create the variable.
310 uint32_t id = TakeNextId();
311 std::unique_ptr<Instruction> variable(
312 new Instruction(context(), spv::Op::OpVariable, ptr_element_type_id, id,
313 std::initializer_list<Operand>{
314 {SPV_OPERAND_TYPE_STORAGE_CLASS,
315 {static_cast<uint32_t>(storage_class)}}}));
316 context()->AddGlobalValue(std::move(variable));
317
318 CopyDecorationsForNewVariable(var, idx, id, ptr_element_type_id, is_array,
319 is_struct, pointee_type_inst);
320
321 // Create a new OpName for the replacement variable.
322 std::vector<std::unique_ptr<Instruction>> names_to_add;
323 for (auto p : context()->GetNames(var->result_id())) {
324 Instruction* name_inst = p.second;
325 std::string name_str = utils::MakeString(name_inst->GetOperand(1).words);
326 if (is_array) {
327 name_str += "[" + utils::ToString(idx) + "]";
328 }
329 if (is_struct) {
330 Instruction* member_name_inst =
331 context()->GetMemberName(pointee_type_inst->result_id(), idx);
332 name_str += ".";
333 if (member_name_inst)
334 name_str += utils::MakeString(member_name_inst->GetOperand(2).words);
335 else
336 // In case the member does not have a name assigned to it, use the
337 // member index.
338 name_str += utils::ToString(idx);
339 }
340
341 std::unique_ptr<Instruction> new_name(new Instruction(
342 context(), spv::Op::OpName, 0, 0,
343 std::initializer_list<Operand>{
344 {SPV_OPERAND_TYPE_ID, {id}},
345 {SPV_OPERAND_TYPE_LITERAL_STRING, utils::MakeVector(name_str)}}));
346 Instruction* new_name_inst = new_name.get();
347 get_def_use_mgr()->AnalyzeInstDefUse(new_name_inst);
348 names_to_add.push_back(std::move(new_name));
349 }
350
351 // We shouldn't add the new names when we are iterating over name ranges
352 // above. We can add all the new names now.
353 for (auto& new_name : names_to_add)
354 context()->AddDebug2Inst(std::move(new_name));
355
356 return id;
357 }
358
GetNumBindingsUsedByType(uint32_t type_id)359 uint32_t DescriptorScalarReplacement::GetNumBindingsUsedByType(
360 uint32_t type_id) {
361 Instruction* type_inst = get_def_use_mgr()->GetDef(type_id);
362
363 // If it's a pointer, look at the underlying type.
364 if (type_inst->opcode() == spv::Op::OpTypePointer) {
365 type_id = type_inst->GetSingleWordInOperand(1);
366 type_inst = get_def_use_mgr()->GetDef(type_id);
367 }
368
369 // Arrays consume N*M binding numbers where N is the array length, and M is
370 // the number of bindings used by each array element.
371 if (type_inst->opcode() == spv::Op::OpTypeArray) {
372 uint32_t element_type_id = type_inst->GetSingleWordInOperand(0);
373 uint32_t length_id = type_inst->GetSingleWordInOperand(1);
374 const analysis::Constant* length_const =
375 context()->get_constant_mgr()->FindDeclaredConstant(length_id);
376 // OpTypeArray's length must always be a constant
377 assert(length_const != nullptr);
378 uint32_t num_elems = length_const->GetU32();
379 return num_elems * GetNumBindingsUsedByType(element_type_id);
380 }
381
382 // The number of bindings consumed by a structure is the sum of the bindings
383 // used by its members.
384 if (type_inst->opcode() == spv::Op::OpTypeStruct &&
385 !descsroautil::IsTypeOfStructuredBuffer(context(), type_inst)) {
386 uint32_t sum = 0;
387 for (uint32_t i = 0; i < type_inst->NumInOperands(); i++)
388 sum += GetNumBindingsUsedByType(type_inst->GetSingleWordInOperand(i));
389 return sum;
390 }
391
392 // All other types are considered to take up 1 binding number.
393 return 1;
394 }
395
ReplaceLoadedValue(Instruction * var,Instruction * value)396 bool DescriptorScalarReplacement::ReplaceLoadedValue(Instruction* var,
397 Instruction* value) {
398 // |var| is the global variable that has to be eliminated (OpVariable).
399 // |value| is the OpLoad instruction that has loaded |var|.
400 // The function expects all users of |value| to be OpCompositeExtract
401 // instructions. Otherwise the function returns false with an error message.
402 assert(value->opcode() == spv::Op::OpLoad);
403 assert(value->GetSingleWordInOperand(0) == var->result_id());
404 std::vector<Instruction*> work_list;
405 bool failed = !get_def_use_mgr()->WhileEachUser(
406 value->result_id(), [this, &work_list](Instruction* use) {
407 if (use->opcode() != spv::Op::OpCompositeExtract) {
408 context()->EmitErrorMessage(
409 "Variable cannot be replaced: invalid instruction", use);
410 return false;
411 }
412 work_list.push_back(use);
413 return true;
414 });
415
416 if (failed) {
417 return false;
418 }
419
420 for (Instruction* use : work_list) {
421 if (!ReplaceCompositeExtract(var, use)) {
422 return false;
423 }
424 }
425
426 // All usages of the loaded value have been killed. We can kill the OpLoad.
427 context()->KillInst(value);
428 return true;
429 }
430
ReplaceCompositeExtract(Instruction * var,Instruction * extract)431 bool DescriptorScalarReplacement::ReplaceCompositeExtract(
432 Instruction* var, Instruction* extract) {
433 assert(extract->opcode() == spv::Op::OpCompositeExtract);
434 // We're currently only supporting extractions of one index at a time. If we
435 // need to, we can handle cases with multiple indexes in the future.
436 if (extract->NumInOperands() != 2) {
437 context()->EmitErrorMessage(
438 "Variable cannot be replaced: invalid instruction", extract);
439 return false;
440 }
441
442 uint32_t replacement_var =
443 GetReplacementVariable(var, extract->GetSingleWordInOperand(1));
444
445 // The result type of the OpLoad is the same as the result type of the
446 // OpCompositeExtract.
447 uint32_t load_id = TakeNextId();
448 std::unique_ptr<Instruction> load(
449 new Instruction(context(), spv::Op::OpLoad, extract->type_id(), load_id,
450 std::initializer_list<Operand>{
451 {SPV_OPERAND_TYPE_ID, {replacement_var}}}));
452 Instruction* load_instr = load.get();
453 get_def_use_mgr()->AnalyzeInstDefUse(load_instr);
454 context()->set_instr_block(load_instr, context()->get_instr_block(extract));
455 extract->InsertBefore(std::move(load));
456 context()->ReplaceAllUsesWith(extract->result_id(), load_id);
457 context()->KillInst(extract);
458 return true;
459 }
460
461 } // namespace opt
462 } // namespace spvtools
463