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