copy_prop_arrays.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957
  1. // Copyright (c) 2018 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/copy_prop_arrays.h"
  15. #include <utility>
  16. #include "source/opt/ir_builder.h"
  17. namespace spvtools {
  18. namespace opt {
  19. namespace {
  20. constexpr uint32_t kLoadPointerInOperand = 0;
  21. constexpr uint32_t kStorePointerInOperand = 0;
  22. constexpr uint32_t kStoreObjectInOperand = 1;
  23. constexpr uint32_t kCompositeExtractObjectInOperand = 0;
  24. constexpr uint32_t kTypePointerStorageClassInIdx = 0;
  25. constexpr uint32_t kTypePointerPointeeInIdx = 1;
  26. constexpr uint32_t kExtInstSetInIdx = 0;
  27. constexpr uint32_t kExtInstOpInIdx = 1;
  28. constexpr uint32_t kInterpolantInIdx = 2;
  29. bool IsDebugDeclareOrValue(Instruction* di) {
  30. auto dbg_opcode = di->GetCommonDebugOpcode();
  31. return dbg_opcode == CommonDebugInfoDebugDeclare ||
  32. dbg_opcode == CommonDebugInfoDebugValue;
  33. }
  34. // Returns the number of members in |type|. If |type| is not a composite type
  35. // or the number of components is not known at compile time, the return value
  36. // will be 0.
  37. uint32_t GetNumberOfMembers(const analysis::Type* type, IRContext* context) {
  38. if (const analysis::Struct* struct_type = type->AsStruct()) {
  39. return static_cast<uint32_t>(struct_type->element_types().size());
  40. } else if (const analysis::Array* array_type = type->AsArray()) {
  41. const analysis::Constant* length_const =
  42. context->get_constant_mgr()->FindDeclaredConstant(
  43. array_type->LengthId());
  44. if (length_const == nullptr) {
  45. // This can happen if the length is an OpSpecConstant.
  46. return 0;
  47. }
  48. assert(length_const->type()->AsInteger());
  49. return length_const->GetU32();
  50. } else if (const analysis::Vector* vector_type = type->AsVector()) {
  51. return vector_type->element_count();
  52. } else if (const analysis::Matrix* matrix_type = type->AsMatrix()) {
  53. return matrix_type->element_count();
  54. } else {
  55. return 0;
  56. }
  57. }
  58. } // namespace
  59. Pass::Status CopyPropagateArrays::Process() {
  60. bool modified = false;
  61. for (Function& function : *get_module()) {
  62. if (function.IsDeclaration()) {
  63. continue;
  64. }
  65. BasicBlock* entry_bb = &*function.begin();
  66. for (auto var_inst = entry_bb->begin();
  67. var_inst->opcode() == spv::Op::OpVariable; ++var_inst) {
  68. worklist_.push(&*var_inst);
  69. }
  70. }
  71. while (!worklist_.empty()) {
  72. Instruction* var_inst = worklist_.front();
  73. worklist_.pop();
  74. // Find the only store to the entire memory location, if it exists.
  75. Instruction* store_inst = FindStoreInstruction(&*var_inst);
  76. if (!store_inst) {
  77. continue;
  78. }
  79. std::unique_ptr<MemoryObject> source_object =
  80. FindSourceObjectIfPossible(&*var_inst, store_inst);
  81. if (source_object != nullptr) {
  82. if (!IsPointerToArrayType(var_inst->type_id()) &&
  83. source_object->GetStorageClass() != spv::StorageClass::Input) {
  84. continue;
  85. }
  86. if (CanUpdateUses(&*var_inst, source_object->GetPointerTypeId(this))) {
  87. modified = true;
  88. PropagateObject(&*var_inst, source_object.get(), store_inst);
  89. }
  90. }
  91. }
  92. return (modified ? Status::SuccessWithChange : Status::SuccessWithoutChange);
  93. }
  94. std::unique_ptr<CopyPropagateArrays::MemoryObject>
  95. CopyPropagateArrays::FindSourceObjectIfPossible(Instruction* var_inst,
  96. Instruction* store_inst) {
  97. assert(var_inst->opcode() == spv::Op::OpVariable && "Expecting a variable.");
  98. // Check that the variable is a composite object where |store_inst|
  99. // dominates all of its loads.
  100. if (!store_inst) {
  101. return nullptr;
  102. }
  103. // Look at the loads to ensure they are dominated by the store.
  104. if (!HasValidReferencesOnly(var_inst, store_inst)) {
  105. return nullptr;
  106. }
  107. // If so, look at the store to see if it is the copy of an object.
  108. std::unique_ptr<MemoryObject> source = GetSourceObjectIfAny(
  109. store_inst->GetSingleWordInOperand(kStoreObjectInOperand));
  110. if (!source) {
  111. return nullptr;
  112. }
  113. // Ensure that |source| does not change between the point at which it is
  114. // loaded, and the position in which |var_inst| is loaded.
  115. //
  116. // For now we will go with the easy to implement approach, and check that the
  117. // entire variable (not just the specific component) is never written to.
  118. if (!HasNoStores(source->GetVariable())) {
  119. return nullptr;
  120. }
  121. return source;
  122. }
  123. Instruction* CopyPropagateArrays::FindStoreInstruction(
  124. const Instruction* var_inst) const {
  125. Instruction* store_inst = nullptr;
  126. get_def_use_mgr()->WhileEachUser(
  127. var_inst, [&store_inst, var_inst](Instruction* use) {
  128. if (use->opcode() == spv::Op::OpStore &&
  129. use->GetSingleWordInOperand(kStorePointerInOperand) ==
  130. var_inst->result_id()) {
  131. if (store_inst == nullptr) {
  132. store_inst = use;
  133. } else {
  134. store_inst = nullptr;
  135. return false;
  136. }
  137. }
  138. return true;
  139. });
  140. return store_inst;
  141. }
  142. void CopyPropagateArrays::PropagateObject(Instruction* var_inst,
  143. MemoryObject* source,
  144. Instruction* insertion_point) {
  145. assert(var_inst->opcode() == spv::Op::OpVariable &&
  146. "This function propagates variables.");
  147. Instruction* new_access_chain = BuildNewAccessChain(insertion_point, source);
  148. context()->KillNamesAndDecorates(var_inst);
  149. UpdateUses(var_inst, new_access_chain);
  150. }
  151. Instruction* CopyPropagateArrays::BuildNewAccessChain(
  152. Instruction* insertion_point,
  153. CopyPropagateArrays::MemoryObject* source) const {
  154. InstructionBuilder builder(
  155. context(), insertion_point,
  156. IRContext::kAnalysisDefUse | IRContext::kAnalysisInstrToBlockMapping);
  157. if (source->AccessChain().size() == 0) {
  158. return source->GetVariable();
  159. }
  160. source->BuildConstants();
  161. std::vector<uint32_t> access_ids(source->AccessChain().size());
  162. std::transform(
  163. source->AccessChain().cbegin(), source->AccessChain().cend(),
  164. access_ids.begin(), [](const AccessChainEntry& entry) {
  165. assert(entry.is_result_id && "Constants needs to be built first.");
  166. return entry.result_id;
  167. });
  168. return builder.AddAccessChain(source->GetPointerTypeId(this),
  169. source->GetVariable()->result_id(), access_ids);
  170. }
  171. bool CopyPropagateArrays::HasNoStores(Instruction* ptr_inst) {
  172. return get_def_use_mgr()->WhileEachUser(ptr_inst, [this](Instruction* use) {
  173. if (use->opcode() == spv::Op::OpLoad) {
  174. return true;
  175. } else if (use->opcode() == spv::Op::OpAccessChain) {
  176. return HasNoStores(use);
  177. } else if (use->IsDecoration() || use->opcode() == spv::Op::OpName) {
  178. return true;
  179. } else if (use->opcode() == spv::Op::OpStore) {
  180. return false;
  181. } else if (use->opcode() == spv::Op::OpImageTexelPointer) {
  182. return true;
  183. } else if (use->opcode() == spv::Op::OpEntryPoint) {
  184. return true;
  185. } else if (IsInterpolationInstruction(use)) {
  186. return true;
  187. }
  188. // Some other instruction. Be conservative.
  189. return false;
  190. });
  191. }
  192. bool CopyPropagateArrays::HasValidReferencesOnly(Instruction* ptr_inst,
  193. Instruction* store_inst) {
  194. BasicBlock* store_block = context()->get_instr_block(store_inst);
  195. DominatorAnalysis* dominator_analysis =
  196. context()->GetDominatorAnalysis(store_block->GetParent());
  197. return get_def_use_mgr()->WhileEachUser(
  198. ptr_inst,
  199. [this, store_inst, dominator_analysis, ptr_inst](Instruction* use) {
  200. if (use->opcode() == spv::Op::OpLoad ||
  201. use->opcode() == spv::Op::OpImageTexelPointer) {
  202. // TODO: If there are many load in the same BB as |store_inst| the
  203. // time to do the multiple traverses can add up. Consider collecting
  204. // those loads and doing a single traversal.
  205. return dominator_analysis->Dominates(store_inst, use);
  206. } else if (IsInterpolationInstruction(use)) {
  207. // GLSL InterpolateAt* instructions work similarly to loads
  208. uint32_t interpolant = use->GetSingleWordInOperand(kInterpolantInIdx);
  209. if (interpolant !=
  210. store_inst->GetSingleWordInOperand(kStorePointerInOperand))
  211. return false;
  212. return dominator_analysis->Dominates(store_inst, use);
  213. } else if (use->opcode() == spv::Op::OpAccessChain) {
  214. return HasValidReferencesOnly(use, store_inst);
  215. } else if (use->IsDecoration() || use->opcode() == spv::Op::OpName) {
  216. return true;
  217. } else if (use->opcode() == spv::Op::OpStore) {
  218. // If we are storing to part of the object it is not an candidate.
  219. return ptr_inst->opcode() == spv::Op::OpVariable &&
  220. store_inst->GetSingleWordInOperand(kStorePointerInOperand) ==
  221. ptr_inst->result_id();
  222. } else if (IsDebugDeclareOrValue(use)) {
  223. return true;
  224. }
  225. // Some other instruction. Be conservative.
  226. return false;
  227. });
  228. }
  229. std::unique_ptr<CopyPropagateArrays::MemoryObject>
  230. CopyPropagateArrays::GetSourceObjectIfAny(uint32_t result) {
  231. Instruction* result_inst = context()->get_def_use_mgr()->GetDef(result);
  232. switch (result_inst->opcode()) {
  233. case spv::Op::OpLoad:
  234. return BuildMemoryObjectFromLoad(result_inst);
  235. case spv::Op::OpCompositeExtract:
  236. return BuildMemoryObjectFromExtract(result_inst);
  237. case spv::Op::OpCompositeConstruct:
  238. return BuildMemoryObjectFromCompositeConstruct(result_inst);
  239. case spv::Op::OpCopyObject:
  240. case spv::Op::OpCopyLogical:
  241. return GetSourceObjectIfAny(result_inst->GetSingleWordInOperand(0));
  242. case spv::Op::OpCompositeInsert:
  243. return BuildMemoryObjectFromInsert(result_inst);
  244. default:
  245. return nullptr;
  246. }
  247. }
  248. std::unique_ptr<CopyPropagateArrays::MemoryObject>
  249. CopyPropagateArrays::BuildMemoryObjectFromLoad(Instruction* load_inst) {
  250. std::vector<uint32_t> components_in_reverse;
  251. analysis::DefUseManager* def_use_mgr = context()->get_def_use_mgr();
  252. Instruction* current_inst = def_use_mgr->GetDef(
  253. load_inst->GetSingleWordInOperand(kLoadPointerInOperand));
  254. // Build the access chain for the memory object by collecting the indices used
  255. // in the OpAccessChain instructions. If we find a variable index, then
  256. // return |nullptr| because we cannot know for sure which memory location is
  257. // used.
  258. //
  259. // It is built in reverse order because the different |OpAccessChain|
  260. // instructions are visited in reverse order from which they are applied.
  261. while (current_inst->opcode() == spv::Op::OpAccessChain) {
  262. for (uint32_t i = current_inst->NumInOperands() - 1; i >= 1; --i) {
  263. uint32_t element_index_id = current_inst->GetSingleWordInOperand(i);
  264. components_in_reverse.push_back(element_index_id);
  265. }
  266. current_inst = def_use_mgr->GetDef(current_inst->GetSingleWordInOperand(0));
  267. }
  268. // If the address in the load is not constructed from an |OpVariable|
  269. // instruction followed by a series of |OpAccessChain| instructions, then
  270. // return |nullptr| because we cannot identify the owner or access chain
  271. // exactly.
  272. if (current_inst->opcode() != spv::Op::OpVariable) {
  273. return nullptr;
  274. }
  275. // Build the memory object. Use |rbegin| and |rend| to put the access chain
  276. // back in the correct order.
  277. return std::unique_ptr<CopyPropagateArrays::MemoryObject>(
  278. new MemoryObject(current_inst, components_in_reverse.rbegin(),
  279. components_in_reverse.rend()));
  280. }
  281. std::unique_ptr<CopyPropagateArrays::MemoryObject>
  282. CopyPropagateArrays::BuildMemoryObjectFromExtract(Instruction* extract_inst) {
  283. assert(extract_inst->opcode() == spv::Op::OpCompositeExtract &&
  284. "Expecting an OpCompositeExtract instruction.");
  285. std::unique_ptr<MemoryObject> result = GetSourceObjectIfAny(
  286. extract_inst->GetSingleWordInOperand(kCompositeExtractObjectInOperand));
  287. if (!result) {
  288. return nullptr;
  289. }
  290. // Copy the indices of the extract instruction to |OpAccessChain| indices.
  291. std::vector<AccessChainEntry> components;
  292. for (uint32_t i = 1; i < extract_inst->NumInOperands(); ++i) {
  293. components.push_back({false, {extract_inst->GetSingleWordInOperand(i)}});
  294. }
  295. result->PushIndirection(components);
  296. return result;
  297. }
  298. std::unique_ptr<CopyPropagateArrays::MemoryObject>
  299. CopyPropagateArrays::BuildMemoryObjectFromCompositeConstruct(
  300. Instruction* conststruct_inst) {
  301. assert(conststruct_inst->opcode() == spv::Op::OpCompositeConstruct &&
  302. "Expecting an OpCompositeConstruct instruction.");
  303. // If every operand in the instruction are part of the same memory object, and
  304. // are being combined in the same order, then the result is the same as the
  305. // parent.
  306. std::unique_ptr<MemoryObject> memory_object =
  307. GetSourceObjectIfAny(conststruct_inst->GetSingleWordInOperand(0));
  308. if (!memory_object) {
  309. return nullptr;
  310. }
  311. if (!memory_object->IsMember()) {
  312. return nullptr;
  313. }
  314. AccessChainEntry last_access = memory_object->AccessChain().back();
  315. if (!IsAccessChainIndexValidAndEqualTo(last_access, 0)) {
  316. return nullptr;
  317. }
  318. memory_object->PopIndirection();
  319. if (memory_object->GetNumberOfMembers() !=
  320. conststruct_inst->NumInOperands()) {
  321. return nullptr;
  322. }
  323. for (uint32_t i = 1; i < conststruct_inst->NumInOperands(); ++i) {
  324. std::unique_ptr<MemoryObject> member_object =
  325. GetSourceObjectIfAny(conststruct_inst->GetSingleWordInOperand(i));
  326. if (!member_object) {
  327. return nullptr;
  328. }
  329. if (!member_object->IsMember()) {
  330. return nullptr;
  331. }
  332. if (!memory_object->Contains(member_object.get())) {
  333. return nullptr;
  334. }
  335. last_access = member_object->AccessChain().back();
  336. if (!IsAccessChainIndexValidAndEqualTo(last_access, i)) {
  337. return nullptr;
  338. }
  339. }
  340. return memory_object;
  341. }
  342. std::unique_ptr<CopyPropagateArrays::MemoryObject>
  343. CopyPropagateArrays::BuildMemoryObjectFromInsert(Instruction* insert_inst) {
  344. assert(insert_inst->opcode() == spv::Op::OpCompositeInsert &&
  345. "Expecting an OpCompositeInsert instruction.");
  346. analysis::DefUseManager* def_use_mgr = context()->get_def_use_mgr();
  347. analysis::TypeManager* type_mgr = context()->get_type_mgr();
  348. const analysis::Type* result_type = type_mgr->GetType(insert_inst->type_id());
  349. uint32_t number_of_elements = GetNumberOfMembers(result_type, context());
  350. if (number_of_elements == 0) {
  351. return nullptr;
  352. }
  353. if (insert_inst->NumInOperands() != 3) {
  354. return nullptr;
  355. }
  356. if (insert_inst->GetSingleWordInOperand(2) != number_of_elements - 1) {
  357. return nullptr;
  358. }
  359. std::unique_ptr<MemoryObject> memory_object =
  360. GetSourceObjectIfAny(insert_inst->GetSingleWordInOperand(0));
  361. if (!memory_object) {
  362. return nullptr;
  363. }
  364. if (!memory_object->IsMember()) {
  365. return nullptr;
  366. }
  367. AccessChainEntry last_access = memory_object->AccessChain().back();
  368. if (!IsAccessChainIndexValidAndEqualTo(last_access, number_of_elements - 1)) {
  369. return nullptr;
  370. }
  371. memory_object->PopIndirection();
  372. Instruction* current_insert =
  373. def_use_mgr->GetDef(insert_inst->GetSingleWordInOperand(1));
  374. for (uint32_t i = number_of_elements - 1; i > 0; --i) {
  375. if (current_insert->opcode() != spv::Op::OpCompositeInsert) {
  376. return nullptr;
  377. }
  378. if (current_insert->NumInOperands() != 3) {
  379. return nullptr;
  380. }
  381. if (current_insert->GetSingleWordInOperand(2) != i - 1) {
  382. return nullptr;
  383. }
  384. std::unique_ptr<MemoryObject> current_memory_object =
  385. GetSourceObjectIfAny(current_insert->GetSingleWordInOperand(0));
  386. if (!current_memory_object) {
  387. return nullptr;
  388. }
  389. if (!current_memory_object->IsMember()) {
  390. return nullptr;
  391. }
  392. if (memory_object->AccessChain().size() + 1 !=
  393. current_memory_object->AccessChain().size()) {
  394. return nullptr;
  395. }
  396. if (!memory_object->Contains(current_memory_object.get())) {
  397. return nullptr;
  398. }
  399. AccessChainEntry current_last_access =
  400. current_memory_object->AccessChain().back();
  401. if (!IsAccessChainIndexValidAndEqualTo(current_last_access, i - 1)) {
  402. return nullptr;
  403. }
  404. current_insert =
  405. def_use_mgr->GetDef(current_insert->GetSingleWordInOperand(1));
  406. }
  407. return memory_object;
  408. }
  409. bool CopyPropagateArrays::IsAccessChainIndexValidAndEqualTo(
  410. const AccessChainEntry& entry, uint32_t value) const {
  411. if (!entry.is_result_id) {
  412. return entry.immediate == value;
  413. }
  414. analysis::ConstantManager* const_mgr = context()->get_constant_mgr();
  415. const analysis::Constant* constant =
  416. const_mgr->FindDeclaredConstant(entry.result_id);
  417. if (!constant || !constant->type()->AsInteger()) {
  418. return false;
  419. }
  420. return constant->GetU32() == value;
  421. }
  422. bool CopyPropagateArrays::IsPointerToArrayType(uint32_t type_id) {
  423. analysis::TypeManager* type_mgr = context()->get_type_mgr();
  424. analysis::Pointer* pointer_type = type_mgr->GetType(type_id)->AsPointer();
  425. if (pointer_type) {
  426. return pointer_type->pointee_type()->kind() == analysis::Type::kArray ||
  427. pointer_type->pointee_type()->kind() == analysis::Type::kImage;
  428. }
  429. return false;
  430. }
  431. bool CopyPropagateArrays::IsInterpolationInstruction(Instruction* inst) {
  432. if (inst->opcode() == spv::Op::OpExtInst &&
  433. inst->GetSingleWordInOperand(kExtInstSetInIdx) ==
  434. context()->get_feature_mgr()->GetExtInstImportId_GLSLstd450()) {
  435. uint32_t ext_inst = inst->GetSingleWordInOperand(kExtInstOpInIdx);
  436. switch (ext_inst) {
  437. case GLSLstd450InterpolateAtCentroid:
  438. case GLSLstd450InterpolateAtOffset:
  439. case GLSLstd450InterpolateAtSample:
  440. return true;
  441. }
  442. }
  443. return false;
  444. }
  445. bool CopyPropagateArrays::CanUpdateUses(Instruction* original_ptr_inst,
  446. uint32_t type_id) {
  447. analysis::TypeManager* type_mgr = context()->get_type_mgr();
  448. analysis::ConstantManager* const_mgr = context()->get_constant_mgr();
  449. analysis::DefUseManager* def_use_mgr = context()->get_def_use_mgr();
  450. analysis::Type* type = type_mgr->GetType(type_id);
  451. if (type->AsRuntimeArray()) {
  452. return false;
  453. }
  454. if (!type->AsStruct() && !type->AsArray() && !type->AsPointer()) {
  455. // If the type is not an aggregate, then the desired type must be the
  456. // same as the current type. No work to do, and we can do that.
  457. return true;
  458. }
  459. return def_use_mgr->WhileEachUse(original_ptr_inst, [this, type_mgr,
  460. const_mgr,
  461. type](Instruction* use,
  462. uint32_t) {
  463. if (IsDebugDeclareOrValue(use)) return true;
  464. switch (use->opcode()) {
  465. case spv::Op::OpLoad: {
  466. analysis::Pointer* pointer_type = type->AsPointer();
  467. uint32_t new_type_id = type_mgr->GetId(pointer_type->pointee_type());
  468. if (new_type_id != use->type_id()) {
  469. return CanUpdateUses(use, new_type_id);
  470. }
  471. return true;
  472. }
  473. case spv::Op::OpExtInst:
  474. if (IsInterpolationInstruction(use)) {
  475. return true;
  476. }
  477. return false;
  478. case spv::Op::OpAccessChain: {
  479. analysis::Pointer* pointer_type = type->AsPointer();
  480. const analysis::Type* pointee_type = pointer_type->pointee_type();
  481. std::vector<uint32_t> access_chain;
  482. for (uint32_t i = 1; i < use->NumInOperands(); ++i) {
  483. const analysis::Constant* index_const =
  484. const_mgr->FindDeclaredConstant(use->GetSingleWordInOperand(i));
  485. if (index_const) {
  486. access_chain.push_back(index_const->GetU32());
  487. } else {
  488. // Variable index means the type is a type where every element
  489. // is the same type. Use element 0 to get the type.
  490. access_chain.push_back(0);
  491. // We are trying to access a struct with variable indices.
  492. // This cannot happen.
  493. if (pointee_type->kind() == analysis::Type::kStruct) {
  494. return false;
  495. }
  496. }
  497. }
  498. const analysis::Type* new_pointee_type =
  499. type_mgr->GetMemberType(pointee_type, access_chain);
  500. analysis::Pointer pointerTy(new_pointee_type,
  501. pointer_type->storage_class());
  502. uint32_t new_pointer_type_id =
  503. context()->get_type_mgr()->GetTypeInstruction(&pointerTy);
  504. if (new_pointer_type_id == 0) {
  505. return false;
  506. }
  507. if (new_pointer_type_id != use->type_id()) {
  508. return CanUpdateUses(use, new_pointer_type_id);
  509. }
  510. return true;
  511. }
  512. case spv::Op::OpCompositeExtract: {
  513. std::vector<uint32_t> access_chain;
  514. for (uint32_t i = 1; i < use->NumInOperands(); ++i) {
  515. access_chain.push_back(use->GetSingleWordInOperand(i));
  516. }
  517. const analysis::Type* new_type =
  518. type_mgr->GetMemberType(type, access_chain);
  519. uint32_t new_type_id = type_mgr->GetTypeInstruction(new_type);
  520. if (new_type_id == 0) {
  521. return false;
  522. }
  523. if (new_type_id != use->type_id()) {
  524. return CanUpdateUses(use, new_type_id);
  525. }
  526. return true;
  527. }
  528. case spv::Op::OpStore:
  529. // If needed, we can create an element-by-element copy to change the
  530. // type of the value being stored. This way we can always handled
  531. // stores.
  532. return true;
  533. case spv::Op::OpImageTexelPointer:
  534. case spv::Op::OpName:
  535. return true;
  536. default:
  537. return use->IsDecoration();
  538. }
  539. });
  540. }
  541. void CopyPropagateArrays::UpdateUses(Instruction* original_ptr_inst,
  542. Instruction* new_ptr_inst) {
  543. analysis::TypeManager* type_mgr = context()->get_type_mgr();
  544. analysis::ConstantManager* const_mgr = context()->get_constant_mgr();
  545. analysis::DefUseManager* def_use_mgr = context()->get_def_use_mgr();
  546. std::vector<std::pair<Instruction*, uint32_t> > uses;
  547. def_use_mgr->ForEachUse(original_ptr_inst,
  548. [&uses](Instruction* use, uint32_t index) {
  549. uses.push_back({use, index});
  550. });
  551. for (auto pair : uses) {
  552. Instruction* use = pair.first;
  553. uint32_t index = pair.second;
  554. if (use->IsCommonDebugInstr()) {
  555. switch (use->GetCommonDebugOpcode()) {
  556. case CommonDebugInfoDebugDeclare: {
  557. if (new_ptr_inst->opcode() == spv::Op::OpVariable ||
  558. new_ptr_inst->opcode() == spv::Op::OpFunctionParameter) {
  559. context()->ForgetUses(use);
  560. use->SetOperand(index, {new_ptr_inst->result_id()});
  561. context()->AnalyzeUses(use);
  562. } else {
  563. // Based on the spec, we cannot use a pointer other than OpVariable
  564. // or OpFunctionParameter for DebugDeclare. We have to use
  565. // DebugValue with Deref.
  566. context()->ForgetUses(use);
  567. // Change DebugDeclare to DebugValue.
  568. use->SetOperand(index - 2,
  569. {static_cast<uint32_t>(CommonDebugInfoDebugValue)});
  570. use->SetOperand(index, {new_ptr_inst->result_id()});
  571. // Add Deref operation.
  572. Instruction* dbg_expr =
  573. def_use_mgr->GetDef(use->GetSingleWordOperand(index + 1));
  574. auto* deref_expr_instr =
  575. context()->get_debug_info_mgr()->DerefDebugExpression(dbg_expr);
  576. use->SetOperand(index + 1, {deref_expr_instr->result_id()});
  577. context()->AnalyzeUses(deref_expr_instr);
  578. context()->AnalyzeUses(use);
  579. }
  580. break;
  581. }
  582. case CommonDebugInfoDebugValue:
  583. context()->ForgetUses(use);
  584. use->SetOperand(index, {new_ptr_inst->result_id()});
  585. context()->AnalyzeUses(use);
  586. break;
  587. default:
  588. assert(false && "Don't know how to rewrite instruction");
  589. break;
  590. }
  591. continue;
  592. }
  593. switch (use->opcode()) {
  594. case spv::Op::OpLoad: {
  595. // Replace the actual use.
  596. context()->ForgetUses(use);
  597. use->SetOperand(index, {new_ptr_inst->result_id()});
  598. // Update the type.
  599. Instruction* pointer_type_inst =
  600. def_use_mgr->GetDef(new_ptr_inst->type_id());
  601. uint32_t new_type_id =
  602. pointer_type_inst->GetSingleWordInOperand(kTypePointerPointeeInIdx);
  603. if (new_type_id != use->type_id()) {
  604. use->SetResultType(new_type_id);
  605. context()->AnalyzeUses(use);
  606. UpdateUses(use, use);
  607. } else {
  608. context()->AnalyzeUses(use);
  609. }
  610. AddUsesToWorklist(use);
  611. } break;
  612. case spv::Op::OpExtInst: {
  613. if (IsInterpolationInstruction(use)) {
  614. // Replace the actual use.
  615. context()->ForgetUses(use);
  616. use->SetOperand(index, {new_ptr_inst->result_id()});
  617. context()->AnalyzeUses(use);
  618. } else {
  619. assert(false && "Don't know how to rewrite instruction");
  620. }
  621. } break;
  622. case spv::Op::OpAccessChain: {
  623. // Update the actual use.
  624. context()->ForgetUses(use);
  625. use->SetOperand(index, {new_ptr_inst->result_id()});
  626. // Convert the ids on the OpAccessChain to indices that can be used to
  627. // get the specific member.
  628. std::vector<uint32_t> access_chain;
  629. for (uint32_t i = 1; i < use->NumInOperands(); ++i) {
  630. const analysis::Constant* index_const =
  631. const_mgr->FindDeclaredConstant(use->GetSingleWordInOperand(i));
  632. if (index_const) {
  633. access_chain.push_back(index_const->GetU32());
  634. } else {
  635. // Variable index means the type is an type where every element
  636. // is the same type. Use element 0 to get the type.
  637. access_chain.push_back(0);
  638. }
  639. }
  640. Instruction* pointer_type_inst =
  641. get_def_use_mgr()->GetDef(new_ptr_inst->type_id());
  642. uint32_t new_pointee_type_id = GetMemberTypeId(
  643. pointer_type_inst->GetSingleWordInOperand(kTypePointerPointeeInIdx),
  644. access_chain);
  645. spv::StorageClass storage_class = static_cast<spv::StorageClass>(
  646. pointer_type_inst->GetSingleWordInOperand(
  647. kTypePointerStorageClassInIdx));
  648. uint32_t new_pointer_type_id =
  649. type_mgr->FindPointerToType(new_pointee_type_id, storage_class);
  650. if (new_pointer_type_id != use->type_id()) {
  651. use->SetResultType(new_pointer_type_id);
  652. context()->AnalyzeUses(use);
  653. UpdateUses(use, use);
  654. } else {
  655. context()->AnalyzeUses(use);
  656. }
  657. } break;
  658. case spv::Op::OpCompositeExtract: {
  659. // Update the actual use.
  660. context()->ForgetUses(use);
  661. use->SetOperand(index, {new_ptr_inst->result_id()});
  662. uint32_t new_type_id = new_ptr_inst->type_id();
  663. std::vector<uint32_t> access_chain;
  664. for (uint32_t i = 1; i < use->NumInOperands(); ++i) {
  665. access_chain.push_back(use->GetSingleWordInOperand(i));
  666. }
  667. new_type_id = GetMemberTypeId(new_type_id, access_chain);
  668. if (new_type_id != use->type_id()) {
  669. use->SetResultType(new_type_id);
  670. context()->AnalyzeUses(use);
  671. UpdateUses(use, use);
  672. } else {
  673. context()->AnalyzeUses(use);
  674. }
  675. } break;
  676. case spv::Op::OpStore:
  677. // If the use is the pointer, then it is the single store to that
  678. // variable. We do not want to replace it. Instead, it will become
  679. // dead after all of the loads are removed, and ADCE will get rid of it.
  680. //
  681. // If the use is the object being stored, we will create a copy of the
  682. // object turning it into the correct type. The copy is done by
  683. // decomposing the object into the base type, which must be the same,
  684. // and then rebuilding them.
  685. if (index == 1) {
  686. Instruction* target_pointer = def_use_mgr->GetDef(
  687. use->GetSingleWordInOperand(kStorePointerInOperand));
  688. Instruction* pointer_type =
  689. def_use_mgr->GetDef(target_pointer->type_id());
  690. uint32_t pointee_type_id =
  691. pointer_type->GetSingleWordInOperand(kTypePointerPointeeInIdx);
  692. uint32_t copy = GenerateCopy(original_ptr_inst, pointee_type_id, use);
  693. assert(copy != 0 &&
  694. "Should not be updating uses unless we know it can be done.");
  695. context()->ForgetUses(use);
  696. use->SetInOperand(index, {copy});
  697. context()->AnalyzeUses(use);
  698. }
  699. break;
  700. case spv::Op::OpDecorate:
  701. // We treat an OpImageTexelPointer as a load. The result type should
  702. // always have the Image storage class, and should not need to be
  703. // updated.
  704. case spv::Op::OpImageTexelPointer:
  705. // Replace the actual use.
  706. context()->ForgetUses(use);
  707. use->SetOperand(index, {new_ptr_inst->result_id()});
  708. context()->AnalyzeUses(use);
  709. break;
  710. default:
  711. assert(false && "Don't know how to rewrite instruction");
  712. break;
  713. }
  714. }
  715. }
  716. uint32_t CopyPropagateArrays::GetMemberTypeId(
  717. uint32_t id, const std::vector<uint32_t>& access_chain) const {
  718. for (uint32_t element_index : access_chain) {
  719. Instruction* type_inst = get_def_use_mgr()->GetDef(id);
  720. switch (type_inst->opcode()) {
  721. case spv::Op::OpTypeArray:
  722. case spv::Op::OpTypeRuntimeArray:
  723. case spv::Op::OpTypeMatrix:
  724. case spv::Op::OpTypeVector:
  725. id = type_inst->GetSingleWordInOperand(0);
  726. break;
  727. case spv::Op::OpTypeStruct:
  728. id = type_inst->GetSingleWordInOperand(element_index);
  729. break;
  730. default:
  731. break;
  732. }
  733. assert(id != 0 &&
  734. "Tried to extract from an object where it cannot be done.");
  735. }
  736. return id;
  737. }
  738. void CopyPropagateArrays::AddUsesToWorklist(Instruction* inst) {
  739. analysis::DefUseManager* def_use_mgr = context()->get_def_use_mgr();
  740. def_use_mgr->ForEachUse(inst, [this](Instruction* use, uint32_t) {
  741. if (use->opcode() == spv::Op::OpStore) {
  742. uint32_t var_id;
  743. Instruction* target_pointer = GetPtr(use, &var_id);
  744. if (target_pointer->opcode() != spv::Op::OpVariable) {
  745. return;
  746. }
  747. worklist_.push(target_pointer);
  748. }
  749. });
  750. }
  751. void CopyPropagateArrays::MemoryObject::PushIndirection(
  752. const std::vector<AccessChainEntry>& access_chain) {
  753. access_chain_.insert(access_chain_.end(), access_chain.begin(),
  754. access_chain.end());
  755. }
  756. uint32_t CopyPropagateArrays::MemoryObject::GetNumberOfMembers() {
  757. IRContext* context = variable_inst_->context();
  758. analysis::TypeManager* type_mgr = context->get_type_mgr();
  759. const analysis::Type* type = type_mgr->GetType(variable_inst_->type_id());
  760. type = type->AsPointer()->pointee_type();
  761. std::vector<uint32_t> access_indices = GetAccessIds();
  762. type = type_mgr->GetMemberType(type, access_indices);
  763. return opt::GetNumberOfMembers(type, context);
  764. }
  765. template <class iterator>
  766. CopyPropagateArrays::MemoryObject::MemoryObject(Instruction* var_inst,
  767. iterator begin, iterator end)
  768. : variable_inst_(var_inst) {
  769. std::transform(begin, end, std::back_inserter(access_chain_),
  770. [](uint32_t id) {
  771. return AccessChainEntry{true, {id}};
  772. });
  773. }
  774. std::vector<uint32_t> CopyPropagateArrays::MemoryObject::GetAccessIds() const {
  775. analysis::ConstantManager* const_mgr =
  776. variable_inst_->context()->get_constant_mgr();
  777. std::vector<uint32_t> indices(AccessChain().size());
  778. std::transform(AccessChain().cbegin(), AccessChain().cend(), indices.begin(),
  779. [&const_mgr](const AccessChainEntry& entry) {
  780. if (entry.is_result_id) {
  781. const analysis::Constant* constant =
  782. const_mgr->FindDeclaredConstant(entry.result_id);
  783. return constant == nullptr ? 0 : constant->GetU32();
  784. }
  785. return entry.immediate;
  786. });
  787. return indices;
  788. }
  789. bool CopyPropagateArrays::MemoryObject::Contains(
  790. CopyPropagateArrays::MemoryObject* other) {
  791. if (this->GetVariable() != other->GetVariable()) {
  792. return false;
  793. }
  794. if (AccessChain().size() > other->AccessChain().size()) {
  795. return false;
  796. }
  797. for (uint32_t i = 0; i < AccessChain().size(); i++) {
  798. if (AccessChain()[i] != other->AccessChain()[i]) {
  799. return false;
  800. }
  801. }
  802. return true;
  803. }
  804. void CopyPropagateArrays::MemoryObject::BuildConstants() {
  805. for (auto& entry : access_chain_) {
  806. if (entry.is_result_id) {
  807. continue;
  808. }
  809. auto context = variable_inst_->context();
  810. analysis::Integer int_type(32, false);
  811. const analysis::Type* uint32_type =
  812. context->get_type_mgr()->GetRegisteredType(&int_type);
  813. analysis::ConstantManager* const_mgr = context->get_constant_mgr();
  814. const analysis::Constant* index_const =
  815. const_mgr->GetConstant(uint32_type, {entry.immediate});
  816. entry.result_id =
  817. const_mgr->GetDefiningInstruction(index_const)->result_id();
  818. entry.is_result_id = true;
  819. }
  820. }
  821. } // namespace opt
  822. } // namespace spvtools