desc_sroa.cpp 15 KB

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