desc_sroa.cpp 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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. #include "source/opt/desc_sroa.h"
  15. #include "source/util/string_utils.h"
  16. namespace spvtools {
  17. namespace opt {
  18. Pass::Status DescriptorScalarReplacement::Process() {
  19. bool modified = false;
  20. std::vector<Instruction*> vars_to_kill;
  21. for (Instruction& var : context()->types_values()) {
  22. if (IsCandidate(&var)) {
  23. modified = true;
  24. if (!ReplaceCandidate(&var)) {
  25. return Status::Failure;
  26. }
  27. vars_to_kill.push_back(&var);
  28. }
  29. }
  30. for (Instruction* var : vars_to_kill) {
  31. context()->KillInst(var);
  32. }
  33. return (modified ? Status::SuccessWithChange : Status::SuccessWithoutChange);
  34. }
  35. bool DescriptorScalarReplacement::IsCandidate(Instruction* var) {
  36. if (var->opcode() != SpvOpVariable) {
  37. return false;
  38. }
  39. uint32_t ptr_type_id = var->type_id();
  40. Instruction* ptr_type_inst =
  41. context()->get_def_use_mgr()->GetDef(ptr_type_id);
  42. if (ptr_type_inst->opcode() != SpvOpTypePointer) {
  43. return false;
  44. }
  45. uint32_t var_type_id = ptr_type_inst->GetSingleWordInOperand(1);
  46. Instruction* var_type_inst =
  47. context()->get_def_use_mgr()->GetDef(var_type_id);
  48. if (var_type_inst->opcode() != SpvOpTypeArray) {
  49. return false;
  50. }
  51. bool has_desc_set_decoration = false;
  52. context()->get_decoration_mgr()->ForEachDecoration(
  53. var->result_id(), SpvDecorationDescriptorSet,
  54. [&has_desc_set_decoration](const Instruction&) {
  55. has_desc_set_decoration = true;
  56. });
  57. if (!has_desc_set_decoration) {
  58. return false;
  59. }
  60. bool has_binding_decoration = false;
  61. context()->get_decoration_mgr()->ForEachDecoration(
  62. var->result_id(), SpvDecorationBinding,
  63. [&has_binding_decoration](const Instruction&) {
  64. has_binding_decoration = true;
  65. });
  66. if (!has_binding_decoration) {
  67. return false;
  68. }
  69. return true;
  70. }
  71. bool DescriptorScalarReplacement::ReplaceCandidate(Instruction* var) {
  72. std::vector<Instruction*> work_list;
  73. bool failed = !get_def_use_mgr()->WhileEachUser(
  74. var->result_id(), [this, &work_list](Instruction* use) {
  75. if (use->opcode() == SpvOpName) {
  76. return true;
  77. }
  78. if (use->IsDecoration()) {
  79. return true;
  80. }
  81. switch (use->opcode()) {
  82. case SpvOpAccessChain:
  83. case SpvOpInBoundsAccessChain:
  84. work_list.push_back(use);
  85. return true;
  86. default:
  87. context()->EmitErrorMessage(
  88. "Variable cannot be replaced: invalid instruction", use);
  89. return false;
  90. }
  91. return true;
  92. });
  93. if (failed) {
  94. return false;
  95. }
  96. for (Instruction* use : work_list) {
  97. if (!ReplaceAccessChain(var, use)) {
  98. return false;
  99. }
  100. }
  101. return true;
  102. }
  103. bool DescriptorScalarReplacement::ReplaceAccessChain(Instruction* var,
  104. Instruction* use) {
  105. if (use->NumInOperands() <= 1) {
  106. context()->EmitErrorMessage(
  107. "Variable cannot be replaced: invalid instruction", use);
  108. return false;
  109. }
  110. uint32_t idx_id = use->GetSingleWordInOperand(1);
  111. const analysis::Constant* idx_const =
  112. context()->get_constant_mgr()->FindDeclaredConstant(idx_id);
  113. if (idx_const == nullptr) {
  114. context()->EmitErrorMessage("Variable cannot be replaced: invalid index",
  115. use);
  116. return false;
  117. }
  118. uint32_t idx = idx_const->GetU32();
  119. uint32_t replacement_var = GetReplacementVariable(var, idx);
  120. if (use->NumInOperands() == 2) {
  121. // We are not indexing into the replacement variable. We can replaces the
  122. // access chain with the replacement varibale itself.
  123. context()->ReplaceAllUsesWith(use->result_id(), replacement_var);
  124. context()->KillInst(use);
  125. return true;
  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. // Same result id and result type.
  131. new_operands.emplace_back(use->GetOperand(0));
  132. new_operands.emplace_back(use->GetOperand(1));
  133. // Use the replacement variable as the base address.
  134. new_operands.push_back({SPV_OPERAND_TYPE_ID, {replacement_var}});
  135. // Drop the first index because it is consumed by the replacment, and copy the
  136. // rest.
  137. for (uint32_t i = 4; i < use->NumOperands(); i++) {
  138. new_operands.emplace_back(use->GetOperand(i));
  139. }
  140. use->ReplaceOperands(new_operands);
  141. context()->UpdateDefUse(use);
  142. return true;
  143. }
  144. uint32_t DescriptorScalarReplacement::GetReplacementVariable(Instruction* var,
  145. uint32_t idx) {
  146. auto replacement_vars = replacement_variables_.find(var);
  147. if (replacement_vars == replacement_variables_.end()) {
  148. uint32_t ptr_type_id = var->type_id();
  149. Instruction* ptr_type_inst = get_def_use_mgr()->GetDef(ptr_type_id);
  150. assert(ptr_type_inst->opcode() == SpvOpTypePointer &&
  151. "Variable should be a pointer to an array.");
  152. uint32_t arr_type_id = ptr_type_inst->GetSingleWordInOperand(1);
  153. Instruction* arr_type_inst = get_def_use_mgr()->GetDef(arr_type_id);
  154. assert(arr_type_inst->opcode() == SpvOpTypeArray &&
  155. "Variable should be a pointer to an array.");
  156. uint32_t array_len_id = arr_type_inst->GetSingleWordInOperand(1);
  157. const analysis::Constant* array_len_const =
  158. context()->get_constant_mgr()->FindDeclaredConstant(array_len_id);
  159. assert(array_len_const != nullptr && "Array length must be a constant.");
  160. uint32_t array_len = array_len_const->GetU32();
  161. replacement_vars = replacement_variables_
  162. .insert({var, std::vector<uint32_t>(array_len, 0)})
  163. .first;
  164. }
  165. if (replacement_vars->second[idx] == 0) {
  166. replacement_vars->second[idx] = CreateReplacementVariable(var, idx);
  167. }
  168. return replacement_vars->second[idx];
  169. }
  170. uint32_t DescriptorScalarReplacement::CreateReplacementVariable(
  171. Instruction* var, uint32_t idx) {
  172. // The storage class for the new variable is the same as the original.
  173. SpvStorageClass storage_class =
  174. static_cast<SpvStorageClass>(var->GetSingleWordInOperand(0));
  175. // The type for the new variable will be a pointer to type of the elements of
  176. // the array.
  177. uint32_t ptr_type_id = var->type_id();
  178. Instruction* ptr_type_inst = get_def_use_mgr()->GetDef(ptr_type_id);
  179. assert(ptr_type_inst->opcode() == SpvOpTypePointer &&
  180. "Variable should be a pointer to an array.");
  181. uint32_t arr_type_id = ptr_type_inst->GetSingleWordInOperand(1);
  182. Instruction* arr_type_inst = get_def_use_mgr()->GetDef(arr_type_id);
  183. assert(arr_type_inst->opcode() == SpvOpTypeArray &&
  184. "Variable should be a pointer to an array.");
  185. uint32_t element_type_id = arr_type_inst->GetSingleWordInOperand(0);
  186. uint32_t ptr_element_type_id = context()->get_type_mgr()->FindPointerToType(
  187. element_type_id, storage_class);
  188. // Create the variable.
  189. uint32_t id = TakeNextId();
  190. std::unique_ptr<Instruction> variable(
  191. new Instruction(context(), SpvOpVariable, ptr_element_type_id, id,
  192. std::initializer_list<Operand>{
  193. {SPV_OPERAND_TYPE_STORAGE_CLASS,
  194. {static_cast<uint32_t>(storage_class)}}}));
  195. context()->AddGlobalValue(std::move(variable));
  196. // Copy all of the decorations to the new variable. The only difference is
  197. // the Binding decoration needs to be adjusted.
  198. for (auto old_decoration :
  199. get_decoration_mgr()->GetDecorationsFor(var->result_id(), true)) {
  200. assert(old_decoration->opcode() == SpvOpDecorate);
  201. std::unique_ptr<Instruction> new_decoration(
  202. old_decoration->Clone(context()));
  203. new_decoration->SetInOperand(0, {id});
  204. uint32_t decoration = new_decoration->GetSingleWordInOperand(1u);
  205. if (decoration == SpvDecorationBinding) {
  206. uint32_t new_binding = new_decoration->GetSingleWordInOperand(2) + idx;
  207. new_decoration->SetInOperand(2, {new_binding});
  208. }
  209. context()->AddAnnotationInst(std::move(new_decoration));
  210. }
  211. // Create a new OpName for the replacement variable.
  212. for (auto p : context()->GetNames(var->result_id())) {
  213. Instruction* name_inst = p.second;
  214. std::string name_str = utils::MakeString(name_inst->GetOperand(1).words);
  215. name_str += "[";
  216. name_str += utils::ToString(idx);
  217. name_str += "]";
  218. std::unique_ptr<Instruction> new_name(new Instruction(
  219. context(), SpvOpName, 0, 0,
  220. std::initializer_list<Operand>{
  221. {SPV_OPERAND_TYPE_ID, {id}},
  222. {SPV_OPERAND_TYPE_LITERAL_STRING, utils::MakeVector(name_str)}}));
  223. Instruction* new_name_inst = new_name.get();
  224. context()->AddDebug2Inst(std::move(new_name));
  225. get_def_use_mgr()->AnalyzeInstDefUse(new_name_inst);
  226. }
  227. return id;
  228. }
  229. } // namespace opt
  230. } // namespace spvtools