Loop invariant code motion initial implementation
[platform/upstream/SPIRV-Tools.git] / source / opt / licm_pass.h
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
15 #ifndef SOURCE_OPT_LICM_PASS_H_
16 #define SOURCE_OPT_LICM_PASS_H_
17
18 #include "opt/basic_block.h"
19 #include "opt/instruction.h"
20 #include "opt/loop_descriptor.h"
21 #include "opt/pass.h"
22
23 #include <queue>
24
25 namespace spvtools {
26 namespace opt {
27
28 class LICMPass : public Pass {
29  public:
30   LICMPass() {}
31
32   const char* name() const override { return "loop-invariant-code-motion"; }
33   Status Process(ir::IRContext*) override;
34
35  private:
36   // Searches the IRContext for functions and processes each, moving invariants
37   // outside loops within the function where possible
38   // Returns true if a change was made to a function within the IRContext
39   bool ProcessIRContext();
40
41   // Checks the function for loops, calling ProcessLoop on each one found.
42   // Returns true if a change was made to the function, false otherwise.
43   bool ProcessFunction(ir::Function* f);
44
45   // Checks for invariants in the loop and attempts to move them to the loops
46   // preheader. Works from inner loop to outer when nested loops are found.
47   // Returns true if a change was made to the loop, false otherwise.
48   bool ProcessLoop(ir::Loop* loop, ir::Function* f);
49
50   // Analyses each instruction in |bb|, hoisting invariants to |pre_header_bb|.
51   // Each child of |bb| wrt to |dom_tree| is pushed to |loop_bbs|
52   bool AnalyseAndHoistFromBB(ir::Loop* loop, ir::Function* f,
53                              ir::BasicBlock* bb,
54                              std::vector<ir::BasicBlock*>* loop_bbs);
55
56   // Returns true if |bb| is immediately contained in |loop|
57   bool IsImmediatelyContainedInLoop(ir::Loop* loop, ir::Function* f,
58                                     ir::BasicBlock* bb);
59
60   // Move the instruction to the given BasicBlock
61   // This method will update the instruction to block mapping for the context
62   void HoistInstruction(ir::Loop* loop, ir::Instruction* inst);
63 };
64
65 }  // namespace opt
66 }  // namespace spvtools
67
68 #endif  // SOURCE_OPT_LICM_PASS_H_