loop_unroller.cpp 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093
  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_unroller.h"
  15. #include <limits>
  16. #include <map>
  17. #include <memory>
  18. #include <unordered_map>
  19. #include <utility>
  20. #include <vector>
  21. #include "source/opt/ir_builder.h"
  22. #include "source/opt/loop_utils.h"
  23. // Implements loop util unrolling functionality for fully and partially
  24. // unrolling loops. Given a factor it will duplicate the loop that many times,
  25. // appending each one to the end of the old loop and removing backedges, to
  26. // create a new unrolled loop.
  27. //
  28. // 1 - User calls LoopUtils::FullyUnroll or LoopUtils::PartiallyUnroll with a
  29. // loop they wish to unroll. LoopUtils::CanPerformUnroll is used to
  30. // validate that a given loop can be unrolled. That method (along with the
  31. // constructor of loop) checks that the IR is in the expected canonicalised
  32. // format.
  33. //
  34. // 2 - The LoopUtils methods create a LoopUnrollerUtilsImpl object to actually
  35. // perform the unrolling. This implements helper methods to copy the loop basic
  36. // blocks and remap the ids of instructions used inside them.
  37. //
  38. // 3 - The core of LoopUnrollerUtilsImpl is the Unroll method, this method
  39. // actually performs the loop duplication. It does this by creating a
  40. // LoopUnrollState object and then copying the loop as given by the factor
  41. // parameter. The LoopUnrollState object retains the state of the unroller
  42. // between the loop body copies as each iteration needs information on the last
  43. // to adjust the phi induction variable, adjust the OpLoopMerge instruction in
  44. // the main loop header, and change the previous continue block to point to the
  45. // new header and the new continue block to the main loop header.
  46. //
  47. // 4 - If the loop is to be fully unrolled then it is simply closed after step
  48. // 3, with the OpLoopMerge being deleted, the backedge removed, and the
  49. // condition blocks folded.
  50. //
  51. // 5 - If it is being partially unrolled: if the unrolling factor leaves the
  52. // loop with an even number of bodies with respect to the number of loop
  53. // iterations then step 3 is all that is needed. If it is uneven then we need to
  54. // duplicate the loop completely and unroll the duplicated loop to cover the
  55. // residual part and adjust the first loop to cover only the "even" part. For
  56. // instance if you request an unroll factor of 3 on a loop with 10 iterations
  57. // then copying the body three times would leave you with three bodies in the
  58. // loop
  59. // where the loop still iterates over each 4 times. So we make two loops one
  60. // iterating once then a second loop of three iterating 3 times.
  61. namespace spvtools {
  62. namespace opt {
  63. namespace {
  64. // Loop control constant value for DontUnroll flag.
  65. static const uint32_t kLoopControlDontUnrollIndex = 2;
  66. // Operand index of the loop control parameter of the OpLoopMerge.
  67. static const uint32_t kLoopControlIndex = 2;
  68. // This utility class encapsulates some of the state we need to maintain between
  69. // loop unrolls. Specifically it maintains key blocks and the induction variable
  70. // in the current loop duplication step and the blocks from the previous one.
  71. // This is because each step of the unroll needs to use data from both the
  72. // preceding step and the original loop.
  73. struct LoopUnrollState {
  74. LoopUnrollState()
  75. : previous_phi_(nullptr),
  76. previous_latch_block_(nullptr),
  77. previous_condition_block_(nullptr),
  78. new_phi(nullptr),
  79. new_continue_block(nullptr),
  80. new_condition_block(nullptr),
  81. new_header_block(nullptr) {}
  82. // Initialize from the loop descriptor class.
  83. LoopUnrollState(Instruction* induction, BasicBlock* latch_block,
  84. BasicBlock* condition, std::vector<Instruction*>&& phis)
  85. : previous_phi_(induction),
  86. previous_latch_block_(latch_block),
  87. previous_condition_block_(condition),
  88. new_phi(nullptr),
  89. new_continue_block(nullptr),
  90. new_condition_block(nullptr),
  91. new_header_block(nullptr) {
  92. previous_phis_ = std::move(phis);
  93. }
  94. // Swap the state so that the new nodes are now the previous nodes.
  95. void NextIterationState() {
  96. previous_phi_ = new_phi;
  97. previous_latch_block_ = new_latch_block;
  98. previous_condition_block_ = new_condition_block;
  99. previous_phis_ = std::move(new_phis_);
  100. // Clear new nodes.
  101. new_phi = nullptr;
  102. new_continue_block = nullptr;
  103. new_condition_block = nullptr;
  104. new_header_block = nullptr;
  105. new_latch_block = nullptr;
  106. // Clear new block/instruction maps.
  107. new_blocks.clear();
  108. new_inst.clear();
  109. ids_to_new_inst.clear();
  110. }
  111. // The induction variable from the immediately preceding loop body.
  112. Instruction* previous_phi_;
  113. // All the phi nodes from the previous loop iteration.
  114. std::vector<Instruction*> previous_phis_;
  115. std::vector<Instruction*> new_phis_;
  116. // The previous latch block. The backedge will be removed from this and
  117. // added to the new latch block.
  118. BasicBlock* previous_latch_block_;
  119. // The previous condition block. This may be folded to flatten the loop.
  120. BasicBlock* previous_condition_block_;
  121. // The new induction variable.
  122. Instruction* new_phi;
  123. // The new continue block.
  124. BasicBlock* new_continue_block;
  125. // The new condition block.
  126. BasicBlock* new_condition_block;
  127. // The new header block.
  128. BasicBlock* new_header_block;
  129. // The new latch block.
  130. BasicBlock* new_latch_block;
  131. // A mapping of new block ids to the original blocks which they were copied
  132. // from.
  133. std::unordered_map<uint32_t, BasicBlock*> new_blocks;
  134. // A mapping of the original instruction ids to the instruction ids to their
  135. // copies.
  136. std::unordered_map<uint32_t, uint32_t> new_inst;
  137. std::unordered_map<uint32_t, Instruction*> ids_to_new_inst;
  138. };
  139. // This class implements the actual unrolling. It uses a LoopUnrollState to
  140. // maintain the state of the unrolling inbetween steps.
  141. class LoopUnrollerUtilsImpl {
  142. public:
  143. using BasicBlockListTy = std::vector<std::unique_ptr<BasicBlock>>;
  144. LoopUnrollerUtilsImpl(IRContext* c, Function* function)
  145. : context_(c),
  146. function_(*function),
  147. loop_condition_block_(nullptr),
  148. loop_induction_variable_(nullptr),
  149. number_of_loop_iterations_(0),
  150. loop_step_value_(0),
  151. loop_init_value_(0) {}
  152. // Unroll the |loop| by given |factor| by copying the whole body |factor|
  153. // times. The resulting basicblock structure will remain a loop.
  154. void PartiallyUnroll(Loop*, size_t factor);
  155. // If partially unrolling the |loop| would leave the loop with too many bodies
  156. // for its number of iterations then this method should be used. This method
  157. // will duplicate the |loop| completely, making the duplicated loop the
  158. // successor of the original's merge block. The original loop will have its
  159. // condition changed to loop over the residual part and the duplicate will be
  160. // partially unrolled. The resulting structure will be two loops.
  161. void PartiallyUnrollResidualFactor(Loop* loop, size_t factor);
  162. // Fully unroll the |loop| by copying the full body by the total number of
  163. // loop iterations, folding all conditions, and removing the backedge from the
  164. // continue block to the header.
  165. void FullyUnroll(Loop* loop);
  166. // Get the ID of the variable in the |phi| paired with |label|.
  167. uint32_t GetPhiDefID(const Instruction* phi, uint32_t label) const;
  168. // Close the loop by removing the OpLoopMerge from the |loop| header block and
  169. // making the backedge point to the merge block.
  170. void CloseUnrolledLoop(Loop* loop);
  171. // Remove the OpConditionalBranch instruction inside |conditional_block| used
  172. // to branch to either exit or continue the loop and replace it with an
  173. // unconditional OpBranch to block |new_target|.
  174. void FoldConditionBlock(BasicBlock* condtion_block, uint32_t new_target);
  175. // Add all blocks_to_add_ to function_ at the |insert_point|.
  176. void AddBlocksToFunction(const BasicBlock* insert_point);
  177. // Duplicates the |old_loop|, cloning each body and remaping the ids without
  178. // removing instructions or changing relative structure. Result will be stored
  179. // in |new_loop|.
  180. void DuplicateLoop(Loop* old_loop, Loop* new_loop);
  181. inline size_t GetLoopIterationCount() const {
  182. return number_of_loop_iterations_;
  183. }
  184. // Extracts the initial state information from the |loop|.
  185. void Init(Loop* loop);
  186. // Replace the uses of each induction variable outside the loop with the final
  187. // value of the induction variable before the loop exit. To reflect the proper
  188. // state of a fully unrolled loop.
  189. void ReplaceInductionUseWithFinalValue(Loop* loop);
  190. // Remove all the instructions in the invalidated_instructions_ vector.
  191. void RemoveDeadInstructions();
  192. // Replace any use of induction variables outwith the loop with the final
  193. // value of the induction variable in the unrolled loop.
  194. void ReplaceOutsideLoopUseWithFinalValue(Loop* loop);
  195. // Set the LoopControl operand of the OpLoopMerge instruction to be
  196. // DontUnroll.
  197. void MarkLoopControlAsDontUnroll(Loop* loop) const;
  198. private:
  199. // Remap all the in |basic_block| to new IDs and keep the mapping of new ids
  200. // to old
  201. // ids. |loop| is used to identify special loop blocks (header, continue,
  202. // ect).
  203. void AssignNewResultIds(BasicBlock* basic_block);
  204. // Using the map built by AssignNewResultIds, replace the uses in |inst|
  205. // by the id that the use maps to.
  206. void RemapOperands(Instruction* inst);
  207. // Using the map built by AssignNewResultIds, for each instruction in
  208. // |basic_block| use
  209. // that map to substitute the IDs used by instructions (in the operands) with
  210. // the new ids.
  211. void RemapOperands(BasicBlock* basic_block);
  212. // Copy the whole body of the loop, all blocks dominated by the |loop| header
  213. // and not dominated by the |loop| merge. The copied body will be linked to by
  214. // the old |loop| continue block and the new body will link to the |loop|
  215. // header via the new continue block. |eliminate_conditions| is used to decide
  216. // whether or not to fold all the condition blocks other than the last one.
  217. void CopyBody(Loop* loop, bool eliminate_conditions);
  218. // Copy a given |block_to_copy| in the |loop| and record the mapping of the
  219. // old/new ids. |preserve_instructions| determines whether or not the method
  220. // will modify (other than result_id) instructions which are copied.
  221. void CopyBasicBlock(Loop* loop, const BasicBlock* block_to_copy,
  222. bool preserve_instructions);
  223. // The actual implementation of the unroll step. Unrolls |loop| by given
  224. // |factor| by copying the body by |factor| times. Also propagates the
  225. // induction variable value throughout the copies.
  226. void Unroll(Loop* loop, size_t factor);
  227. // Fills the loop_blocks_inorder_ field with the ordered list of basic blocks
  228. // as computed by the method ComputeLoopOrderedBlocks.
  229. void ComputeLoopOrderedBlocks(Loop* loop);
  230. // Adds the blocks_to_add_ to both the |loop| and to the parent of |loop| if
  231. // the parent exists.
  232. void AddBlocksToLoop(Loop* loop) const;
  233. // After the partially unroll step the phi instructions in the header block
  234. // will be in an illegal format. This function makes the phis legal by making
  235. // the edge from the latch block come from the new latch block and the value
  236. // to be the actual value of the phi at that point.
  237. void LinkLastPhisToStart(Loop* loop) const;
  238. // A pointer to the IRContext. Used to add/remove instructions and for usedef
  239. // chains.
  240. IRContext* context_;
  241. // A reference the function the loop is within.
  242. Function& function_;
  243. // A list of basic blocks to be added to the loop at the end of an unroll
  244. // step.
  245. BasicBlockListTy blocks_to_add_;
  246. // List of instructions which are now dead and can be removed.
  247. std::vector<Instruction*> invalidated_instructions_;
  248. // Maintains the current state of the transform between calls to unroll.
  249. LoopUnrollState state_;
  250. // An ordered list containing the loop basic blocks.
  251. std::vector<BasicBlock*> loop_blocks_inorder_;
  252. // The block containing the condition check which contains a conditional
  253. // branch to the merge and continue block.
  254. BasicBlock* loop_condition_block_;
  255. // The induction variable of the loop.
  256. Instruction* loop_induction_variable_;
  257. // Phis used in the loop need to be remapped to use the actual result values
  258. // and then be remapped at the end.
  259. std::vector<Instruction*> loop_phi_instructions_;
  260. // The number of loop iterations that the loop would preform pre-unroll.
  261. size_t number_of_loop_iterations_;
  262. // The amount that the loop steps each iteration.
  263. int64_t loop_step_value_;
  264. // The value the loop starts stepping from.
  265. int64_t loop_init_value_;
  266. };
  267. /*
  268. * Static helper functions.
  269. */
  270. // Retrieve the index of the OpPhi instruction |phi| which corresponds to the
  271. // incoming |block| id.
  272. static uint32_t GetPhiIndexFromLabel(const BasicBlock* block,
  273. const Instruction* phi) {
  274. for (uint32_t i = 1; i < phi->NumInOperands(); i += 2) {
  275. if (block->id() == phi->GetSingleWordInOperand(i)) {
  276. return i;
  277. }
  278. }
  279. assert(false && "Could not find operand in instruction.");
  280. return 0;
  281. }
  282. void LoopUnrollerUtilsImpl::Init(Loop* loop) {
  283. loop_condition_block_ = loop->FindConditionBlock();
  284. // When we reinit the second loop during PartiallyUnrollResidualFactor we need
  285. // to use the cached value from the duplicate step as the dominator tree
  286. // basded solution, loop->FindConditionBlock, requires all the nodes to be
  287. // connected up with the correct branches. They won't be at this point.
  288. if (!loop_condition_block_) {
  289. loop_condition_block_ = state_.new_condition_block;
  290. }
  291. assert(loop_condition_block_);
  292. loop_induction_variable_ = loop->FindConditionVariable(loop_condition_block_);
  293. assert(loop_induction_variable_);
  294. bool found = loop->FindNumberOfIterations(
  295. loop_induction_variable_, &*loop_condition_block_->ctail(),
  296. &number_of_loop_iterations_, &loop_step_value_, &loop_init_value_);
  297. (void)found; // To silence unused variable warning on release builds.
  298. assert(found);
  299. // Blocks are stored in an unordered set of ids in the loop class, we need to
  300. // create the dominator ordered list.
  301. ComputeLoopOrderedBlocks(loop);
  302. }
  303. // This function is used to partially unroll the loop when the factor provided
  304. // would normally lead to an illegal optimization. Instead of just unrolling the
  305. // loop it creates two loops and unrolls one and adjusts the condition on the
  306. // other. The end result being that the new loop pair iterates over the correct
  307. // number of bodies.
  308. void LoopUnrollerUtilsImpl::PartiallyUnrollResidualFactor(Loop* loop,
  309. size_t factor) {
  310. // TODO(1841): Handle id overflow.
  311. std::unique_ptr<Instruction> new_label{new Instruction(
  312. context_, SpvOp::SpvOpLabel, 0, context_->TakeNextId(), {})};
  313. std::unique_ptr<BasicBlock> new_exit_bb{new BasicBlock(std::move(new_label))};
  314. // Save the id of the block before we move it.
  315. uint32_t new_merge_id = new_exit_bb->id();
  316. // Add the block the list of blocks to add, we want this merge block to be
  317. // right at the start of the new blocks.
  318. blocks_to_add_.push_back(std::move(new_exit_bb));
  319. BasicBlock* new_exit_bb_raw = blocks_to_add_[0].get();
  320. Instruction& original_conditional_branch = *loop_condition_block_->tail();
  321. // Duplicate the loop, providing access to the blocks of both loops.
  322. // This is a naked new due to the VS2013 requirement of not having unique
  323. // pointers in vectors, as it will be inserted into a vector with
  324. // loop_descriptor.AddLoop.
  325. std::unique_ptr<Loop> new_loop = MakeUnique<Loop>(*loop);
  326. // Clear the basic blocks of the new loop.
  327. new_loop->ClearBlocks();
  328. DuplicateLoop(loop, new_loop.get());
  329. // Add the blocks to the function.
  330. AddBlocksToFunction(loop->GetMergeBlock());
  331. blocks_to_add_.clear();
  332. // Create a new merge block for the first loop.
  333. InstructionBuilder builder{context_, new_exit_bb_raw};
  334. // Make the first loop branch to the second.
  335. builder.AddBranch(new_loop->GetHeaderBlock()->id());
  336. loop_condition_block_ = state_.new_condition_block;
  337. loop_induction_variable_ = state_.new_phi;
  338. // Unroll the new loop by the factor with the usual -1 to account for the
  339. // existing block iteration.
  340. Unroll(new_loop.get(), factor);
  341. LinkLastPhisToStart(new_loop.get());
  342. AddBlocksToLoop(new_loop.get());
  343. // Add the new merge block to the back of the list of blocks to be added. It
  344. // needs to be the last block added to maintain dominator order in the binary.
  345. blocks_to_add_.push_back(
  346. std::unique_ptr<BasicBlock>(new_loop->GetMergeBlock()));
  347. // Add the blocks to the function.
  348. AddBlocksToFunction(loop->GetMergeBlock());
  349. // Reset the usedef analysis.
  350. context_->InvalidateAnalysesExceptFor(
  351. IRContext::Analysis::kAnalysisLoopAnalysis);
  352. analysis::DefUseManager* def_use_manager = context_->get_def_use_mgr();
  353. // The loop condition.
  354. Instruction* condition_check = def_use_manager->GetDef(
  355. original_conditional_branch.GetSingleWordOperand(0));
  356. // This should have been checked by the LoopUtils::CanPerformUnroll function
  357. // before entering this.
  358. assert(loop->IsSupportedCondition(condition_check->opcode()));
  359. // We need to account for the initial body when calculating the remainder.
  360. int64_t remainder = Loop::GetResidualConditionValue(
  361. condition_check->opcode(), loop_init_value_, loop_step_value_,
  362. number_of_loop_iterations_, factor);
  363. assert(remainder > std::numeric_limits<int32_t>::min() &&
  364. remainder < std::numeric_limits<int32_t>::max());
  365. Instruction* new_constant = nullptr;
  366. // If the remainder is negative then we add a signed constant, otherwise just
  367. // add an unsigned constant.
  368. if (remainder < 0) {
  369. new_constant = builder.GetSintConstant(static_cast<int32_t>(remainder));
  370. } else {
  371. new_constant = builder.GetUintConstant(static_cast<int32_t>(remainder));
  372. }
  373. uint32_t constant_id = new_constant->result_id();
  374. // Update the condition check.
  375. condition_check->SetInOperand(1, {constant_id});
  376. // Update the next phi node. The phi will have a constant value coming in from
  377. // the preheader block. For the duplicated loop we need to update the constant
  378. // to be the amount of iterations covered by the first loop and the incoming
  379. // block to be the first loops new merge block.
  380. std::vector<Instruction*> new_inductions;
  381. new_loop->GetInductionVariables(new_inductions);
  382. std::vector<Instruction*> old_inductions;
  383. loop->GetInductionVariables(old_inductions);
  384. for (size_t index = 0; index < new_inductions.size(); ++index) {
  385. Instruction* new_induction = new_inductions[index];
  386. Instruction* old_induction = old_inductions[index];
  387. // Get the index of the loop initalizer, the value coming in from the
  388. // preheader.
  389. uint32_t initalizer_index =
  390. GetPhiIndexFromLabel(new_loop->GetPreHeaderBlock(), old_induction);
  391. // Replace the second loop initalizer with the phi from the first
  392. new_induction->SetInOperand(initalizer_index - 1,
  393. {old_induction->result_id()});
  394. new_induction->SetInOperand(initalizer_index, {new_merge_id});
  395. // If the use of the first loop induction variable is outside of the loop
  396. // then replace that use with the second loop induction variable.
  397. uint32_t second_loop_induction = new_induction->result_id();
  398. auto replace_use_outside_of_loop = [loop, second_loop_induction](
  399. Instruction* user,
  400. uint32_t operand_index) {
  401. if (!loop->IsInsideLoop(user)) {
  402. user->SetOperand(operand_index, {second_loop_induction});
  403. }
  404. };
  405. context_->get_def_use_mgr()->ForEachUse(old_induction,
  406. replace_use_outside_of_loop);
  407. }
  408. context_->InvalidateAnalysesExceptFor(
  409. IRContext::Analysis::kAnalysisLoopAnalysis);
  410. context_->ReplaceAllUsesWith(loop->GetMergeBlock()->id(), new_merge_id);
  411. LoopDescriptor& loop_descriptor = *context_->GetLoopDescriptor(&function_);
  412. loop_descriptor.AddLoop(std::move(new_loop), loop->GetParent());
  413. RemoveDeadInstructions();
  414. }
  415. // Mark this loop as DontUnroll as it will already be unrolled and it may not
  416. // be safe to unroll a previously partially unrolled loop.
  417. void LoopUnrollerUtilsImpl::MarkLoopControlAsDontUnroll(Loop* loop) const {
  418. Instruction* loop_merge_inst = loop->GetHeaderBlock()->GetLoopMergeInst();
  419. assert(loop_merge_inst &&
  420. "Loop merge instruction could not be found after entering unroller "
  421. "(should have exited before this)");
  422. loop_merge_inst->SetInOperand(kLoopControlIndex,
  423. {kLoopControlDontUnrollIndex});
  424. }
  425. // Duplicate the |loop| body |factor| - 1 number of times while keeping the loop
  426. // backedge intact. This will leave the loop with |factor| number of bodies
  427. // after accounting for the initial body.
  428. void LoopUnrollerUtilsImpl::Unroll(Loop* loop, size_t factor) {
  429. // If we unroll a loop partially it will not be safe to unroll it further.
  430. // This is due to the current method of calculating the number of loop
  431. // iterations.
  432. MarkLoopControlAsDontUnroll(loop);
  433. std::vector<Instruction*> inductions;
  434. loop->GetInductionVariables(inductions);
  435. state_ = LoopUnrollState{loop_induction_variable_, loop->GetLatchBlock(),
  436. loop_condition_block_, std::move(inductions)};
  437. for (size_t i = 0; i < factor - 1; ++i) {
  438. CopyBody(loop, true);
  439. }
  440. }
  441. void LoopUnrollerUtilsImpl::RemoveDeadInstructions() {
  442. // Remove the dead instructions.
  443. for (Instruction* inst : invalidated_instructions_) {
  444. context_->KillInst(inst);
  445. }
  446. }
  447. void LoopUnrollerUtilsImpl::ReplaceInductionUseWithFinalValue(Loop* loop) {
  448. context_->InvalidateAnalysesExceptFor(
  449. IRContext::Analysis::kAnalysisLoopAnalysis |
  450. IRContext::Analysis::kAnalysisDefUse |
  451. IRContext::Analysis::kAnalysisInstrToBlockMapping);
  452. std::vector<Instruction*> inductions;
  453. loop->GetInductionVariables(inductions);
  454. for (size_t index = 0; index < inductions.size(); ++index) {
  455. uint32_t trip_step_id = GetPhiDefID(state_.previous_phis_[index],
  456. state_.previous_latch_block_->id());
  457. context_->ReplaceAllUsesWith(inductions[index]->result_id(), trip_step_id);
  458. invalidated_instructions_.push_back(inductions[index]);
  459. }
  460. }
  461. // Fully unroll the loop by partially unrolling it by the number of loop
  462. // iterations minus one for the body already accounted for.
  463. void LoopUnrollerUtilsImpl::FullyUnroll(Loop* loop) {
  464. // We unroll the loop by number of iterations in the loop.
  465. Unroll(loop, number_of_loop_iterations_);
  466. // The first condition block is preserved until now so it can be copied.
  467. FoldConditionBlock(loop_condition_block_, 1);
  468. // Delete the OpLoopMerge and remove the backedge to the header.
  469. CloseUnrolledLoop(loop);
  470. // Mark the loop for later deletion. This allows us to preserve the loop
  471. // iterators but still disregard dead loops.
  472. loop->MarkLoopForRemoval();
  473. // If the loop has a parent add the new blocks to the parent.
  474. if (loop->GetParent()) {
  475. AddBlocksToLoop(loop->GetParent());
  476. }
  477. // Add the blocks to the function.
  478. AddBlocksToFunction(loop->GetMergeBlock());
  479. ReplaceInductionUseWithFinalValue(loop);
  480. RemoveDeadInstructions();
  481. // Invalidate all analyses.
  482. context_->InvalidateAnalysesExceptFor(
  483. IRContext::Analysis::kAnalysisLoopAnalysis |
  484. IRContext::Analysis::kAnalysisDefUse);
  485. }
  486. // Copy a given basic block, give it a new result_id, and store the new block
  487. // and the id mapping in the state. |preserve_instructions| is used to determine
  488. // whether or not this function should edit instructions other than the
  489. // |result_id|.
  490. void LoopUnrollerUtilsImpl::CopyBasicBlock(Loop* loop, const BasicBlock* itr,
  491. bool preserve_instructions) {
  492. // Clone the block exactly, including the IDs.
  493. BasicBlock* basic_block = itr->Clone(context_);
  494. basic_block->SetParent(itr->GetParent());
  495. // Assign each result a new unique ID and keep a mapping of the old ids to
  496. // the new ones.
  497. AssignNewResultIds(basic_block);
  498. // If this is the continue block we are copying.
  499. if (itr == loop->GetContinueBlock()) {
  500. // Make the OpLoopMerge point to this block for the continue.
  501. if (!preserve_instructions) {
  502. Instruction* merge_inst = loop->GetHeaderBlock()->GetLoopMergeInst();
  503. merge_inst->SetInOperand(1, {basic_block->id()});
  504. context_->UpdateDefUse(merge_inst);
  505. }
  506. state_.new_continue_block = basic_block;
  507. }
  508. // If this is the header block we are copying.
  509. if (itr == loop->GetHeaderBlock()) {
  510. state_.new_header_block = basic_block;
  511. if (!preserve_instructions) {
  512. // Remove the loop merge instruction if it exists.
  513. Instruction* merge_inst = basic_block->GetLoopMergeInst();
  514. if (merge_inst) invalidated_instructions_.push_back(merge_inst);
  515. }
  516. }
  517. // If this is the latch block being copied, record it in the state.
  518. if (itr == loop->GetLatchBlock()) state_.new_latch_block = basic_block;
  519. // If this is the condition block we are copying.
  520. if (itr == loop_condition_block_) {
  521. state_.new_condition_block = basic_block;
  522. }
  523. // Add this block to the list of blocks to add to the function at the end of
  524. // the unrolling process.
  525. blocks_to_add_.push_back(std::unique_ptr<BasicBlock>(basic_block));
  526. // Keep tracking the old block via a map.
  527. state_.new_blocks[itr->id()] = basic_block;
  528. }
  529. void LoopUnrollerUtilsImpl::CopyBody(Loop* loop, bool eliminate_conditions) {
  530. // Copy each basic block in the loop, give them new ids, and save state
  531. // information.
  532. for (const BasicBlock* itr : loop_blocks_inorder_) {
  533. CopyBasicBlock(loop, itr, false);
  534. }
  535. // Set the previous latch block to point to the new header.
  536. Instruction* latch_branch = state_.previous_latch_block_->terminator();
  537. latch_branch->SetInOperand(0, {state_.new_header_block->id()});
  538. context_->UpdateDefUse(latch_branch);
  539. // As the algorithm copies the original loop blocks exactly, the tail of the
  540. // latch block on iterations after the first one will be a branch to the new
  541. // header and not the actual loop header. The last continue block in the loop
  542. // should always be a backedge to the global header.
  543. Instruction* new_latch_branch = state_.new_latch_block->terminator();
  544. new_latch_branch->SetInOperand(0, {loop->GetHeaderBlock()->id()});
  545. context_->AnalyzeUses(new_latch_branch);
  546. std::vector<Instruction*> inductions;
  547. loop->GetInductionVariables(inductions);
  548. for (size_t index = 0; index < inductions.size(); ++index) {
  549. Instruction* master_copy = inductions[index];
  550. assert(master_copy->result_id() != 0);
  551. Instruction* induction_clone =
  552. state_.ids_to_new_inst[state_.new_inst[master_copy->result_id()]];
  553. state_.new_phis_.push_back(induction_clone);
  554. assert(induction_clone->result_id() != 0);
  555. if (!state_.previous_phis_.empty()) {
  556. state_.new_inst[master_copy->result_id()] = GetPhiDefID(
  557. state_.previous_phis_[index], state_.previous_latch_block_->id());
  558. } else {
  559. // Do not replace the first phi block ids.
  560. state_.new_inst[master_copy->result_id()] = master_copy->result_id();
  561. }
  562. }
  563. if (eliminate_conditions &&
  564. state_.new_condition_block != loop_condition_block_) {
  565. FoldConditionBlock(state_.new_condition_block, 1);
  566. }
  567. // Only reference to the header block is the backedge in the latch block,
  568. // don't change this.
  569. state_.new_inst[loop->GetHeaderBlock()->id()] = loop->GetHeaderBlock()->id();
  570. for (auto& pair : state_.new_blocks) {
  571. RemapOperands(pair.second);
  572. }
  573. for (Instruction* dead_phi : state_.new_phis_)
  574. invalidated_instructions_.push_back(dead_phi);
  575. // Swap the state so the new is now the previous.
  576. state_.NextIterationState();
  577. }
  578. uint32_t LoopUnrollerUtilsImpl::GetPhiDefID(const Instruction* phi,
  579. uint32_t label) const {
  580. for (uint32_t operand = 3; operand < phi->NumOperands(); operand += 2) {
  581. if (phi->GetSingleWordOperand(operand) == label) {
  582. return phi->GetSingleWordOperand(operand - 1);
  583. }
  584. }
  585. assert(false && "Could not find a phi index matching the provided label");
  586. return 0;
  587. }
  588. void LoopUnrollerUtilsImpl::FoldConditionBlock(BasicBlock* condition_block,
  589. uint32_t operand_label) {
  590. // Remove the old conditional branch to the merge and continue blocks.
  591. Instruction& old_branch = *condition_block->tail();
  592. uint32_t new_target = old_branch.GetSingleWordOperand(operand_label);
  593. context_->KillInst(&old_branch);
  594. // Add the new unconditional branch to the merge block.
  595. InstructionBuilder builder(
  596. context_, condition_block,
  597. IRContext::Analysis::kAnalysisDefUse |
  598. IRContext::Analysis::kAnalysisInstrToBlockMapping);
  599. builder.AddBranch(new_target);
  600. }
  601. void LoopUnrollerUtilsImpl::CloseUnrolledLoop(Loop* loop) {
  602. // Remove the OpLoopMerge instruction from the function.
  603. Instruction* merge_inst = loop->GetHeaderBlock()->GetLoopMergeInst();
  604. invalidated_instructions_.push_back(merge_inst);
  605. // Remove the final backedge to the header and make it point instead to the
  606. // merge block.
  607. Instruction* latch_instruction = state_.previous_latch_block_->terminator();
  608. latch_instruction->SetInOperand(0, {loop->GetMergeBlock()->id()});
  609. context_->UpdateDefUse(latch_instruction);
  610. // Remove all induction variables as the phis will now be invalid. Replace all
  611. // uses with the constant initializer value (all uses of phis will be in
  612. // the first iteration with the subsequent phis already having been removed).
  613. std::vector<Instruction*> inductions;
  614. loop->GetInductionVariables(inductions);
  615. // We can use the state instruction mechanism to replace all internal loop
  616. // values within the first loop trip (as the subsequent ones will be updated
  617. // by the copy function) with the value coming in from the preheader and then
  618. // use context ReplaceAllUsesWith for the uses outside the loop with the final
  619. // trip phi value.
  620. state_.new_inst.clear();
  621. for (Instruction* induction : inductions) {
  622. uint32_t initalizer_id =
  623. GetPhiDefID(induction, loop->GetPreHeaderBlock()->id());
  624. state_.new_inst[induction->result_id()] = initalizer_id;
  625. }
  626. for (BasicBlock* block : loop_blocks_inorder_) {
  627. RemapOperands(block);
  628. }
  629. // Rewrite the last phis, since they may still reference the original phi.
  630. for (Instruction* last_phi : state_.previous_phis_) {
  631. RemapOperands(last_phi);
  632. }
  633. }
  634. // Uses the first loop to create a copy of the loop with new IDs.
  635. void LoopUnrollerUtilsImpl::DuplicateLoop(Loop* old_loop, Loop* new_loop) {
  636. std::vector<BasicBlock*> new_block_order;
  637. // Copy every block in the old loop.
  638. for (const BasicBlock* itr : loop_blocks_inorder_) {
  639. CopyBasicBlock(old_loop, itr, true);
  640. new_block_order.push_back(blocks_to_add_.back().get());
  641. }
  642. // Clone the merge block, give it a new id and record it in the state.
  643. BasicBlock* new_merge = old_loop->GetMergeBlock()->Clone(context_);
  644. new_merge->SetParent(old_loop->GetMergeBlock()->GetParent());
  645. AssignNewResultIds(new_merge);
  646. state_.new_blocks[old_loop->GetMergeBlock()->id()] = new_merge;
  647. // Remap the operands of every instruction in the loop to point to the new
  648. // copies.
  649. for (auto& pair : state_.new_blocks) {
  650. RemapOperands(pair.second);
  651. }
  652. loop_blocks_inorder_ = std::move(new_block_order);
  653. AddBlocksToLoop(new_loop);
  654. new_loop->SetHeaderBlock(state_.new_header_block);
  655. new_loop->SetContinueBlock(state_.new_continue_block);
  656. new_loop->SetLatchBlock(state_.new_latch_block);
  657. new_loop->SetMergeBlock(new_merge);
  658. }
  659. // Whenever the utility copies a block it stores it in a tempory buffer, this
  660. // function adds the buffer into the Function. The blocks will be inserted
  661. // after the block |insert_point|.
  662. void LoopUnrollerUtilsImpl::AddBlocksToFunction(
  663. const BasicBlock* insert_point) {
  664. for (auto basic_block_iterator = function_.begin();
  665. basic_block_iterator != function_.end(); ++basic_block_iterator) {
  666. if (basic_block_iterator->id() == insert_point->id()) {
  667. basic_block_iterator.InsertBefore(&blocks_to_add_);
  668. return;
  669. }
  670. }
  671. assert(
  672. false &&
  673. "Could not add basic blocks to function as insert point was not found.");
  674. }
  675. // Assign all result_ids in |basic_block| instructions to new IDs and preserve
  676. // the mapping of new ids to old ones.
  677. void LoopUnrollerUtilsImpl::AssignNewResultIds(BasicBlock* basic_block) {
  678. analysis::DefUseManager* def_use_mgr = context_->get_def_use_mgr();
  679. // Label instructions aren't covered by normal traversal of the
  680. // instructions.
  681. // TODO(1841): Handle id overflow.
  682. uint32_t new_label_id = context_->TakeNextId();
  683. // Assign a new id to the label.
  684. state_.new_inst[basic_block->GetLabelInst()->result_id()] = new_label_id;
  685. basic_block->GetLabelInst()->SetResultId(new_label_id);
  686. def_use_mgr->AnalyzeInstDefUse(basic_block->GetLabelInst());
  687. for (Instruction& inst : *basic_block) {
  688. uint32_t old_id = inst.result_id();
  689. // Ignore stores etc.
  690. if (old_id == 0) {
  691. continue;
  692. }
  693. // Give the instruction a new id.
  694. // TODO(1841): Handle id overflow.
  695. inst.SetResultId(context_->TakeNextId());
  696. def_use_mgr->AnalyzeInstDef(&inst);
  697. // Save the mapping of old_id -> new_id.
  698. state_.new_inst[old_id] = inst.result_id();
  699. // Check if this instruction is the induction variable.
  700. if (loop_induction_variable_->result_id() == old_id) {
  701. // Save a pointer to the new copy of it.
  702. state_.new_phi = &inst;
  703. }
  704. state_.ids_to_new_inst[inst.result_id()] = &inst;
  705. }
  706. }
  707. void LoopUnrollerUtilsImpl::RemapOperands(Instruction* inst) {
  708. auto remap_operands_to_new_ids = [this](uint32_t* id) {
  709. auto itr = state_.new_inst.find(*id);
  710. if (itr != state_.new_inst.end()) {
  711. *id = itr->second;
  712. }
  713. };
  714. inst->ForEachInId(remap_operands_to_new_ids);
  715. context_->AnalyzeUses(inst);
  716. }
  717. void LoopUnrollerUtilsImpl::RemapOperands(BasicBlock* basic_block) {
  718. for (Instruction& inst : *basic_block) {
  719. RemapOperands(&inst);
  720. }
  721. }
  722. // Generate the ordered list of basic blocks in the |loop| and cache it for
  723. // later use.
  724. void LoopUnrollerUtilsImpl::ComputeLoopOrderedBlocks(Loop* loop) {
  725. loop_blocks_inorder_.clear();
  726. loop->ComputeLoopStructuredOrder(&loop_blocks_inorder_);
  727. }
  728. // Adds the blocks_to_add_ to both the loop and to the parent.
  729. void LoopUnrollerUtilsImpl::AddBlocksToLoop(Loop* loop) const {
  730. // Add the blocks to this loop.
  731. for (auto& block_itr : blocks_to_add_) {
  732. loop->AddBasicBlock(block_itr.get());
  733. }
  734. // Add the blocks to the parent as well.
  735. if (loop->GetParent()) AddBlocksToLoop(loop->GetParent());
  736. }
  737. void LoopUnrollerUtilsImpl::LinkLastPhisToStart(Loop* loop) const {
  738. std::vector<Instruction*> inductions;
  739. loop->GetInductionVariables(inductions);
  740. for (size_t i = 0; i < inductions.size(); ++i) {
  741. Instruction* last_phi_in_block = state_.previous_phis_[i];
  742. uint32_t phi_index =
  743. GetPhiIndexFromLabel(state_.previous_latch_block_, last_phi_in_block);
  744. uint32_t phi_variable =
  745. last_phi_in_block->GetSingleWordInOperand(phi_index - 1);
  746. uint32_t phi_label = last_phi_in_block->GetSingleWordInOperand(phi_index);
  747. Instruction* phi = inductions[i];
  748. phi->SetInOperand(phi_index - 1, {phi_variable});
  749. phi->SetInOperand(phi_index, {phi_label});
  750. }
  751. }
  752. // Duplicate the |loop| body |factor| number of times while keeping the loop
  753. // backedge intact.
  754. void LoopUnrollerUtilsImpl::PartiallyUnroll(Loop* loop, size_t factor) {
  755. Unroll(loop, factor);
  756. LinkLastPhisToStart(loop);
  757. AddBlocksToLoop(loop);
  758. AddBlocksToFunction(loop->GetMergeBlock());
  759. RemoveDeadInstructions();
  760. }
  761. /*
  762. * End LoopUtilsImpl.
  763. */
  764. } // namespace
  765. /*
  766. *
  767. * Begin Utils.
  768. *
  769. * */
  770. bool LoopUtils::CanPerformUnroll() {
  771. // The loop is expected to be in structured order.
  772. if (!loop_->GetHeaderBlock()->GetMergeInst()) {
  773. return false;
  774. }
  775. // Find check the loop has a condition we can find and evaluate.
  776. const BasicBlock* condition = loop_->FindConditionBlock();
  777. if (!condition) return false;
  778. // Check that we can find and process the induction variable.
  779. const Instruction* induction = loop_->FindConditionVariable(condition);
  780. if (!induction || induction->opcode() != SpvOpPhi) return false;
  781. // Check that we can find the number of loop iterations.
  782. if (!loop_->FindNumberOfIterations(induction, &*condition->ctail(), nullptr))
  783. return false;
  784. // Make sure the latch block is a unconditional branch to the header
  785. // block.
  786. const Instruction& branch = *loop_->GetLatchBlock()->ctail();
  787. bool branching_assumption =
  788. branch.opcode() == SpvOpBranch &&
  789. branch.GetSingleWordInOperand(0) == loop_->GetHeaderBlock()->id();
  790. if (!branching_assumption) {
  791. return false;
  792. }
  793. std::vector<Instruction*> inductions;
  794. loop_->GetInductionVariables(inductions);
  795. // Ban breaks within the loop.
  796. const std::vector<uint32_t>& merge_block_preds =
  797. context_->cfg()->preds(loop_->GetMergeBlock()->id());
  798. if (merge_block_preds.size() != 1) {
  799. return false;
  800. }
  801. // Ban continues within the loop.
  802. const std::vector<uint32_t>& continue_block_preds =
  803. context_->cfg()->preds(loop_->GetContinueBlock()->id());
  804. if (continue_block_preds.size() != 1) {
  805. return false;
  806. }
  807. // Ban returns in the loop.
  808. // Iterate over all the blocks within the loop and check that none of them
  809. // exit the loop.
  810. for (uint32_t label_id : loop_->GetBlocks()) {
  811. const BasicBlock* block = context_->cfg()->block(label_id);
  812. if (block->ctail()->opcode() == SpvOp::SpvOpKill ||
  813. block->ctail()->opcode() == SpvOp::SpvOpReturn ||
  814. block->ctail()->opcode() == SpvOp::SpvOpReturnValue ||
  815. block->ctail()->opcode() == SpvOp::SpvOpTerminateInvocation) {
  816. return false;
  817. }
  818. }
  819. // Can only unroll inner loops.
  820. if (!loop_->AreAllChildrenMarkedForRemoval()) {
  821. return false;
  822. }
  823. return true;
  824. }
  825. bool LoopUtils::PartiallyUnroll(size_t factor) {
  826. if (factor == 1 || !CanPerformUnroll()) return false;
  827. // Create the unroller utility.
  828. LoopUnrollerUtilsImpl unroller{context_,
  829. loop_->GetHeaderBlock()->GetParent()};
  830. unroller.Init(loop_);
  831. // If the unrolling factor is larger than or the same size as the loop just
  832. // fully unroll the loop.
  833. if (factor >= unroller.GetLoopIterationCount()) {
  834. unroller.FullyUnroll(loop_);
  835. return true;
  836. }
  837. // If the loop unrolling factor is an residual number of iterations we need to
  838. // let run the loop for the residual part then let it branch into the unrolled
  839. // remaining part. We add one when calucating the remainder to take into
  840. // account the one iteration already in the loop.
  841. if (unroller.GetLoopIterationCount() % factor != 0) {
  842. unroller.PartiallyUnrollResidualFactor(loop_, factor);
  843. } else {
  844. unroller.PartiallyUnroll(loop_, factor);
  845. }
  846. return true;
  847. }
  848. bool LoopUtils::FullyUnroll() {
  849. if (!CanPerformUnroll()) return false;
  850. std::vector<Instruction*> inductions;
  851. loop_->GetInductionVariables(inductions);
  852. LoopUnrollerUtilsImpl unroller{context_,
  853. loop_->GetHeaderBlock()->GetParent()};
  854. unroller.Init(loop_);
  855. unroller.FullyUnroll(loop_);
  856. return true;
  857. }
  858. void LoopUtils::Finalize() {
  859. // Clean up the loop descriptor to preserve the analysis.
  860. LoopDescriptor* LD = context_->GetLoopDescriptor(&function_);
  861. LD->PostModificationCleanup();
  862. }
  863. /*
  864. *
  865. * Begin Pass.
  866. *
  867. */
  868. Pass::Status LoopUnroller::Process() {
  869. bool changed = false;
  870. for (Function& f : *context()->module()) {
  871. LoopDescriptor* LD = context()->GetLoopDescriptor(&f);
  872. for (Loop& loop : *LD) {
  873. LoopUtils loop_utils{context(), &loop};
  874. if (!loop.HasUnrollLoopControl() || !loop_utils.CanPerformUnroll()) {
  875. continue;
  876. }
  877. if (fully_unroll_) {
  878. loop_utils.FullyUnroll();
  879. } else {
  880. loop_utils.PartiallyUnroll(unroll_factor_);
  881. }
  882. changed = true;
  883. }
  884. LD->PostModificationCleanup();
  885. }
  886. return changed ? Status::SuccessWithChange : Status::SuccessWithoutChange;
  887. }
  888. } // namespace opt
  889. } // namespace spvtools