loop_unswitch_pass.cpp 23 KB

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