xref: /llvm-project/llvm/lib/Transforms/Vectorize/LoopVectorizationPlanner.h (revision 1edd22030ccb9603f21d13150847ea40a4136d45)
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   template <typename T> T *tryInsertInstruction(T *R) {
51     if (BB)
52       BB->insert(R, InsertPt);
53     return R;
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   VPInstruction *createNaryOp(unsigned Opcode,
160                               std::initializer_list<VPValue *> Operands,
161                               std::optional<FastMathFlags> FMFs = {},
162                               DebugLoc DL = {}, const Twine &Name = "") {
163     if (FMFs)
164       return tryInsertInstruction(
165           new VPInstruction(Opcode, Operands, *FMFs, DL, Name));
166     return createInstruction(Opcode, Operands, DL, Name);
167   }
168 
169   VPInstruction *createOverflowingOp(unsigned Opcode,
170                                      std::initializer_list<VPValue *> Operands,
171                                      VPRecipeWithIRFlags::WrapFlagsTy WrapFlags,
172                                      DebugLoc DL = {}, const Twine &Name = "") {
173     return tryInsertInstruction(
174         new VPInstruction(Opcode, Operands, WrapFlags, DL, Name));
175   }
176 
177   VPValue *createNot(VPValue *Operand, DebugLoc DL = {},
178                      const Twine &Name = "") {
179     return createInstruction(VPInstruction::Not, {Operand}, DL, Name);
180   }
181 
182   VPValue *createAnd(VPValue *LHS, VPValue *RHS, DebugLoc DL = {},
183                      const Twine &Name = "") {
184     return createInstruction(Instruction::BinaryOps::And, {LHS, RHS}, DL, Name);
185   }
186 
187   VPValue *createOr(VPValue *LHS, VPValue *RHS, DebugLoc DL = {},
188                     const Twine &Name = "") {
189 
190     return tryInsertInstruction(new VPInstruction(
191         Instruction::BinaryOps::Or, {LHS, RHS},
192         VPRecipeWithIRFlags::DisjointFlagsTy(false), DL, Name));
193   }
194 
195   VPValue *createLogicalAnd(VPValue *LHS, VPValue *RHS, DebugLoc DL = {},
196                             const Twine &Name = "") {
197     return tryInsertInstruction(
198         new VPInstruction(VPInstruction::LogicalAnd, {LHS, RHS}, DL, Name));
199   }
200 
201   VPValue *createSelect(VPValue *Cond, VPValue *TrueVal, VPValue *FalseVal,
202                         DebugLoc DL = {}, const Twine &Name = "",
203                         std::optional<FastMathFlags> FMFs = std::nullopt) {
204     auto *Select =
205         FMFs ? new VPInstruction(Instruction::Select, {Cond, TrueVal, FalseVal},
206                                  *FMFs, DL, Name)
207              : new VPInstruction(Instruction::Select, {Cond, TrueVal, FalseVal},
208                                  DL, Name);
209     return tryInsertInstruction(Select);
210   }
211 
212   /// Create a new ICmp VPInstruction with predicate \p Pred and operands \p A
213   /// and \p B.
214   /// TODO: add createFCmp when needed.
215   VPValue *createICmp(CmpInst::Predicate Pred, VPValue *A, VPValue *B,
216                       DebugLoc DL = {}, const Twine &Name = "") {
217     assert(Pred >= CmpInst::FIRST_ICMP_PREDICATE &&
218            Pred <= CmpInst::LAST_ICMP_PREDICATE && "invalid predicate");
219     return tryInsertInstruction(
220         new VPInstruction(Instruction::ICmp, Pred, A, B, DL, Name));
221   }
222 
223   VPInstruction *createPtrAdd(VPValue *Ptr, VPValue *Offset, DebugLoc DL,
224                               const Twine &Name = "") {
225     return createInstruction(VPInstruction::PtrAdd, {Ptr, Offset}, DL, Name);
226   }
227 
228   VPDerivedIVRecipe *createDerivedIV(InductionDescriptor::InductionKind Kind,
229                                      FPMathOperator *FPBinOp, VPValue *Start,
230                                      VPCanonicalIVPHIRecipe *CanonicalIV,
231                                      VPValue *Step) {
232     return tryInsertInstruction(
233         new VPDerivedIVRecipe(Kind, FPBinOp, Start, CanonicalIV, Step));
234   }
235 
236   VPScalarCastRecipe *createScalarCast(Instruction::CastOps Opcode, VPValue *Op,
237                                        Type *ResultTy) {
238     return tryInsertInstruction(new VPScalarCastRecipe(Opcode, Op, ResultTy));
239   }
240 
241   VPWidenCastRecipe *createWidenCast(Instruction::CastOps Opcode, VPValue *Op,
242                                      Type *ResultTy) {
243     return tryInsertInstruction(new VPWidenCastRecipe(Opcode, Op, ResultTy));
244   }
245 
246   VPScalarIVStepsRecipe *
247   createScalarIVSteps(Instruction::BinaryOps InductionOpcode,
248                       FPMathOperator *FPBinOp, VPValue *IV, VPValue *Step) {
249     return tryInsertInstruction(new VPScalarIVStepsRecipe(
250         IV, Step, InductionOpcode,
251         FPBinOp ? FPBinOp->getFastMathFlags() : FastMathFlags()));
252   }
253 
254   //===--------------------------------------------------------------------===//
255   // RAII helpers.
256   //===--------------------------------------------------------------------===//
257 
258   /// RAII object that stores the current insertion point and restores it when
259   /// the object is destroyed.
260   class InsertPointGuard {
261     VPBuilder &Builder;
262     VPBasicBlock *Block;
263     VPBasicBlock::iterator Point;
264 
265   public:
266     InsertPointGuard(VPBuilder &B)
267         : Builder(B), Block(B.getInsertBlock()), Point(B.getInsertPoint()) {}
268 
269     InsertPointGuard(const InsertPointGuard &) = delete;
270     InsertPointGuard &operator=(const InsertPointGuard &) = delete;
271 
272     ~InsertPointGuard() { Builder.restoreIP(VPInsertPoint(Block, Point)); }
273   };
274 };
275 
276 /// TODO: The following VectorizationFactor was pulled out of
277 /// LoopVectorizationCostModel class. LV also deals with
278 /// VectorizerParams::VectorizationFactor.
279 /// We need to streamline them.
280 
281 /// Information about vectorization costs.
282 struct VectorizationFactor {
283   /// Vector width with best cost.
284   ElementCount Width;
285 
286   /// Cost of the loop with that width.
287   InstructionCost Cost;
288 
289   /// Cost of the scalar loop.
290   InstructionCost ScalarCost;
291 
292   /// The minimum trip count required to make vectorization profitable, e.g. due
293   /// to runtime checks.
294   ElementCount MinProfitableTripCount;
295 
296   VectorizationFactor(ElementCount Width, InstructionCost Cost,
297                       InstructionCost ScalarCost)
298       : Width(Width), Cost(Cost), ScalarCost(ScalarCost) {}
299 
300   /// Width 1 means no vectorization, cost 0 means uncomputed cost.
301   static VectorizationFactor Disabled() {
302     return {ElementCount::getFixed(1), 0, 0};
303   }
304 
305   bool operator==(const VectorizationFactor &rhs) const {
306     return Width == rhs.Width && Cost == rhs.Cost;
307   }
308 
309   bool operator!=(const VectorizationFactor &rhs) const {
310     return !(*this == rhs);
311   }
312 };
313 
314 /// A class that represents two vectorization factors (initialized with 0 by
315 /// default). One for fixed-width vectorization and one for scalable
316 /// vectorization. This can be used by the vectorizer to choose from a range of
317 /// fixed and/or scalable VFs in order to find the most cost-effective VF to
318 /// vectorize with.
319 struct FixedScalableVFPair {
320   ElementCount FixedVF;
321   ElementCount ScalableVF;
322 
323   FixedScalableVFPair()
324       : FixedVF(ElementCount::getFixed(0)),
325         ScalableVF(ElementCount::getScalable(0)) {}
326   FixedScalableVFPair(const ElementCount &Max) : FixedScalableVFPair() {
327     *(Max.isScalable() ? &ScalableVF : &FixedVF) = Max;
328   }
329   FixedScalableVFPair(const ElementCount &FixedVF,
330                       const ElementCount &ScalableVF)
331       : FixedVF(FixedVF), ScalableVF(ScalableVF) {
332     assert(!FixedVF.isScalable() && ScalableVF.isScalable() &&
333            "Invalid scalable properties");
334   }
335 
336   static FixedScalableVFPair getNone() { return FixedScalableVFPair(); }
337 
338   /// \return true if either fixed- or scalable VF is non-zero.
339   explicit operator bool() const { return FixedVF || ScalableVF; }
340 
341   /// \return true if either fixed- or scalable VF is a valid vector VF.
342   bool hasVector() const { return FixedVF.isVector() || ScalableVF.isVector(); }
343 };
344 
345 /// Planner drives the vectorization process after having passed
346 /// Legality checks.
347 class LoopVectorizationPlanner {
348   /// The loop that we evaluate.
349   Loop *OrigLoop;
350 
351   /// Loop Info analysis.
352   LoopInfo *LI;
353 
354   /// The dominator tree.
355   DominatorTree *DT;
356 
357   /// Target Library Info.
358   const TargetLibraryInfo *TLI;
359 
360   /// Target Transform Info.
361   const TargetTransformInfo &TTI;
362 
363   /// The legality analysis.
364   LoopVectorizationLegality *Legal;
365 
366   /// The profitability analysis.
367   LoopVectorizationCostModel &CM;
368 
369   /// The interleaved access analysis.
370   InterleavedAccessInfo &IAI;
371 
372   PredicatedScalarEvolution &PSE;
373 
374   const LoopVectorizeHints &Hints;
375 
376   OptimizationRemarkEmitter *ORE;
377 
378   SmallVector<VPlanPtr, 4> VPlans;
379 
380   /// Profitable vector factors.
381   SmallVector<VectorizationFactor, 8> ProfitableVFs;
382 
383   /// A builder used to construct the current plan.
384   VPBuilder Builder;
385 
386   /// Computes the cost of \p Plan for vectorization factor \p VF.
387   ///
388   /// The current implementation requires access to the
389   /// LoopVectorizationLegality to handle inductions and reductions, which is
390   /// why it is kept separate from the VPlan-only cost infrastructure.
391   ///
392   /// TODO: Move to VPlan::cost once the use of LoopVectorizationLegality has
393   /// been retired.
394   InstructionCost cost(VPlan &Plan, ElementCount VF) const;
395 
396   /// Precompute costs for certain instructions using the legacy cost model. The
397   /// function is used to bring up the VPlan-based cost model to initially avoid
398   /// taking different decisions due to inaccuracies in the legacy cost model.
399   InstructionCost precomputeCosts(VPlan &Plan, ElementCount VF,
400                                   VPCostContext &CostCtx) const;
401 
402 public:
403   LoopVectorizationPlanner(
404       Loop *L, LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI,
405       const TargetTransformInfo &TTI, LoopVectorizationLegality *Legal,
406       LoopVectorizationCostModel &CM, InterleavedAccessInfo &IAI,
407       PredicatedScalarEvolution &PSE, const LoopVectorizeHints &Hints,
408       OptimizationRemarkEmitter *ORE)
409       : OrigLoop(L), LI(LI), DT(DT), TLI(TLI), TTI(TTI), Legal(Legal), CM(CM),
410         IAI(IAI), PSE(PSE), Hints(Hints), ORE(ORE) {}
411 
412   /// Build VPlans for the specified \p UserVF and \p UserIC if they are
413   /// non-zero or all applicable candidate VFs otherwise. If vectorization and
414   /// interleaving should be avoided up-front, no plans are generated.
415   void plan(ElementCount UserVF, unsigned UserIC);
416 
417   /// Use the VPlan-native path to plan how to best vectorize, return the best
418   /// VF and its cost.
419   VectorizationFactor planInVPlanNativePath(ElementCount UserVF);
420 
421   /// Return the VPlan for \p VF. At the moment, there is always a single VPlan
422   /// for each VF.
423   VPlan &getPlanFor(ElementCount VF) const;
424 
425   /// Compute and return the most profitable vectorization factor. Also collect
426   /// all profitable VFs in ProfitableVFs.
427   VectorizationFactor computeBestVF();
428 
429   /// Generate the IR code for the vectorized loop captured in VPlan \p BestPlan
430   /// according to the best selected \p VF and  \p UF.
431   ///
432   /// TODO: \p IsEpilogueVectorization is needed to avoid issues due to epilogue
433   /// vectorization re-using plans for both the main and epilogue vector loops.
434   /// It should be removed once the re-use issue has been fixed.
435   /// \p ExpandedSCEVs is passed during execution of the plan for epilogue loop
436   /// to re-use expansion results generated during main plan execution.
437   ///
438   /// Returns a mapping of SCEVs to their expanded IR values.
439   /// Note that this is a temporary workaround needed due to the current
440   /// epilogue handling.
441   DenseMap<const SCEV *, Value *>
442   executePlan(ElementCount VF, unsigned UF, VPlan &BestPlan,
443               InnerLoopVectorizer &LB, DominatorTree *DT,
444               bool IsEpilogueVectorization,
445               const DenseMap<const SCEV *, Value *> *ExpandedSCEVs = nullptr);
446 
447 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
448   void printPlans(raw_ostream &O);
449 #endif
450 
451   /// Look through the existing plans and return true if we have one with
452   /// vectorization factor \p VF.
453   bool hasPlanWithVF(ElementCount VF) const {
454     return any_of(VPlans,
455                   [&](const VPlanPtr &Plan) { return Plan->hasVF(VF); });
456   }
457 
458   /// Test a \p Predicate on a \p Range of VF's. Return the value of applying
459   /// \p Predicate on Range.Start, possibly decreasing Range.End such that the
460   /// returned value holds for the entire \p Range.
461   static bool
462   getDecisionAndClampRange(const std::function<bool(ElementCount)> &Predicate,
463                            VFRange &Range);
464 
465   /// \return The most profitable vectorization factor and the cost of that VF
466   /// for vectorizing the epilogue. Returns VectorizationFactor::Disabled if
467   /// epilogue vectorization is not supported for the loop.
468   VectorizationFactor
469   selectEpilogueVectorizationFactor(const ElementCount MaxVF, unsigned IC);
470 
471   /// Emit remarks for recipes with invalid costs in the available VPlans.
472   void emitInvalidCostRemarks(OptimizationRemarkEmitter *ORE);
473 
474 protected:
475   /// Build VPlans for power-of-2 VF's between \p MinVF and \p MaxVF inclusive,
476   /// according to the information gathered by Legal when it checked if it is
477   /// legal to vectorize the loop.
478   void buildVPlans(ElementCount MinVF, ElementCount MaxVF);
479 
480 private:
481   /// Build a VPlan according to the information gathered by Legal. \return a
482   /// VPlan for vectorization factors \p Range.Start and up to \p Range.End
483   /// exclusive, possibly decreasing \p Range.End.
484   VPlanPtr buildVPlan(VFRange &Range);
485 
486   /// Build a VPlan using VPRecipes according to the information gather by
487   /// Legal. This method is only used for the legacy inner loop vectorizer.
488   /// \p Range's largest included VF is restricted to the maximum VF the
489   /// returned VPlan is valid for. If no VPlan can be built for the input range,
490   /// set the largest included VF to the maximum VF for which no plan could be
491   /// built.
492   VPlanPtr tryToBuildVPlanWithVPRecipes(VFRange &Range);
493 
494   /// Build VPlans for power-of-2 VF's between \p MinVF and \p MaxVF inclusive,
495   /// according to the information gathered by Legal when it checked if it is
496   /// legal to vectorize the loop. This method creates VPlans using VPRecipes.
497   void buildVPlansWithVPRecipes(ElementCount MinVF, ElementCount MaxVF);
498 
499   // Adjust the recipes for reductions. For in-loop reductions the chain of
500   // instructions leading from the loop exit instr to the phi need to be
501   // converted to reductions, with one operand being vector and the other being
502   // the scalar reduction chain. For other reductions, a select is introduced
503   // between the phi and live-out recipes when folding the tail.
504   void adjustRecipesForReductions(VPlanPtr &Plan,
505                                   VPRecipeBuilder &RecipeBuilder,
506                                   ElementCount MinVF);
507 
508 #ifndef NDEBUG
509   /// \return The most profitable vectorization factor for the available VPlans
510   /// and the cost of that VF.
511   /// This is now only used to verify the decisions by the new VPlan-based
512   /// cost-model and will be retired once the VPlan-based cost-model is
513   /// stabilized.
514   VectorizationFactor selectVectorizationFactor();
515 #endif
516 
517   /// Returns true if the per-lane cost of VectorizationFactor A is lower than
518   /// that of B.
519   bool isMoreProfitable(const VectorizationFactor &A,
520                         const VectorizationFactor &B) const;
521 
522   /// Determines if we have the infrastructure to vectorize the loop and its
523   /// epilogue, assuming the main loop is vectorized by \p VF.
524   bool isCandidateForEpilogueVectorization(const ElementCount VF) const;
525 };
526 
527 } // namespace llvm
528 
529 #endif // LLVM_TRANSFORMS_VECTORIZE_LOOPVECTORIZATIONPLANNER_H
530