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.
29 for (VPRecipeBase &R : *VPBB) {
30 auto *RepR = dyn_cast<VPReplicateRecipe>(&R);
31 if (!RepR || !match(RepR, m_Intrinsic<Intrinsic::assume>()))
32 continue;
33 Worklist.push_back(RepR);
34 EphRecipes.insert(RepR);
35 }
36 }
37
38 // Process operands of candidates in worklist and add them to the set of
39 // ephemeral recipes, if they don't have side-effects and are only used by
40 // other ephemeral recipes.
41 while (!Worklist.empty()) {
42 VPRecipeBase *Cur = Worklist.pop_back_val();
43 for (VPValue *Op : Cur->operands()) {
44 auto *OpR = Op->getDefiningRecipe();
45 if (!OpR || OpR->mayHaveSideEffects() || EphRecipes.contains(OpR))
46 continue;
47 if (any_of(Op->users(), [EphRecipes](VPUser *U) {
48 auto *UR = dyn_cast<VPRecipeBase>(U);
49 return !UR || !EphRecipes.contains(UR);
50 }))
51 continue;
52 EphRecipes.insert(OpR);
53 Worklist.push_back(OpR);
54 }
55 }
56}
57
59 const VPRecipeBase *B) const {
60 if (A == B)
61 return false;
62
63 auto LocalComesBefore = [](const VPRecipeBase *A, const VPRecipeBase *B) {
64 for (auto &R : *A->getParent()) {
65 if (&R == A)
66 return true;
67 if (&R == B)
68 return false;
69 }
70 llvm_unreachable("recipe not found");
71 };
72 const VPBlockBase *ParentA = A->getParent();
73 const VPBlockBase *ParentB = B->getParent();
74 if (ParentA == ParentB)
75 return LocalComesBefore(A, B);
76
77 return Base::properlyDominates(ParentA, ParentB);
78}
79
83 unsigned OverrideMaxNumRegs) const {
85 for (const auto &[RegClass, MaxUsers] : MaxLocalUsers) {
86 unsigned AvailableRegs = OverrideMaxNumRegs > 0
87 ? OverrideMaxNumRegs
88 : TTI.getNumberOfRegisters(RegClass);
89 if (MaxUsers > AvailableRegs) {
90 // Assume that for each register used past what's available we get one
91 // spill and reload.
92 unsigned Spills = MaxUsers - AvailableRegs;
93 InstructionCost SpillCost =
94 TTI.getRegisterClassSpillCost(RegClass, CostKind) +
95 TTI.getRegisterClassReloadCost(RegClass, CostKind);
96 InstructionCost TotalCost = Spills * SpillCost;
97 LLVM_DEBUG(dbgs() << "LV(REG): Cost of " << TotalCost << " from "
98 << Spills << " spills of "
99 << TTI.getRegisterClassName(RegClass) << "\n");
100 Cost += TotalCost;
101 }
102 }
103 return Cost;
104}
105
108 const SmallPtrSetImpl<const Value *> &ValuesToIgnore) {
109 // Each 'key' in the map opens a new interval. The values
110 // of the map are the index of the 'last seen' usage of the
111 // VPValue that is the key.
113
114 // Maps indices to recipes.
116 // Marks the end of each interval.
117 IntervalMap EndPoint;
118 // Saves the list of VPValues that are used in the loop.
120 // Saves the list of values that are used in the loop but are defined outside
121 // the loop (not including non-recipe values such as arguments and
122 // constants).
123 SmallSetVector<VPValue *, 8> LoopInvariants;
124 if (!Plan.getVectorTripCount().user_empty())
125 LoopInvariants.insert(&Plan.getVectorTripCount());
126
127 // We scan the loop in a topological order in order and assign a number to
128 // each recipe. We use RPO to ensure that defs are met before their users. We
129 // assume that each recipe that has in-loop users starts an interval. We
130 // record every time that an in-loop value is used, so we have a list of the
131 // first occurences of each recipe and last occurrence of each VPValue.
132 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
134 LoopRegion);
136 if (!VPBB->getParent())
137 break;
138 for (VPRecipeBase &R : *VPBB) {
139 Idx2Recipe.push_back(&R);
140
141 // Save the end location of each USE.
142 for (VPValue *U : R.operands()) {
143 if (isa<VPRecipeValue>(U)) {
144 // Overwrite previous end points.
145 EndPoint[U] = Idx2Recipe.size();
146 Ends.insert(U);
147 } else if (auto *IRV = dyn_cast<VPIRValue>(U)) {
148 // Ignore non-recipe values such as arguments, constants, etc.
149 // FIXME: Might need some motivation why these values are ignored. If
150 // for example an argument is used inside the loop it will increase
151 // the register pressure (so shouldn't we add it to LoopInvariants).
152 if (!isa<Instruction>(IRV->getValue()))
153 continue;
154 // This recipe is outside the loop, record it and continue.
155 LoopInvariants.insert(U);
156 }
157 // Other types of VPValue are currently not tracked.
158 }
159 }
160 if (VPBB == LoopRegion->getExiting()) {
161 // VPWidenIntOrFpInductionRecipes are used implicitly at the end of the
162 // exiting block, where their increment will get materialized eventually.
163 for (auto &R : LoopRegion->getEntryBasicBlock()->phis()) {
164 if (auto *WideIV = dyn_cast<VPWidenIntOrFpInductionRecipe>(&R)) {
165 EndPoint[WideIV] = Idx2Recipe.size();
166 Ends.insert(WideIV);
167 }
168 }
169 }
170 }
171
172 // Saves the list of intervals that end with the index in 'key'.
173 using VPValueList = SmallVector<VPValue *, 2>;
175
176 // Next, we transpose the EndPoints into a multi map that holds the list of
177 // intervals that *end* at a specific location.
178 for (auto &Interval : EndPoint)
179 TransposeEnds[Interval.second].push_back(Interval.first);
180
181 SmallPtrSet<VPValue *, 8> OpenIntervals;
184
185 LLVM_DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
186
187 const auto &TTICapture = TTI;
188 auto GetRegUsage = [&TTICapture](Type *Ty, ElementCount VF) -> unsigned {
189 if (Ty->isTokenTy() || !VectorType::isValidElementType(Ty) ||
190 (VF.isScalable() &&
191 !TTICapture.isElementTypeLegalForScalableVector(Ty)))
192 return 0;
193 return TTICapture.getRegUsageForType(VectorType::get(Ty, VF));
194 };
195
196 VPValue *CanIV = LoopRegion->getCanonicalIV();
197 // Note: canonical IVs are retained even if they have no users.
198 if (!CanIV->user_empty())
199 OpenIntervals.insert(CanIV);
200
201 // We scan the instructions linearly and record each time that a new interval
202 // starts, by placing it in a set. If we find this value in TransposEnds then
203 // we remove it from the set. The max register usage is the maximum register
204 // usage of the recipes of the set.
205 for (unsigned int Idx = 0, Sz = Idx2Recipe.size(); Idx < Sz; ++Idx) {
206 VPRecipeBase *R = Idx2Recipe[Idx];
207
208 // Remove all of the VPValues that end at this location.
209 VPValueList &List = TransposeEnds[Idx];
210 for (VPValue *ToRemove : List)
211 OpenIntervals.erase(ToRemove);
212
213 // Ignore recipes that are never used within the loop and do not have side
214 // effects.
215 if (none_of(R->definedValues(),
216 [&Ends](VPValue *Def) { return Ends.count(Def); }) &&
217 !R->mayHaveSideEffects())
218 continue;
219
220 // Skip recipes for ignored values.
221 // TODO: Should mark recipes for ephemeral values that cannot be removed
222 // explictly in VPlan.
223 if (isa<VPSingleDefRecipe>(R) &&
224 ValuesToIgnore.contains(
225 cast<VPSingleDefRecipe>(R)->getUnderlyingValue()))
226 continue;
227
228 // For each VF find the maximum usage of registers.
229 for (unsigned J = 0, E = VFs.size(); J < E; ++J) {
230 // Count the number of registers used, per register class, given all open
231 // intervals.
232 // Note that elements in this SmallMapVector will be default constructed
233 // as 0. So we can use "RegUsage[ClassID] += n" in the code below even if
234 // there is no previous entry for ClassID.
236
237 for (auto *VPV : OpenIntervals) {
238 // Skip artificial values or values that weren't present in the original
239 // loop.
240 // TODO: Remove skipping values that weren't present in the original
241 // loop after removing the legacy
242 // LoopVectorizationCostModel::calculateRegisterUsage
244 VPBranchOnMaskRecipe>(VPV) ||
246 continue;
247
248 if (VFs[J].isScalar() || VPV == CanIV ||
253 (cast<VPReductionPHIRecipe>(VPV))->isInLoop())) {
254 unsigned ClassID =
255 TTI.getRegisterClassForType(false, VPV->getScalarType());
256 // FIXME: The target might use more than one register for the type
257 // even in the scalar case.
258 RegUsage[ClassID] += 1;
259 } else {
260 // The output from scaled phis and scaled reductions actually has
261 // fewer lanes than the VF.
262 unsigned ScaleFactor =
263 vputils::getVFScaleFactor(VPV->getDefiningRecipe());
264 ElementCount VF = VFs[J];
265 if (ScaleFactor > 1) {
266 VF = VFs[J].divideCoefficientBy(ScaleFactor);
267 LLVM_DEBUG(dbgs() << "LV(REG): Scaled down VF from " << VFs[J]
268 << " to " << VF << " for " << *R << "\n";);
269 }
270
271 Type *ScalarTy = VPV->getScalarType();
272 unsigned ClassID = TTI.getRegisterClassForType(true, ScalarTy);
273 RegUsage[ClassID] += GetRegUsage(ScalarTy, VF);
274 }
275 }
276
277 for (const auto &Pair : RegUsage) {
278 auto &Entry = MaxUsages[J][Pair.first];
279 Entry = std::max(Entry, Pair.second);
280 }
281 }
282
283 LLVM_DEBUG(dbgs() << "LV(REG): At #" << Idx << " Interval # "
284 << OpenIntervals.size() << '\n');
285
286 // Add used VPValues defined by the current recipe to the list of open
287 // intervals.
288 for (VPValue *DefV : R->definedValues())
289 if (Ends.contains(DefV))
290 OpenIntervals.insert(DefV);
291 }
292
293 // We also search for instructions that are defined outside the loop, but are
294 // used inside the loop. We need this number separately from the max-interval
295 // usage number because when we unroll, loop-invariant values do not take
296 // more register.
298 for (unsigned Idx = 0, End = VFs.size(); Idx < End; ++Idx) {
299 // Note that elements in this SmallMapVector will be default constructed
300 // as 0. So we can use "Invariant[ClassID] += n" in the code below even if
301 // there is no previous entry for ClassID.
303
304 for (auto *In : LoopInvariants) {
305 // FIXME: The target might use more than one register for the type
306 // even in the scalar case.
307 bool IsScalar = vputils::onlyScalarValuesUsed(In);
308
309 ElementCount VF = IsScalar ? ElementCount::getFixed(1) : VFs[Idx];
310 unsigned ClassID =
311 TTI.getRegisterClassForType(VF.isVector(), In->getScalarType());
312 Invariant[ClassID] += GetRegUsage(In->getScalarType(), VF);
313 }
314
315 LLVM_DEBUG({
316 dbgs() << "LV(REG): VF = " << VFs[Idx] << '\n';
317 dbgs() << "LV(REG): Found max usage: " << MaxUsages[Idx].size()
318 << " item\n";
319 for (const auto &pair : MaxUsages[Idx]) {
320 dbgs() << "LV(REG): RegisterClass: "
321 << TTI.getRegisterClassName(pair.first) << ", " << pair.second
322 << " registers\n";
323 }
324 dbgs() << "LV(REG): Found invariant usage: " << Invariant.size()
325 << " item\n";
326 for (const auto &pair : Invariant) {
327 dbgs() << "LV(REG): RegisterClass: "
328 << TTI.getRegisterClassName(pair.first) << ", " << pair.second
329 << " registers\n";
330 }
331 });
332
333 RU.LoopInvariantRegs = Invariant;
334 RU.MaxLocalUsers = MaxUsages[Idx];
335 RUs[Idx] = RU;
336 }
337
338 return RUs;
339}
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:324
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:309
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
Definition SmallPtrSet.h:99
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
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:368
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
Definition VPlan.h:4380
iterator_range< iterator > phis()
Returns an iterator range over the PHI-like recipes in the block.
Definition VPlan.h:4468
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
Definition VPlan.h:94
const VPBasicBlock * getEntryBasicBlock() const
Definition VPlan.cpp:216
static auto blocksOnly(T &&Range)
Return an iterator range over Range which only includes BlockTy blocks.
Definition VPlanUtils.h:384
A recipe for generating conditional branches on the bits of a mask.
Definition VPlan.h:3496
A recipe for generating the phi node tracking the current scalar iteration index.
Definition VPlan.h:4073
A recipe for converting Current into Start + Current * Step.
Definition VPlan.h:4174
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:4605
const VPBlockBase * getEntry() const
Definition VPlan.h:4649
VPRegionValue * getCanonicalIV()
Return the canonical induction variable of the region, null for replicating regions.
Definition VPlan.h:4725
const VPBlockBase * getExiting() const
Definition VPlan.h:4661
VPReplicateRecipe replicates a given instruction producing multiple scalar copies of the original sca...
Definition VPlan.h:3388
A recipe for handling phi nodes of integer and floating-point inductions, producing their scalar valu...
Definition VPlan.h:4235
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:2267
A recipe to compute the pointers for widened memory accesses of SourceElementTy, with the Stride expr...
Definition VPlan.h:2349
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4792
VPSymbolicValue & getVectorTripCount()
The vector trip count.
Definition VPlan.h:4983
LLVM_ABI_FOR_TEST VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
Definition VPlan.cpp:1077
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
SmallVector< VPRegisterUsage, 8 > calculateRegisterUsageForPlan(VPlan &Plan, ArrayRef< ElementCount > VFs, const TargetTransformInfo &TTI, const SmallPtrSetImpl< const Value * > &ValuesToIgnore)
Estimate the register usage for Plan and vectorization factors in VFs by calculating the highest numb...
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:1746
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:1753
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.