1//===- SLPUtils.h - SLP Vectorizer free utility helpers --------*- 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// Internal header used by SLPVectorizer.cpp. It declares free helper
10// functions that do not depend on BoUpSLP, InstructionsState, or any other
11// SLP-private type. Splitting them out keeps SLPVectorizer.cpp focused on
12// the build / legality / cost / codegen pipeline.
13//
14//===----------------------------------------------------------------------===//
15
16#ifndef LLVM_LIB_TRANSFORMS_VECTORIZE_SLPVECTORIZER_SLPUTILS_H
17#define LLVM_LIB_TRANSFORMS_VECTORIZE_SLPVECTORIZER_SLPUTILS_H
18
19#include "llvm/ADT/APInt.h"
20#include "llvm/ADT/ArrayRef.h"
21#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/STLFunctionalExtras.h"
23#include "llvm/ADT/SmallBitVector.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/Analysis/MemoryLocation.h"
26#include "llvm/Analysis/TargetTransformInfo.h"
27#include "llvm/IR/Intrinsics.h"
28
29#include <cstdint>
30#include <limits>
31#include <optional>
32#include <string>
33#include <tuple>
34
35namespace llvm {
36class AssumptionCache;
37class Constant;
38class DataLayout;
39class DebugLoc;
40class InsertElementInst;
41class Instruction;
42class IRBuilderBase;
43class LoadInst;
44class Loop;
45class PHINode;
46class ScalarEvolution;
47class TargetLibraryInfo;
48class Type;
49class Value;
50} // namespace llvm
51
52namespace llvm::slpvectorizer {
53
54class SLPAnalysisCache;
55
56/// Limit of the number of uses for potentially transformed instructions/values,
57/// used in checks to avoid compile-time explode.
58inline constexpr int UsesLimit = 64;
59
60/// \returns True if the value is a constant (but not globals/constant
61/// expressions).
62bool isConstant(Value *V);
63
64/// \returns True if \p V is the integer identity constant for binary \p Opcode
65/// (e.g. 0 for add, 1 for mul, all-ones for and). Floating-point identities are
66/// excluded: a ConstantInt never matches the ConstantFP getBinOpIdentity()
67/// returns for FAdd/FMul, whose identity fast-math may break anyway.
68bool isBinOpIdentityConstant(const Value *V, unsigned Opcode);
69
70/// \returns True if \p V is an integer binary operator, which gives an undef
71/// result for the undef operands: neither a shift nor a division.
72bool isUndefTolerantBinOp(const Value *V);
73
74/// \returns the load operand of the undef tolerant binary operator \p V, if
75/// any.
76const LoadInst *getLoadOfUndefTolerantBinOp(const Value *V);
77
78/// \returns the opcode of the combines emitted for a reassociated node:
79/// subtract chains regroup their positive and negative operand columns with
80/// plain adds.
81unsigned getReassocCombineOpcode(unsigned Opcode);
82
83/// \returns True if \p I can be a link of a flattenable binary chain:
84/// subtracts flatten as adds of a negated leaf, float subtracts need reassoc
85/// to allow the regrouping.
86bool isReassocChainLink(const Instruction *I);
87
88/// Checks if \p V is one of vector-like instructions, i.e. undef,
89/// insertelement/extractelement with constant indices for fixed vector type
90/// or extractvalue instruction.
91bool isVectorLikeInstWithConstOps(Value *V);
92
93/// \returns the number of elements for Ty.
94unsigned getNumElements(Type *Ty);
95
96/// Returns power-of-2 number of elements in a single register (part), given
97/// the total number of elements \p Size and number of registers (parts) \p
98/// NumParts.
99unsigned getPartNumElems(unsigned Size, unsigned NumParts);
100
101/// Returns correct remaining number of elements, considering total amount
102/// \p Size, (power-of-2 number) of elements in a single register
103/// \p PartNumElems and current register (part) \p Part.
104unsigned getNumElems(unsigned Size, unsigned PartNumElems, unsigned Part);
105
106#if !defined(NDEBUG)
107/// Print a short descriptor of the instruction bundle suitable for debug
108/// output.
109std::string shortBundleName(ArrayRef<Value *> VL, int Idx = -1);
110#endif
111
112/// \returns True if all of the instructions in \p VL are in the same block.
113bool allSameBlock(ArrayRef<Value *> VL);
114
115/// \returns True if all of the values in \p VL are constants (but not
116/// globals/constant expressions).
117bool allConstant(ArrayRef<Value *> VL);
118
119/// \returns True if all of the values in \p VL are identical or some of them
120/// are UndefValue.
121bool isSplat(ArrayRef<Value *> VL);
122
123/// Checks if \p LHS and \p RHS are the same intrinsic, or one is llvm.fma
124/// and the other is llvm.fmuladd, since both lower to the same fused
125/// vector operation.
126/// \returns the intrinsic ID to use for the pair (\p RHS if the IDs match,
127/// otherwise Intrinsic::fma), or Intrinsic::not_intrinsic if they are not
128/// equivalent.
129Intrinsic::ID isEquivalentIntrinsicID(Intrinsic::ID LHS, Intrinsic::ID RHS);
130
131/// \returns True if \p I is commutative, handles CmpInst and BinaryOperator.
132/// For BinaryOperator, it also checks if \p ValWithUses is used in specific
133/// patterns that make it effectively commutative (like equality comparisons
134/// with zero).
135/// In most cases, users should not call this function directly (since \p I and
136/// \p ValWithUses are the same). However, when analyzing interchangeable
137/// instructions, we need to use the converted opcode along with the original
138/// uses.
139/// \param I The instruction to check for commutativity
140/// \param ValWithUses The value whose uses are analyzed for special
141/// patterns
142bool isCommutative(const Instruction *I, const Value *ValWithUses,
143 bool IsCopyable = false);
144
145/// This is a helper function to check whether \p I is commutative.
146/// This is a convenience wrapper that calls the two-parameter version of
147/// isCommutative with the same instruction for both parameters. This is
148/// the common case where the instruction being checked for commutativity
149/// is the same as the instruction whose uses are analyzed for special
150/// patterns (see the two-parameter version above for details).
151/// \param I The instruction to check for commutativity
152/// \returns true if the instruction is commutative, false otherwise
153bool isCommutative(const Instruction *I);
154
155/// Checks if the operand is commutative. In commutative operations, not all
156/// operands might commutable, e.g. for fmuladd only 2 first operands are
157/// commutable.
158bool isCommutableOperand(const Instruction *I, Value *ValWithUses, unsigned Op,
159 bool IsCopyable = false);
160
161/// \returns number of operands of \p I, considering commutativity. Returns 2
162/// for commutative intrinsics.
163/// \param I The instruction to check for commutativity
164unsigned getNumberOfPotentiallyCommutativeOps(Instruction *I);
165
166/// \returns inserting or extracting index of InsertElement, ExtractElement
167/// or InsertValue instruction, using \p Offset as base offset for index.
168/// \returns std::nullopt if the index is not an immediate.
169std::optional<unsigned> getElementIndex(const Value *Inst, unsigned Offset = 0);
170
171/// \returns True if all of the values in \p VL use the same opcode.
172/// For comparison instructions, also checks if predicates match.
173/// PoisonValues are considered matching. Interchangeable instructions are
174/// not considered.
175bool allSameOpcode(ArrayRef<Value *> VL);
176
177/// \returns Optional element Idx for Extract{Value,Element} instructions.
178std::optional<unsigned> getExtractIndex(const Instruction *E);
179
180/// Compute the inverse permutation \p Mask of \p Indices.
181void inversePermutation(ArrayRef<unsigned> Indices, SmallVectorImpl<int> &Mask);
182
183/// Reorders the list of scalars in accordance with the given \p Mask.
184void reorderScalars(SmallVectorImpl<Value *> &Scalars, ArrayRef<int> Mask);
185
186/// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
187/// contains original mask for the scalars reused in the node. Procedure
188/// transform this mask in accordance with the given \p Mask.
189void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask);
190
191/// Reorders the given \p Order according to the given \p Mask. \p Order - is
192/// the original order of the scalars. Procedure transforms the provided order
193/// in accordance with the given \p Mask. If the resulting \p Order is just an
194/// identity order, \p Order is cleared.
195void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask,
196 bool BottomOrder = false);
197
198/// Check if \p Order represents reverse order.
199bool isReverseOrder(ArrayRef<unsigned> Order);
200
201/// Checks if the given mask is a "clustered" mask with the same clusters of
202/// size \p Sz, which are not identity submasks.
203bool isRepeatedNonIdentityClusteredMask(ArrayRef<int> Mask, unsigned Sz);
204
205/// Fills unset elements of \p Order (marked with the sentinel value equal to
206/// the order size) with the corresponding elements of \p SecondaryOrder,
207/// skipping already used indices, or with the identity order if
208/// \p SecondaryOrder is empty.
209void combineOrders(MutableArrayRef<unsigned> Order,
210 ArrayRef<unsigned> SecondaryOrder);
211
212/// \returns True iff every value in \p VL has the same Type as the first.
213bool allSameType(ArrayRef<Value *> VL);
214
215/// Checks if the provided value does not require scheduling. It does not
216/// require scheduling if this is not an instruction or it is an instruction
217/// that does not read/write memory and all operands are either not
218/// instructions or phi nodes or instructions from different blocks.
219bool areAllOperandsNonInsts(Value *V);
220
221/// Checks if the provided value does not require scheduling. It does not
222/// require scheduling if this is not an instruction or it is an instruction
223/// that does not read/write memory and all users are phi nodes or
224/// instructions from different blocks.
225bool isUsedOutsideBlock(Value *V);
226
227/// Checks if the specified value does not require scheduling. It does not
228/// require scheduling if all operands and all users do not need to be
229/// scheduled in the current basic block.
230bool doesNotNeedToBeScheduled(Value *V);
231
232/// Checks if the specified array of instructions does not require scheduling.
233/// It is so if all either instructions have operands that do not require
234/// scheduling or their users do not require scheduling since they are phis or
235/// in other basic blocks.
236bool doesNotNeedToSchedule(ArrayRef<Value *> VL);
237
238/// \returns inserting or extracting index of InsertElement / ExtractElement
239/// instruction, using \p Offset as base offset for index. Only instantiated
240/// for InsertElementInst and ExtractElementInst (see SLPUtils.cpp).
241template <typename T>
242std::optional<unsigned> getInsertExtractIndex(const Value *Inst,
243 unsigned Offset);
244
245void transformScalarShuffleIndiciesToVector(unsigned VecTyNumElements,
246 SmallVectorImpl<int> &Mask);
247
248/// \returns the number of groups of shufflevector
249/// A group has the following features
250/// 1. All of value in a group are shufflevector.
251/// 2. The mask of all shufflevector is isExtractSubvectorMask.
252/// 3. The mask of all shufflevector uses all of the elements of the source.
253/// e.g., it is 1 group (%0)
254/// %1 = shufflevector <16 x i8> %0, <16 x i8> poison,
255/// <8 x i32> <i32 0, i32 1, i32 2, i32 3, i32 4, i32 5, i32 6, i32 7>
256/// %2 = shufflevector <16 x i8> %0, <16 x i8> poison,
257/// <8 x i32> <i32 8, i32 9, i32 10, i32 11, i32 12, i32 13, i32 14, i32 15>
258/// it is 2 groups (%3 and %4)
259/// %5 = shufflevector <8 x i16> %3, <8 x i16> poison,
260/// <4 x i32> <i32 0, i32 1, i32 2, i32 3>
261/// %6 = shufflevector <8 x i16> %3, <8 x i16> poison,
262/// <4 x i32> <i32 4, i32 5, i32 6, i32 7>
263/// %7 = shufflevector <8 x i16> %4, <8 x i16> poison,
264/// <4 x i32> <i32 0, i32 1, i32 2, i32 3>
265/// %8 = shufflevector <8 x i16> %4, <8 x i16> poison,
266/// <4 x i32> <i32 4, i32 5, i32 6, i32 7>
267/// it is 0 group
268/// %12 = shufflevector <8 x i16> %10, <8 x i16> poison,
269/// <4 x i32> <i32 0, i32 1, i32 2, i32 3>
270/// %13 = shufflevector <8 x i16> %11, <8 x i16> poison,
271/// <4 x i32> <i32 0, i32 1, i32 2, i32 3>
272unsigned getShufflevectorNumGroups(ArrayRef<Value *> VL);
273
274/// \returns a shufflevector mask which is used to vectorize shufflevectors
275/// e.g.,
276/// %5 = shufflevector <8 x i16> %3, <8 x i16> poison,
277/// <4 x i32> <i32 0, i32 1, i32 2, i32 3>
278/// %6 = shufflevector <8 x i16> %3, <8 x i16> poison,
279/// <4 x i32> <i32 4, i32 5, i32 6, i32 7>
280/// %7 = shufflevector <8 x i16> %4, <8 x i16> poison,
281/// <4 x i32> <i32 0, i32 1, i32 2, i32 3>
282/// %8 = shufflevector <8 x i16> %4, <8 x i16> poison,
283/// <4 x i32> <i32 4, i32 5, i32 6, i32 7>
284/// the result is
285/// <0, 1, 2, 3, 12, 13, 14, 15, 16, 17, 18, 19, 28, 29, 30, 31>
286SmallVector<int> calculateShufflevectorMask(ArrayRef<Value *> VL);
287
288/// Checks if the values in \p VL can be represented as a shuffle of at most
289/// two vector operands (extractelement lanes). On success, \p Mask is the
290/// equivalent shuffle mask.
291std::optional<TargetTransformInfo::ShuffleKind>
292isFixedVectorShuffle(ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask,
293 AssumptionCache *AC, SLPAnalysisCache &Cache);
294
295/// Creates subvector insert. Generates shuffle using \p Generator or
296/// using default shuffle.
297Value *createInsertVector(
298 IRBuilderBase &Builder, Value *Vec, Value *V, unsigned Index,
299 function_ref<Value *(Value *, Value *, ArrayRef<int>)> Generator = {});
300
301/// Generates subvector extract.
302Value *createExtractVector(IRBuilderBase &Builder, Value *Vec,
303 unsigned SubVecVF, unsigned Index);
304
305/// Specifies the way the mask should be analyzed for undefs/poisonous elements
306/// in the shuffle mask.
307enum class UseMask {
308 FirstArg, ///< The mask is expected to be for permutation of 1-2 vectors,
309 ///< check for the mask elements for the first argument (mask
310 ///< indices are in range [0:VF)).
311 SecondArg, ///< The mask is expected to be for permutation of 2 vectors, check
312 ///< for the mask elements for the second argument (mask indices
313 ///< are in range [VF:2*VF))
314 UndefsAsMask ///< Consider undef mask elements (-1) as placeholders for
315 ///< future shuffle elements and mark them as ones as being used
316 ///< in future. Non-undef elements are considered as unused since
317 ///< they're already marked as used in the mask.
318};
319
320/// Prepares a use bitset for the given mask either for the first argument or
321/// for the second.
322SmallBitVector buildUseMask(int VF, ArrayRef<int> Mask, UseMask MaskArg);
323
324/// Checks if the given value is actually an undefined constant vector.
325/// Also, if the \p UseMask is not empty, tries to check if the non-masked
326/// elements actually mask the insertelement buildvector, if any.
327template <bool IsPoisonOnly = false>
328SmallBitVector isUndefVector(const Value *V,
329 const SmallBitVector &UseMask = {});
330
331/// \returns True if in-tree use also needs extract. This refers to
332/// possible scalar operand in vectorized instruction.
333bool doesInTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
334 TargetLibraryInfo *TLI,
335 const TargetTransformInfo *TTI);
336
337/// \returns the AA location that is being access by the instruction.
338MemoryLocation getLocation(Instruction *I);
339
340/// \returns True if the instruction is not a volatile or atomic load/store.
341bool isSimple(Instruction *I);
342
343/// Checks if the loads with scalar type \p ScalarTy and pointer operands
344/// \p PointerOps are each (optionally via a constant-offset GEP) a
345/// `select Cond, A, B` picking between the same two base pointers A/B on
346/// every lane - the shape a fully unrolled `x = cond ? A[i] : B[i]` takes. On
347/// success \p TrueBase / \p FalseBase are the candidate bases and
348/// \p Conditions holds each lane's `select` condition, used to build the
349/// blend mask. Lane \p Idx must be at `Base + Idx * sizeof(ScalarTy)`; only
350/// dense, natural lane order starting at the base is recognized (reordered or
351/// partial groups fall back to Gather/Scatter).
352bool isSelectedBaseLoad(Type *ScalarTy, ArrayRef<Value *> PointerOps,
353 const DataLayout &DL, Value *&TrueBase,
354 Value *&FalseBase,
355 SmallVectorImpl<Value *> &Conditions);
356
357/// Returns the alignment of the shared base pointer of a blended load for
358/// the loads \p VL.
359Align computeBlendedLoadBaseAlignment(ArrayRef<Value *> VL,
360 const DataLayout &DL);
361
362/// Returns the common type for the indices of the single-index GEP lanes of
363/// a GEP node with the main op \p VL0, or nullptr if no such type exists.
364/// \p IsGEPLane tells which lanes of \p VL are matching GEPs, whose index is
365/// used as is; all other lanes (copyable, poison, non-GEP pointers) are
366/// modeled as gep V, 0 and just take a zero index of the common type.
367/// The common type is the index type of \p VL0 if all matching lanes share
368/// it. Otherwise the constant indices are cast: to the pointer index type if
369/// there are no non-constant indices (or the index type of \p VL0 already is
370/// the pointer index type), or to the index type of \p VL0 if all the
371/// non-constant indices have that type and all the constants are
372/// representable in it (GEP indices are sign-extended to the pointer index
373/// width, so the value must fit as a signed number). A non-constant index of
374/// a different type cannot be cast without a new instruction, so no common
375/// type exists.
376Type *getCommonGEPIndexType(ArrayRef<Value *> VL, Instruction *VL0,
377 function_ref<bool(Value *)> IsGEPLane,
378 const DataLayout &DL);
379
380/// Checks if the pointers \p PointerOps of the gathered loads, which are not
381/// compatible in the usual sense (some of them are constant-offset pointers,
382/// some have runtime indices), still form a cheap address vector as a
383/// copyable GEP node: a splat of the common base and a vector of indices.
384/// The constant-offset lanes are the base itself or single-index GEPs of the
385/// base with a constant index (modeled as gep V, 0 or as matching lanes with
386/// constant indices), the other lanes are single-index GEPs of the base of
387/// the same shape, whose indices are affine in a single runtime value (the
388/// stride): optionally cast (all with the same cast opcode) values, each of
389/// which is the stride itself or a binary operation of the stride and a
390/// constant, like b[i * S] or b[S + i]. Duplicate lanes are not accepted:
391/// the node would be a shuffled non-full vector, gathering the loads is
392/// cheaper then.
393bool isCopyableGEPAddressVector(ArrayRef<Value *> PointerOps);
394
395/// Shuffles \p Mask in accordance with the given \p SubMask.
396/// \param ExtendingManyInputs Supports reshuffling of the mask with not only
397/// one but two input vectors.
398void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask,
399 bool ExtendingManyInputs = false);
400
401/// Order may have elements assigned special value (size) which is out of
402/// bounds. Such indices only appear on places which correspond to undef values
403/// (see canReuseExtract for details) and used in order to avoid undef values
404/// have effect on operands ordering.
405/// The first loop below simply finds all unused indices and then the next loop
406/// nest assigns these indices for undef values positions.
407/// As an example below Order has two undef positions and they have assigned
408/// values 3 and 7 respectively:
409/// before: 6 9 5 4 9 2 1 0
410/// after: 6 3 5 4 7 2 1 0
411void fixupOrderingIndices(MutableArrayRef<unsigned> Order);
412
413/// \returns a bitset for selecting opcodes. false for Opcode0 and true for
414/// Opcode1.
415SmallBitVector getAltInstrMask(ArrayRef<Value *> VL, Type *ScalarTy,
416 unsigned Opcode0, unsigned Opcode1);
417
418/// Replicates the given \p Val \p VF times.
419SmallVector<Constant *> replicateMask(ArrayRef<Constant *> Val, unsigned VF);
420
421/// \returns the masked division/remainder intrinsic corresponding to \p
422/// Opcode. Disabled lanes of these intrinsics are poison rather than UB,
423/// unlike the plain opcode.
424Intrinsic::ID getMaskedDivRemIntrinsic(unsigned Opcode);
425
426/// Returns true if \p I forms a vectorizable bundle on its own and its single
427/// user does not tear the vector apart. Loads and addresses are excluded: the
428/// tree is built without the users, so it does not pay off the extracts. A
429/// cast, feeding a multi-used cast, is excluded for the same reason, such a
430/// user stays scalar. The fp-to-int conversions move the result to the other
431/// register domain, so the extracts are paid on top of the repacking. The
432/// values, feeding the inserts, are vectorized together with them by the
433/// dedicated attempt.
434bool isOnceUsedSeed(const Instruction *I);
435
436/// If \p V is a single-use fpext of a single-use fptrunc forming a round-trip
437/// back to the type of \p V, returns the fptrunc; the round-trip source is its
438/// operand, always an instruction of the same type as \p V. If
439/// \p MustBeElidable, matches only when the intermediate rounding may be
440/// removed: both casts must allow contraction and the widening cast cannot
441/// produce nan/inf.
442Instruction *lookThroughCastRoundTrip(Value *V, bool MustBeElidable);
443
444/// Narrow reduction leaf: the value, the shift applied after widening and
445/// the mask applied in the narrow type before widening, clearing the bits
446/// the absorbed narrow shls shift out and applying the absorbed narrow
447/// and-masks. Lossless narrow shls contribute their known-zero bits to the
448/// mask so matching lanes can form a splat. All-ones mask means nothing
449/// was absorbed and no 'and' is needed.
450struct NarrowedLeafInfo {
451 NarrowedLeafInfo(Value *V, unsigned Shift, APInt Mask)
452 : V(V), Shift(Shift), Mask(std::move(Mask)) {}
453
454 Value *V = nullptr;
455 unsigned Shift = 0;
456 APInt Mask;
457 /// Set to false, if the or chain is not disjoint
458 bool Disjoint = true;
459};
460
461/// Recursively collects the narrow leaves of the widened reduction value
462/// \p V. zext is looked through directly, same-kind binops per operand,
463/// shl of a zext - only if no bits are shifted out in the current type,
464/// shls in narrower types fold into the shift and ands with a constant into
465/// the mask applied in the narrow type. Also collects the looked-through
466/// instructions into \p ChainInsts.
467void collectNarrowedLeaves(Value *V, unsigned RdxOpcode, unsigned WideBW,
468 unsigned MaxDepth,
469 SmallVectorImpl<NarrowedLeafInfo> &Leaves,
470 SmallVectorImpl<Instruction *> &ChainInsts);
471
472TargetTransformInfo::TargetCostKind getSLPCostKind(const Function *F);
473
474/// Returns a saturating unsigned upper bound of the scalar V. The numeric
475/// bound keeps precision on arithmetic carries, where bit-wise analysis
476/// loses it.
477APInt getScalarMaxValue(const Value *V, unsigned Depth = 0);
478
479/// Checks if the values in \p VL are zero-extended sub-fields of the same
480/// wider integer scalar. Returns the source scalar, the field width and the
481/// field permutation mask. The extraction dual of the lane-packing layout.
482/// The field-to-lane mapping of the bitcast to the field vector is defined
483/// for little-endian targets only.
484std::optional<std::tuple<Value *, unsigned, SmallVector<int>>>
485matchGatheredExtractedFields(ArrayRef<Value *> VL, const DataLayout &DL);
486
487/// Description of a bitfield packing of vector lanes into a scalar value:
488/// every lane contributes a disjoint contiguous byte field of the result.
489struct BitPackInfo {
490 static constexpr unsigned NoLane = std::numeric_limits<unsigned>::max();
491 unsigned FieldWidth = 0;
492 /// Lane covering each field, NoLane if the field is always zero.
493 SmallVector<unsigned, 8> LaneOfField;
494 /// Per-lane right-shift amounts bringing the field content to the low bits.
495 SmallVector<uint64_t, 8> LShrAmts;
496
497 /// True if any lane needs a right shift to align its field content.
498 bool needsShift() const {
499 return any_of(Range: LShrAmts, P: [](uint64_t A) { return A != 0; });
500 }
501};
502
503/// Computes the bitfield packing layout from the per-lane possibly set bits
504/// of the source values, the per-lane left-shift amounts and the per-lane
505/// masks (all-ones for unmasked lanes).
506std::optional<BitPackInfo> computeBitPackInfo(unsigned BitWidth,
507 ArrayRef<APInt> PossibleBits,
508 ArrayRef<uint64_t> ShlAmts,
509 ArrayRef<APInt> Masks);
510
511/// Returns the byte shuffle mask packing the per-lane fields of the shifted
512/// lanes (BytesPerLane bytes each) into the packed scalar of NumBytes bytes.
513SmallVector<int> getBitPackMask(const BitPackInfo &Info, unsigned NumBytes,
514 unsigned NumElts, unsigned BytesPerLane);
515
516/// Builds the bitfield packing of X into \p ResultTy per the layout and the
517/// shift width. \p NumInsts returns the number of emitted instructions.
518Value *buildBitPack(IRBuilderBase &Builder, Value *X, const BitPackInfo &Info,
519 Type *ResultTy, unsigned ShiftWidth, unsigned &NumInsts);
520
521/// The debug values of the erased \p From are kept on its replacement \p To.
522/// A record placed before \p To is cloned right after it, while the original
523/// one is killed together with the scalar, so the variable is undefined up to
524/// \p To. The clone is skipped if it would pass a record of the same variable,
525/// otherwise the variable would show a stale value.
526void redirectDbgValues(Instruction &From, Value &To);
527/// \returns true if \p IE1 is inserted before \p IE2 in their build-vector
528/// chain. Both must have constant insert indices and belong to one chain.
529bool isFirstInsertElement(const InsertElementInst *IE1,
530 const InsertElementInst *IE2);
531
532/// \returns the debug location of \p PN, or an unknown location if it has
533/// none.
534DebugLoc getDebugLocFromPHI(const PHINode &PN);
535
536/// \returns the number of elements of the homogeneous aggregate built by
537/// \p InsertInst (insertelement or insertvalue), or std::nullopt if it is not
538/// a homogeneous aggregate.
539std::optional<unsigned> getAggregateSize(Instruction *InsertInst);
540
541/// \returns the innermost loop starting from \p L for which at least one value
542/// in \p VL is not loop-invariant.
543const Loop *findInnermostNonInvariantLoop(const Loop *L, ArrayRef<Value *> VL);
544
545/// \returns an estimated trip count for \p L, bounded by the loop-aware budget
546/// \p LoopAwareTripCount. Returns 1 when the budget is 0.
547unsigned getLoopTripCount(const Loop *L, ScalarEvolution &SE,
548 unsigned LoopAwareTripCount);
549
550} // namespace llvm::slpvectorizer
551
552#endif // LLVM_LIB_TRANSFORMS_VECTORIZE_SLPVECTORIZER_SLPUTILS_H
553