loop_unswitch_pass.cpp 23 KB

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