LLVM 24.0.0git
VPlanAnalysis.cpp
Go to the documentation of this file.
1//===- VPlanAnalysis.cpp - Various Analyses working on VPlan ----*- C++ -*-===//
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#include "VPlanAnalysis.h"
10#include "VPlan.h"
11#include "VPlanCFG.h"
12#include "VPlanDominatorTree.h"
13#include "VPlanHelpers.h"
14#include "VPlanPatternMatch.h"
17
18using namespace llvm;
19using namespace VPlanPatternMatch;
20
21#define DEBUG_TYPE "vplan"
22
24 VPlan &Plan, DenseSet<VPRecipeBase *> &EphRecipes) {
25 // First, collect seed recipes which are operands of assumes.
31 continue;
32 Worklist.push_back(&RepR);
33 EphRecipes.insert(&RepR);
34 }
35 }
36
37 // Process operands of candidates in worklist and add them to the set of
38 // ephemeral recipes, if they don't have side-effects and are only used by
39 // other ephemeral recipes.
40 while (!Worklist.empty()) {
41 VPRecipeBase *Cur = Worklist.pop_back_val();
42 for (VPValue *Op : Cur->operands()) {
43 auto *OpR = Op->getDefiningRecipe();
44 if (!OpR || OpR->mayHaveSideEffects() || EphRecipes.contains(OpR))
45 continue;
46 if (any_of(Op->users(), [EphRecipes](VPUser *U) {
47 auto *UR = dyn_cast<VPRecipeBase>(U);
48 return !UR || !EphRecipes.contains(UR);
49 }))
50 continue;
51 EphRecipes.insert(OpR);
52 Worklist.push_back(OpR);
53 }
54 }
55}
56
58 const VPRecipeBase *B) const {
59 if (A == B)
60 return false;
61
62 auto LocalComesBefore = [](const VPRecipeBase *A, const VPRecipeBase *B) {
63 for (auto &R : *A->getParent()) {
64 if (&R == A)
65 return true;
66 if (&R == B)
67 return false;
68 }
69 llvm_unreachable("recipe not found");
70 };
71 const VPBlockBase *ParentA = A->getParent();
72 const VPBlockBase *ParentB = B->getParent();
73 if (ParentA == ParentB)
74 return LocalComesBefore(A, B);
75
76 return Base::properlyDominates(ParentA, ParentB);
77}
78
82 unsigned OverrideMaxNumRegs) const {
84 for (const auto &[RegClass, MaxUsers] : MaxLocalUsers) {
85 unsigned AvailableRegs = OverrideMaxNumRegs > 0
86 ? OverrideMaxNumRegs
87 : TTI.getNumberOfRegisters(RegClass);
88 if (MaxUsers > AvailableRegs) {
89 // Assume that for each register used past what's available we get one
90 // spill and reload.
91 unsigned Spills = MaxUsers - AvailableRegs;
92 InstructionCost SpillCost =
93 TTI.getRegisterClassSpillCost(RegClass, CostKind) +
94 TTI.getRegisterClassReloadCost(RegClass, CostKind);
95 InstructionCost TotalCost = Spills * SpillCost;
96 LLVM_DEBUG(dbgs() << "LV(REG): Cost of " << TotalCost << " from "
97 << Spills << " spills of "
98 << TTI.getRegisterClassName(RegClass) << "\n");
99 Cost += TotalCost;
100 }
101 }
102 return Cost;
103}
104
107 const TargetTransformInfo &TTI) {
108 DenseSet<VPRecipeBase *> EphemeralRecipes;
109 collectEphemeralRecipesForVPlan(Plan, EphemeralRecipes);
110
111 // Each 'key' in the map opens a new interval. The values
112 // of the map are the index of the 'last seen' usage of the
113 // VPValue that is the key.
115
116 // Maps indices to recipes.
118 // Marks the end of each interval.
119 IntervalMap EndPoint;
120 // Saves the list of VPValues that are used in the loop.
122 // Saves the list of values that are used in the loop but are defined outside
123 // the loop (not including non-recipe values such as arguments and
124 // constants).
125 SmallSetVector<VPValue *, 8> LoopInvariants;
126 if (!Plan.getVectorTripCount().user_empty())
127 LoopInvariants.insert(&Plan.getVectorTripCount());
128
129 // We scan the loop in a topological order in order and assign a number to
130 // each recipe. We use RPO to ensure that defs are met before their users. We
131 // assume that each recipe that has in-loop users starts an interval. We
132 // record every time that an in-loop value is used, so we have a list of the
133 // first occurences of each recipe and last occurrence of each VPValue.
134 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
136 LoopRegion);
138 if (!VPBB->getParent())
139 break;
140 for (VPRecipeBase &R : *VPBB) {
141 Idx2Recipe.push_back(&R);
142
143 // Save the end location of each USE.
144 for (VPValue *U : R.operands()) {
145 if (isa<VPRecipeValue>(U)) {
146 // Overwrite previous end points.
147 EndPoint[U] = Idx2Recipe.size();
148 Ends.insert(U);
149 } else if (auto *IRV = dyn_cast<VPIRValue>(U)) {
150 // Ignore non-recipe values such as arguments, constants, etc.
151 // FIXME: Might need some motivation why these values are ignored. If
152 // for example an argument is used inside the loop it will increase
153 // the register pressure (so shouldn't we add it to LoopInvariants).
154 if (!isa<Instruction>(IRV->getValue()))
155 continue;
156 // This recipe is outside the loop, record it and continue.
157 LoopInvariants.insert(U);
158 }
159 // Other types of VPValue are currently not tracked.
160 }
161 }
162 if (VPBB == LoopRegion->getExiting()) {
163 // VPWidenIntOrFpInductionRecipes are used implicitly at the end of the
164 // exiting block, where their increment will get materialized eventually.
166 LoopRegion->getEntryBasicBlock()->phis())) {
167 EndPoint[&WideIV] = Idx2Recipe.size();
168 Ends.insert(&WideIV);
169 }
170 }
171 }
172
173 // Saves the list of intervals that end with the index in 'key'.
174 using VPValueList = SmallVector<VPValue *, 2>;
176
177 // Next, we transpose the EndPoints into a multi map that holds the list of
178 // intervals that *end* at a specific location.
179 for (auto &Interval : EndPoint)
180 TransposeEnds[Interval.second].push_back(Interval.first);
181
182 SmallPtrSet<VPValue *, 8> OpenIntervals;
185
186 LLVM_DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
187
188 const auto &TTICapture = TTI;
189 auto GetRegUsage = [&TTICapture](Type *Ty, ElementCount VF) -> unsigned {
190 if (Ty->isTokenTy() || !VectorType::isValidElementType(Ty) ||
191 (VF.isScalable() &&
192 !TTICapture.isElementTypeLegalForScalableVector(Ty)))
193 return 0;
194 return TTICapture.getRegUsageForType(VectorType::get(Ty, VF));
195 };
196
197 VPValue *CanIV = LoopRegion->getCanonicalIV();
198 // Note: canonical IVs are retained even if they have no users.
199 if (!CanIV->user_empty())
200 OpenIntervals.insert(CanIV);
201
202 // We scan the instructions linearly and record each time that a new interval
203 // starts, by placing it in a set. If we find this value in TransposEnds then
204 // we remove it from the set. The max register usage is the maximum register
205 // usage of the recipes of the set.
206 for (unsigned int Idx = 0, Sz = Idx2Recipe.size(); Idx < Sz; ++Idx) {
207 VPRecipeBase *R = Idx2Recipe[Idx];
208
209 // Remove all of the VPValues that end at this location.
210 VPValueList &List = TransposeEnds[Idx];
211 for (VPValue *ToRemove : List)
212 OpenIntervals.erase(ToRemove);
213
214 // Ignore recipes that are never used within the loop and do not have side
215 // effects.
216 if (none_of(R->definedValues(),
217 [&Ends](VPValue *Def) { return Ends.count(Def); }) &&
218 !R->mayHaveSideEffects())
219 continue;
220
221 // Skip recipes for ephemeral values, i.e. those only feeding assumes. They
222 // are removed before code generation and must not contribute to the
223 // register pressure of the plan.
224 if (EphemeralRecipes.contains(R))
225 continue;
226
227 // For each VF find the maximum usage of registers.
228 for (unsigned J = 0, E = VFs.size(); J < E; ++J) {
229 // Count the number of registers used, per register class, given all open
230 // intervals.
231 // Note that elements in this SmallMapVector will be default constructed
232 // as 0. So we can use "RegUsage[ClassID] += n" in the code below even if
233 // there is no previous entry for ClassID.
235
236 for (auto *VPV : OpenIntervals) {
237 // Skip artificial values or values that weren't present in the original
238 // loop.
239 // TODO: Remove skipping values that weren't present in the original
240 // loop after removing the legacy
241 // LoopVectorizationCostModel::calculateRegisterUsage
243 VPBranchOnMaskRecipe>(VPV) ||
245 continue;
246
247 if (VFs[J].isScalar() || VPV == CanIV ||
252 (cast<VPReductionPHIRecipe>(VPV))->isInLoop())) {
253 unsigned ClassID =
254 TTI.getRegisterClassForType(false, VPV->getScalarType());
255 // FIXME: The target might use more than one register for the type
256 // even in the scalar case.
257 RegUsage[ClassID] += 1;
258 } else {
259 // The output from scaled phis and scaled reductions actually has
260 // fewer lanes than the VF.
261 unsigned ScaleFactor =
262 vputils::getVFScaleFactor(VPV->getDefiningRecipe());
263 ElementCount VF = VFs[J];
264 if (ScaleFactor > 1) {
265 VF = VFs[J].divideCoefficientBy(ScaleFactor);
266 LLVM_DEBUG(dbgs() << "LV(REG): Scaled down VF from " << VFs[J]
267 << " to " << VF << " for " << *R << "\n";);
268 }
269
270 Type *ScalarTy = VPV->getScalarType();
271 unsigned ClassID = TTI.getRegisterClassForType(true, ScalarTy);
272 RegUsage[ClassID] += GetRegUsage(ScalarTy, VF);
273 }
274 }
275
276 for (const auto &Pair : RegUsage) {
277 auto &Entry = MaxUsages[J][Pair.first];
278 Entry = std::max(Entry, Pair.second);
279 }
280 }
281
282 LLVM_DEBUG(dbgs() << "LV(REG): At #" << Idx << " Interval # "
283 << OpenIntervals.size() << '\n');
284
285 // Add used VPValues defined by the current recipe to the list of open
286 // intervals.
287 for (VPValue *DefV : R->definedValues())
288 if (Ends.contains(DefV))
289 OpenIntervals.insert(DefV);
290 }
291
292 // We also search for instructions that are defined outside the loop, but are
293 // used inside the loop. We need this number separately from the max-interval
294 // usage number because when we unroll, loop-invariant values do not take
295 // more register.
297 for (unsigned Idx = 0, End = VFs.size(); Idx < End; ++Idx) {
298 // Note that elements in this SmallMapVector will be default constructed
299 // as 0. So we can use "Invariant[ClassID] += n" in the code below even if
300 // there is no previous entry for ClassID.
302
303 for (auto *In : LoopInvariants) {
304 // FIXME: The target might use more than one register for the type
305 // even in the scalar case.
306 bool IsScalar = vputils::onlyScalarValuesUsed(In);
307
308 ElementCount VF = IsScalar ? ElementCount::getFixed(1) : VFs[Idx];
309 unsigned ClassID =
310 TTI.getRegisterClassForType(VF.isVector(), In->getScalarType());
311 Invariant[ClassID] += GetRegUsage(In->getScalarType(), VF);
312 }
313
314 LLVM_DEBUG({
315 dbgs() << "LV(REG): VF = " << VFs[Idx] << '\n';
316 dbgs() << "LV(REG): Found max usage: " << MaxUsages[Idx].size()
317 << " item\n";
318 for (const auto &pair : MaxUsages[Idx]) {
319 dbgs() << "LV(REG): RegisterClass: "
320 << TTI.getRegisterClassName(pair.first) << ", " << pair.second
321 << " registers\n";
322 }
323 dbgs() << "LV(REG): Found invariant usage: " << Invariant.size()
324 << " item\n";
325 for (const auto &pair : Invariant) {
326 dbgs() << "LV(REG): RegisterClass: "
327 << TTI.getRegisterClassName(pair.first) << ", " << pair.second
328 << " registers\n";
329 }
330 });
331
332 RU.LoopInvariantRegs = Invariant;
333 RU.MaxLocalUsers = MaxUsages[Idx];
334 RUs[Idx] = RU;
335 }
336
337 return RUs;
338}
ReachingDefInfo InstSet & ToRemove
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static cl::opt< OutputCostKind > CostKind("cost-kind", cl::desc("Target cost kind"), cl::init(OutputCostKind::RecipThroughput), cl::values(clEnumValN(OutputCostKind::RecipThroughput, "throughput", "Reciprocal throughput"), clEnumValN(OutputCostKind::Latency, "latency", "Instruction latency"), clEnumValN(OutputCostKind::CodeSize, "code-size", "Code size"), clEnumValN(OutputCostKind::SizeAndLatency, "size-latency", "Code size and latency"), clEnumValN(OutputCostKind::All, "all", "Print all cost kinds")))
std::pair< uint64_t, uint64_t > Interval
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
#define LLVM_DEBUG(...)
Definition Debug.h:119
This pass exposes codegen information to IR-level passes.
This file implements dominator tree analysis for a single level of a VPlan's H-CFG.
This file contains the declarations of different VPlan-related auxiliary helpers.
This file contains the declarations of the Vectorization Plan base classes:
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
bool properlyDominates(const DomTreeNodeBase< VPBlockBase > *A, const DomTreeNodeBase< VPBlockBase > *B) const
constexpr bool isVector() const
One or more elements.
Definition TypeSize.h:320
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:305
size_type size() const
Definition MapVector.h:58
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
size_type size() const
bool erase(PtrType Ptr)
Remove pointer from the set.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:345
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
TargetCostKind
The kind of cost model.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:363
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
Definition VPlan.h:4418
iterator_range< iterator > phis()
Returns an iterator range over the PHI-like recipes in the block.
Definition VPlan.h:4506
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
Definition VPlan.h:95
const VPBasicBlock * getEntryBasicBlock() const
Definition VPlan.cpp:188
static auto blocksOnly(T &&Range)
Return an iterator range over Range which only includes BlockTy blocks.
Definition VPlanUtils.h:431
A recipe for generating conditional branches on the bits of a mask.
Definition VPlan.h:3510
A recipe for generating the phi node tracking the current scalar iteration index.
Definition VPlan.h:4098
A recipe for converting Current into Start + Current * Step.
Definition VPlan.h:4199
bool properlyDominates(const VPRecipeBase *A, const VPRecipeBase *B) const
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
Definition VPlan.h:411
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
Definition VPlan.h:4643
const VPBlockBase * getEntry() const
Definition VPlan.h:4687
VPRegionValue * getCanonicalIV()
Return the canonical induction variable of the region, null for replicating regions.
Definition VPlan.h:4763
const VPBlockBase * getExiting() const
Definition VPlan.h:4699
VPReplicateRecipe replicates a given instruction producing multiple scalar copies of the original sca...
Definition VPlan.h:3401
A recipe for handling phi nodes of integer and floating-point inductions, producing their scalar valu...
Definition VPlan.h:4260
This class augments VPValue with operands which provide the inverse def-use edges from VPValue's user...
Definition VPlanValue.h:401
operand_range operands()
Definition VPlanValue.h:474
This is the base class of the VPlan Def/Use graph, used for modeling the data flow into,...
Definition VPlanValue.h:50
bool user_empty() const
Definition VPlanValue.h:161
A recipe to compute a pointer to the last element of each part of a widened memory access for widened...
Definition VPlan.h:2276
A recipe to compute the pointers for widened memory accesses of SourceElementTy, with the Stride expr...
Definition VPlan.h:2358
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4830
VPSymbolicValue & getVectorTripCount()
The vector trip count.
Definition VPlan.h:5028
LLVM_ABI_FOR_TEST VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
Definition VPlan.cpp:1033
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:182
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
bool match(Val *V, const Pattern &P)
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
auto m_VPValue()
Match an arbitrary VPValue and ignore it.
VPInstruction_match< VPInstruction::ExtractLastPart, Op0_t > m_ExtractLastPart(const Op0_t &Op0)
bool onlyScalarValuesUsed(const VPValue *Def)
Returns true if only scalar values of Def are used by all users.
unsigned getVFScaleFactor(VPRecipeBase *R)
Get the VF scaling factor applied to the recipe's output, if the recipe has one.
This is an optimization pass for GlobalISel generic memory operations.
InstructionCost Cost
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
iterator_range< df_iterator< VPBlockDeepTraversalWrapper< VPBlockBase * > > > vp_depth_first_deep(VPBlockBase *G)
Returns an iterator range to traverse the graph starting at G in depth-first order while traversing t...
Definition VPlanCFG.h:285
auto make_isa_range(RangeT &&Range)
Return a range over Range containing only elements for which isa<T> holds, casting each of them to T.
Definition STLExtras.h:567
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:1762
void collectEphemeralRecipesForVPlan(VPlan &Plan, DenseSet< VPRecipeBase * > &EphRecipes)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
SmallVector< VPRegisterUsage, 8 > calculateRegisterUsageForPlan(VPlan &Plan, ArrayRef< ElementCount > VFs, const TargetTransformInfo &TTI)
Estimate the register usage for Plan and vectorization factors in VFs by calculating the highest numb...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
TargetTransformInfo TTI
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
A MapVector that performs no allocations if smaller than a certain size.
Definition MapVector.h:342
A struct that represents some properties of the register usage of a loop.
SmallMapVector< unsigned, unsigned, 4 > MaxLocalUsers
Holds the maximum number of concurrent live intervals in the loop.
InstructionCost spillCost(const TargetTransformInfo &TTI, TargetTransformInfo::TargetCostKind CostKind, unsigned OverrideMaxNumRegs=0) const
Calculate the estimated cost of any spills due to using more registers than the number available for ...
SmallMapVector< unsigned, unsigned, 4 > LoopInvariantRegs
Holds the number of loop invariant values that are used in the loop.