1 //===- LoopVectorizationPlanner.h - Planner for LoopVectorization ---------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// This file provides a LoopVectorizationPlanner class.
11 /// InnerLoopVectorizer vectorizes loops which contain only one basic
12 /// LoopVectorizationPlanner - drives the vectorization process after having
13 /// passed Legality checks.
14 /// The planner builds and optimizes the Vectorization Plans which record the
15 /// decisions how to vectorize the given loop. In particular, represent the
16 /// control-flow of the vectorized version, the replication of instructions that
17 /// are to be scalarized, and interleave access groups.
18 ///
19 /// Also provides a VPlan-based builder utility analogous to IRBuilder.
20 /// It provides an instruction-level API for generating VPInstructions while
21 /// abstracting away the Recipe manipulation details.
22 //===----------------------------------------------------------------------===//
23 
24 #ifndef LLVM_TRANSFORMS_VECTORIZE_LOOPVECTORIZATIONPLANNER_H
25 #define LLVM_TRANSFORMS_VECTORIZE_LOOPVECTORIZATIONPLANNER_H
26 
27 #include "VPlan.h"
28 #include "llvm/Analysis/LoopInfo.h"
29 #include "llvm/Analysis/TargetLibraryInfo.h"
30 #include "llvm/Analysis/TargetTransformInfo.h"
31 
32 namespace llvm {
33 
34 class LoopVectorizationLegality;
35 class LoopVectorizationCostModel;
36 class PredicatedScalarEvolution;
37 class LoopVectorizationRequirements;
38 class LoopVectorizeHints;
39 class OptimizationRemarkEmitter;
40 class VPRecipeBuilder;
41 
42 /// VPlan-based builder utility analogous to IRBuilder.
43 class VPBuilder {
44   VPBasicBlock *BB = nullptr;
45   VPBasicBlock::iterator InsertPt = VPBasicBlock::iterator();
46 
47   VPInstruction *createInstruction(unsigned Opcode,
48                                    ArrayRef<VPValue *> Operands) {
49     VPInstruction *Instr = new VPInstruction(Opcode, Operands);
50     if (BB)
51       BB->insert(Instr, InsertPt);
52     return Instr;
53   }
54 
55   VPInstruction *createInstruction(unsigned Opcode,
56                                    std::initializer_list<VPValue *> Operands) {
57     return createInstruction(Opcode, ArrayRef<VPValue *>(Operands));
58   }
59 
60 public:
61   VPBuilder() {}
62 
63   /// Clear the insertion point: created instructions will not be inserted into
64   /// a block.
65   void clearInsertionPoint() {
66     BB = nullptr;
67     InsertPt = VPBasicBlock::iterator();
68   }
69 
70   VPBasicBlock *getInsertBlock() const { return BB; }
71   VPBasicBlock::iterator getInsertPoint() const { return InsertPt; }
72 
73   /// InsertPoint - A saved insertion point.
74   class VPInsertPoint {
75     VPBasicBlock *Block = nullptr;
76     VPBasicBlock::iterator Point;
77 
78   public:
79     /// Creates a new insertion point which doesn't point to anything.
80     VPInsertPoint() = default;
81 
82     /// Creates a new insertion point at the given location.
83     VPInsertPoint(VPBasicBlock *InsertBlock, VPBasicBlock::iterator InsertPoint)
84         : Block(InsertBlock), Point(InsertPoint) {}
85 
86     /// Returns true if this insert point is set.
87     bool isSet() const { return Block != nullptr; }
88 
89     VPBasicBlock *getBlock() const { return Block; }
90     VPBasicBlock::iterator getPoint() const { return Point; }
91   };
92 
93   /// Sets the current insert point to a previously-saved location.
94   void restoreIP(VPInsertPoint IP) {
95     if (IP.isSet())
96       setInsertPoint(IP.getBlock(), IP.getPoint());
97     else
98       clearInsertionPoint();
99   }
100 
101   /// This specifies that created VPInstructions should be appended to the end
102   /// of the specified block.
103   void setInsertPoint(VPBasicBlock *TheBB) {
104     assert(TheBB && "Attempting to set a null insert point");
105     BB = TheBB;
106     InsertPt = BB->end();
107   }
108 
109   /// This specifies that created instructions should be inserted at the
110   /// specified point.
111   void setInsertPoint(VPBasicBlock *TheBB, VPBasicBlock::iterator IP) {
112     BB = TheBB;
113     InsertPt = IP;
114   }
115 
116   /// Insert and return the specified instruction.
117   VPInstruction *insert(VPInstruction *I) const {
118     BB->insert(I, InsertPt);
119     return I;
120   }
121 
122   /// Create an N-ary operation with \p Opcode, \p Operands and set \p Inst as
123   /// its underlying Instruction.
124   VPValue *createNaryOp(unsigned Opcode, ArrayRef<VPValue *> Operands,
125                         Instruction *Inst = nullptr) {
126     VPInstruction *NewVPInst = createInstruction(Opcode, Operands);
127     NewVPInst->setUnderlyingValue(Inst);
128     return NewVPInst;
129   }
130   VPValue *createNaryOp(unsigned Opcode,
131                         std::initializer_list<VPValue *> Operands,
132                         Instruction *Inst = nullptr) {
133     return createNaryOp(Opcode, ArrayRef<VPValue *>(Operands), Inst);
134   }
135 
136   VPValue *createNot(VPValue *Operand) {
137     return createInstruction(VPInstruction::Not, {Operand});
138   }
139 
140   VPValue *createAnd(VPValue *LHS, VPValue *RHS) {
141     return createInstruction(Instruction::BinaryOps::And, {LHS, RHS});
142   }
143 
144   VPValue *createOr(VPValue *LHS, VPValue *RHS) {
145     return createInstruction(Instruction::BinaryOps::Or, {LHS, RHS});
146   }
147 
148   VPValue *createSelect(VPValue *Cond, VPValue *TrueVal, VPValue *FalseVal) {
149     return createNaryOp(Instruction::Select, {Cond, TrueVal, FalseVal});
150   }
151 
152   //===--------------------------------------------------------------------===//
153   // RAII helpers.
154   //===--------------------------------------------------------------------===//
155 
156   /// RAII object that stores the current insertion point and restores it when
157   /// the object is destroyed.
158   class InsertPointGuard {
159     VPBuilder &Builder;
160     VPBasicBlock *Block;
161     VPBasicBlock::iterator Point;
162 
163   public:
164     InsertPointGuard(VPBuilder &B)
165         : Builder(B), Block(B.getInsertBlock()), Point(B.getInsertPoint()) {}
166 
167     InsertPointGuard(const InsertPointGuard &) = delete;
168     InsertPointGuard &operator=(const InsertPointGuard &) = delete;
169 
170     ~InsertPointGuard() { Builder.restoreIP(VPInsertPoint(Block, Point)); }
171   };
172 };
173 
174 /// TODO: The following VectorizationFactor was pulled out of
175 /// LoopVectorizationCostModel class. LV also deals with
176 /// VectorizerParams::VectorizationFactor and VectorizationCostTy.
177 /// We need to streamline them.
178 
179 /// Information about vectorization costs
180 struct VectorizationFactor {
181   // Vector width with best cost
182   ElementCount Width;
183   // Cost of the loop with that width
184   unsigned Cost;
185 
186   // Width 1 means no vectorization, cost 0 means uncomputed cost.
187   static VectorizationFactor Disabled() {
188     return {ElementCount::getFixed(1), 0};
189   }
190 
191   bool operator==(const VectorizationFactor &rhs) const {
192     return Width == rhs.Width && Cost == rhs.Cost;
193   }
194 
195   bool operator!=(const VectorizationFactor &rhs) const {
196     return !(*this == rhs);
197   }
198 };
199 
200 /// Planner drives the vectorization process after having passed
201 /// Legality checks.
202 class LoopVectorizationPlanner {
203   /// The loop that we evaluate.
204   Loop *OrigLoop;
205 
206   /// Loop Info analysis.
207   LoopInfo *LI;
208 
209   /// Target Library Info.
210   const TargetLibraryInfo *TLI;
211 
212   /// Target Transform Info.
213   const TargetTransformInfo *TTI;
214 
215   /// The legality analysis.
216   LoopVectorizationLegality *Legal;
217 
218   /// The profitability analysis.
219   LoopVectorizationCostModel &CM;
220 
221   /// The interleaved access analysis.
222   InterleavedAccessInfo &IAI;
223 
224   PredicatedScalarEvolution &PSE;
225 
226   const LoopVectorizeHints &Hints;
227 
228   LoopVectorizationRequirements &Requirements;
229 
230   OptimizationRemarkEmitter *ORE;
231 
232   SmallVector<VPlanPtr, 4> VPlans;
233 
234   /// A builder used to construct the current plan.
235   VPBuilder Builder;
236 
237   /// The best number of elements of the vector types used in the
238   /// transformed loop. BestVF = None means that vectorization is
239   /// disabled.
240   Optional<ElementCount> BestVF = None;
241   unsigned BestUF = 0;
242 
243 public:
244   LoopVectorizationPlanner(Loop *L, LoopInfo *LI, const TargetLibraryInfo *TLI,
245                            const TargetTransformInfo *TTI,
246                            LoopVectorizationLegality *Legal,
247                            LoopVectorizationCostModel &CM,
248                            InterleavedAccessInfo &IAI,
249                            PredicatedScalarEvolution &PSE,
250                            const LoopVectorizeHints &Hints,
251                            LoopVectorizationRequirements &Requirements,
252                            OptimizationRemarkEmitter *ORE)
253       : OrigLoop(L), LI(LI), TLI(TLI), TTI(TTI), Legal(Legal), CM(CM), IAI(IAI),
254         PSE(PSE), Hints(Hints), Requirements(Requirements), ORE(ORE) {}
255 
256   /// Plan how to best vectorize, return the best VF and its cost, or None if
257   /// vectorization and interleaving should be avoided up front.
258   Optional<VectorizationFactor> plan(ElementCount UserVF, unsigned UserIC);
259 
260   /// Use the VPlan-native path to plan how to best vectorize, return the best
261   /// VF and its cost.
262   VectorizationFactor planInVPlanNativePath(ElementCount UserVF);
263 
264   /// Finalize the best decision and dispose of all other VPlans.
265   void setBestPlan(ElementCount VF, unsigned UF);
266 
267   /// Generate the IR code for the body of the vectorized loop according to the
268   /// best selected VPlan.
269   void executePlan(InnerLoopVectorizer &LB, DominatorTree *DT);
270 
271 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
272   void printPlans(raw_ostream &O);
273 #endif
274 
275   /// Look through the existing plans and return true if we have one with all
276   /// the vectorization factors in question.
277   bool hasPlanWithVFs(const ArrayRef<ElementCount> VFs) const {
278     return any_of(VPlans, [&](const VPlanPtr &Plan) {
279       return all_of(VFs, [&](const ElementCount &VF) {
280         return Plan->hasVF(VF);
281       });
282     });
283   }
284 
285   /// Test a \p Predicate on a \p Range of VF's. Return the value of applying
286   /// \p Predicate on Range.Start, possibly decreasing Range.End such that the
287   /// returned value holds for the entire \p Range.
288   static bool
289   getDecisionAndClampRange(const std::function<bool(ElementCount)> &Predicate,
290                            VFRange &Range);
291 
292 protected:
293   /// Collect the instructions from the original loop that would be trivially
294   /// dead in the vectorized loop if generated.
295   void collectTriviallyDeadInstructions(
296       SmallPtrSetImpl<Instruction *> &DeadInstructions);
297 
298   /// Build VPlans for power-of-2 VF's between \p MinVF and \p MaxVF inclusive,
299   /// according to the information gathered by Legal when it checked if it is
300   /// legal to vectorize the loop.
301   void buildVPlans(ElementCount MinVF, ElementCount MaxVF);
302 
303 private:
304   /// Build a VPlan according to the information gathered by Legal. \return a
305   /// VPlan for vectorization factors \p Range.Start and up to \p Range.End
306   /// exclusive, possibly decreasing \p Range.End.
307   VPlanPtr buildVPlan(VFRange &Range);
308 
309   /// Build a VPlan using VPRecipes according to the information gather by
310   /// Legal. This method is only used for the legacy inner loop vectorizer.
311   VPlanPtr buildVPlanWithVPRecipes(
312       VFRange &Range, SmallPtrSetImpl<Instruction *> &DeadInstructions,
313       const DenseMap<Instruction *, Instruction *> &SinkAfter);
314 
315   /// Build VPlans for power-of-2 VF's between \p MinVF and \p MaxVF inclusive,
316   /// according to the information gathered by Legal when it checked if it is
317   /// legal to vectorize the loop. This method creates VPlans using VPRecipes.
318   void buildVPlansWithVPRecipes(ElementCount MinVF, ElementCount MaxVF);
319 
320   /// Adjust the recipes for any inloop reductions. The chain of instructions
321   /// leading from the loop exit instr to the phi need to be converted to
322   /// reductions, with one operand being vector and the other being the scalar
323   /// reduction chain.
324   void adjustRecipesForInLoopReductions(VPlanPtr &Plan,
325                                         VPRecipeBuilder &RecipeBuilder);
326 };
327 
328 } // namespace llvm
329 
330 #endif // LLVM_TRANSFORMS_VECTORIZE_LOOPVECTORIZATIONPLANNER_H
331