loop_unroller.cpp 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064
  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, for each instruction in
  205. // |basic_block| use
  206. // that map to substitute the IDs used by instructions (in the operands) with
  207. // the new ids.
  208. void RemapOperands(BasicBlock* basic_block);
  209. // Copy the whole body of the loop, all blocks dominated by the |loop| header
  210. // and not dominated by the |loop| merge. The copied body will be linked to by
  211. // the old |loop| continue block and the new body will link to the |loop|
  212. // header via the new continue block. |eliminate_conditions| is used to decide
  213. // whether or not to fold all the condition blocks other than the last one.
  214. void CopyBody(Loop* loop, bool eliminate_conditions);
  215. // Copy a given |block_to_copy| in the |loop| and record the mapping of the
  216. // old/new ids. |preserve_instructions| determines whether or not the method
  217. // will modify (other than result_id) instructions which are copied.
  218. void CopyBasicBlock(Loop* loop, const BasicBlock* block_to_copy,
  219. bool preserve_instructions);
  220. // The actual implementation of the unroll step. Unrolls |loop| by given
  221. // |factor| by copying the body by |factor| times. Also propagates the
  222. // induction variable value throughout the copies.
  223. void Unroll(Loop* loop, size_t factor);
  224. // Fills the loop_blocks_inorder_ field with the ordered list of basic blocks
  225. // as computed by the method ComputeLoopOrderedBlocks.
  226. void ComputeLoopOrderedBlocks(Loop* loop);
  227. // Adds the blocks_to_add_ to both the |loop| and to the parent of |loop| if
  228. // the parent exists.
  229. void AddBlocksToLoop(Loop* loop) const;
  230. // After the partially unroll step the phi instructions in the header block
  231. // will be in an illegal format. This function makes the phis legal by making
  232. // the edge from the latch block come from the new latch block and the value
  233. // to be the actual value of the phi at that point.
  234. void LinkLastPhisToStart(Loop* loop) const;
  235. // A pointer to the IRContext. Used to add/remove instructions and for usedef
  236. // chains.
  237. IRContext* context_;
  238. // A reference the function the loop is within.
  239. Function& function_;
  240. // A list of basic blocks to be added to the loop at the end of an unroll
  241. // step.
  242. BasicBlockListTy blocks_to_add_;
  243. // List of instructions which are now dead and can be removed.
  244. std::vector<Instruction*> invalidated_instructions_;
  245. // Maintains the current state of the transform between calls to unroll.
  246. LoopUnrollState state_;
  247. // An ordered list containing the loop basic blocks.
  248. std::vector<BasicBlock*> loop_blocks_inorder_;
  249. // The block containing the condition check which contains a conditional
  250. // branch to the merge and continue block.
  251. BasicBlock* loop_condition_block_;
  252. // The induction variable of the loop.
  253. Instruction* loop_induction_variable_;
  254. // Phis used in the loop need to be remapped to use the actual result values
  255. // and then be remapped at the end.
  256. std::vector<Instruction*> loop_phi_instructions_;
  257. // The number of loop iterations that the loop would preform pre-unroll.
  258. size_t number_of_loop_iterations_;
  259. // The amount that the loop steps each iteration.
  260. int64_t loop_step_value_;
  261. // The value the loop starts stepping from.
  262. int64_t loop_init_value_;
  263. };
  264. /*
  265. * Static helper functions.
  266. */
  267. // Retrieve the index of the OpPhi instruction |phi| which corresponds to the
  268. // incoming |block| id.
  269. static uint32_t GetPhiIndexFromLabel(const BasicBlock* block,
  270. const Instruction* phi) {
  271. for (uint32_t i = 1; i < phi->NumInOperands(); i += 2) {
  272. if (block->id() == phi->GetSingleWordInOperand(i)) {
  273. return i;
  274. }
  275. }
  276. assert(false && "Could not find operand in instruction.");
  277. return 0;
  278. }
  279. void LoopUnrollerUtilsImpl::Init(Loop* loop) {
  280. loop_condition_block_ = loop->FindConditionBlock();
  281. // When we reinit the second loop during PartiallyUnrollResidualFactor we need
  282. // to use the cached value from the duplicate step as the dominator tree
  283. // basded solution, loop->FindConditionBlock, requires all the nodes to be
  284. // connected up with the correct branches. They won't be at this point.
  285. if (!loop_condition_block_) {
  286. loop_condition_block_ = state_.new_condition_block;
  287. }
  288. assert(loop_condition_block_);
  289. loop_induction_variable_ = loop->FindConditionVariable(loop_condition_block_);
  290. assert(loop_induction_variable_);
  291. bool found = loop->FindNumberOfIterations(
  292. loop_induction_variable_, &*loop_condition_block_->ctail(),
  293. &number_of_loop_iterations_, &loop_step_value_, &loop_init_value_);
  294. (void)found; // To silence unused variable warning on release builds.
  295. assert(found);
  296. // Blocks are stored in an unordered set of ids in the loop class, we need to
  297. // create the dominator ordered list.
  298. ComputeLoopOrderedBlocks(loop);
  299. }
  300. // This function is used to partially unroll the loop when the factor provided
  301. // would normally lead to an illegal optimization. Instead of just unrolling the
  302. // loop it creates two loops and unrolls one and adjusts the condition on the
  303. // other. The end result being that the new loop pair iterates over the correct
  304. // number of bodies.
  305. void LoopUnrollerUtilsImpl::PartiallyUnrollResidualFactor(Loop* loop,
  306. size_t factor) {
  307. std::unique_ptr<Instruction> new_label{new Instruction(
  308. context_, SpvOp::SpvOpLabel, 0, context_->TakeNextId(), {})};
  309. std::unique_ptr<BasicBlock> new_exit_bb{new BasicBlock(std::move(new_label))};
  310. // Save the id of the block before we move it.
  311. uint32_t new_merge_id = new_exit_bb->id();
  312. // Add the block the list of blocks to add, we want this merge block to be
  313. // right at the start of the new blocks.
  314. blocks_to_add_.push_back(std::move(new_exit_bb));
  315. BasicBlock* new_exit_bb_raw = blocks_to_add_[0].get();
  316. Instruction& original_conditional_branch = *loop_condition_block_->tail();
  317. // Duplicate the loop, providing access to the blocks of both loops.
  318. // This is a naked new due to the VS2013 requirement of not having unique
  319. // pointers in vectors, as it will be inserted into a vector with
  320. // loop_descriptor.AddLoop.
  321. Loop* new_loop = new Loop(*loop);
  322. // Clear the basic blocks of the new loop.
  323. new_loop->ClearBlocks();
  324. DuplicateLoop(loop, new_loop);
  325. // Add the blocks to the function.
  326. AddBlocksToFunction(loop->GetMergeBlock());
  327. blocks_to_add_.clear();
  328. // Create a new merge block for the first loop.
  329. InstructionBuilder builder{context_, new_exit_bb_raw};
  330. // Make the first loop branch to the second.
  331. builder.AddBranch(new_loop->GetHeaderBlock()->id());
  332. loop_condition_block_ = state_.new_condition_block;
  333. loop_induction_variable_ = state_.new_phi;
  334. // Unroll the new loop by the factor with the usual -1 to account for the
  335. // existing block iteration.
  336. Unroll(new_loop, factor);
  337. LinkLastPhisToStart(new_loop);
  338. AddBlocksToLoop(new_loop);
  339. // Add the new merge block to the back of the list of blocks to be added. It
  340. // needs to be the last block added to maintain dominator order in the binary.
  341. blocks_to_add_.push_back(
  342. std::unique_ptr<BasicBlock>(new_loop->GetMergeBlock()));
  343. // Add the blocks to the function.
  344. AddBlocksToFunction(loop->GetMergeBlock());
  345. // Reset the usedef analysis.
  346. context_->InvalidateAnalysesExceptFor(
  347. IRContext::Analysis::kAnalysisLoopAnalysis);
  348. analysis::DefUseManager* def_use_manager = context_->get_def_use_mgr();
  349. // The loop condition.
  350. Instruction* condition_check = def_use_manager->GetDef(
  351. original_conditional_branch.GetSingleWordOperand(0));
  352. // This should have been checked by the LoopUtils::CanPerformUnroll function
  353. // before entering this.
  354. assert(loop->IsSupportedCondition(condition_check->opcode()));
  355. // We need to account for the initial body when calculating the remainder.
  356. int64_t remainder = Loop::GetResidualConditionValue(
  357. condition_check->opcode(), loop_init_value_, loop_step_value_,
  358. number_of_loop_iterations_, factor);
  359. assert(remainder > std::numeric_limits<int32_t>::min() &&
  360. remainder < std::numeric_limits<int32_t>::max());
  361. Instruction* new_constant = nullptr;
  362. // If the remainder is negative then we add a signed constant, otherwise just
  363. // add an unsigned constant.
  364. if (remainder < 0) {
  365. new_constant =
  366. builder.Add32BitSignedIntegerConstant(static_cast<int32_t>(remainder));
  367. } else {
  368. new_constant = builder.Add32BitUnsignedIntegerConstant(
  369. static_cast<int32_t>(remainder));
  370. }
  371. uint32_t constant_id = new_constant->result_id();
  372. // Update the condition check.
  373. condition_check->SetInOperand(1, {constant_id});
  374. // Update the next phi node. The phi will have a constant value coming in from
  375. // the preheader block. For the duplicated loop we need to update the constant
  376. // to be the amount of iterations covered by the first loop and the incoming
  377. // block to be the first loops new merge block.
  378. std::vector<Instruction*> new_inductions;
  379. new_loop->GetInductionVariables(new_inductions);
  380. std::vector<Instruction*> old_inductions;
  381. loop->GetInductionVariables(old_inductions);
  382. for (size_t index = 0; index < new_inductions.size(); ++index) {
  383. Instruction* new_induction = new_inductions[index];
  384. Instruction* old_induction = old_inductions[index];
  385. // Get the index of the loop initalizer, the value coming in from the
  386. // preheader.
  387. uint32_t initalizer_index =
  388. GetPhiIndexFromLabel(new_loop->GetPreHeaderBlock(), old_induction);
  389. // Replace the second loop initalizer with the phi from the first
  390. new_induction->SetInOperand(initalizer_index - 1,
  391. {old_induction->result_id()});
  392. new_induction->SetInOperand(initalizer_index, {new_merge_id});
  393. // If the use of the first loop induction variable is outside of the loop
  394. // then replace that use with the second loop induction variable.
  395. uint32_t second_loop_induction = new_induction->result_id();
  396. auto replace_use_outside_of_loop = [loop, second_loop_induction](
  397. Instruction* user,
  398. uint32_t operand_index) {
  399. if (!loop->IsInsideLoop(user)) {
  400. user->SetOperand(operand_index, {second_loop_induction});
  401. }
  402. };
  403. context_->get_def_use_mgr()->ForEachUse(old_induction,
  404. replace_use_outside_of_loop);
  405. }
  406. context_->InvalidateAnalysesExceptFor(
  407. IRContext::Analysis::kAnalysisLoopAnalysis);
  408. context_->ReplaceAllUsesWith(loop->GetMergeBlock()->id(), new_merge_id);
  409. LoopDescriptor& loop_descriptor = *context_->GetLoopDescriptor(&function_);
  410. loop_descriptor.AddLoop(new_loop, loop->GetParent());
  411. RemoveDeadInstructions();
  412. }
  413. // Mark this loop as DontUnroll as it will already be unrolled and it may not
  414. // be safe to unroll a previously partially unrolled loop.
  415. void LoopUnrollerUtilsImpl::MarkLoopControlAsDontUnroll(Loop* loop) const {
  416. Instruction* loop_merge_inst = loop->GetHeaderBlock()->GetLoopMergeInst();
  417. assert(loop_merge_inst &&
  418. "Loop merge instruction could not be found after entering unroller "
  419. "(should have exited before this)");
  420. loop_merge_inst->SetInOperand(kLoopControlIndex,
  421. {kLoopControlDontUnrollIndex});
  422. }
  423. // Duplicate the |loop| body |factor| - 1 number of times while keeping the loop
  424. // backedge intact. This will leave the loop with |factor| number of bodies
  425. // after accounting for the initial body.
  426. void LoopUnrollerUtilsImpl::Unroll(Loop* loop, size_t factor) {
  427. // If we unroll a loop partially it will not be safe to unroll it further.
  428. // This is due to the current method of calculating the number of loop
  429. // iterations.
  430. MarkLoopControlAsDontUnroll(loop);
  431. std::vector<Instruction*> inductions;
  432. loop->GetInductionVariables(inductions);
  433. state_ = LoopUnrollState{loop_induction_variable_, loop->GetLatchBlock(),
  434. loop_condition_block_, std::move(inductions)};
  435. for (size_t i = 0; i < factor - 1; ++i) {
  436. CopyBody(loop, true);
  437. }
  438. }
  439. void LoopUnrollerUtilsImpl::RemoveDeadInstructions() {
  440. // Remove the dead instructions.
  441. for (Instruction* inst : invalidated_instructions_) {
  442. context_->KillInst(inst);
  443. }
  444. }
  445. void LoopUnrollerUtilsImpl::ReplaceInductionUseWithFinalValue(Loop* loop) {
  446. context_->InvalidateAnalysesExceptFor(
  447. IRContext::Analysis::kAnalysisLoopAnalysis);
  448. std::vector<Instruction*> inductions;
  449. loop->GetInductionVariables(inductions);
  450. for (size_t index = 0; index < inductions.size(); ++index) {
  451. uint32_t trip_step_id = GetPhiDefID(state_.previous_phis_[index],
  452. state_.previous_latch_block_->id());
  453. context_->ReplaceAllUsesWith(inductions[index]->result_id(), trip_step_id);
  454. invalidated_instructions_.push_back(inductions[index]);
  455. }
  456. }
  457. // Fully unroll the loop by partially unrolling it by the number of loop
  458. // iterations minus one for the body already accounted for.
  459. void LoopUnrollerUtilsImpl::FullyUnroll(Loop* loop) {
  460. // We unroll the loop by number of iterations in the loop.
  461. Unroll(loop, number_of_loop_iterations_);
  462. // The first condition block is preserved until now so it can be copied.
  463. FoldConditionBlock(loop_condition_block_, 1);
  464. // Delete the OpLoopMerge and remove the backedge to the header.
  465. CloseUnrolledLoop(loop);
  466. // Mark the loop for later deletion. This allows us to preserve the loop
  467. // iterators but still disregard dead loops.
  468. loop->MarkLoopForRemoval();
  469. // If the loop has a parent add the new blocks to the parent.
  470. if (loop->GetParent()) {
  471. AddBlocksToLoop(loop->GetParent());
  472. }
  473. // Add the blocks to the function.
  474. AddBlocksToFunction(loop->GetMergeBlock());
  475. ReplaceInductionUseWithFinalValue(loop);
  476. RemoveDeadInstructions();
  477. // Invalidate all analyses.
  478. context_->InvalidateAnalysesExceptFor(
  479. IRContext::Analysis::kAnalysisLoopAnalysis);
  480. }
  481. // Copy a given basic block, give it a new result_id, and store the new block
  482. // and the id mapping in the state. |preserve_instructions| is used to determine
  483. // whether or not this function should edit instructions other than the
  484. // |result_id|.
  485. void LoopUnrollerUtilsImpl::CopyBasicBlock(Loop* loop, const BasicBlock* itr,
  486. bool preserve_instructions) {
  487. // Clone the block exactly, including the IDs.
  488. BasicBlock* basic_block = itr->Clone(context_);
  489. basic_block->SetParent(itr->GetParent());
  490. // Assign each result a new unique ID and keep a mapping of the old ids to
  491. // the new ones.
  492. AssignNewResultIds(basic_block);
  493. // If this is the continue block we are copying.
  494. if (itr == loop->GetContinueBlock()) {
  495. // Make the OpLoopMerge point to this block for the continue.
  496. if (!preserve_instructions) {
  497. Instruction* merge_inst = loop->GetHeaderBlock()->GetLoopMergeInst();
  498. merge_inst->SetInOperand(1, {basic_block->id()});
  499. }
  500. state_.new_continue_block = basic_block;
  501. }
  502. // If this is the header block we are copying.
  503. if (itr == loop->GetHeaderBlock()) {
  504. state_.new_header_block = basic_block;
  505. if (!preserve_instructions) {
  506. // Remove the loop merge instruction if it exists.
  507. Instruction* merge_inst = basic_block->GetLoopMergeInst();
  508. if (merge_inst) invalidated_instructions_.push_back(merge_inst);
  509. }
  510. }
  511. // If this is the latch block being copied, record it in the state.
  512. if (itr == loop->GetLatchBlock()) state_.new_latch_block = basic_block;
  513. // If this is the condition block we are copying.
  514. if (itr == loop_condition_block_) {
  515. state_.new_condition_block = basic_block;
  516. }
  517. // Add this block to the list of blocks to add to the function at the end of
  518. // the unrolling process.
  519. blocks_to_add_.push_back(std::unique_ptr<BasicBlock>(basic_block));
  520. // Keep tracking the old block via a map.
  521. state_.new_blocks[itr->id()] = basic_block;
  522. }
  523. void LoopUnrollerUtilsImpl::CopyBody(Loop* loop, bool eliminate_conditions) {
  524. // Copy each basic block in the loop, give them new ids, and save state
  525. // information.
  526. for (const BasicBlock* itr : loop_blocks_inorder_) {
  527. CopyBasicBlock(loop, itr, false);
  528. }
  529. // Set the previous latch block to point to the new header.
  530. Instruction& latch_branch = *state_.previous_latch_block_->tail();
  531. latch_branch.SetInOperand(0, {state_.new_header_block->id()});
  532. // As the algorithm copies the original loop blocks exactly, the tail of the
  533. // latch block on iterations after the first one will be a branch to the new
  534. // header and not the actual loop header. The last continue block in the loop
  535. // should always be a backedge to the global header.
  536. Instruction& new_latch_branch = *state_.new_latch_block->tail();
  537. new_latch_branch.SetInOperand(0, {loop->GetHeaderBlock()->id()});
  538. std::vector<Instruction*> inductions;
  539. loop->GetInductionVariables(inductions);
  540. for (size_t index = 0; index < inductions.size(); ++index) {
  541. Instruction* master_copy = inductions[index];
  542. assert(master_copy->result_id() != 0);
  543. Instruction* induction_clone =
  544. state_.ids_to_new_inst[state_.new_inst[master_copy->result_id()]];
  545. state_.new_phis_.push_back(induction_clone);
  546. assert(induction_clone->result_id() != 0);
  547. if (!state_.previous_phis_.empty()) {
  548. state_.new_inst[master_copy->result_id()] = GetPhiDefID(
  549. state_.previous_phis_[index], state_.previous_latch_block_->id());
  550. } else {
  551. // Do not replace the first phi block ids.
  552. state_.new_inst[master_copy->result_id()] = master_copy->result_id();
  553. }
  554. }
  555. if (eliminate_conditions &&
  556. state_.new_condition_block != loop_condition_block_) {
  557. FoldConditionBlock(state_.new_condition_block, 1);
  558. }
  559. // Only reference to the header block is the backedge in the latch block,
  560. // don't change this.
  561. state_.new_inst[loop->GetHeaderBlock()->id()] = loop->GetHeaderBlock()->id();
  562. for (auto& pair : state_.new_blocks) {
  563. RemapOperands(pair.second);
  564. }
  565. for (Instruction* dead_phi : state_.new_phis_)
  566. invalidated_instructions_.push_back(dead_phi);
  567. // Swap the state so the new is now the previous.
  568. state_.NextIterationState();
  569. }
  570. uint32_t LoopUnrollerUtilsImpl::GetPhiDefID(const Instruction* phi,
  571. uint32_t label) const {
  572. for (uint32_t operand = 3; operand < phi->NumOperands(); operand += 2) {
  573. if (phi->GetSingleWordOperand(operand) == label) {
  574. return phi->GetSingleWordOperand(operand - 1);
  575. }
  576. }
  577. assert(false && "Could not find a phi index matching the provided label");
  578. return 0;
  579. }
  580. void LoopUnrollerUtilsImpl::FoldConditionBlock(BasicBlock* condition_block,
  581. uint32_t operand_label) {
  582. // Remove the old conditional branch to the merge and continue blocks.
  583. Instruction& old_branch = *condition_block->tail();
  584. uint32_t new_target = old_branch.GetSingleWordOperand(operand_label);
  585. context_->KillInst(&old_branch);
  586. // Add the new unconditional branch to the merge block.
  587. InstructionBuilder builder{context_, condition_block};
  588. builder.AddBranch(new_target);
  589. }
  590. void LoopUnrollerUtilsImpl::CloseUnrolledLoop(Loop* loop) {
  591. // Remove the OpLoopMerge instruction from the function.
  592. Instruction* merge_inst = loop->GetHeaderBlock()->GetLoopMergeInst();
  593. invalidated_instructions_.push_back(merge_inst);
  594. // Remove the final backedge to the header and make it point instead to the
  595. // merge block.
  596. state_.previous_latch_block_->tail()->SetInOperand(
  597. 0, {loop->GetMergeBlock()->id()});
  598. // Remove all induction variables as the phis will now be invalid. Replace all
  599. // uses with the constant initializer value (all uses of phis will be in
  600. // the first iteration with the subsequent phis already having been removed).
  601. std::vector<Instruction*> inductions;
  602. loop->GetInductionVariables(inductions);
  603. // We can use the state instruction mechanism to replace all internal loop
  604. // values within the first loop trip (as the subsequent ones will be updated
  605. // by the copy function) with the value coming in from the preheader and then
  606. // use context ReplaceAllUsesWith for the uses outside the loop with the final
  607. // trip phi value.
  608. state_.new_inst.clear();
  609. for (Instruction* induction : inductions) {
  610. uint32_t initalizer_id =
  611. GetPhiDefID(induction, loop->GetPreHeaderBlock()->id());
  612. state_.new_inst[induction->result_id()] = initalizer_id;
  613. }
  614. for (BasicBlock* block : loop_blocks_inorder_) {
  615. RemapOperands(block);
  616. }
  617. }
  618. // Uses the first loop to create a copy of the loop with new IDs.
  619. void LoopUnrollerUtilsImpl::DuplicateLoop(Loop* old_loop, Loop* new_loop) {
  620. std::vector<BasicBlock*> new_block_order;
  621. // Copy every block in the old loop.
  622. for (const BasicBlock* itr : loop_blocks_inorder_) {
  623. CopyBasicBlock(old_loop, itr, true);
  624. new_block_order.push_back(blocks_to_add_.back().get());
  625. }
  626. // Clone the merge block, give it a new id and record it in the state.
  627. BasicBlock* new_merge = old_loop->GetMergeBlock()->Clone(context_);
  628. new_merge->SetParent(old_loop->GetMergeBlock()->GetParent());
  629. AssignNewResultIds(new_merge);
  630. state_.new_blocks[old_loop->GetMergeBlock()->id()] = new_merge;
  631. // Remap the operands of every instruction in the loop to point to the new
  632. // copies.
  633. for (auto& pair : state_.new_blocks) {
  634. RemapOperands(pair.second);
  635. }
  636. loop_blocks_inorder_ = std::move(new_block_order);
  637. AddBlocksToLoop(new_loop);
  638. new_loop->SetHeaderBlock(state_.new_header_block);
  639. new_loop->SetContinueBlock(state_.new_continue_block);
  640. new_loop->SetLatchBlock(state_.new_latch_block);
  641. new_loop->SetMergeBlock(new_merge);
  642. }
  643. // Whenever the utility copies a block it stores it in a tempory buffer, this
  644. // function adds the buffer into the Function. The blocks will be inserted
  645. // after the block |insert_point|.
  646. void LoopUnrollerUtilsImpl::AddBlocksToFunction(
  647. const BasicBlock* insert_point) {
  648. for (auto basic_block_iterator = function_.begin();
  649. basic_block_iterator != function_.end(); ++basic_block_iterator) {
  650. if (basic_block_iterator->id() == insert_point->id()) {
  651. basic_block_iterator.InsertBefore(&blocks_to_add_);
  652. return;
  653. }
  654. }
  655. assert(
  656. false &&
  657. "Could not add basic blocks to function as insert point was not found.");
  658. }
  659. // Assign all result_ids in |basic_block| instructions to new IDs and preserve
  660. // the mapping of new ids to old ones.
  661. void LoopUnrollerUtilsImpl::AssignNewResultIds(BasicBlock* basic_block) {
  662. // Label instructions aren't covered by normal traversal of the
  663. // instructions.
  664. uint32_t new_label_id = context_->TakeNextId();
  665. // Assign a new id to the label.
  666. state_.new_inst[basic_block->GetLabelInst()->result_id()] = new_label_id;
  667. basic_block->GetLabelInst()->SetResultId(new_label_id);
  668. for (Instruction& inst : *basic_block) {
  669. uint32_t old_id = inst.result_id();
  670. // Ignore stores etc.
  671. if (old_id == 0) {
  672. continue;
  673. }
  674. // Give the instruction a new id.
  675. inst.SetResultId(context_->TakeNextId());
  676. // Save the mapping of old_id -> new_id.
  677. state_.new_inst[old_id] = inst.result_id();
  678. // Check if this instruction is the induction variable.
  679. if (loop_induction_variable_->result_id() == old_id) {
  680. // Save a pointer to the new copy of it.
  681. state_.new_phi = &inst;
  682. }
  683. state_.ids_to_new_inst[inst.result_id()] = &inst;
  684. }
  685. }
  686. // For all instructions in |basic_block| check if the operands used are from a
  687. // copied instruction and if so swap out the operand for the copy of it.
  688. void LoopUnrollerUtilsImpl::RemapOperands(BasicBlock* basic_block) {
  689. for (Instruction& inst : *basic_block) {
  690. auto remap_operands_to_new_ids = [this](uint32_t* id) {
  691. auto itr = state_.new_inst.find(*id);
  692. if (itr != state_.new_inst.end()) {
  693. *id = itr->second;
  694. }
  695. };
  696. inst.ForEachInId(remap_operands_to_new_ids);
  697. }
  698. }
  699. // Generate the ordered list of basic blocks in the |loop| and cache it for
  700. // later use.
  701. void LoopUnrollerUtilsImpl::ComputeLoopOrderedBlocks(Loop* loop) {
  702. loop_blocks_inorder_.clear();
  703. loop->ComputeLoopStructuredOrder(&loop_blocks_inorder_);
  704. }
  705. // Adds the blocks_to_add_ to both the loop and to the parent.
  706. void LoopUnrollerUtilsImpl::AddBlocksToLoop(Loop* loop) const {
  707. // Add the blocks to this loop.
  708. for (auto& block_itr : blocks_to_add_) {
  709. loop->AddBasicBlock(block_itr.get());
  710. }
  711. // Add the blocks to the parent as well.
  712. if (loop->GetParent()) AddBlocksToLoop(loop->GetParent());
  713. }
  714. void LoopUnrollerUtilsImpl::LinkLastPhisToStart(Loop* loop) const {
  715. std::vector<Instruction*> inductions;
  716. loop->GetInductionVariables(inductions);
  717. for (size_t i = 0; i < inductions.size(); ++i) {
  718. Instruction* last_phi_in_block = state_.previous_phis_[i];
  719. uint32_t phi_index =
  720. GetPhiIndexFromLabel(state_.previous_latch_block_, last_phi_in_block);
  721. uint32_t phi_variable =
  722. last_phi_in_block->GetSingleWordInOperand(phi_index - 1);
  723. uint32_t phi_label = last_phi_in_block->GetSingleWordInOperand(phi_index);
  724. Instruction* phi = inductions[i];
  725. phi->SetInOperand(phi_index - 1, {phi_variable});
  726. phi->SetInOperand(phi_index, {phi_label});
  727. }
  728. }
  729. // Duplicate the |loop| body |factor| number of times while keeping the loop
  730. // backedge intact.
  731. void LoopUnrollerUtilsImpl::PartiallyUnroll(Loop* loop, size_t factor) {
  732. Unroll(loop, factor);
  733. LinkLastPhisToStart(loop);
  734. AddBlocksToLoop(loop);
  735. AddBlocksToFunction(loop->GetMergeBlock());
  736. RemoveDeadInstructions();
  737. }
  738. /*
  739. * End LoopUtilsImpl.
  740. */
  741. } // namespace
  742. /*
  743. *
  744. * Begin Utils.
  745. *
  746. * */
  747. bool LoopUtils::CanPerformUnroll() {
  748. // The loop is expected to be in structured order.
  749. if (!loop_->GetHeaderBlock()->GetMergeInst()) {
  750. return false;
  751. }
  752. // Find check the loop has a condition we can find and evaluate.
  753. const BasicBlock* condition = loop_->FindConditionBlock();
  754. if (!condition) return false;
  755. // Check that we can find and process the induction variable.
  756. const Instruction* induction = loop_->FindConditionVariable(condition);
  757. if (!induction || induction->opcode() != SpvOpPhi) return false;
  758. // Check that we can find the number of loop iterations.
  759. if (!loop_->FindNumberOfIterations(induction, &*condition->ctail(), nullptr))
  760. return false;
  761. // Make sure the latch block is a unconditional branch to the header
  762. // block.
  763. const Instruction& branch = *loop_->GetLatchBlock()->ctail();
  764. bool branching_assumption =
  765. branch.opcode() == SpvOpBranch &&
  766. branch.GetSingleWordInOperand(0) == loop_->GetHeaderBlock()->id();
  767. if (!branching_assumption) {
  768. return false;
  769. }
  770. std::vector<Instruction*> inductions;
  771. loop_->GetInductionVariables(inductions);
  772. // Ban breaks within the loop.
  773. const std::vector<uint32_t>& merge_block_preds =
  774. context_->cfg()->preds(loop_->GetMergeBlock()->id());
  775. if (merge_block_preds.size() != 1) {
  776. return false;
  777. }
  778. // Ban continues within the loop.
  779. const std::vector<uint32_t>& continue_block_preds =
  780. context_->cfg()->preds(loop_->GetContinueBlock()->id());
  781. if (continue_block_preds.size() != 1) {
  782. return false;
  783. }
  784. // Ban returns in the loop.
  785. // Iterate over all the blocks within the loop and check that none of them
  786. // exit the loop.
  787. for (uint32_t label_id : loop_->GetBlocks()) {
  788. const BasicBlock* block = context_->cfg()->block(label_id);
  789. if (block->ctail()->opcode() == SpvOp::SpvOpKill ||
  790. block->ctail()->opcode() == SpvOp::SpvOpReturn ||
  791. block->ctail()->opcode() == SpvOp::SpvOpReturnValue) {
  792. return false;
  793. }
  794. }
  795. // Can only unroll inner loops.
  796. if (!loop_->AreAllChildrenMarkedForRemoval()) {
  797. return false;
  798. }
  799. return true;
  800. }
  801. bool LoopUtils::PartiallyUnroll(size_t factor) {
  802. if (factor == 1 || !CanPerformUnroll()) return false;
  803. // Create the unroller utility.
  804. LoopUnrollerUtilsImpl unroller{context_,
  805. loop_->GetHeaderBlock()->GetParent()};
  806. unroller.Init(loop_);
  807. // If the unrolling factor is larger than or the same size as the loop just
  808. // fully unroll the loop.
  809. if (factor >= unroller.GetLoopIterationCount()) {
  810. unroller.FullyUnroll(loop_);
  811. return true;
  812. }
  813. // If the loop unrolling factor is an residual number of iterations we need to
  814. // let run the loop for the residual part then let it branch into the unrolled
  815. // remaining part. We add one when calucating the remainder to take into
  816. // account the one iteration already in the loop.
  817. if (unroller.GetLoopIterationCount() % factor != 0) {
  818. unroller.PartiallyUnrollResidualFactor(loop_, factor);
  819. } else {
  820. unroller.PartiallyUnroll(loop_, factor);
  821. }
  822. return true;
  823. }
  824. bool LoopUtils::FullyUnroll() {
  825. if (!CanPerformUnroll()) return false;
  826. std::vector<Instruction*> inductions;
  827. loop_->GetInductionVariables(inductions);
  828. LoopUnrollerUtilsImpl unroller{context_,
  829. loop_->GetHeaderBlock()->GetParent()};
  830. unroller.Init(loop_);
  831. unroller.FullyUnroll(loop_);
  832. return true;
  833. }
  834. void LoopUtils::Finalize() {
  835. // Clean up the loop descriptor to preserve the analysis.
  836. LoopDescriptor* LD = context_->GetLoopDescriptor(&function_);
  837. LD->PostModificationCleanup();
  838. }
  839. /*
  840. *
  841. * Begin Pass.
  842. *
  843. */
  844. Pass::Status LoopUnroller::Process() {
  845. bool changed = false;
  846. for (Function& f : *context()->module()) {
  847. LoopDescriptor* LD = context()->GetLoopDescriptor(&f);
  848. for (Loop& loop : *LD) {
  849. LoopUtils loop_utils{context(), &loop};
  850. if (!loop.HasUnrollLoopControl() || !loop_utils.CanPerformUnroll()) {
  851. continue;
  852. }
  853. if (fully_unroll_) {
  854. loop_utils.FullyUnroll();
  855. } else {
  856. loop_utils.PartiallyUnroll(unroll_factor_);
  857. }
  858. changed = true;
  859. }
  860. LD->PostModificationCleanup();
  861. }
  862. return changed ? Status::SuccessWithChange : Status::SuccessWithoutChange;
  863. }
  864. } // namespace opt
  865. } // namespace spvtools