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