xref: /freebsd-src/contrib/llvm-project/llvm/lib/Transforms/Vectorize/LoopVectorizationPlanner.h (revision e9ac41698b2f322d55ccf9da50a3596edb2c1800)
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/ADT/SmallSet.h"
29 #include "llvm/Support/InstructionCost.h"
30 
31 namespace llvm {
32 
33 class LoopInfo;
34 class DominatorTree;
35 class LoopVectorizationLegality;
36 class LoopVectorizationCostModel;
37 class PredicatedScalarEvolution;
38 class LoopVectorizeHints;
39 class OptimizationRemarkEmitter;
40 class TargetTransformInfo;
41 class TargetLibraryInfo;
42 class VPRecipeBuilder;
43 
44 /// VPlan-based builder utility analogous to IRBuilder.
45 class VPBuilder {
46   VPBasicBlock *BB = nullptr;
47   VPBasicBlock::iterator InsertPt = VPBasicBlock::iterator();
48 
49   /// Insert \p VPI in BB at InsertPt if BB is set.
50   VPInstruction *tryInsertInstruction(VPInstruction *VPI) {
51     if (BB)
52       BB->insert(VPI, InsertPt);
53     return VPI;
54   }
55 
56   VPInstruction *createInstruction(unsigned Opcode,
57                                    ArrayRef<VPValue *> Operands, DebugLoc DL,
58                                    const Twine &Name = "") {
59     return tryInsertInstruction(new VPInstruction(Opcode, Operands, DL, Name));
60   }
61 
62   VPInstruction *createInstruction(unsigned Opcode,
63                                    std::initializer_list<VPValue *> Operands,
64                                    DebugLoc DL, const Twine &Name = "") {
65     return createInstruction(Opcode, ArrayRef<VPValue *>(Operands), DL, Name);
66   }
67 
68 public:
69   VPBuilder() = default;
70   VPBuilder(VPBasicBlock *InsertBB) { setInsertPoint(InsertBB); }
71 
72   /// Clear the insertion point: created instructions will not be inserted into
73   /// a block.
74   void clearInsertionPoint() {
75     BB = nullptr;
76     InsertPt = VPBasicBlock::iterator();
77   }
78 
79   VPBasicBlock *getInsertBlock() const { return BB; }
80   VPBasicBlock::iterator getInsertPoint() const { return InsertPt; }
81 
82   /// InsertPoint - A saved insertion point.
83   class VPInsertPoint {
84     VPBasicBlock *Block = nullptr;
85     VPBasicBlock::iterator Point;
86 
87   public:
88     /// Creates a new insertion point which doesn't point to anything.
89     VPInsertPoint() = default;
90 
91     /// Creates a new insertion point at the given location.
92     VPInsertPoint(VPBasicBlock *InsertBlock, VPBasicBlock::iterator InsertPoint)
93         : Block(InsertBlock), Point(InsertPoint) {}
94 
95     /// Returns true if this insert point is set.
96     bool isSet() const { return Block != nullptr; }
97 
98     VPBasicBlock *getBlock() const { return Block; }
99     VPBasicBlock::iterator getPoint() const { return Point; }
100   };
101 
102   /// Sets the current insert point to a previously-saved location.
103   void restoreIP(VPInsertPoint IP) {
104     if (IP.isSet())
105       setInsertPoint(IP.getBlock(), IP.getPoint());
106     else
107       clearInsertionPoint();
108   }
109 
110   /// This specifies that created VPInstructions should be appended to the end
111   /// of the specified block.
112   void setInsertPoint(VPBasicBlock *TheBB) {
113     assert(TheBB && "Attempting to set a null insert point");
114     BB = TheBB;
115     InsertPt = BB->end();
116   }
117 
118   /// This specifies that created instructions should be inserted at the
119   /// specified point.
120   void setInsertPoint(VPBasicBlock *TheBB, VPBasicBlock::iterator IP) {
121     BB = TheBB;
122     InsertPt = IP;
123   }
124 
125   /// This specifies that created instructions should be inserted at the
126   /// specified point.
127   void setInsertPoint(VPRecipeBase *IP) {
128     BB = IP->getParent();
129     InsertPt = IP->getIterator();
130   }
131 
132   /// Create an N-ary operation with \p Opcode, \p Operands and set \p Inst as
133   /// its underlying Instruction.
134   VPValue *createNaryOp(unsigned Opcode, ArrayRef<VPValue *> Operands,
135                         Instruction *Inst = nullptr, const Twine &Name = "") {
136     DebugLoc DL;
137     if (Inst)
138       DL = Inst->getDebugLoc();
139     VPInstruction *NewVPInst = createInstruction(Opcode, Operands, DL, Name);
140     NewVPInst->setUnderlyingValue(Inst);
141     return NewVPInst;
142   }
143   VPValue *createNaryOp(unsigned Opcode, ArrayRef<VPValue *> Operands,
144                         DebugLoc DL, const Twine &Name = "") {
145     return createInstruction(Opcode, Operands, DL, Name);
146   }
147 
148   VPInstruction *createOverflowingOp(unsigned Opcode,
149                                      std::initializer_list<VPValue *> Operands,
150                                      VPRecipeWithIRFlags::WrapFlagsTy WrapFlags,
151                                      DebugLoc DL = {}, const Twine &Name = "") {
152     return tryInsertInstruction(
153         new VPInstruction(Opcode, Operands, WrapFlags, DL, Name));
154   }
155   VPValue *createNot(VPValue *Operand, DebugLoc DL = {},
156                      const Twine &Name = "") {
157     return createInstruction(VPInstruction::Not, {Operand}, DL, Name);
158   }
159 
160   VPValue *createAnd(VPValue *LHS, VPValue *RHS, DebugLoc DL = {},
161                      const Twine &Name = "") {
162     return createInstruction(Instruction::BinaryOps::And, {LHS, RHS}, DL, Name);
163   }
164 
165   VPValue *createOr(VPValue *LHS, VPValue *RHS, DebugLoc DL = {},
166                     const Twine &Name = "") {
167     return createInstruction(Instruction::BinaryOps::Or, {LHS, RHS}, DL, Name);
168   }
169 
170   VPValue *createSelect(VPValue *Cond, VPValue *TrueVal, VPValue *FalseVal,
171                         DebugLoc DL = {}, const Twine &Name = "",
172                         std::optional<FastMathFlags> FMFs = std::nullopt) {
173     auto *Select =
174         FMFs ? new VPInstruction(Instruction::Select, {Cond, TrueVal, FalseVal},
175                                  *FMFs, DL, Name)
176              : new VPInstruction(Instruction::Select, {Cond, TrueVal, FalseVal},
177                                  DL, Name);
178     return tryInsertInstruction(Select);
179   }
180 
181   /// Create a new ICmp VPInstruction with predicate \p Pred and operands \p A
182   /// and \p B.
183   /// TODO: add createFCmp when needed.
184   VPValue *createICmp(CmpInst::Predicate Pred, VPValue *A, VPValue *B,
185                       DebugLoc DL = {}, const Twine &Name = "");
186 
187   //===--------------------------------------------------------------------===//
188   // RAII helpers.
189   //===--------------------------------------------------------------------===//
190 
191   /// RAII object that stores the current insertion point and restores it when
192   /// the object is destroyed.
193   class InsertPointGuard {
194     VPBuilder &Builder;
195     VPBasicBlock *Block;
196     VPBasicBlock::iterator Point;
197 
198   public:
199     InsertPointGuard(VPBuilder &B)
200         : Builder(B), Block(B.getInsertBlock()), Point(B.getInsertPoint()) {}
201 
202     InsertPointGuard(const InsertPointGuard &) = delete;
203     InsertPointGuard &operator=(const InsertPointGuard &) = delete;
204 
205     ~InsertPointGuard() { Builder.restoreIP(VPInsertPoint(Block, Point)); }
206   };
207 };
208 
209 /// TODO: The following VectorizationFactor was pulled out of
210 /// LoopVectorizationCostModel class. LV also deals with
211 /// VectorizerParams::VectorizationFactor and VectorizationCostTy.
212 /// We need to streamline them.
213 
214 /// Information about vectorization costs.
215 struct VectorizationFactor {
216   /// Vector width with best cost.
217   ElementCount Width;
218 
219   /// Cost of the loop with that width.
220   InstructionCost Cost;
221 
222   /// Cost of the scalar loop.
223   InstructionCost ScalarCost;
224 
225   /// The minimum trip count required to make vectorization profitable, e.g. due
226   /// to runtime checks.
227   ElementCount MinProfitableTripCount;
228 
229   VectorizationFactor(ElementCount Width, InstructionCost Cost,
230                       InstructionCost ScalarCost)
231       : Width(Width), Cost(Cost), ScalarCost(ScalarCost) {}
232 
233   /// Width 1 means no vectorization, cost 0 means uncomputed cost.
234   static VectorizationFactor Disabled() {
235     return {ElementCount::getFixed(1), 0, 0};
236   }
237 
238   bool operator==(const VectorizationFactor &rhs) const {
239     return Width == rhs.Width && Cost == rhs.Cost;
240   }
241 
242   bool operator!=(const VectorizationFactor &rhs) const {
243     return !(*this == rhs);
244   }
245 };
246 
247 /// ElementCountComparator creates a total ordering for ElementCount
248 /// for the purposes of using it in a set structure.
249 struct ElementCountComparator {
250   bool operator()(const ElementCount &LHS, const ElementCount &RHS) const {
251     return std::make_tuple(LHS.isScalable(), LHS.getKnownMinValue()) <
252            std::make_tuple(RHS.isScalable(), RHS.getKnownMinValue());
253   }
254 };
255 using ElementCountSet = SmallSet<ElementCount, 16, ElementCountComparator>;
256 
257 /// A class that represents two vectorization factors (initialized with 0 by
258 /// default). One for fixed-width vectorization and one for scalable
259 /// vectorization. This can be used by the vectorizer to choose from a range of
260 /// fixed and/or scalable VFs in order to find the most cost-effective VF to
261 /// vectorize with.
262 struct FixedScalableVFPair {
263   ElementCount FixedVF;
264   ElementCount ScalableVF;
265 
266   FixedScalableVFPair()
267       : FixedVF(ElementCount::getFixed(0)),
268         ScalableVF(ElementCount::getScalable(0)) {}
269   FixedScalableVFPair(const ElementCount &Max) : FixedScalableVFPair() {
270     *(Max.isScalable() ? &ScalableVF : &FixedVF) = Max;
271   }
272   FixedScalableVFPair(const ElementCount &FixedVF,
273                       const ElementCount &ScalableVF)
274       : FixedVF(FixedVF), ScalableVF(ScalableVF) {
275     assert(!FixedVF.isScalable() && ScalableVF.isScalable() &&
276            "Invalid scalable properties");
277   }
278 
279   static FixedScalableVFPair getNone() { return FixedScalableVFPair(); }
280 
281   /// \return true if either fixed- or scalable VF is non-zero.
282   explicit operator bool() const { return FixedVF || ScalableVF; }
283 
284   /// \return true if either fixed- or scalable VF is a valid vector VF.
285   bool hasVector() const { return FixedVF.isVector() || ScalableVF.isVector(); }
286 };
287 
288 /// Planner drives the vectorization process after having passed
289 /// Legality checks.
290 class LoopVectorizationPlanner {
291   /// The loop that we evaluate.
292   Loop *OrigLoop;
293 
294   /// Loop Info analysis.
295   LoopInfo *LI;
296 
297   /// The dominator tree.
298   DominatorTree *DT;
299 
300   /// Target Library Info.
301   const TargetLibraryInfo *TLI;
302 
303   /// Target Transform Info.
304   const TargetTransformInfo &TTI;
305 
306   /// The legality analysis.
307   LoopVectorizationLegality *Legal;
308 
309   /// The profitability analysis.
310   LoopVectorizationCostModel &CM;
311 
312   /// The interleaved access analysis.
313   InterleavedAccessInfo &IAI;
314 
315   PredicatedScalarEvolution &PSE;
316 
317   const LoopVectorizeHints &Hints;
318 
319   OptimizationRemarkEmitter *ORE;
320 
321   SmallVector<VPlanPtr, 4> VPlans;
322 
323   /// Profitable vector factors.
324   SmallVector<VectorizationFactor, 8> ProfitableVFs;
325 
326   /// A builder used to construct the current plan.
327   VPBuilder Builder;
328 
329 public:
330   LoopVectorizationPlanner(
331       Loop *L, LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI,
332       const TargetTransformInfo &TTI, LoopVectorizationLegality *Legal,
333       LoopVectorizationCostModel &CM, InterleavedAccessInfo &IAI,
334       PredicatedScalarEvolution &PSE, const LoopVectorizeHints &Hints,
335       OptimizationRemarkEmitter *ORE)
336       : OrigLoop(L), LI(LI), DT(DT), TLI(TLI), TTI(TTI), Legal(Legal), CM(CM),
337         IAI(IAI), PSE(PSE), Hints(Hints), ORE(ORE) {}
338 
339   /// Plan how to best vectorize, return the best VF and its cost, or
340   /// std::nullopt if vectorization and interleaving should be avoided up front.
341   std::optional<VectorizationFactor> plan(ElementCount UserVF, unsigned UserIC);
342 
343   /// Use the VPlan-native path to plan how to best vectorize, return the best
344   /// VF and its cost.
345   VectorizationFactor planInVPlanNativePath(ElementCount UserVF);
346 
347   /// Return the best VPlan for \p VF.
348   VPlan &getBestPlanFor(ElementCount VF) const;
349 
350   /// Generate the IR code for the vectorized loop captured in VPlan \p BestPlan
351   /// according to the best selected \p VF and  \p UF.
352   ///
353   /// TODO: \p IsEpilogueVectorization is needed to avoid issues due to epilogue
354   /// vectorization re-using plans for both the main and epilogue vector loops.
355   /// It should be removed once the re-use issue has been fixed.
356   /// \p ExpandedSCEVs is passed during execution of the plan for epilogue loop
357   /// to re-use expansion results generated during main plan execution.
358   ///
359   /// Returns a mapping of SCEVs to their expanded IR values and a mapping for
360   /// the reduction resume values. Note that this is a temporary workaround
361   /// needed due to the current epilogue handling.
362   std::pair<DenseMap<const SCEV *, Value *>,
363             DenseMap<const RecurrenceDescriptor *, Value *>>
364   executePlan(ElementCount VF, unsigned UF, VPlan &BestPlan,
365               InnerLoopVectorizer &LB, DominatorTree *DT,
366               bool IsEpilogueVectorization,
367               const DenseMap<const SCEV *, Value *> *ExpandedSCEVs = nullptr);
368 
369 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
370   void printPlans(raw_ostream &O);
371 #endif
372 
373   /// Look through the existing plans and return true if we have one with
374   /// vectorization factor \p VF.
375   bool hasPlanWithVF(ElementCount VF) const {
376     return any_of(VPlans,
377                   [&](const VPlanPtr &Plan) { return Plan->hasVF(VF); });
378   }
379 
380   /// Test a \p Predicate on a \p Range of VF's. Return the value of applying
381   /// \p Predicate on Range.Start, possibly decreasing Range.End such that the
382   /// returned value holds for the entire \p Range.
383   static bool
384   getDecisionAndClampRange(const std::function<bool(ElementCount)> &Predicate,
385                            VFRange &Range);
386 
387   /// \return The most profitable vectorization factor and the cost of that VF
388   /// for vectorizing the epilogue. Returns VectorizationFactor::Disabled if
389   /// epilogue vectorization is not supported for the loop.
390   VectorizationFactor
391   selectEpilogueVectorizationFactor(const ElementCount MaxVF, unsigned IC);
392 
393 protected:
394   /// Build VPlans for power-of-2 VF's between \p MinVF and \p MaxVF inclusive,
395   /// according to the information gathered by Legal when it checked if it is
396   /// legal to vectorize the loop.
397   void buildVPlans(ElementCount MinVF, ElementCount MaxVF);
398 
399 private:
400   /// Build a VPlan according to the information gathered by Legal. \return a
401   /// VPlan for vectorization factors \p Range.Start and up to \p Range.End
402   /// exclusive, possibly decreasing \p Range.End.
403   VPlanPtr buildVPlan(VFRange &Range);
404 
405   /// Build a VPlan using VPRecipes according to the information gather by
406   /// Legal. This method is only used for the legacy inner loop vectorizer.
407   /// \p Range's largest included VF is restricted to the maximum VF the
408   /// returned VPlan is valid for. If no VPlan can be built for the input range,
409   /// set the largest included VF to the maximum VF for which no plan could be
410   /// built.
411   VPlanPtr tryToBuildVPlanWithVPRecipes(VFRange &Range);
412 
413   /// Build VPlans for power-of-2 VF's between \p MinVF and \p MaxVF inclusive,
414   /// according to the information gathered by Legal when it checked if it is
415   /// legal to vectorize the loop. This method creates VPlans using VPRecipes.
416   void buildVPlansWithVPRecipes(ElementCount MinVF, ElementCount MaxVF);
417 
418   // Adjust the recipes for reductions. For in-loop reductions the chain of
419   // instructions leading from the loop exit instr to the phi need to be
420   // converted to reductions, with one operand being vector and the other being
421   // the scalar reduction chain. For other reductions, a select is introduced
422   // between the phi and live-out recipes when folding the tail.
423   void adjustRecipesForReductions(VPBasicBlock *LatchVPBB, VPlanPtr &Plan,
424                                   VPRecipeBuilder &RecipeBuilder,
425                                   ElementCount MinVF);
426 
427   /// \return The most profitable vectorization factor and the cost of that VF.
428   /// This method checks every VF in \p CandidateVFs.
429   VectorizationFactor
430   selectVectorizationFactor(const ElementCountSet &CandidateVFs);
431 
432   /// Returns true if the per-lane cost of VectorizationFactor A is lower than
433   /// that of B.
434   bool isMoreProfitable(const VectorizationFactor &A,
435                         const VectorizationFactor &B) const;
436 
437   /// Determines if we have the infrastructure to vectorize the loop and its
438   /// epilogue, assuming the main loop is vectorized by \p VF.
439   bool isCandidateForEpilogueVectorization(const ElementCount VF) const;
440 };
441 
442 } // namespace llvm
443 
444 #endif // LLVM_TRANSFORMS_VECTORIZE_LOOPVECTORIZATIONPLANNER_H
445