1 // Copyright (c) 2016 Google Inc.
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_FUNCTION_H_
16 #define SOURCE_OPT_FUNCTION_H_
17 
18 #include <algorithm>
19 #include <functional>
20 #include <memory>
21 #include <string>
22 #include <utility>
23 #include <vector>
24 
25 #include "source/opt/basic_block.h"
26 #include "source/opt/instruction.h"
27 #include "source/opt/iterator.h"
28 
29 namespace spvtools {
30 namespace opt {
31 
32 class CFG;
33 class IRContext;
34 class Module;
35 
36 // A SPIR-V function.
37 class Function {
38  public:
39   using iterator = UptrVectorIterator<BasicBlock>;
40   using const_iterator = UptrVectorIterator<BasicBlock, true>;
41 
42   // Creates a function instance declared by the given OpFunction instruction
43   // |def_inst|.
44   inline explicit Function(std::unique_ptr<Instruction> def_inst);
45 
46   explicit Function(const Function& f) = delete;
47 
48   // Creates a clone of the instruction in the given |context|
49   //
50   // The parent module will default to null and needs to be explicitly set by
51   // the user.
52   Function* Clone(IRContext*) const;
53   // The OpFunction instruction that begins the definition of this function.
DefInst()54   Instruction& DefInst() { return *def_inst_; }
DefInst()55   const Instruction& DefInst() const { return *def_inst_; }
56 
57   // Appends a parameter to this function.
58   inline void AddParameter(std::unique_ptr<Instruction> p);
59   // Appends a basic block to this function.
60   inline void AddBasicBlock(std::unique_ptr<BasicBlock> b);
61   // Appends a basic block to this function at the position |ip|.
62   inline void AddBasicBlock(std::unique_ptr<BasicBlock> b, iterator ip);
63   template <typename T>
64   inline void AddBasicBlocks(T begin, T end, iterator ip);
65 
66   // Move basic block with |id| to the position after |ip|. Both have to be
67   // contained in this function.
68   inline void MoveBasicBlockToAfter(uint32_t id, BasicBlock* ip);
69 
70   // Delete all basic blocks that contain no instructions.
71   inline void RemoveEmptyBlocks();
72 
73   // Saves the given function end instruction.
74   inline void SetFunctionEnd(std::unique_ptr<Instruction> end_inst);
75 
76   // Returns the given function end instruction.
EndInst()77   inline Instruction* EndInst() { return end_inst_.get(); }
EndInst()78   inline const Instruction* EndInst() const { return end_inst_.get(); }
79 
80   // Returns function's id
result_id()81   inline uint32_t result_id() const { return def_inst_->result_id(); }
82 
83   // Returns function's return type id
type_id()84   inline uint32_t type_id() const { return def_inst_->type_id(); }
85 
86   // Returns the entry basic block for this function.
entry()87   const std::unique_ptr<BasicBlock>& entry() const { return blocks_.front(); }
88 
begin()89   iterator begin() { return iterator(&blocks_, blocks_.begin()); }
end()90   iterator end() { return iterator(&blocks_, blocks_.end()); }
begin()91   const_iterator begin() const { return cbegin(); }
end()92   const_iterator end() const { return cend(); }
cbegin()93   const_iterator cbegin() const {
94     return const_iterator(&blocks_, blocks_.cbegin());
95   }
cend()96   const_iterator cend() const {
97     return const_iterator(&blocks_, blocks_.cend());
98   }
99 
100   // Returns an iterator to the basic block |id|.
FindBlock(uint32_t bb_id)101   iterator FindBlock(uint32_t bb_id) {
102     return std::find_if(begin(), end(), [bb_id](const BasicBlock& it_bb) {
103       return bb_id == it_bb.id();
104     });
105   }
106 
107   // Runs the given function |f| on each instruction in this function, and
108   // optionally on debug line instructions that might precede them.
109   void ForEachInst(const std::function<void(Instruction*)>& f,
110                    bool run_on_debug_line_insts = false);
111   void ForEachInst(const std::function<void(const Instruction*)>& f,
112                    bool run_on_debug_line_insts = false) const;
113   bool WhileEachInst(const std::function<bool(Instruction*)>& f,
114                      bool run_on_debug_line_insts = false);
115   bool WhileEachInst(const std::function<bool(const Instruction*)>& f,
116                      bool run_on_debug_line_insts = false) const;
117 
118   // Runs the given function |f| on each parameter instruction in this function,
119   // and optionally on debug line instructions that might precede them.
120   void ForEachParam(const std::function<void(const Instruction*)>& f,
121                     bool run_on_debug_line_insts = false) const;
122   void ForEachParam(const std::function<void(Instruction*)>& f,
123                     bool run_on_debug_line_insts = false);
124 
125   BasicBlock* InsertBasicBlockAfter(std::unique_ptr<BasicBlock>&& new_block,
126                                     BasicBlock* position);
127 
128   // Return true if the function calls itself either directly or indirectly.
129   bool IsRecursive() const;
130 
131   // Pretty-prints all the basic blocks in this function into a std::string.
132   //
133   // |options| are the disassembly options. SPV_BINARY_TO_TEXT_OPTION_NO_HEADER
134   // is always added to |options|.
135   std::string PrettyPrint(uint32_t options = 0u) const;
136 
137   // Dump this function on stderr.  Useful when running interactive
138   // debuggers.
139   void Dump() const;
140 
141  private:
142   // The OpFunction instruction that begins the definition of this function.
143   std::unique_ptr<Instruction> def_inst_;
144   // All parameters to this function.
145   std::vector<std::unique_ptr<Instruction>> params_;
146   // All basic blocks inside this function in specification order
147   std::vector<std::unique_ptr<BasicBlock>> blocks_;
148   // The OpFunctionEnd instruction.
149   std::unique_ptr<Instruction> end_inst_;
150 };
151 
152 // Pretty-prints |func| to |str|. Returns |str|.
153 std::ostream& operator<<(std::ostream& str, const Function& func);
154 
Function(std::unique_ptr<Instruction> def_inst)155 inline Function::Function(std::unique_ptr<Instruction> def_inst)
156     : def_inst_(std::move(def_inst)), end_inst_() {}
157 
AddParameter(std::unique_ptr<Instruction> p)158 inline void Function::AddParameter(std::unique_ptr<Instruction> p) {
159   params_.emplace_back(std::move(p));
160 }
161 
AddBasicBlock(std::unique_ptr<BasicBlock> b)162 inline void Function::AddBasicBlock(std::unique_ptr<BasicBlock> b) {
163   AddBasicBlock(std::move(b), end());
164 }
165 
AddBasicBlock(std::unique_ptr<BasicBlock> b,iterator ip)166 inline void Function::AddBasicBlock(std::unique_ptr<BasicBlock> b,
167                                     iterator ip) {
168   ip.InsertBefore(std::move(b));
169 }
170 
171 template <typename T>
AddBasicBlocks(T src_begin,T src_end,iterator ip)172 inline void Function::AddBasicBlocks(T src_begin, T src_end, iterator ip) {
173   blocks_.insert(ip.Get(), std::make_move_iterator(src_begin),
174                  std::make_move_iterator(src_end));
175 }
176 
MoveBasicBlockToAfter(uint32_t id,BasicBlock * ip)177 inline void Function::MoveBasicBlockToAfter(uint32_t id, BasicBlock* ip) {
178   auto block_to_move = std::move(*FindBlock(id).Get());
179 
180   assert(block_to_move->GetParent() == ip->GetParent() &&
181          "Both blocks have to be in the same function.");
182 
183   InsertBasicBlockAfter(std::move(block_to_move), ip);
184   blocks_.erase(std::find(std::begin(blocks_), std::end(blocks_), nullptr));
185 }
186 
RemoveEmptyBlocks()187 inline void Function::RemoveEmptyBlocks() {
188   auto first_empty =
189       std::remove_if(std::begin(blocks_), std::end(blocks_),
190                      [](const std::unique_ptr<BasicBlock>& bb) -> bool {
191                        return bb->GetLabelInst()->opcode() == SpvOpNop;
192                      });
193   blocks_.erase(first_empty, std::end(blocks_));
194 }
195 
SetFunctionEnd(std::unique_ptr<Instruction> end_inst)196 inline void Function::SetFunctionEnd(std::unique_ptr<Instruction> end_inst) {
197   end_inst_ = std::move(end_inst);
198 }
199 
200 }  // namespace opt
201 }  // namespace spvtools
202 
203 #endif  // SOURCE_OPT_FUNCTION_H_
204