loop_unswitch_pass.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  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/loop_unswitch_pass.h"
  15. #include <functional>
  16. #include <list>
  17. #include <memory>
  18. #include <type_traits>
  19. #include <unordered_map>
  20. #include <unordered_set>
  21. #include <utility>
  22. #include <vector>
  23. #include "source/opt/basic_block.h"
  24. #include "source/opt/dominator_tree.h"
  25. #include "source/opt/fold.h"
  26. #include "source/opt/function.h"
  27. #include "source/opt/instruction.h"
  28. #include "source/opt/ir_builder.h"
  29. #include "source/opt/ir_context.h"
  30. #include "source/opt/loop_descriptor.h"
  31. #include "source/opt/loop_utils.h"
  32. namespace spvtools {
  33. namespace opt {
  34. namespace {
  35. constexpr uint32_t kTypePointerStorageClassInIdx = 0;
  36. // This class handle the unswitch procedure for a given loop.
  37. // The unswitch will not happen if:
  38. // - The loop has any instruction that will prevent it;
  39. // - The loop invariant condition is not uniform.
  40. class LoopUnswitch {
  41. public:
  42. LoopUnswitch(IRContext* context, Function* function, Loop* loop,
  43. LoopDescriptor* loop_desc)
  44. : function_(function),
  45. loop_(loop),
  46. loop_desc_(*loop_desc),
  47. context_(context),
  48. switch_block_(nullptr) {}
  49. // Returns true if the loop can be unswitched.
  50. // Can be unswitch if:
  51. // - The loop has no instructions that prevents it (such as barrier);
  52. // - The loop has one conditional branch or switch that do not depends on the
  53. // loop;
  54. // - The loop invariant condition is uniform;
  55. bool CanUnswitchLoop() {
  56. if (switch_block_) return true;
  57. if (loop_->IsSafeToClone()) return false;
  58. CFG& cfg = *context_->cfg();
  59. for (uint32_t bb_id : loop_->GetBlocks()) {
  60. BasicBlock* bb = cfg.block(bb_id);
  61. if (loop_->GetLatchBlock() == bb) {
  62. continue;
  63. }
  64. if (bb->terminator()->IsBranch() &&
  65. bb->terminator()->opcode() != spv::Op::OpBranch) {
  66. if (IsConditionNonConstantLoopInvariant(bb->terminator())) {
  67. switch_block_ = bb;
  68. break;
  69. }
  70. }
  71. }
  72. return switch_block_;
  73. }
  74. // Return the iterator to the basic block |bb|.
  75. Function::iterator FindBasicBlockPosition(BasicBlock* bb_to_find) {
  76. Function::iterator it = function_->FindBlock(bb_to_find->id());
  77. assert(it != function_->end() && "Basic Block not found");
  78. return it;
  79. }
  80. // Creates a new basic block and insert it into the function |fn| at the
  81. // position |ip|. This function preserves the def/use and instr to block
  82. // managers.
  83. BasicBlock* CreateBasicBlock(Function::iterator ip) {
  84. analysis::DefUseManager* def_use_mgr = context_->get_def_use_mgr();
  85. // TODO(1841): Handle id overflow.
  86. BasicBlock* bb = &*ip.InsertBefore(std::unique_ptr<BasicBlock>(
  87. new BasicBlock(std::unique_ptr<Instruction>(new Instruction(
  88. context_, spv::Op::OpLabel, 0, context_->TakeNextId(), {})))));
  89. bb->SetParent(function_);
  90. def_use_mgr->AnalyzeInstDef(bb->GetLabelInst());
  91. context_->set_instr_block(bb->GetLabelInst(), bb);
  92. return bb;
  93. }
  94. Instruction* GetValueForDefaultPathForSwitch(Instruction* switch_inst) {
  95. assert(switch_inst->opcode() == spv::Op::OpSwitch &&
  96. "The given instructoin must be an OpSwitch.");
  97. // Find a value that can be used to select the default path.
  98. // If none are possible, then it will just use 0. The value does not matter
  99. // because this path will never be taken because the new switch outside of
  100. // the loop cannot select this path either.
  101. std::vector<uint32_t> existing_values;
  102. for (uint32_t i = 2; i < switch_inst->NumInOperands(); i += 2) {
  103. existing_values.push_back(switch_inst->GetSingleWordInOperand(i));
  104. }
  105. std::sort(existing_values.begin(), existing_values.end());
  106. uint32_t value_for_default_path = 0;
  107. if (existing_values.size() < std::numeric_limits<uint32_t>::max()) {
  108. for (value_for_default_path = 0;
  109. value_for_default_path < existing_values.size();
  110. value_for_default_path++) {
  111. if (existing_values[value_for_default_path] != value_for_default_path) {
  112. break;
  113. }
  114. }
  115. }
  116. InstructionBuilder builder(
  117. context_, static_cast<Instruction*>(nullptr),
  118. IRContext::kAnalysisDefUse | IRContext::kAnalysisInstrToBlockMapping);
  119. return builder.GetUintConstant(value_for_default_path);
  120. }
  121. // Unswitches |loop_|.
  122. void PerformUnswitch() {
  123. assert(CanUnswitchLoop() &&
  124. "Cannot unswitch if there is not constant condition");
  125. assert(loop_->GetPreHeaderBlock() && "This loop has no pre-header block");
  126. assert(loop_->IsLCSSA() && "This loop is not in LCSSA form");
  127. CFG& cfg = *context_->cfg();
  128. DominatorTree* dom_tree =
  129. &context_->GetDominatorAnalysis(function_)->GetDomTree();
  130. analysis::DefUseManager* def_use_mgr = context_->get_def_use_mgr();
  131. LoopUtils loop_utils(context_, loop_);
  132. //////////////////////////////////////////////////////////////////////////////
  133. // Step 1: Create the if merge block for structured modules.
  134. // To do so, the |loop_| merge block will become the if's one and we
  135. // create a merge for the loop. This will limit the amount of duplicated
  136. // code the structured control flow imposes.
  137. // For non structured program, the new loop will be connected to
  138. // the old loop's exit blocks.
  139. //////////////////////////////////////////////////////////////////////////////
  140. // Get the merge block if it exists.
  141. BasicBlock* if_merge_block = loop_->GetMergeBlock();
  142. // The merge block is only created if the loop has a unique exit block. We
  143. // have this guarantee for structured loops, for compute loop it will
  144. // trivially help maintain both a structured-like form and LCSAA.
  145. BasicBlock* loop_merge_block =
  146. if_merge_block
  147. ? CreateBasicBlock(FindBasicBlockPosition(if_merge_block))
  148. : nullptr;
  149. if (loop_merge_block) {
  150. // Add the instruction and update managers.
  151. InstructionBuilder builder(
  152. context_, loop_merge_block,
  153. IRContext::kAnalysisDefUse | IRContext::kAnalysisInstrToBlockMapping);
  154. builder.AddBranch(if_merge_block->id());
  155. builder.SetInsertPoint(&*loop_merge_block->begin());
  156. cfg.RegisterBlock(loop_merge_block);
  157. def_use_mgr->AnalyzeInstDef(loop_merge_block->GetLabelInst());
  158. // Update CFG.
  159. if_merge_block->ForEachPhiInst(
  160. [loop_merge_block, &builder, this](Instruction* phi) {
  161. Instruction* cloned = phi->Clone(context_);
  162. cloned->SetResultId(TakeNextId());
  163. builder.AddInstruction(std::unique_ptr<Instruction>(cloned));
  164. phi->SetInOperand(0, {cloned->result_id()});
  165. phi->SetInOperand(1, {loop_merge_block->id()});
  166. for (uint32_t j = phi->NumInOperands() - 1; j > 1; j--)
  167. phi->RemoveInOperand(j);
  168. });
  169. // Copy the predecessor list (will get invalidated otherwise).
  170. std::vector<uint32_t> preds = cfg.preds(if_merge_block->id());
  171. for (uint32_t pid : preds) {
  172. if (pid == loop_merge_block->id()) continue;
  173. BasicBlock* p_bb = cfg.block(pid);
  174. p_bb->ForEachSuccessorLabel(
  175. [if_merge_block, loop_merge_block](uint32_t* id) {
  176. if (*id == if_merge_block->id()) *id = loop_merge_block->id();
  177. });
  178. cfg.AddEdge(pid, loop_merge_block->id());
  179. }
  180. cfg.RemoveNonExistingEdges(if_merge_block->id());
  181. // Update loop descriptor.
  182. if (Loop* ploop = loop_->GetParent()) {
  183. ploop->AddBasicBlock(loop_merge_block);
  184. loop_desc_.SetBasicBlockToLoop(loop_merge_block->id(), ploop);
  185. }
  186. // Update the dominator tree.
  187. DominatorTreeNode* loop_merge_dtn =
  188. dom_tree->GetOrInsertNode(loop_merge_block);
  189. DominatorTreeNode* if_merge_block_dtn =
  190. dom_tree->GetOrInsertNode(if_merge_block);
  191. loop_merge_dtn->parent_ = if_merge_block_dtn->parent_;
  192. loop_merge_dtn->children_.push_back(if_merge_block_dtn);
  193. loop_merge_dtn->parent_->children_.push_back(loop_merge_dtn);
  194. if_merge_block_dtn->parent_->children_.erase(std::find(
  195. if_merge_block_dtn->parent_->children_.begin(),
  196. if_merge_block_dtn->parent_->children_.end(), if_merge_block_dtn));
  197. loop_->SetMergeBlock(loop_merge_block);
  198. }
  199. ////////////////////////////////////////////////////////////////////////////
  200. // Step 2: Build a new preheader for |loop_|, use the old one
  201. // for the invariant branch.
  202. ////////////////////////////////////////////////////////////////////////////
  203. BasicBlock* if_block = loop_->GetPreHeaderBlock();
  204. // If this preheader is the parent loop header,
  205. // we need to create a dedicated block for the if.
  206. BasicBlock* loop_pre_header =
  207. CreateBasicBlock(++FindBasicBlockPosition(if_block));
  208. InstructionBuilder(
  209. context_, loop_pre_header,
  210. IRContext::kAnalysisDefUse | IRContext::kAnalysisInstrToBlockMapping)
  211. .AddBranch(loop_->GetHeaderBlock()->id());
  212. if_block->tail()->SetInOperand(0, {loop_pre_header->id()});
  213. // Update loop descriptor.
  214. if (Loop* ploop = loop_desc_[if_block]) {
  215. ploop->AddBasicBlock(loop_pre_header);
  216. loop_desc_.SetBasicBlockToLoop(loop_pre_header->id(), ploop);
  217. }
  218. // Update the CFG.
  219. cfg.RegisterBlock(loop_pre_header);
  220. def_use_mgr->AnalyzeInstDef(loop_pre_header->GetLabelInst());
  221. cfg.AddEdge(if_block->id(), loop_pre_header->id());
  222. cfg.RemoveNonExistingEdges(loop_->GetHeaderBlock()->id());
  223. loop_->GetHeaderBlock()->ForEachPhiInst(
  224. [loop_pre_header, if_block](Instruction* phi) {
  225. phi->ForEachInId([loop_pre_header, if_block](uint32_t* id) {
  226. if (*id == if_block->id()) {
  227. *id = loop_pre_header->id();
  228. }
  229. });
  230. });
  231. loop_->SetPreHeaderBlock(loop_pre_header);
  232. // Update the dominator tree.
  233. DominatorTreeNode* loop_pre_header_dtn =
  234. dom_tree->GetOrInsertNode(loop_pre_header);
  235. DominatorTreeNode* if_block_dtn = dom_tree->GetTreeNode(if_block);
  236. loop_pre_header_dtn->parent_ = if_block_dtn;
  237. assert(
  238. if_block_dtn->children_.size() == 1 &&
  239. "A loop preheader should only have the header block as a child in the "
  240. "dominator tree");
  241. loop_pre_header_dtn->children_.push_back(if_block_dtn->children_[0]);
  242. if_block_dtn->children_.clear();
  243. if_block_dtn->children_.push_back(loop_pre_header_dtn);
  244. // Make domination queries valid.
  245. dom_tree->ResetDFNumbering();
  246. // Compute an ordered list of basic block to clone: loop blocks + pre-header
  247. // + merge block.
  248. loop_->ComputeLoopStructuredOrder(&ordered_loop_blocks_, true, true);
  249. /////////////////////////////
  250. // Do the actual unswitch: //
  251. // - Clone the loop //
  252. // - Connect exits //
  253. // - Specialize the loop //
  254. /////////////////////////////
  255. Instruction* iv_condition = &*switch_block_->tail();
  256. spv::Op iv_opcode = iv_condition->opcode();
  257. Instruction* condition =
  258. def_use_mgr->GetDef(iv_condition->GetOperand(0).words[0]);
  259. analysis::ConstantManager* cst_mgr = context_->get_constant_mgr();
  260. const analysis::Type* cond_type =
  261. context_->get_type_mgr()->GetType(condition->type_id());
  262. // Build the list of value for which we need to clone and specialize the
  263. // loop.
  264. std::vector<std::pair<Instruction*, BasicBlock*>> constant_branch;
  265. // Special case for the original loop
  266. Instruction* original_loop_constant_value;
  267. if (iv_opcode == spv::Op::OpBranchConditional) {
  268. constant_branch.emplace_back(
  269. cst_mgr->GetDefiningInstruction(cst_mgr->GetConstant(cond_type, {0})),
  270. nullptr);
  271. original_loop_constant_value =
  272. cst_mgr->GetDefiningInstruction(cst_mgr->GetConstant(cond_type, {1}));
  273. } else {
  274. // We are looking to take the default branch, so we can't provide a
  275. // specific value.
  276. original_loop_constant_value =
  277. GetValueForDefaultPathForSwitch(iv_condition);
  278. for (uint32_t i = 2; i < iv_condition->NumInOperands(); i += 2) {
  279. constant_branch.emplace_back(
  280. cst_mgr->GetDefiningInstruction(cst_mgr->GetConstant(
  281. cond_type, iv_condition->GetInOperand(i).words)),
  282. nullptr);
  283. }
  284. }
  285. // Get the loop landing pads.
  286. std::unordered_set<uint32_t> if_merging_blocks;
  287. std::function<bool(uint32_t)> is_from_original_loop;
  288. if (loop_->GetHeaderBlock()->GetLoopMergeInst()) {
  289. if_merging_blocks.insert(if_merge_block->id());
  290. is_from_original_loop = [this](uint32_t id) {
  291. return loop_->IsInsideLoop(id) || loop_->GetMergeBlock()->id() == id;
  292. };
  293. } else {
  294. loop_->GetExitBlocks(&if_merging_blocks);
  295. is_from_original_loop = [this](uint32_t id) {
  296. return loop_->IsInsideLoop(id);
  297. };
  298. }
  299. for (auto& specialisation_pair : constant_branch) {
  300. Instruction* specialisation_value = specialisation_pair.first;
  301. //////////////////////////////////////////////////////////
  302. // Step 3: Duplicate |loop_|.
  303. //////////////////////////////////////////////////////////
  304. LoopUtils::LoopCloningResult clone_result;
  305. Loop* cloned_loop =
  306. loop_utils.CloneLoop(&clone_result, ordered_loop_blocks_);
  307. specialisation_pair.second = cloned_loop->GetPreHeaderBlock();
  308. ////////////////////////////////////
  309. // Step 4: Specialize the loop. //
  310. ////////////////////////////////////
  311. {
  312. SpecializeLoop(cloned_loop, condition, specialisation_value);
  313. ///////////////////////////////////////////////////////////
  314. // Step 5: Connect convergent edges to the landing pads. //
  315. ///////////////////////////////////////////////////////////
  316. for (uint32_t merge_bb_id : if_merging_blocks) {
  317. BasicBlock* merge = context_->cfg()->block(merge_bb_id);
  318. // We are in LCSSA so we only care about phi instructions.
  319. merge->ForEachPhiInst(
  320. [is_from_original_loop, &clone_result](Instruction* phi) {
  321. uint32_t num_in_operands = phi->NumInOperands();
  322. for (uint32_t i = 0; i < num_in_operands; i += 2) {
  323. uint32_t pred = phi->GetSingleWordInOperand(i + 1);
  324. if (is_from_original_loop(pred)) {
  325. pred = clone_result.value_map_.at(pred);
  326. uint32_t incoming_value_id = phi->GetSingleWordInOperand(i);
  327. // Not all the incoming values are coming from the loop.
  328. ValueMapTy::iterator new_value =
  329. clone_result.value_map_.find(incoming_value_id);
  330. if (new_value != clone_result.value_map_.end()) {
  331. incoming_value_id = new_value->second;
  332. }
  333. phi->AddOperand({SPV_OPERAND_TYPE_ID, {incoming_value_id}});
  334. phi->AddOperand({SPV_OPERAND_TYPE_ID, {pred}});
  335. }
  336. }
  337. });
  338. }
  339. }
  340. function_->AddBasicBlocks(clone_result.cloned_bb_.begin(),
  341. clone_result.cloned_bb_.end(),
  342. ++FindBasicBlockPosition(if_block));
  343. }
  344. // Specialize the existing loop.
  345. SpecializeLoop(loop_, condition, original_loop_constant_value);
  346. BasicBlock* original_loop_target = loop_->GetPreHeaderBlock();
  347. /////////////////////////////////////
  348. // Finally: connect the new loops. //
  349. /////////////////////////////////////
  350. // Delete the old jump
  351. context_->KillInst(&*if_block->tail());
  352. InstructionBuilder builder(context_, if_block);
  353. if (iv_opcode == spv::Op::OpBranchConditional) {
  354. assert(constant_branch.size() == 1);
  355. builder.AddConditionalBranch(
  356. condition->result_id(), original_loop_target->id(),
  357. constant_branch[0].second->id(),
  358. if_merge_block ? if_merge_block->id() : kInvalidId);
  359. } else {
  360. std::vector<std::pair<Operand::OperandData, uint32_t>> targets;
  361. for (auto& t : constant_branch) {
  362. targets.emplace_back(t.first->GetInOperand(0).words, t.second->id());
  363. }
  364. builder.AddSwitch(condition->result_id(), original_loop_target->id(),
  365. targets,
  366. if_merge_block ? if_merge_block->id() : kInvalidId);
  367. }
  368. switch_block_ = nullptr;
  369. ordered_loop_blocks_.clear();
  370. context_->InvalidateAnalysesExceptFor(
  371. IRContext::Analysis::kAnalysisLoopAnalysis);
  372. }
  373. private:
  374. using ValueMapTy = std::unordered_map<uint32_t, uint32_t>;
  375. using BlockMapTy = std::unordered_map<uint32_t, BasicBlock*>;
  376. Function* function_;
  377. Loop* loop_;
  378. LoopDescriptor& loop_desc_;
  379. IRContext* context_;
  380. BasicBlock* switch_block_;
  381. // Map between instructions and if they are dynamically uniform.
  382. std::unordered_map<uint32_t, bool> dynamically_uniform_;
  383. // The loop basic blocks in structured order.
  384. std::vector<BasicBlock*> ordered_loop_blocks_;
  385. // Returns the next usable id for the context.
  386. uint32_t TakeNextId() {
  387. // TODO(1841): Handle id overflow.
  388. return context_->TakeNextId();
  389. }
  390. // Simplifies |loop| assuming the instruction |to_version_insn| takes the
  391. // value |cst_value|. |block_range| is an iterator range returning the loop
  392. // basic blocks in a structured order (dominator first).
  393. // The function will ignore basic blocks returned by |block_range| if they
  394. // does not belong to the loop.
  395. // The set |dead_blocks| will contain all the dead basic blocks.
  396. //
  397. // Requirements:
  398. // - |loop| must be in the LCSSA form;
  399. // - |cst_value| must be constant.
  400. void SpecializeLoop(Loop* loop, Instruction* to_version_insn,
  401. Instruction* cst_value) {
  402. analysis::DefUseManager* def_use_mgr = context_->get_def_use_mgr();
  403. std::function<bool(uint32_t)> ignore_node;
  404. ignore_node = [loop](uint32_t bb_id) { return !loop->IsInsideLoop(bb_id); };
  405. std::vector<std::pair<Instruction*, uint32_t>> use_list;
  406. def_use_mgr->ForEachUse(to_version_insn,
  407. [&use_list, &ignore_node, this](
  408. Instruction* inst, uint32_t operand_index) {
  409. BasicBlock* bb = context_->get_instr_block(inst);
  410. if (!bb || ignore_node(bb->id())) {
  411. // Out of the loop, the specialization does not
  412. // apply any more.
  413. return;
  414. }
  415. use_list.emplace_back(inst, operand_index);
  416. });
  417. // First pass: inject the specialized value into the loop (and only the
  418. // loop).
  419. for (auto use : use_list) {
  420. Instruction* inst = use.first;
  421. uint32_t operand_index = use.second;
  422. // To also handle switch, cst_value can be nullptr: this case
  423. // means that we are looking to branch to the default target of
  424. // the switch. We don't actually know its value so we don't touch
  425. // it if it not a switch.
  426. assert(cst_value && "We do not have a value to use.");
  427. inst->SetOperand(operand_index, {cst_value->result_id()});
  428. def_use_mgr->AnalyzeInstUse(inst);
  429. }
  430. }
  431. // Returns true if |var| is dynamically uniform.
  432. // Note: this is currently approximated as uniform.
  433. bool IsDynamicallyUniform(Instruction* var, const BasicBlock* entry,
  434. const DominatorTree& post_dom_tree) {
  435. assert(post_dom_tree.IsPostDominator());
  436. analysis::DefUseManager* def_use_mgr = context_->get_def_use_mgr();
  437. auto it = dynamically_uniform_.find(var->result_id());
  438. if (it != dynamically_uniform_.end()) return it->second;
  439. analysis::DecorationManager* dec_mgr = context_->get_decoration_mgr();
  440. bool& is_uniform = dynamically_uniform_[var->result_id()];
  441. is_uniform = false;
  442. dec_mgr->WhileEachDecoration(var->result_id(),
  443. uint32_t(spv::Decoration::Uniform),
  444. [&is_uniform](const Instruction&) {
  445. is_uniform = true;
  446. return false;
  447. });
  448. if (is_uniform) {
  449. return is_uniform;
  450. }
  451. BasicBlock* parent = context_->get_instr_block(var);
  452. if (!parent) {
  453. return is_uniform = true;
  454. }
  455. if (!post_dom_tree.Dominates(parent->id(), entry->id())) {
  456. return is_uniform = false;
  457. }
  458. if (var->opcode() == spv::Op::OpLoad) {
  459. const uint32_t PtrTypeId =
  460. def_use_mgr->GetDef(var->GetSingleWordInOperand(0))->type_id();
  461. const Instruction* PtrTypeInst = def_use_mgr->GetDef(PtrTypeId);
  462. auto storage_class = spv::StorageClass(
  463. PtrTypeInst->GetSingleWordInOperand(kTypePointerStorageClassInIdx));
  464. if (storage_class != spv::StorageClass::Uniform &&
  465. storage_class != spv::StorageClass::UniformConstant) {
  466. return is_uniform = false;
  467. }
  468. } else {
  469. if (!context_->IsCombinatorInstruction(var)) {
  470. return is_uniform = false;
  471. }
  472. }
  473. return is_uniform = var->WhileEachInId([entry, &post_dom_tree,
  474. this](const uint32_t* id) {
  475. return IsDynamicallyUniform(context_->get_def_use_mgr()->GetDef(*id),
  476. entry, post_dom_tree);
  477. });
  478. }
  479. // Returns true if |insn| is not a constant, but is loop invariant and
  480. // dynamically uniform.
  481. bool IsConditionNonConstantLoopInvariant(Instruction* insn) {
  482. assert(insn->IsBranch());
  483. assert(insn->opcode() != spv::Op::OpBranch);
  484. analysis::DefUseManager* def_use_mgr = context_->get_def_use_mgr();
  485. Instruction* condition = def_use_mgr->GetDef(insn->GetOperand(0).words[0]);
  486. if (condition->IsConstant()) {
  487. return false;
  488. }
  489. if (loop_->IsInsideLoop(condition)) {
  490. return false;
  491. }
  492. return IsDynamicallyUniform(
  493. condition, function_->entry().get(),
  494. context_->GetPostDominatorAnalysis(function_)->GetDomTree());
  495. }
  496. };
  497. } // namespace
  498. Pass::Status LoopUnswitchPass::Process() {
  499. bool modified = false;
  500. Module* module = context()->module();
  501. // Process each function in the module
  502. for (Function& f : *module) {
  503. modified |= ProcessFunction(&f);
  504. }
  505. return modified ? Status::SuccessWithChange : Status::SuccessWithoutChange;
  506. }
  507. bool LoopUnswitchPass::ProcessFunction(Function* f) {
  508. bool modified = false;
  509. std::unordered_set<Loop*> processed_loop;
  510. LoopDescriptor& loop_descriptor = *context()->GetLoopDescriptor(f);
  511. bool loop_changed = true;
  512. while (loop_changed) {
  513. loop_changed = false;
  514. for (Loop& loop : make_range(
  515. ++TreeDFIterator<Loop>(loop_descriptor.GetPlaceholderRootLoop()),
  516. TreeDFIterator<Loop>())) {
  517. if (processed_loop.count(&loop)) continue;
  518. processed_loop.insert(&loop);
  519. LoopUnswitch unswitcher(context(), f, &loop, &loop_descriptor);
  520. while (unswitcher.CanUnswitchLoop()) {
  521. if (!loop.IsLCSSA()) {
  522. LoopUtils(context(), &loop).MakeLoopClosedSSA();
  523. }
  524. modified = true;
  525. loop_changed = true;
  526. unswitcher.PerformUnswitch();
  527. }
  528. if (loop_changed) break;
  529. }
  530. }
  531. return modified;
  532. }
  533. } // namespace opt
  534. } // namespace spvtools