LLVM 18.0.0git
LoopVectorizationPlanner.h
Go to the documentation of this file.
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"
30
31namespace llvm {
32
33class LoopInfo;
34class LoopVectorizationLegality;
35class LoopVectorizationCostModel;
36class PredicatedScalarEvolution;
37class LoopVectorizeHints;
38class OptimizationRemarkEmitter;
39class TargetTransformInfo;
40class TargetLibraryInfo;
41class VPRecipeBuilder;
42
43/// VPlan-based builder utility analogous to IRBuilder.
44class VPBuilder {
45 VPBasicBlock *BB = nullptr;
47
48 /// Insert \p VPI in BB at InsertPt if BB is set.
49 VPInstruction *tryInsertInstruction(VPInstruction *VPI) {
50 if (BB)
51 BB->insert(VPI, InsertPt);
52 return VPI;
53 }
54
55 VPInstruction *createInstruction(unsigned Opcode,
57 const Twine &Name = "") {
58 return tryInsertInstruction(new VPInstruction(Opcode, Operands, DL, Name));
59 }
60
61 VPInstruction *createInstruction(unsigned Opcode,
62 std::initializer_list<VPValue *> Operands,
63 DebugLoc DL, const Twine &Name = "") {
64 return createInstruction(Opcode, ArrayRef<VPValue *>(Operands), DL, Name);
65 }
66
67public:
68 VPBuilder() = default;
69 VPBuilder(VPBasicBlock *InsertBB) { setInsertPoint(InsertBB); }
70
71 /// Clear the insertion point: created instructions will not be inserted into
72 /// a block.
74 BB = nullptr;
75 InsertPt = VPBasicBlock::iterator();
76 }
77
78 VPBasicBlock *getInsertBlock() const { return BB; }
79 VPBasicBlock::iterator getInsertPoint() const { return InsertPt; }
80
81 /// InsertPoint - A saved insertion point.
83 VPBasicBlock *Block = nullptr;
85
86 public:
87 /// Creates a new insertion point which doesn't point to anything.
88 VPInsertPoint() = default;
89
90 /// Creates a new insertion point at the given location.
92 : Block(InsertBlock), Point(InsertPoint) {}
93
94 /// Returns true if this insert point is set.
95 bool isSet() const { return Block != nullptr; }
96
97 VPBasicBlock *getBlock() const { return Block; }
98 VPBasicBlock::iterator getPoint() const { return Point; }
99 };
100
101 /// Sets the current insert point to a previously-saved location.
103 if (IP.isSet())
104 setInsertPoint(IP.getBlock(), IP.getPoint());
105 else
107 }
108
109 /// This specifies that created VPInstructions should be appended to the end
110 /// of the specified block.
112 assert(TheBB && "Attempting to set a null insert point");
113 BB = TheBB;
114 InsertPt = BB->end();
115 }
116
117 /// This specifies that created instructions should be inserted at the
118 /// specified point.
120 BB = TheBB;
121 InsertPt = IP;
122 }
123
124 /// This specifies that created instructions should be inserted at the
125 /// specified point.
127 BB = IP->getParent();
128 InsertPt = IP->getIterator();
129 }
130
131 /// Create an N-ary operation with \p Opcode, \p Operands and set \p Inst as
132 /// its underlying Instruction.
134 Instruction *Inst = nullptr, const Twine &Name = "") {
135 DebugLoc DL;
136 if (Inst)
137 DL = Inst->getDebugLoc();
138 VPInstruction *NewVPInst = createInstruction(Opcode, Operands, DL, Name);
139 NewVPInst->setUnderlyingValue(Inst);
140 return NewVPInst;
141 }
143 DebugLoc DL, const Twine &Name = "") {
144 return createInstruction(Opcode, Operands, DL, Name);
145 }
146
148 std::initializer_list<VPValue *> Operands,
150 DebugLoc DL, const Twine &Name = "") {
151 return tryInsertInstruction(
152 new VPInstruction(Opcode, Operands, WrapFlags, DL, Name));
153 }
154 VPValue *createNot(VPValue *Operand, DebugLoc DL, const Twine &Name = "") {
155 return createInstruction(VPInstruction::Not, {Operand}, DL, Name);
156 }
157
159 const Twine &Name = "") {
160 return createInstruction(Instruction::BinaryOps::And, {LHS, RHS}, DL, Name);
161 }
162
164 const Twine &Name = "") {
165 return createInstruction(Instruction::BinaryOps::Or, {LHS, RHS}, DL, Name);
166 }
167
169 DebugLoc DL, const Twine &Name = "") {
170 return createNaryOp(Instruction::Select, {Cond, TrueVal, FalseVal}, DL,
171 Name);
172 }
173
174 /// Create a new ICmp VPInstruction with predicate \p Pred and operands \p A
175 /// and \p B.
176 /// TODO: add createFCmp when needed.
178 DebugLoc DL = {}, const Twine &Name = "");
179
180 //===--------------------------------------------------------------------===//
181 // RAII helpers.
182 //===--------------------------------------------------------------------===//
183
184 /// RAII object that stores the current insertion point and restores it when
185 /// the object is destroyed.
187 VPBuilder &Builder;
188 VPBasicBlock *Block;
190
191 public:
193 : Builder(B), Block(B.getInsertBlock()), Point(B.getInsertPoint()) {}
194
197
198 ~InsertPointGuard() { Builder.restoreIP(VPInsertPoint(Block, Point)); }
199 };
200};
201
202/// TODO: The following VectorizationFactor was pulled out of
203/// LoopVectorizationCostModel class. LV also deals with
204/// VectorizerParams::VectorizationFactor and VectorizationCostTy.
205/// We need to streamline them.
206
207/// Information about vectorization costs.
209 /// Vector width with best cost.
211
212 /// Cost of the loop with that width.
214
215 /// Cost of the scalar loop.
217
218 /// The minimum trip count required to make vectorization profitable, e.g. due
219 /// to runtime checks.
221
225
226 /// Width 1 means no vectorization, cost 0 means uncomputed cost.
228 return {ElementCount::getFixed(1), 0, 0};
229 }
230
231 bool operator==(const VectorizationFactor &rhs) const {
232 return Width == rhs.Width && Cost == rhs.Cost;
233 }
234
235 bool operator!=(const VectorizationFactor &rhs) const {
236 return !(*this == rhs);
237 }
238};
239
240/// ElementCountComparator creates a total ordering for ElementCount
241/// for the purposes of using it in a set structure.
243 bool operator()(const ElementCount &LHS, const ElementCount &RHS) const {
244 return std::make_tuple(LHS.isScalable(), LHS.getKnownMinValue()) <
245 std::make_tuple(RHS.isScalable(), RHS.getKnownMinValue());
246 }
247};
249
250/// A class that represents two vectorization factors (initialized with 0 by
251/// default). One for fixed-width vectorization and one for scalable
252/// vectorization. This can be used by the vectorizer to choose from a range of
253/// fixed and/or scalable VFs in order to find the most cost-effective VF to
254/// vectorize with.
258
260 : FixedVF(ElementCount::getFixed(0)),
261 ScalableVF(ElementCount::getScalable(0)) {}
263 *(Max.isScalable() ? &ScalableVF : &FixedVF) = Max;
264 }
269 "Invalid scalable properties");
270 }
271
273
274 /// \return true if either fixed- or scalable VF is non-zero.
275 explicit operator bool() const { return FixedVF || ScalableVF; }
276
277 /// \return true if either fixed- or scalable VF is a valid vector VF.
278 bool hasVector() const { return FixedVF.isVector() || ScalableVF.isVector(); }
279};
280
281/// Planner drives the vectorization process after having passed
282/// Legality checks.
284 /// The loop that we evaluate.
285 Loop *OrigLoop;
286
287 /// Loop Info analysis.
288 LoopInfo *LI;
289
290 /// Target Library Info.
291 const TargetLibraryInfo *TLI;
292
293 /// Target Transform Info.
295
296 /// The legality analysis.
298
299 /// The profitability analysis.
301
302 /// The interleaved access analysis.
304
306
307 const LoopVectorizeHints &Hints;
308
310
312
313 /// Profitable vector factors.
315
316 /// A builder used to construct the current plan.
317 VPBuilder Builder;
318
319public:
326 const LoopVectorizeHints &Hints,
328 : OrigLoop(L), LI(LI), TLI(TLI), TTI(TTI), Legal(Legal), CM(CM), IAI(IAI),
329 PSE(PSE), Hints(Hints), ORE(ORE) {}
330
331 /// Plan how to best vectorize, return the best VF and its cost, or
332 /// std::nullopt if vectorization and interleaving should be avoided up front.
333 std::optional<VectorizationFactor> plan(ElementCount UserVF, unsigned UserIC);
334
335 /// Use the VPlan-native path to plan how to best vectorize, return the best
336 /// VF and its cost.
338
339 /// Return the best VPlan for \p VF.
341
342 /// Generate the IR code for the body of the vectorized loop according to the
343 /// best selected \p VF, \p UF and VPlan \p BestPlan.
344 /// TODO: \p IsEpilogueVectorization is needed to avoid issues due to epilogue
345 /// vectorization re-using plans for both the main and epilogue vector loops.
346 /// It should be removed once the re-use issue has been fixed.
347 /// \p ExpandedSCEVs is passed during execution of the plan for epilogue loop
348 /// to re-use expansion results generated during main plan execution. Returns
349 /// a mapping of SCEVs to their expanded IR values. Note that this is a
350 /// temporary workaround needed due to the current epilogue handling.
352 executePlan(ElementCount VF, unsigned UF, VPlan &BestPlan,
354 bool IsEpilogueVectorization,
355 DenseMap<const SCEV *, Value *> *ExpandedSCEVs = nullptr);
356
357#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
358 void printPlans(raw_ostream &O);
359#endif
360
361 /// Look through the existing plans and return true if we have one with
362 /// vectorization factor \p VF.
364 return any_of(VPlans,
365 [&](const VPlanPtr &Plan) { return Plan->hasVF(VF); });
366 }
367
368 /// Test a \p Predicate on a \p Range of VF's. Return the value of applying
369 /// \p Predicate on Range.Start, possibly decreasing Range.End such that the
370 /// returned value holds for the entire \p Range.
371 static bool
372 getDecisionAndClampRange(const std::function<bool(ElementCount)> &Predicate,
373 VFRange &Range);
374
375 /// \return The most profitable vectorization factor and the cost of that VF
376 /// for vectorizing the epilogue. Returns VectorizationFactor::Disabled if
377 /// epilogue vectorization is not supported for the loop.
379 selectEpilogueVectorizationFactor(const ElementCount MaxVF, unsigned IC);
380
381protected:
382 /// Build VPlans for power-of-2 VF's between \p MinVF and \p MaxVF inclusive,
383 /// according to the information gathered by Legal when it checked if it is
384 /// legal to vectorize the loop.
385 void buildVPlans(ElementCount MinVF, ElementCount MaxVF);
386
387private:
388 /// Build a VPlan according to the information gathered by Legal. \return a
389 /// VPlan for vectorization factors \p Range.Start and up to \p Range.End
390 /// exclusive, possibly decreasing \p Range.End.
391 VPlanPtr buildVPlan(VFRange &Range);
392
393 /// Build a VPlan using VPRecipes according to the information gather by
394 /// Legal. This method is only used for the legacy inner loop vectorizer.
395 /// \p Range's largest included VF is restricted to the maximum VF the
396 /// returned VPlan is valid for. If no VPlan can be built for the input range,
397 /// set the largest included VF to the maximum VF for which no plan could be
398 /// built.
399 VPlanPtr tryToBuildVPlanWithVPRecipes(VFRange &Range);
400
401 /// Build VPlans for power-of-2 VF's between \p MinVF and \p MaxVF inclusive,
402 /// according to the information gathered by Legal when it checked if it is
403 /// legal to vectorize the loop. This method creates VPlans using VPRecipes.
404 void buildVPlansWithVPRecipes(ElementCount MinVF, ElementCount MaxVF);
405
406 // Adjust the recipes for reductions. For in-loop reductions the chain of
407 // instructions leading from the loop exit instr to the phi need to be
408 // converted to reductions, with one operand being vector and the other being
409 // the scalar reduction chain. For other reductions, a select is introduced
410 // between the phi and live-out recipes when folding the tail.
411 void adjustRecipesForReductions(VPBasicBlock *LatchVPBB, VPlanPtr &Plan,
412 VPRecipeBuilder &RecipeBuilder,
413 ElementCount MinVF);
414
415 /// \return The most profitable vectorization factor and the cost of that VF.
416 /// This method checks every VF in \p CandidateVFs.
418 selectVectorizationFactor(const ElementCountSet &CandidateVFs);
419
420 /// Returns true if the per-lane cost of VectorizationFactor A is lower than
421 /// that of B.
422 bool isMoreProfitable(const VectorizationFactor &A,
423 const VectorizationFactor &B) const;
424
425 /// Determines if we have the infrastructure to vectorize the loop and its
426 /// epilogue, assuming the main loop is vectorized by \p VF.
427 bool isCandidateForEpilogueVectorization(const ElementCount VF) const;
428};
429
430} // namespace llvm
431
432#endif // LLVM_TRANSFORMS_VECTORIZE_LOOPVECTORIZATIONPLANNER_H
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
assume Assume Builder
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
std::string Name
This file defines an InstructionCost class that is used when calculating the cost of an instruction,...
mir Rename Register Operands
const SmallVectorImpl< MachineOperand > & Cond
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallSet class.
This file contains the declarations of the Vectorization Plan base classes:
Value * RHS
Value * LHS
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:711
A debug info location.
Definition: DebugLoc.h:33
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:166
constexpr bool isVector() const
One or more elements.
Definition: TypeSize.h:306
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition: TypeSize.h:291
InnerLoopVectorizer vectorizes loops which contain only one basic block to a specified vectorization ...
Drive the analysis of interleaved memory accesses in the loop.
Definition: VectorUtils.h:777
LoopVectorizationCostModel - estimates the expected speedups due to vectorization.
LoopVectorizationLegality checks if it is legal to vectorize a loop, and to what vectorization factor...
Planner drives the vectorization process after having passed Legality checks.
std::optional< VectorizationFactor > plan(ElementCount UserVF, unsigned UserIC)
Plan how to best vectorize, return the best VF and its cost, or std::nullopt if vectorization and int...
VectorizationFactor selectEpilogueVectorizationFactor(const ElementCount MaxVF, unsigned IC)
VectorizationFactor planInVPlanNativePath(ElementCount UserVF)
Use the VPlan-native path to plan how to best vectorize, return the best VF and its cost.
void buildVPlans(ElementCount MinVF, ElementCount MaxVF)
Build VPlans for power-of-2 VF's between MinVF and MaxVF inclusive, according to the information gath...
VPlan & getBestPlanFor(ElementCount VF) const
Return the best VPlan for VF.
DenseMap< const SCEV *, Value * > executePlan(ElementCount VF, unsigned UF, VPlan &BestPlan, InnerLoopVectorizer &LB, DominatorTree *DT, bool IsEpilogueVectorization, DenseMap< const SCEV *, Value * > *ExpandedSCEVs=nullptr)
Generate the IR code for the body of the vectorized loop according to the best selected VF,...
LoopVectorizationPlanner(Loop *L, LoopInfo *LI, const TargetLibraryInfo *TLI, const TargetTransformInfo &TTI, LoopVectorizationLegality *Legal, LoopVectorizationCostModel &CM, InterleavedAccessInfo &IAI, PredicatedScalarEvolution &PSE, const LoopVectorizeHints &Hints, OptimizationRemarkEmitter *ORE)
static bool getDecisionAndClampRange(const std::function< bool(ElementCount)> &Predicate, VFRange &Range)
Test a Predicate on a Range of VF's.
void printPlans(raw_ostream &O)
bool hasPlanWithVF(ElementCount VF) const
Look through the existing plans and return true if we have one with vectorization factor VF.
Utility class for getting and setting loop vectorizer hints in the form of loop metadata.
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:47
The optimization diagnostic interface.
An interface layer with SCEV used to manage how we see SCEV expressions for values in the context of ...
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:135
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1200
Provides information about what library functions are available for the current target.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
Definition: VPlan.h:2253
RecipeListTy::iterator iterator
Instruction iterators...
Definition: VPlan.h:2274
iterator end()
Definition: VPlan.h:2284
void insert(VPRecipeBase *Recipe, iterator InsertPt)
Definition: VPlan.h:2312
RAII object that stores the current insertion point and restores it when the object is destroyed.
InsertPointGuard(const InsertPointGuard &)=delete
InsertPointGuard & operator=(const InsertPointGuard &)=delete
InsertPoint - A saved insertion point.
VPInsertPoint(VPBasicBlock *InsertBlock, VPBasicBlock::iterator InsertPoint)
Creates a new insertion point at the given location.
VPBasicBlock::iterator getPoint() const
VPInsertPoint()=default
Creates a new insertion point which doesn't point to anything.
bool isSet() const
Returns true if this insert point is set.
VPlan-based builder utility analogous to IRBuilder.
void setInsertPoint(VPBasicBlock *TheBB, VPBasicBlock::iterator IP)
This specifies that created instructions should be inserted at the specified point.
void setInsertPoint(VPRecipeBase *IP)
This specifies that created instructions should be inserted at the specified point.
void restoreIP(VPInsertPoint IP)
Sets the current insert point to a previously-saved location.
VPValue * createOr(VPValue *LHS, VPValue *RHS, DebugLoc DL, const Twine &Name="")
VPBasicBlock * getInsertBlock() const
VPBasicBlock::iterator getInsertPoint() const
VPInstruction * createOverflowingOp(unsigned Opcode, std::initializer_list< VPValue * > Operands, VPRecipeWithIRFlags::WrapFlagsTy WrapFlags, DebugLoc DL, const Twine &Name="")
VPBuilder(VPBasicBlock *InsertBB)
VPValue * createNot(VPValue *Operand, DebugLoc DL, const Twine &Name="")
VPValue * createNaryOp(unsigned Opcode, ArrayRef< VPValue * > Operands, Instruction *Inst=nullptr, const Twine &Name="")
Create an N-ary operation with Opcode, Operands and set Inst as its underlying Instruction.
VPValue * createICmp(CmpInst::Predicate Pred, VPValue *A, VPValue *B, DebugLoc DL={}, const Twine &Name="")
Create a new ICmp VPInstruction with predicate Pred and operands A and B.
VPValue * createNaryOp(unsigned Opcode, ArrayRef< VPValue * > Operands, DebugLoc DL, const Twine &Name="")
void clearInsertionPoint()
Clear the insertion point: created instructions will not be inserted into a block.
VPBuilder()=default
VPValue * createSelect(VPValue *Cond, VPValue *TrueVal, VPValue *FalseVal, DebugLoc DL, const Twine &Name="")
VPValue * createAnd(VPValue *LHS, VPValue *RHS, DebugLoc DL, const Twine &Name="")
void setInsertPoint(VPBasicBlock *TheBB)
This specifies that created VPInstructions should be appended to the end of the specified block.
This is a concrete Recipe that models a single VPlan-level instruction.
Definition: VPlan.h:1018
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
Definition: VPlan.h:707
VPBasicBlock * getParent()
Definition: VPlan.h:729
Helper class to create VPRecipies from IR instructions.
void setUnderlyingValue(Value *Val)
Definition: VPlanValue.h:77
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition: VPlan.h:2474
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition: TypeSize.h:166
self_iterator getIterator()
Definition: ilist_node.h:82
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1734
std::unique_ptr< VPlan > VPlanPtr
Definition: VPlan.h:131
ElementCountComparator creates a total ordering for ElementCount for the purposes of using it in a se...
bool operator()(const ElementCount &LHS, const ElementCount &RHS) const
A class that represents two vectorization factors (initialized with 0 by default).
FixedScalableVFPair(const ElementCount &FixedVF, const ElementCount &ScalableVF)
FixedScalableVFPair(const ElementCount &Max)
static FixedScalableVFPair getNone()
A range of powers-of-2 vectorization factors with fixed start and adjustable end.
Definition: VPlan.h:84
TODO: The following VectorizationFactor was pulled out of LoopVectorizationCostModel class.
InstructionCost Cost
Cost of the loop with that width.
ElementCount MinProfitableTripCount
The minimum trip count required to make vectorization profitable, e.g.
bool operator==(const VectorizationFactor &rhs) const
ElementCount Width
Vector width with best cost.
InstructionCost ScalarCost
Cost of the scalar loop.
bool operator!=(const VectorizationFactor &rhs) const
static VectorizationFactor Disabled()
Width 1 means no vectorization, cost 0 means uncomputed cost.
VectorizationFactor(ElementCount Width, InstructionCost Cost, InstructionCost ScalarCost)