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 varibale 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 replacment, and copy the
139 // 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 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 std::unique_ptr<Instruction> new_decoration(old_decoration->Clone(context()));
217 new_decoration->SetInOperand(0, {new_var_id});
218
219 if (IsDecorationBinding(new_decoration.get())) {
220 new_decoration->SetInOperand(2, {new_binding});
221 }
222 context()->AddAnnotationInst(std::move(new_decoration));
223 }
224
CreateNewDecorationForMemberDecorate(Instruction * old_member_decoration,uint32_t new_var_id)225 void DescriptorScalarReplacement::CreateNewDecorationForMemberDecorate(
226 Instruction* old_member_decoration, uint32_t new_var_id) {
227 std::vector<Operand> operands(
228 {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {new_var_id}}});
229 auto new_decorate_operand_begin = old_member_decoration->begin() + 2u;
230 auto new_decorate_operand_end = old_member_decoration->end();
231 operands.insert(operands.end(), new_decorate_operand_begin,
232 new_decorate_operand_end);
233 get_decoration_mgr()->AddDecoration(SpvOpDecorate, std::move(operands));
234 }
235
CreateReplacementVariable(Instruction * var,uint32_t idx)236 uint32_t DescriptorScalarReplacement::CreateReplacementVariable(
237 Instruction* var, uint32_t idx) {
238 // The storage class for the new variable is the same as the original.
239 SpvStorageClass storage_class =
240 static_cast<SpvStorageClass>(var->GetSingleWordInOperand(0));
241
242 // The type for the new variable will be a pointer to type of the elements of
243 // the array.
244 uint32_t ptr_type_id = var->type_id();
245 Instruction* ptr_type_inst = get_def_use_mgr()->GetDef(ptr_type_id);
246 assert(ptr_type_inst->opcode() == SpvOpTypePointer &&
247 "Variable should be a pointer to an array or structure.");
248 uint32_t pointee_type_id = ptr_type_inst->GetSingleWordInOperand(1);
249 Instruction* pointee_type_inst = get_def_use_mgr()->GetDef(pointee_type_id);
250 const bool is_array = pointee_type_inst->opcode() == SpvOpTypeArray;
251 const bool is_struct = pointee_type_inst->opcode() == SpvOpTypeStruct;
252 assert((is_array || is_struct) &&
253 "Variable should be a pointer to an array or structure.");
254
255 uint32_t element_type_id =
256 is_array ? pointee_type_inst->GetSingleWordInOperand(0)
257 : pointee_type_inst->GetSingleWordInOperand(idx);
258
259 uint32_t ptr_element_type_id = context()->get_type_mgr()->FindPointerToType(
260 element_type_id, storage_class);
261
262 // Create the variable.
263 uint32_t id = TakeNextId();
264 std::unique_ptr<Instruction> variable(
265 new Instruction(context(), SpvOpVariable, ptr_element_type_id, id,
266 std::initializer_list<Operand>{
267 {SPV_OPERAND_TYPE_STORAGE_CLASS,
268 {static_cast<uint32_t>(storage_class)}}}));
269 context()->AddGlobalValue(std::move(variable));
270
271 CopyDecorationsForNewVariable(var, idx, id, ptr_element_type_id, is_array,
272 is_struct, pointee_type_inst);
273
274 // Create a new OpName for the replacement variable.
275 std::vector<std::unique_ptr<Instruction>> names_to_add;
276 for (auto p : context()->GetNames(var->result_id())) {
277 Instruction* name_inst = p.second;
278 std::string name_str = utils::MakeString(name_inst->GetOperand(1).words);
279 if (is_array) {
280 name_str += "[" + utils::ToString(idx) + "]";
281 }
282 if (is_struct) {
283 Instruction* member_name_inst =
284 context()->GetMemberName(pointee_type_inst->result_id(), idx);
285 name_str += ".";
286 if (member_name_inst)
287 name_str += utils::MakeString(member_name_inst->GetOperand(2).words);
288 else
289 // In case the member does not have a name assigned to it, use the
290 // member index.
291 name_str += utils::ToString(idx);
292 }
293
294 std::unique_ptr<Instruction> new_name(new Instruction(
295 context(), SpvOpName, 0, 0,
296 std::initializer_list<Operand>{
297 {SPV_OPERAND_TYPE_ID, {id}},
298 {SPV_OPERAND_TYPE_LITERAL_STRING, utils::MakeVector(name_str)}}));
299 Instruction* new_name_inst = new_name.get();
300 get_def_use_mgr()->AnalyzeInstDefUse(new_name_inst);
301 names_to_add.push_back(std::move(new_name));
302 }
303
304 // We shouldn't add the new names when we are iterating over name ranges
305 // above. We can add all the new names now.
306 for (auto& new_name : names_to_add)
307 context()->AddDebug2Inst(std::move(new_name));
308
309 return id;
310 }
311
GetNumBindingsUsedByType(uint32_t type_id)312 uint32_t DescriptorScalarReplacement::GetNumBindingsUsedByType(
313 uint32_t type_id) {
314 Instruction* type_inst = get_def_use_mgr()->GetDef(type_id);
315
316 // If it's a pointer, look at the underlying type.
317 if (type_inst->opcode() == SpvOpTypePointer) {
318 type_id = type_inst->GetSingleWordInOperand(1);
319 type_inst = get_def_use_mgr()->GetDef(type_id);
320 }
321
322 // Arrays consume N*M binding numbers where N is the array length, and M is
323 // the number of bindings used by each array element.
324 if (type_inst->opcode() == SpvOpTypeArray) {
325 uint32_t element_type_id = type_inst->GetSingleWordInOperand(0);
326 uint32_t length_id = type_inst->GetSingleWordInOperand(1);
327 const analysis::Constant* length_const =
328 context()->get_constant_mgr()->FindDeclaredConstant(length_id);
329 // OpTypeArray's length must always be a constant
330 assert(length_const != nullptr);
331 uint32_t num_elems = length_const->GetU32();
332 return num_elems * GetNumBindingsUsedByType(element_type_id);
333 }
334
335 // The number of bindings consumed by a structure is the sum of the bindings
336 // used by its members.
337 if (type_inst->opcode() == SpvOpTypeStruct &&
338 !descsroautil::IsTypeOfStructuredBuffer(context(), type_inst)) {
339 uint32_t sum = 0;
340 for (uint32_t i = 0; i < type_inst->NumInOperands(); i++)
341 sum += GetNumBindingsUsedByType(type_inst->GetSingleWordInOperand(i));
342 return sum;
343 }
344
345 // All other types are considered to take up 1 binding number.
346 return 1;
347 }
348
ReplaceLoadedValue(Instruction * var,Instruction * value)349 bool DescriptorScalarReplacement::ReplaceLoadedValue(Instruction* var,
350 Instruction* value) {
351 // |var| is the global variable that has to be eliminated (OpVariable).
352 // |value| is the OpLoad instruction that has loaded |var|.
353 // The function expects all users of |value| to be OpCompositeExtract
354 // instructions. Otherwise the function returns false with an error message.
355 assert(value->opcode() == SpvOpLoad);
356 assert(value->GetSingleWordInOperand(0) == var->result_id());
357 std::vector<Instruction*> work_list;
358 bool failed = !get_def_use_mgr()->WhileEachUser(
359 value->result_id(), [this, &work_list](Instruction* use) {
360 if (use->opcode() != SpvOpCompositeExtract) {
361 context()->EmitErrorMessage(
362 "Variable cannot be replaced: invalid instruction", use);
363 return false;
364 }
365 work_list.push_back(use);
366 return true;
367 });
368
369 if (failed) {
370 return false;
371 }
372
373 for (Instruction* use : work_list) {
374 if (!ReplaceCompositeExtract(var, use)) {
375 return false;
376 }
377 }
378
379 // All usages of the loaded value have been killed. We can kill the OpLoad.
380 context()->KillInst(value);
381 return true;
382 }
383
ReplaceCompositeExtract(Instruction * var,Instruction * extract)384 bool DescriptorScalarReplacement::ReplaceCompositeExtract(
385 Instruction* var, Instruction* extract) {
386 assert(extract->opcode() == SpvOpCompositeExtract);
387 // We're currently only supporting extractions of one index at a time. If we
388 // need to, we can handle cases with multiple indexes in the future.
389 if (extract->NumInOperands() != 2) {
390 context()->EmitErrorMessage(
391 "Variable cannot be replaced: invalid instruction", extract);
392 return false;
393 }
394
395 uint32_t replacement_var =
396 GetReplacementVariable(var, extract->GetSingleWordInOperand(1));
397
398 // The result type of the OpLoad is the same as the result type of the
399 // OpCompositeExtract.
400 uint32_t load_id = TakeNextId();
401 std::unique_ptr<Instruction> load(
402 new Instruction(context(), SpvOpLoad, extract->type_id(), load_id,
403 std::initializer_list<Operand>{
404 {SPV_OPERAND_TYPE_ID, {replacement_var}}}));
405 Instruction* load_instr = load.get();
406 get_def_use_mgr()->AnalyzeInstDefUse(load_instr);
407 context()->set_instr_block(load_instr, context()->get_instr_block(extract));
408 extract->InsertBefore(std::move(load));
409 context()->ReplaceAllUsesWith(extract->result_id(), load_id);
410 context()->KillInst(extract);
411 return true;
412 }
413
414 } // namespace opt
415 } // namespace spvtools
416