1 //===- llvm/Analysis/VectorUtils.h - Vector utilities -----------*- 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 // This file defines some vectorizer utilities.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #ifndef LLVM_ANALYSIS_VECTORUTILS_H
14 #define LLVM_ANALYSIS_VECTORUTILS_H
15
16 #include "llvm/ADT/MapVector.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/Analysis/LoopAccessAnalysis.h"
19 #include "llvm/Support/CheckedArithmetic.h"
20
21 namespace llvm {
22 class TargetLibraryInfo;
23
24 /// Describes the type of Parameters
25 enum class VFParamKind {
26 Vector, // No semantic information.
27 OMP_Linear, // declare simd linear(i)
28 OMP_LinearRef, // declare simd linear(ref(i))
29 OMP_LinearVal, // declare simd linear(val(i))
30 OMP_LinearUVal, // declare simd linear(uval(i))
31 OMP_LinearPos, // declare simd linear(i:c) uniform(c)
32 OMP_LinearValPos, // declare simd linear(val(i:c)) uniform(c)
33 OMP_LinearRefPos, // declare simd linear(ref(i:c)) uniform(c)
34 OMP_LinearUValPos, // declare simd linear(uval(i:c)) uniform(c)
35 OMP_Uniform, // declare simd uniform(i)
36 GlobalPredicate, // Global logical predicate that acts on all lanes
37 // of the input and output mask concurrently. For
38 // example, it is implied by the `M` token in the
39 // Vector Function ABI mangled name.
40 Unknown
41 };
42
43 /// Describes the type of Instruction Set Architecture
44 enum class VFISAKind {
45 AdvancedSIMD, // AArch64 Advanced SIMD (NEON)
46 SVE, // AArch64 Scalable Vector Extension
47 SSE, // x86 SSE
48 AVX, // x86 AVX
49 AVX2, // x86 AVX2
50 AVX512, // x86 AVX512
51 LLVM, // LLVM internal ISA for functions that are not
52 // attached to an existing ABI via name mangling.
53 Unknown // Unknown ISA
54 };
55
56 /// Encapsulates information needed to describe a parameter.
57 ///
58 /// The description of the parameter is not linked directly to
59 /// OpenMP or any other vector function description. This structure
60 /// is extendible to handle other paradigms that describe vector
61 /// functions and their parameters.
62 struct VFParameter {
63 unsigned ParamPos; // Parameter Position in Scalar Function.
64 VFParamKind ParamKind; // Kind of Parameter.
65 int LinearStepOrPos = 0; // Step or Position of the Parameter.
66 Align Alignment = Align(); // Optional alignment in bytes, defaulted to 1.
67
68 // Comparison operator.
69 bool operator==(const VFParameter &Other) const {
70 return std::tie(ParamPos, ParamKind, LinearStepOrPos, Alignment) ==
71 std::tie(Other.ParamPos, Other.ParamKind, Other.LinearStepOrPos,
72 Other.Alignment);
73 }
74 };
75
76 /// Contains the information about the kind of vectorization
77 /// available.
78 ///
79 /// This object in independent on the paradigm used to
80 /// represent vector functions. in particular, it is not attached to
81 /// any target-specific ABI.
82 struct VFShape {
83 ElementCount VF; // Vectorization factor.
84 SmallVector<VFParameter, 8> Parameters; // List of parameter information.
85 // Comparison operator.
86 bool operator==(const VFShape &Other) const {
87 return std::tie(VF, Parameters) == std::tie(Other.VF, Other.Parameters);
88 }
89
90 /// Update the parameter in position P.ParamPos to P.
updateParamVFShape91 void updateParam(VFParameter P) {
92 assert(P.ParamPos < Parameters.size() && "Invalid parameter position.");
93 Parameters[P.ParamPos] = P;
94 assert(hasValidParameterList() && "Invalid parameter list");
95 }
96
97 // Retrieve the VFShape that can be used to map a (scalar) function to itself,
98 // with VF = 1.
getScalarShapeVFShape99 static VFShape getScalarShape(const CallInst &CI) {
100 return VFShape::get(CI, ElementCount::getFixed(1),
101 /*HasGlobalPredicate*/ false);
102 }
103
104 // Retrieve the basic vectorization shape of the function, where all
105 // parameters are mapped to VFParamKind::Vector with \p EC
106 // lanes. Specifies whether the function has a Global Predicate
107 // argument via \p HasGlobalPred.
getVFShape108 static VFShape get(const CallInst &CI, ElementCount EC, bool HasGlobalPred) {
109 SmallVector<VFParameter, 8> Parameters;
110 for (unsigned I = 0; I < CI.arg_size(); ++I)
111 Parameters.push_back(VFParameter({I, VFParamKind::Vector}));
112 if (HasGlobalPred)
113 Parameters.push_back(
114 VFParameter({CI.arg_size(), VFParamKind::GlobalPredicate}));
115
116 return {EC, Parameters};
117 }
118 /// Sanity check on the Parameters in the VFShape.
119 bool hasValidParameterList() const;
120 };
121
122 /// Holds the VFShape for a specific scalar to vector function mapping.
123 struct VFInfo {
124 VFShape Shape; /// Classification of the vector function.
125 std::string ScalarName; /// Scalar Function Name.
126 std::string VectorName; /// Vector Function Name associated to this VFInfo.
127 VFISAKind ISA; /// Instruction Set Architecture.
128 };
129
130 namespace VFABI {
131 /// LLVM Internal VFABI ISA token for vector functions.
132 static constexpr char const *_LLVM_ = "_LLVM_";
133 /// Prefix for internal name redirection for vector function that
134 /// tells the compiler to scalarize the call using the scalar name
135 /// of the function. For example, a mangled name like
136 /// `_ZGV_LLVM_N2v_foo(_LLVM_Scalarize_foo)` would tell the
137 /// vectorizer to vectorize the scalar call `foo`, and to scalarize
138 /// it once vectorization is done.
139 static constexpr char const *_LLVM_Scalarize_ = "_LLVM_Scalarize_";
140
141 /// Function to construct a VFInfo out of a mangled names in the
142 /// following format:
143 ///
144 /// <VFABI_name>{(<redirection>)}
145 ///
146 /// where <VFABI_name> is the name of the vector function, mangled according
147 /// to the rules described in the Vector Function ABI of the target vector
148 /// extension (or <isa> from now on). The <VFABI_name> is in the following
149 /// format:
150 ///
151 /// _ZGV<isa><mask><vlen><parameters>_<scalarname>[(<redirection>)]
152 ///
153 /// This methods support demangling rules for the following <isa>:
154 ///
155 /// * AArch64: https://developer.arm.com/docs/101129/latest
156 ///
157 /// * x86 (libmvec): https://sourceware.org/glibc/wiki/libmvec and
158 /// https://sourceware.org/glibc/wiki/libmvec?action=AttachFile&do=view&target=VectorABI.txt
159 ///
160 /// \param MangledName -> input string in the format
161 /// _ZGV<isa><mask><vlen><parameters>_<scalarname>[(<redirection>)].
162 /// \param M -> Module used to retrieve informations about the vector
163 /// function that are not possible to retrieve from the mangled
164 /// name. At the moment, this parameter is needed only to retrieve the
165 /// Vectorization Factor of scalable vector functions from their
166 /// respective IR declarations.
167 Optional<VFInfo> tryDemangleForVFABI(StringRef MangledName, const Module &M);
168
169 /// This routine mangles the given VectorName according to the LangRef
170 /// specification for vector-function-abi-variant attribute and is specific to
171 /// the TLI mappings. It is the responsibility of the caller to make sure that
172 /// this is only used if all parameters in the vector function are vector type.
173 /// This returned string holds scalar-to-vector mapping:
174 /// _ZGV<isa><mask><vlen><vparams>_<scalarname>(<vectorname>)
175 ///
176 /// where:
177 ///
178 /// <isa> = "_LLVM_"
179 /// <mask> = "N". Note: TLI does not support masked interfaces.
180 /// <vlen> = Number of concurrent lanes, stored in the `VectorizationFactor`
181 /// field of the `VecDesc` struct. If the number of lanes is scalable
182 /// then 'x' is printed instead.
183 /// <vparams> = "v", as many as are the numArgs.
184 /// <scalarname> = the name of the scalar function.
185 /// <vectorname> = the name of the vector function.
186 std::string mangleTLIVectorName(StringRef VectorName, StringRef ScalarName,
187 unsigned numArgs, ElementCount VF);
188
189 /// Retrieve the `VFParamKind` from a string token.
190 VFParamKind getVFParamKindFromString(const StringRef Token);
191
192 // Name of the attribute where the variant mappings are stored.
193 static constexpr char const *MappingsAttrName = "vector-function-abi-variant";
194
195 /// Populates a set of strings representing the Vector Function ABI variants
196 /// associated to the CallInst CI. If the CI does not contain the
197 /// vector-function-abi-variant attribute, we return without populating
198 /// VariantMappings, i.e. callers of getVectorVariantNames need not check for
199 /// the presence of the attribute (see InjectTLIMappings).
200 void getVectorVariantNames(const CallInst &CI,
201 SmallVectorImpl<std::string> &VariantMappings);
202 } // end namespace VFABI
203
204 /// The Vector Function Database.
205 ///
206 /// Helper class used to find the vector functions associated to a
207 /// scalar CallInst.
208 class VFDatabase {
209 /// The Module of the CallInst CI.
210 const Module *M;
211 /// The CallInst instance being queried for scalar to vector mappings.
212 const CallInst &CI;
213 /// List of vector functions descriptors associated to the call
214 /// instruction.
215 const SmallVector<VFInfo, 8> ScalarToVectorMappings;
216
217 /// Retrieve the scalar-to-vector mappings associated to the rule of
218 /// a vector Function ABI.
getVFABIMappings(const CallInst & CI,SmallVectorImpl<VFInfo> & Mappings)219 static void getVFABIMappings(const CallInst &CI,
220 SmallVectorImpl<VFInfo> &Mappings) {
221 if (!CI.getCalledFunction())
222 return;
223
224 const StringRef ScalarName = CI.getCalledFunction()->getName();
225
226 SmallVector<std::string, 8> ListOfStrings;
227 // The check for the vector-function-abi-variant attribute is done when
228 // retrieving the vector variant names here.
229 VFABI::getVectorVariantNames(CI, ListOfStrings);
230 if (ListOfStrings.empty())
231 return;
232 for (const auto &MangledName : ListOfStrings) {
233 const Optional<VFInfo> Shape =
234 VFABI::tryDemangleForVFABI(MangledName, *(CI.getModule()));
235 // A match is found via scalar and vector names, and also by
236 // ensuring that the variant described in the attribute has a
237 // corresponding definition or declaration of the vector
238 // function in the Module M.
239 if (Shape.hasValue() && (Shape.getValue().ScalarName == ScalarName)) {
240 assert(CI.getModule()->getFunction(Shape.getValue().VectorName) &&
241 "Vector function is missing.");
242 Mappings.push_back(Shape.getValue());
243 }
244 }
245 }
246
247 public:
248 /// Retrieve all the VFInfo instances associated to the CallInst CI.
getMappings(const CallInst & CI)249 static SmallVector<VFInfo, 8> getMappings(const CallInst &CI) {
250 SmallVector<VFInfo, 8> Ret;
251
252 // Get mappings from the Vector Function ABI variants.
253 getVFABIMappings(CI, Ret);
254
255 // Other non-VFABI variants should be retrieved here.
256
257 return Ret;
258 }
259
260 /// Constructor, requires a CallInst instance.
VFDatabase(CallInst & CI)261 VFDatabase(CallInst &CI)
262 : M(CI.getModule()), CI(CI),
263 ScalarToVectorMappings(VFDatabase::getMappings(CI)) {}
264 /// \defgroup VFDatabase query interface.
265 ///
266 /// @{
267 /// Retrieve the Function with VFShape \p Shape.
getVectorizedFunction(const VFShape & Shape)268 Function *getVectorizedFunction(const VFShape &Shape) const {
269 if (Shape == VFShape::getScalarShape(CI))
270 return CI.getCalledFunction();
271
272 for (const auto &Info : ScalarToVectorMappings)
273 if (Info.Shape == Shape)
274 return M->getFunction(Info.VectorName);
275
276 return nullptr;
277 }
278 /// @}
279 };
280
281 template <typename T> class ArrayRef;
282 class DemandedBits;
283 class GetElementPtrInst;
284 template <typename InstTy> class InterleaveGroup;
285 class IRBuilderBase;
286 class Loop;
287 class ScalarEvolution;
288 class TargetTransformInfo;
289 class Type;
290 class Value;
291
292 namespace Intrinsic {
293 typedef unsigned ID;
294 }
295
296 /// A helper function for converting Scalar types to vector types. If
297 /// the incoming type is void, we return void. If the EC represents a
298 /// scalar, we return the scalar type.
ToVectorTy(Type * Scalar,ElementCount EC)299 inline Type *ToVectorTy(Type *Scalar, ElementCount EC) {
300 if (Scalar->isVoidTy() || Scalar->isMetadataTy() || EC.isScalar())
301 return Scalar;
302 return VectorType::get(Scalar, EC);
303 }
304
ToVectorTy(Type * Scalar,unsigned VF)305 inline Type *ToVectorTy(Type *Scalar, unsigned VF) {
306 return ToVectorTy(Scalar, ElementCount::getFixed(VF));
307 }
308
309 /// Identify if the intrinsic is trivially vectorizable.
310 /// This method returns true if the intrinsic's argument types are all scalars
311 /// for the scalar form of the intrinsic and all vectors (or scalars handled by
312 /// hasVectorInstrinsicScalarOpd) for the vector form of the intrinsic.
313 bool isTriviallyVectorizable(Intrinsic::ID ID);
314
315 /// Identifies if the vector form of the intrinsic has a scalar operand.
316 bool hasVectorInstrinsicScalarOpd(Intrinsic::ID ID, unsigned ScalarOpdIdx);
317
318 /// Identifies if the vector form of the intrinsic has a scalar operand that has
319 /// an overloaded type.
320 bool hasVectorInstrinsicOverloadedScalarOpd(Intrinsic::ID ID,
321 unsigned ScalarOpdIdx);
322
323 /// Returns intrinsic ID for call.
324 /// For the input call instruction it finds mapping intrinsic and returns
325 /// its intrinsic ID, in case it does not found it return not_intrinsic.
326 Intrinsic::ID getVectorIntrinsicIDForCall(const CallInst *CI,
327 const TargetLibraryInfo *TLI);
328
329 /// Find the operand of the GEP that should be checked for consecutive
330 /// stores. This ignores trailing indices that have no effect on the final
331 /// pointer.
332 unsigned getGEPInductionOperand(const GetElementPtrInst *Gep);
333
334 /// If the argument is a GEP, then returns the operand identified by
335 /// getGEPInductionOperand. However, if there is some other non-loop-invariant
336 /// operand, it returns that instead.
337 Value *stripGetElementPtr(Value *Ptr, ScalarEvolution *SE, Loop *Lp);
338
339 /// If a value has only one user that is a CastInst, return it.
340 Value *getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty);
341
342 /// Get the stride of a pointer access in a loop. Looks for symbolic
343 /// strides "a[i*stride]". Returns the symbolic stride, or null otherwise.
344 Value *getStrideFromPointer(Value *Ptr, ScalarEvolution *SE, Loop *Lp);
345
346 /// Given a vector and an element number, see if the scalar value is
347 /// already around as a register, for example if it were inserted then extracted
348 /// from the vector.
349 Value *findScalarElement(Value *V, unsigned EltNo);
350
351 /// If all non-negative \p Mask elements are the same value, return that value.
352 /// If all elements are negative (undefined) or \p Mask contains different
353 /// non-negative values, return -1.
354 int getSplatIndex(ArrayRef<int> Mask);
355
356 /// Get splat value if the input is a splat vector or return nullptr.
357 /// The value may be extracted from a splat constants vector or from
358 /// a sequence of instructions that broadcast a single value into a vector.
359 Value *getSplatValue(const Value *V);
360
361 /// Return true if each element of the vector value \p V is poisoned or equal to
362 /// every other non-poisoned element. If an index element is specified, either
363 /// every element of the vector is poisoned or the element at that index is not
364 /// poisoned and equal to every other non-poisoned element.
365 /// This may be more powerful than the related getSplatValue() because it is
366 /// not limited by finding a scalar source value to a splatted vector.
367 bool isSplatValue(const Value *V, int Index = -1, unsigned Depth = 0);
368
369 /// Replace each shuffle mask index with the scaled sequential indices for an
370 /// equivalent mask of narrowed elements. Mask elements that are less than 0
371 /// (sentinel values) are repeated in the output mask.
372 ///
373 /// Example with Scale = 4:
374 /// <4 x i32> <3, 2, 0, -1> -->
375 /// <16 x i8> <12, 13, 14, 15, 8, 9, 10, 11, 0, 1, 2, 3, -1, -1, -1, -1>
376 ///
377 /// This is the reverse process of widening shuffle mask elements, but it always
378 /// succeeds because the indexes can always be multiplied (scaled up) to map to
379 /// narrower vector elements.
380 void narrowShuffleMaskElts(int Scale, ArrayRef<int> Mask,
381 SmallVectorImpl<int> &ScaledMask);
382
383 /// Try to transform a shuffle mask by replacing elements with the scaled index
384 /// for an equivalent mask of widened elements. If all mask elements that would
385 /// map to a wider element of the new mask are the same negative number
386 /// (sentinel value), that element of the new mask is the same value. If any
387 /// element in a given slice is negative and some other element in that slice is
388 /// not the same value, return false (partial matches with sentinel values are
389 /// not allowed).
390 ///
391 /// Example with Scale = 4:
392 /// <16 x i8> <12, 13, 14, 15, 8, 9, 10, 11, 0, 1, 2, 3, -1, -1, -1, -1> -->
393 /// <4 x i32> <3, 2, 0, -1>
394 ///
395 /// This is the reverse process of narrowing shuffle mask elements if it
396 /// succeeds. This transform is not always possible because indexes may not
397 /// divide evenly (scale down) to map to wider vector elements.
398 bool widenShuffleMaskElts(int Scale, ArrayRef<int> Mask,
399 SmallVectorImpl<int> &ScaledMask);
400
401 /// Compute a map of integer instructions to their minimum legal type
402 /// size.
403 ///
404 /// C semantics force sub-int-sized values (e.g. i8, i16) to be promoted to int
405 /// type (e.g. i32) whenever arithmetic is performed on them.
406 ///
407 /// For targets with native i8 or i16 operations, usually InstCombine can shrink
408 /// the arithmetic type down again. However InstCombine refuses to create
409 /// illegal types, so for targets without i8 or i16 registers, the lengthening
410 /// and shrinking remains.
411 ///
412 /// Most SIMD ISAs (e.g. NEON) however support vectors of i8 or i16 even when
413 /// their scalar equivalents do not, so during vectorization it is important to
414 /// remove these lengthens and truncates when deciding the profitability of
415 /// vectorization.
416 ///
417 /// This function analyzes the given range of instructions and determines the
418 /// minimum type size each can be converted to. It attempts to remove or
419 /// minimize type size changes across each def-use chain, so for example in the
420 /// following code:
421 ///
422 /// %1 = load i8, i8*
423 /// %2 = add i8 %1, 2
424 /// %3 = load i16, i16*
425 /// %4 = zext i8 %2 to i32
426 /// %5 = zext i16 %3 to i32
427 /// %6 = add i32 %4, %5
428 /// %7 = trunc i32 %6 to i16
429 ///
430 /// Instruction %6 must be done at least in i16, so computeMinimumValueSizes
431 /// will return: {%1: 16, %2: 16, %3: 16, %4: 16, %5: 16, %6: 16, %7: 16}.
432 ///
433 /// If the optional TargetTransformInfo is provided, this function tries harder
434 /// to do less work by only looking at illegal types.
435 MapVector<Instruction*, uint64_t>
436 computeMinimumValueSizes(ArrayRef<BasicBlock*> Blocks,
437 DemandedBits &DB,
438 const TargetTransformInfo *TTI=nullptr);
439
440 /// Compute the union of two access-group lists.
441 ///
442 /// If the list contains just one access group, it is returned directly. If the
443 /// list is empty, returns nullptr.
444 MDNode *uniteAccessGroups(MDNode *AccGroups1, MDNode *AccGroups2);
445
446 /// Compute the access-group list of access groups that @p Inst1 and @p Inst2
447 /// are both in. If either instruction does not access memory at all, it is
448 /// considered to be in every list.
449 ///
450 /// If the list contains just one access group, it is returned directly. If the
451 /// list is empty, returns nullptr.
452 MDNode *intersectAccessGroups(const Instruction *Inst1,
453 const Instruction *Inst2);
454
455 /// Specifically, let Kinds = [MD_tbaa, MD_alias_scope, MD_noalias, MD_fpmath,
456 /// MD_nontemporal, MD_access_group].
457 /// For K in Kinds, we get the MDNode for K from each of the
458 /// elements of VL, compute their "intersection" (i.e., the most generic
459 /// metadata value that covers all of the individual values), and set I's
460 /// metadata for M equal to the intersection value.
461 ///
462 /// This function always sets a (possibly null) value for each K in Kinds.
463 Instruction *propagateMetadata(Instruction *I, ArrayRef<Value *> VL);
464
465 /// Create a mask that filters the members of an interleave group where there
466 /// are gaps.
467 ///
468 /// For example, the mask for \p Group with interleave-factor 3
469 /// and \p VF 4, that has only its first member present is:
470 ///
471 /// <1,0,0,1,0,0,1,0,0,1,0,0>
472 ///
473 /// Note: The result is a mask of 0's and 1's, as opposed to the other
474 /// create[*]Mask() utilities which create a shuffle mask (mask that
475 /// consists of indices).
476 Constant *createBitMaskForGaps(IRBuilderBase &Builder, unsigned VF,
477 const InterleaveGroup<Instruction> &Group);
478
479 /// Create a mask with replicated elements.
480 ///
481 /// This function creates a shuffle mask for replicating each of the \p VF
482 /// elements in a vector \p ReplicationFactor times. It can be used to
483 /// transform a mask of \p VF elements into a mask of
484 /// \p VF * \p ReplicationFactor elements used by a predicated
485 /// interleaved-group of loads/stores whose Interleaved-factor ==
486 /// \p ReplicationFactor.
487 ///
488 /// For example, the mask for \p ReplicationFactor=3 and \p VF=4 is:
489 ///
490 /// <0,0,0,1,1,1,2,2,2,3,3,3>
491 llvm::SmallVector<int, 16> createReplicatedMask(unsigned ReplicationFactor,
492 unsigned VF);
493
494 /// Create an interleave shuffle mask.
495 ///
496 /// This function creates a shuffle mask for interleaving \p NumVecs vectors of
497 /// vectorization factor \p VF into a single wide vector. The mask is of the
498 /// form:
499 ///
500 /// <0, VF, VF * 2, ..., VF * (NumVecs - 1), 1, VF + 1, VF * 2 + 1, ...>
501 ///
502 /// For example, the mask for VF = 4 and NumVecs = 2 is:
503 ///
504 /// <0, 4, 1, 5, 2, 6, 3, 7>.
505 llvm::SmallVector<int, 16> createInterleaveMask(unsigned VF, unsigned NumVecs);
506
507 /// Create a stride shuffle mask.
508 ///
509 /// This function creates a shuffle mask whose elements begin at \p Start and
510 /// are incremented by \p Stride. The mask can be used to deinterleave an
511 /// interleaved vector into separate vectors of vectorization factor \p VF. The
512 /// mask is of the form:
513 ///
514 /// <Start, Start + Stride, ..., Start + Stride * (VF - 1)>
515 ///
516 /// For example, the mask for Start = 0, Stride = 2, and VF = 4 is:
517 ///
518 /// <0, 2, 4, 6>
519 llvm::SmallVector<int, 16> createStrideMask(unsigned Start, unsigned Stride,
520 unsigned VF);
521
522 /// Create a sequential shuffle mask.
523 ///
524 /// This function creates shuffle mask whose elements are sequential and begin
525 /// at \p Start. The mask contains \p NumInts integers and is padded with \p
526 /// NumUndefs undef values. The mask is of the form:
527 ///
528 /// <Start, Start + 1, ... Start + NumInts - 1, undef_1, ... undef_NumUndefs>
529 ///
530 /// For example, the mask for Start = 0, NumInsts = 4, and NumUndefs = 4 is:
531 ///
532 /// <0, 1, 2, 3, undef, undef, undef, undef>
533 llvm::SmallVector<int, 16>
534 createSequentialMask(unsigned Start, unsigned NumInts, unsigned NumUndefs);
535
536 /// Concatenate a list of vectors.
537 ///
538 /// This function generates code that concatenate the vectors in \p Vecs into a
539 /// single large vector. The number of vectors should be greater than one, and
540 /// their element types should be the same. The number of elements in the
541 /// vectors should also be the same; however, if the last vector has fewer
542 /// elements, it will be padded with undefs.
543 Value *concatenateVectors(IRBuilderBase &Builder, ArrayRef<Value *> Vecs);
544
545 /// Given a mask vector of i1, Return true if all of the elements of this
546 /// predicate mask are known to be false or undef. That is, return true if all
547 /// lanes can be assumed inactive.
548 bool maskIsAllZeroOrUndef(Value *Mask);
549
550 /// Given a mask vector of i1, Return true if all of the elements of this
551 /// predicate mask are known to be true or undef. That is, return true if all
552 /// lanes can be assumed active.
553 bool maskIsAllOneOrUndef(Value *Mask);
554
555 /// Given a mask vector of the form <Y x i1>, return an APInt (of bitwidth Y)
556 /// for each lane which may be active.
557 APInt possiblyDemandedEltsInMask(Value *Mask);
558
559 /// The group of interleaved loads/stores sharing the same stride and
560 /// close to each other.
561 ///
562 /// Each member in this group has an index starting from 0, and the largest
563 /// index should be less than interleaved factor, which is equal to the absolute
564 /// value of the access's stride.
565 ///
566 /// E.g. An interleaved load group of factor 4:
567 /// for (unsigned i = 0; i < 1024; i+=4) {
568 /// a = A[i]; // Member of index 0
569 /// b = A[i+1]; // Member of index 1
570 /// d = A[i+3]; // Member of index 3
571 /// ...
572 /// }
573 ///
574 /// An interleaved store group of factor 4:
575 /// for (unsigned i = 0; i < 1024; i+=4) {
576 /// ...
577 /// A[i] = a; // Member of index 0
578 /// A[i+1] = b; // Member of index 1
579 /// A[i+2] = c; // Member of index 2
580 /// A[i+3] = d; // Member of index 3
581 /// }
582 ///
583 /// Note: the interleaved load group could have gaps (missing members), but
584 /// the interleaved store group doesn't allow gaps.
585 template <typename InstTy> class InterleaveGroup {
586 public:
InterleaveGroup(uint32_t Factor,bool Reverse,Align Alignment)587 InterleaveGroup(uint32_t Factor, bool Reverse, Align Alignment)
588 : Factor(Factor), Reverse(Reverse), Alignment(Alignment),
589 InsertPos(nullptr) {}
590
InterleaveGroup(InstTy * Instr,int32_t Stride,Align Alignment)591 InterleaveGroup(InstTy *Instr, int32_t Stride, Align Alignment)
592 : Alignment(Alignment), InsertPos(Instr) {
593 Factor = std::abs(Stride);
594 assert(Factor > 1 && "Invalid interleave factor");
595
596 Reverse = Stride < 0;
597 Members[0] = Instr;
598 }
599
isReverse()600 bool isReverse() const { return Reverse; }
getFactor()601 uint32_t getFactor() const { return Factor; }
getAlign()602 Align getAlign() const { return Alignment; }
getNumMembers()603 uint32_t getNumMembers() const { return Members.size(); }
604
605 /// Try to insert a new member \p Instr with index \p Index and
606 /// alignment \p NewAlign. The index is related to the leader and it could be
607 /// negative if it is the new leader.
608 ///
609 /// \returns false if the instruction doesn't belong to the group.
insertMember(InstTy * Instr,int32_t Index,Align NewAlign)610 bool insertMember(InstTy *Instr, int32_t Index, Align NewAlign) {
611 // Make sure the key fits in an int32_t.
612 Optional<int32_t> MaybeKey = checkedAdd(Index, SmallestKey);
613 if (!MaybeKey)
614 return false;
615 int32_t Key = *MaybeKey;
616
617 // Skip if the key is used for either the tombstone or empty special values.
618 if (DenseMapInfo<int32_t>::getTombstoneKey() == Key ||
619 DenseMapInfo<int32_t>::getEmptyKey() == Key)
620 return false;
621
622 // Skip if there is already a member with the same index.
623 if (Members.find(Key) != Members.end())
624 return false;
625
626 if (Key > LargestKey) {
627 // The largest index is always less than the interleave factor.
628 if (Index >= static_cast<int32_t>(Factor))
629 return false;
630
631 LargestKey = Key;
632 } else if (Key < SmallestKey) {
633
634 // Make sure the largest index fits in an int32_t.
635 Optional<int32_t> MaybeLargestIndex = checkedSub(LargestKey, Key);
636 if (!MaybeLargestIndex)
637 return false;
638
639 // The largest index is always less than the interleave factor.
640 if (*MaybeLargestIndex >= static_cast<int64_t>(Factor))
641 return false;
642
643 SmallestKey = Key;
644 }
645
646 // It's always safe to select the minimum alignment.
647 Alignment = std::min(Alignment, NewAlign);
648 Members[Key] = Instr;
649 return true;
650 }
651
652 /// Get the member with the given index \p Index
653 ///
654 /// \returns nullptr if contains no such member.
getMember(uint32_t Index)655 InstTy *getMember(uint32_t Index) const {
656 int32_t Key = SmallestKey + Index;
657 return Members.lookup(Key);
658 }
659
660 /// Get the index for the given member. Unlike the key in the member
661 /// map, the index starts from 0.
getIndex(const InstTy * Instr)662 uint32_t getIndex(const InstTy *Instr) const {
663 for (auto I : Members) {
664 if (I.second == Instr)
665 return I.first - SmallestKey;
666 }
667
668 llvm_unreachable("InterleaveGroup contains no such member");
669 }
670
getInsertPos()671 InstTy *getInsertPos() const { return InsertPos; }
setInsertPos(InstTy * Inst)672 void setInsertPos(InstTy *Inst) { InsertPos = Inst; }
673
674 /// Add metadata (e.g. alias info) from the instructions in this group to \p
675 /// NewInst.
676 ///
677 /// FIXME: this function currently does not add noalias metadata a'la
678 /// addNewMedata. To do that we need to compute the intersection of the
679 /// noalias info from all members.
680 void addMetadata(InstTy *NewInst) const;
681
682 /// Returns true if this Group requires a scalar iteration to handle gaps.
requiresScalarEpilogue()683 bool requiresScalarEpilogue() const {
684 // If the last member of the Group exists, then a scalar epilog is not
685 // needed for this group.
686 if (getMember(getFactor() - 1))
687 return false;
688
689 // We have a group with gaps. It therefore cannot be a group of stores,
690 // and it can't be a reversed access, because such groups get invalidated.
691 assert(!getMember(0)->mayWriteToMemory() &&
692 "Group should have been invalidated");
693 assert(!isReverse() && "Group should have been invalidated");
694
695 // This is a group of loads, with gaps, and without a last-member
696 return true;
697 }
698
699 private:
700 uint32_t Factor; // Interleave Factor.
701 bool Reverse;
702 Align Alignment;
703 DenseMap<int32_t, InstTy *> Members;
704 int32_t SmallestKey = 0;
705 int32_t LargestKey = 0;
706
707 // To avoid breaking dependences, vectorized instructions of an interleave
708 // group should be inserted at either the first load or the last store in
709 // program order.
710 //
711 // E.g. %even = load i32 // Insert Position
712 // %add = add i32 %even // Use of %even
713 // %odd = load i32
714 //
715 // store i32 %even
716 // %odd = add i32 // Def of %odd
717 // store i32 %odd // Insert Position
718 InstTy *InsertPos;
719 };
720
721 /// Drive the analysis of interleaved memory accesses in the loop.
722 ///
723 /// Use this class to analyze interleaved accesses only when we can vectorize
724 /// a loop. Otherwise it's meaningless to do analysis as the vectorization
725 /// on interleaved accesses is unsafe.
726 ///
727 /// The analysis collects interleave groups and records the relationships
728 /// between the member and the group in a map.
729 class InterleavedAccessInfo {
730 public:
InterleavedAccessInfo(PredicatedScalarEvolution & PSE,Loop * L,DominatorTree * DT,LoopInfo * LI,const LoopAccessInfo * LAI)731 InterleavedAccessInfo(PredicatedScalarEvolution &PSE, Loop *L,
732 DominatorTree *DT, LoopInfo *LI,
733 const LoopAccessInfo *LAI)
734 : PSE(PSE), TheLoop(L), DT(DT), LI(LI), LAI(LAI) {}
735
~InterleavedAccessInfo()736 ~InterleavedAccessInfo() { invalidateGroups(); }
737
738 /// Analyze the interleaved accesses and collect them in interleave
739 /// groups. Substitute symbolic strides using \p Strides.
740 /// Consider also predicated loads/stores in the analysis if
741 /// \p EnableMaskedInterleavedGroup is true.
742 void analyzeInterleaving(bool EnableMaskedInterleavedGroup);
743
744 /// Invalidate groups, e.g., in case all blocks in loop will be predicated
745 /// contrary to original assumption. Although we currently prevent group
746 /// formation for predicated accesses, we may be able to relax this limitation
747 /// in the future once we handle more complicated blocks. Returns true if any
748 /// groups were invalidated.
invalidateGroups()749 bool invalidateGroups() {
750 if (InterleaveGroups.empty()) {
751 assert(
752 !RequiresScalarEpilogue &&
753 "RequiresScalarEpilog should not be set without interleave groups");
754 return false;
755 }
756
757 InterleaveGroupMap.clear();
758 for (auto *Ptr : InterleaveGroups)
759 delete Ptr;
760 InterleaveGroups.clear();
761 RequiresScalarEpilogue = false;
762 return true;
763 }
764
765 /// Check if \p Instr belongs to any interleave group.
isInterleaved(Instruction * Instr)766 bool isInterleaved(Instruction *Instr) const {
767 return InterleaveGroupMap.find(Instr) != InterleaveGroupMap.end();
768 }
769
770 /// Get the interleave group that \p Instr belongs to.
771 ///
772 /// \returns nullptr if doesn't have such group.
773 InterleaveGroup<Instruction> *
getInterleaveGroup(const Instruction * Instr)774 getInterleaveGroup(const Instruction *Instr) const {
775 return InterleaveGroupMap.lookup(Instr);
776 }
777
778 iterator_range<SmallPtrSetIterator<llvm::InterleaveGroup<Instruction> *>>
getInterleaveGroups()779 getInterleaveGroups() {
780 return make_range(InterleaveGroups.begin(), InterleaveGroups.end());
781 }
782
783 /// Returns true if an interleaved group that may access memory
784 /// out-of-bounds requires a scalar epilogue iteration for correctness.
requiresScalarEpilogue()785 bool requiresScalarEpilogue() const { return RequiresScalarEpilogue; }
786
787 /// Invalidate groups that require a scalar epilogue (due to gaps). This can
788 /// happen when optimizing for size forbids a scalar epilogue, and the gap
789 /// cannot be filtered by masking the load/store.
790 void invalidateGroupsRequiringScalarEpilogue();
791
792 private:
793 /// A wrapper around ScalarEvolution, used to add runtime SCEV checks.
794 /// Simplifies SCEV expressions in the context of existing SCEV assumptions.
795 /// The interleaved access analysis can also add new predicates (for example
796 /// by versioning strides of pointers).
797 PredicatedScalarEvolution &PSE;
798
799 Loop *TheLoop;
800 DominatorTree *DT;
801 LoopInfo *LI;
802 const LoopAccessInfo *LAI;
803
804 /// True if the loop may contain non-reversed interleaved groups with
805 /// out-of-bounds accesses. We ensure we don't speculatively access memory
806 /// out-of-bounds by executing at least one scalar epilogue iteration.
807 bool RequiresScalarEpilogue = false;
808
809 /// Holds the relationships between the members and the interleave group.
810 DenseMap<Instruction *, InterleaveGroup<Instruction> *> InterleaveGroupMap;
811
812 SmallPtrSet<InterleaveGroup<Instruction> *, 4> InterleaveGroups;
813
814 /// Holds dependences among the memory accesses in the loop. It maps a source
815 /// access to a set of dependent sink accesses.
816 DenseMap<Instruction *, SmallPtrSet<Instruction *, 2>> Dependences;
817
818 /// The descriptor for a strided memory access.
819 struct StrideDescriptor {
820 StrideDescriptor() = default;
StrideDescriptorStrideDescriptor821 StrideDescriptor(int64_t Stride, const SCEV *Scev, uint64_t Size,
822 Align Alignment)
823 : Stride(Stride), Scev(Scev), Size(Size), Alignment(Alignment) {}
824
825 // The access's stride. It is negative for a reverse access.
826 int64_t Stride = 0;
827
828 // The scalar expression of this access.
829 const SCEV *Scev = nullptr;
830
831 // The size of the memory object.
832 uint64_t Size = 0;
833
834 // The alignment of this access.
835 Align Alignment;
836 };
837
838 /// A type for holding instructions and their stride descriptors.
839 using StrideEntry = std::pair<Instruction *, StrideDescriptor>;
840
841 /// Create a new interleave group with the given instruction \p Instr,
842 /// stride \p Stride and alignment \p Align.
843 ///
844 /// \returns the newly created interleave group.
845 InterleaveGroup<Instruction> *
createInterleaveGroup(Instruction * Instr,int Stride,Align Alignment)846 createInterleaveGroup(Instruction *Instr, int Stride, Align Alignment) {
847 assert(!InterleaveGroupMap.count(Instr) &&
848 "Already in an interleaved access group");
849 InterleaveGroupMap[Instr] =
850 new InterleaveGroup<Instruction>(Instr, Stride, Alignment);
851 InterleaveGroups.insert(InterleaveGroupMap[Instr]);
852 return InterleaveGroupMap[Instr];
853 }
854
855 /// Release the group and remove all the relationships.
releaseGroup(InterleaveGroup<Instruction> * Group)856 void releaseGroup(InterleaveGroup<Instruction> *Group) {
857 for (unsigned i = 0; i < Group->getFactor(); i++)
858 if (Instruction *Member = Group->getMember(i))
859 InterleaveGroupMap.erase(Member);
860
861 InterleaveGroups.erase(Group);
862 delete Group;
863 }
864
865 /// Collect all the accesses with a constant stride in program order.
866 void collectConstStrideAccesses(
867 MapVector<Instruction *, StrideDescriptor> &AccessStrideInfo,
868 const ValueToValueMap &Strides);
869
870 /// Returns true if \p Stride is allowed in an interleaved group.
871 static bool isStrided(int Stride);
872
873 /// Returns true if \p BB is a predicated block.
isPredicated(BasicBlock * BB)874 bool isPredicated(BasicBlock *BB) const {
875 return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
876 }
877
878 /// Returns true if LoopAccessInfo can be used for dependence queries.
areDependencesValid()879 bool areDependencesValid() const {
880 return LAI && LAI->getDepChecker().getDependences();
881 }
882
883 /// Returns true if memory accesses \p A and \p B can be reordered, if
884 /// necessary, when constructing interleaved groups.
885 ///
886 /// \p A must precede \p B in program order. We return false if reordering is
887 /// not necessary or is prevented because \p A and \p B may be dependent.
canReorderMemAccessesForInterleavedGroups(StrideEntry * A,StrideEntry * B)888 bool canReorderMemAccessesForInterleavedGroups(StrideEntry *A,
889 StrideEntry *B) const {
890 // Code motion for interleaved accesses can potentially hoist strided loads
891 // and sink strided stores. The code below checks the legality of the
892 // following two conditions:
893 //
894 // 1. Potentially moving a strided load (B) before any store (A) that
895 // precedes B, or
896 //
897 // 2. Potentially moving a strided store (A) after any load or store (B)
898 // that A precedes.
899 //
900 // It's legal to reorder A and B if we know there isn't a dependence from A
901 // to B. Note that this determination is conservative since some
902 // dependences could potentially be reordered safely.
903
904 // A is potentially the source of a dependence.
905 auto *Src = A->first;
906 auto SrcDes = A->second;
907
908 // B is potentially the sink of a dependence.
909 auto *Sink = B->first;
910 auto SinkDes = B->second;
911
912 // Code motion for interleaved accesses can't violate WAR dependences.
913 // Thus, reordering is legal if the source isn't a write.
914 if (!Src->mayWriteToMemory())
915 return true;
916
917 // At least one of the accesses must be strided.
918 if (!isStrided(SrcDes.Stride) && !isStrided(SinkDes.Stride))
919 return true;
920
921 // If dependence information is not available from LoopAccessInfo,
922 // conservatively assume the instructions can't be reordered.
923 if (!areDependencesValid())
924 return false;
925
926 // If we know there is a dependence from source to sink, assume the
927 // instructions can't be reordered. Otherwise, reordering is legal.
928 return Dependences.find(Src) == Dependences.end() ||
929 !Dependences.lookup(Src).count(Sink);
930 }
931
932 /// Collect the dependences from LoopAccessInfo.
933 ///
934 /// We process the dependences once during the interleaved access analysis to
935 /// enable constant-time dependence queries.
collectDependences()936 void collectDependences() {
937 if (!areDependencesValid())
938 return;
939 auto *Deps = LAI->getDepChecker().getDependences();
940 for (auto Dep : *Deps)
941 Dependences[Dep.getSource(*LAI)].insert(Dep.getDestination(*LAI));
942 }
943 };
944
945 } // llvm namespace
946
947 #endif
948