VectorUtils.h 38 KB

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