VectorUtils.cpp 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612
  1. //===----------- VectorUtils.cpp - Vectorizer utility functions -----------===//
  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 vectorizer utilities.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/Analysis/VectorUtils.h"
  13. #include "llvm/ADT/EquivalenceClasses.h"
  14. #include "llvm/Analysis/DemandedBits.h"
  15. #include "llvm/Analysis/LoopInfo.h"
  16. #include "llvm/Analysis/LoopIterator.h"
  17. #include "llvm/Analysis/ScalarEvolution.h"
  18. #include "llvm/Analysis/ScalarEvolutionExpressions.h"
  19. #include "llvm/Analysis/TargetTransformInfo.h"
  20. #include "llvm/Analysis/ValueTracking.h"
  21. #include "llvm/IR/Constants.h"
  22. #include "llvm/IR/GetElementPtrTypeIterator.h"
  23. #include "llvm/IR/IRBuilder.h"
  24. #include "llvm/IR/PatternMatch.h"
  25. #include "llvm/IR/Value.h"
  26. #include "llvm/Support/CommandLine.h"
  27. #define DEBUG_TYPE "vectorutils"
  28. using namespace llvm;
  29. using namespace llvm::PatternMatch;
  30. /// Maximum factor for an interleaved memory access.
  31. static cl::opt<unsigned> MaxInterleaveGroupFactor(
  32. "max-interleave-group-factor", cl::Hidden,
  33. cl::desc("Maximum factor for an interleaved access group (default = 8)"),
  34. cl::init(8));
  35. /// Return true if all of the intrinsic's arguments and return type are scalars
  36. /// for the scalar form of the intrinsic, and vectors for the vector form of the
  37. /// intrinsic (except operands that are marked as always being scalar by
  38. /// isVectorIntrinsicWithScalarOpAtArg).
  39. bool llvm::isTriviallyVectorizable(Intrinsic::ID ID) {
  40. switch (ID) {
  41. case Intrinsic::abs: // Begin integer bit-manipulation.
  42. case Intrinsic::bswap:
  43. case Intrinsic::bitreverse:
  44. case Intrinsic::ctpop:
  45. case Intrinsic::ctlz:
  46. case Intrinsic::cttz:
  47. case Intrinsic::fshl:
  48. case Intrinsic::fshr:
  49. case Intrinsic::smax:
  50. case Intrinsic::smin:
  51. case Intrinsic::umax:
  52. case Intrinsic::umin:
  53. case Intrinsic::sadd_sat:
  54. case Intrinsic::ssub_sat:
  55. case Intrinsic::uadd_sat:
  56. case Intrinsic::usub_sat:
  57. case Intrinsic::smul_fix:
  58. case Intrinsic::smul_fix_sat:
  59. case Intrinsic::umul_fix:
  60. case Intrinsic::umul_fix_sat:
  61. case Intrinsic::sqrt: // Begin floating-point.
  62. case Intrinsic::sin:
  63. case Intrinsic::cos:
  64. case Intrinsic::exp:
  65. case Intrinsic::exp2:
  66. case Intrinsic::log:
  67. case Intrinsic::log10:
  68. case Intrinsic::log2:
  69. case Intrinsic::fabs:
  70. case Intrinsic::minnum:
  71. case Intrinsic::maxnum:
  72. case Intrinsic::minimum:
  73. case Intrinsic::maximum:
  74. case Intrinsic::copysign:
  75. case Intrinsic::floor:
  76. case Intrinsic::ceil:
  77. case Intrinsic::trunc:
  78. case Intrinsic::rint:
  79. case Intrinsic::nearbyint:
  80. case Intrinsic::round:
  81. case Intrinsic::roundeven:
  82. case Intrinsic::pow:
  83. case Intrinsic::fma:
  84. case Intrinsic::fmuladd:
  85. case Intrinsic::powi:
  86. case Intrinsic::canonicalize:
  87. case Intrinsic::fptosi_sat:
  88. case Intrinsic::fptoui_sat:
  89. return true;
  90. default:
  91. return false;
  92. }
  93. }
  94. /// Identifies if the vector form of the intrinsic has a scalar operand.
  95. bool llvm::isVectorIntrinsicWithScalarOpAtArg(Intrinsic::ID ID,
  96. unsigned ScalarOpdIdx) {
  97. switch (ID) {
  98. case Intrinsic::abs:
  99. case Intrinsic::ctlz:
  100. case Intrinsic::cttz:
  101. case Intrinsic::powi:
  102. return (ScalarOpdIdx == 1);
  103. case Intrinsic::smul_fix:
  104. case Intrinsic::smul_fix_sat:
  105. case Intrinsic::umul_fix:
  106. case Intrinsic::umul_fix_sat:
  107. return (ScalarOpdIdx == 2);
  108. default:
  109. return false;
  110. }
  111. }
  112. bool llvm::isVectorIntrinsicWithOverloadTypeAtArg(Intrinsic::ID ID,
  113. unsigned OpdIdx) {
  114. switch (ID) {
  115. case Intrinsic::fptosi_sat:
  116. case Intrinsic::fptoui_sat:
  117. return OpdIdx == 0;
  118. case Intrinsic::powi:
  119. return OpdIdx == 1;
  120. default:
  121. return false;
  122. }
  123. }
  124. /// Returns intrinsic ID for call.
  125. /// For the input call instruction it finds mapping intrinsic and returns
  126. /// its ID, in case it does not found it return not_intrinsic.
  127. Intrinsic::ID llvm::getVectorIntrinsicIDForCall(const CallInst *CI,
  128. const TargetLibraryInfo *TLI) {
  129. Intrinsic::ID ID = getIntrinsicForCallSite(*CI, TLI);
  130. if (ID == Intrinsic::not_intrinsic)
  131. return Intrinsic::not_intrinsic;
  132. if (isTriviallyVectorizable(ID) || ID == Intrinsic::lifetime_start ||
  133. ID == Intrinsic::lifetime_end || ID == Intrinsic::assume ||
  134. ID == Intrinsic::experimental_noalias_scope_decl ||
  135. ID == Intrinsic::sideeffect || ID == Intrinsic::pseudoprobe)
  136. return ID;
  137. return Intrinsic::not_intrinsic;
  138. }
  139. /// Find the operand of the GEP that should be checked for consecutive
  140. /// stores. This ignores trailing indices that have no effect on the final
  141. /// pointer.
  142. unsigned llvm::getGEPInductionOperand(const GetElementPtrInst *Gep) {
  143. const DataLayout &DL = Gep->getModule()->getDataLayout();
  144. unsigned LastOperand = Gep->getNumOperands() - 1;
  145. TypeSize GEPAllocSize = DL.getTypeAllocSize(Gep->getResultElementType());
  146. // Walk backwards and try to peel off zeros.
  147. while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) {
  148. // Find the type we're currently indexing into.
  149. gep_type_iterator GEPTI = gep_type_begin(Gep);
  150. std::advance(GEPTI, LastOperand - 2);
  151. // If it's a type with the same allocation size as the result of the GEP we
  152. // can peel off the zero index.
  153. if (DL.getTypeAllocSize(GEPTI.getIndexedType()) != GEPAllocSize)
  154. break;
  155. --LastOperand;
  156. }
  157. return LastOperand;
  158. }
  159. /// If the argument is a GEP, then returns the operand identified by
  160. /// getGEPInductionOperand. However, if there is some other non-loop-invariant
  161. /// operand, it returns that instead.
  162. Value *llvm::stripGetElementPtr(Value *Ptr, ScalarEvolution *SE, Loop *Lp) {
  163. GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
  164. if (!GEP)
  165. return Ptr;
  166. unsigned InductionOperand = getGEPInductionOperand(GEP);
  167. // Check that all of the gep indices are uniform except for our induction
  168. // operand.
  169. for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i)
  170. if (i != InductionOperand &&
  171. !SE->isLoopInvariant(SE->getSCEV(GEP->getOperand(i)), Lp))
  172. return Ptr;
  173. return GEP->getOperand(InductionOperand);
  174. }
  175. /// If a value has only one user that is a CastInst, return it.
  176. Value *llvm::getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty) {
  177. Value *UniqueCast = nullptr;
  178. for (User *U : Ptr->users()) {
  179. CastInst *CI = dyn_cast<CastInst>(U);
  180. if (CI && CI->getType() == Ty) {
  181. if (!UniqueCast)
  182. UniqueCast = CI;
  183. else
  184. return nullptr;
  185. }
  186. }
  187. return UniqueCast;
  188. }
  189. /// Get the stride of a pointer access in a loop. Looks for symbolic
  190. /// strides "a[i*stride]". Returns the symbolic stride, or null otherwise.
  191. Value *llvm::getStrideFromPointer(Value *Ptr, ScalarEvolution *SE, Loop *Lp) {
  192. auto *PtrTy = dyn_cast<PointerType>(Ptr->getType());
  193. if (!PtrTy || PtrTy->isAggregateType())
  194. return nullptr;
  195. // Try to remove a gep instruction to make the pointer (actually index at this
  196. // point) easier analyzable. If OrigPtr is equal to Ptr we are analyzing the
  197. // pointer, otherwise, we are analyzing the index.
  198. Value *OrigPtr = Ptr;
  199. // The size of the pointer access.
  200. int64_t PtrAccessSize = 1;
  201. Ptr = stripGetElementPtr(Ptr, SE, Lp);
  202. const SCEV *V = SE->getSCEV(Ptr);
  203. if (Ptr != OrigPtr)
  204. // Strip off casts.
  205. while (const SCEVIntegralCastExpr *C = dyn_cast<SCEVIntegralCastExpr>(V))
  206. V = C->getOperand();
  207. const SCEVAddRecExpr *S = dyn_cast<SCEVAddRecExpr>(V);
  208. if (!S)
  209. return nullptr;
  210. V = S->getStepRecurrence(*SE);
  211. if (!V)
  212. return nullptr;
  213. // Strip off the size of access multiplication if we are still analyzing the
  214. // pointer.
  215. if (OrigPtr == Ptr) {
  216. if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(V)) {
  217. if (M->getOperand(0)->getSCEVType() != scConstant)
  218. return nullptr;
  219. const APInt &APStepVal = cast<SCEVConstant>(M->getOperand(0))->getAPInt();
  220. // Huge step value - give up.
  221. if (APStepVal.getBitWidth() > 64)
  222. return nullptr;
  223. int64_t StepVal = APStepVal.getSExtValue();
  224. if (PtrAccessSize != StepVal)
  225. return nullptr;
  226. V = M->getOperand(1);
  227. }
  228. }
  229. // Strip off casts.
  230. Type *StripedOffRecurrenceCast = nullptr;
  231. if (const SCEVIntegralCastExpr *C = dyn_cast<SCEVIntegralCastExpr>(V)) {
  232. StripedOffRecurrenceCast = C->getType();
  233. V = C->getOperand();
  234. }
  235. // Look for the loop invariant symbolic value.
  236. const SCEVUnknown *U = dyn_cast<SCEVUnknown>(V);
  237. if (!U)
  238. return nullptr;
  239. Value *Stride = U->getValue();
  240. if (!Lp->isLoopInvariant(Stride))
  241. return nullptr;
  242. // If we have stripped off the recurrence cast we have to make sure that we
  243. // return the value that is used in this loop so that we can replace it later.
  244. if (StripedOffRecurrenceCast)
  245. Stride = getUniqueCastUse(Stride, Lp, StripedOffRecurrenceCast);
  246. return Stride;
  247. }
  248. /// Given a vector and an element number, see if the scalar value is
  249. /// already around as a register, for example if it were inserted then extracted
  250. /// from the vector.
  251. Value *llvm::findScalarElement(Value *V, unsigned EltNo) {
  252. assert(V->getType()->isVectorTy() && "Not looking at a vector?");
  253. VectorType *VTy = cast<VectorType>(V->getType());
  254. // For fixed-length vector, return undef for out of range access.
  255. if (auto *FVTy = dyn_cast<FixedVectorType>(VTy)) {
  256. unsigned Width = FVTy->getNumElements();
  257. if (EltNo >= Width)
  258. return UndefValue::get(FVTy->getElementType());
  259. }
  260. if (Constant *C = dyn_cast<Constant>(V))
  261. return C->getAggregateElement(EltNo);
  262. if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
  263. // If this is an insert to a variable element, we don't know what it is.
  264. if (!isa<ConstantInt>(III->getOperand(2)))
  265. return nullptr;
  266. unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
  267. // If this is an insert to the element we are looking for, return the
  268. // inserted value.
  269. if (EltNo == IIElt)
  270. return III->getOperand(1);
  271. // Guard against infinite loop on malformed, unreachable IR.
  272. if (III == III->getOperand(0))
  273. return nullptr;
  274. // Otherwise, the insertelement doesn't modify the value, recurse on its
  275. // vector input.
  276. return findScalarElement(III->getOperand(0), EltNo);
  277. }
  278. ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V);
  279. // Restrict the following transformation to fixed-length vector.
  280. if (SVI && isa<FixedVectorType>(SVI->getType())) {
  281. unsigned LHSWidth =
  282. cast<FixedVectorType>(SVI->getOperand(0)->getType())->getNumElements();
  283. int InEl = SVI->getMaskValue(EltNo);
  284. if (InEl < 0)
  285. return UndefValue::get(VTy->getElementType());
  286. if (InEl < (int)LHSWidth)
  287. return findScalarElement(SVI->getOperand(0), InEl);
  288. return findScalarElement(SVI->getOperand(1), InEl - LHSWidth);
  289. }
  290. // Extract a value from a vector add operation with a constant zero.
  291. // TODO: Use getBinOpIdentity() to generalize this.
  292. Value *Val; Constant *C;
  293. if (match(V, m_Add(m_Value(Val), m_Constant(C))))
  294. if (Constant *Elt = C->getAggregateElement(EltNo))
  295. if (Elt->isNullValue())
  296. return findScalarElement(Val, EltNo);
  297. // If the vector is a splat then we can trivially find the scalar element.
  298. if (isa<ScalableVectorType>(VTy))
  299. if (Value *Splat = getSplatValue(V))
  300. if (EltNo < VTy->getElementCount().getKnownMinValue())
  301. return Splat;
  302. // Otherwise, we don't know.
  303. return nullptr;
  304. }
  305. int llvm::getSplatIndex(ArrayRef<int> Mask) {
  306. int SplatIndex = -1;
  307. for (int M : Mask) {
  308. // Ignore invalid (undefined) mask elements.
  309. if (M < 0)
  310. continue;
  311. // There can be only 1 non-negative mask element value if this is a splat.
  312. if (SplatIndex != -1 && SplatIndex != M)
  313. return -1;
  314. // Initialize the splat index to the 1st non-negative mask element.
  315. SplatIndex = M;
  316. }
  317. assert((SplatIndex == -1 || SplatIndex >= 0) && "Negative index?");
  318. return SplatIndex;
  319. }
  320. /// Get splat value if the input is a splat vector or return nullptr.
  321. /// This function is not fully general. It checks only 2 cases:
  322. /// the input value is (1) a splat constant vector or (2) a sequence
  323. /// of instructions that broadcasts a scalar at element 0.
  324. Value *llvm::getSplatValue(const Value *V) {
  325. if (isa<VectorType>(V->getType()))
  326. if (auto *C = dyn_cast<Constant>(V))
  327. return C->getSplatValue();
  328. // shuf (inselt ?, Splat, 0), ?, <0, undef, 0, ...>
  329. Value *Splat;
  330. if (match(V,
  331. m_Shuffle(m_InsertElt(m_Value(), m_Value(Splat), m_ZeroInt()),
  332. m_Value(), m_ZeroMask())))
  333. return Splat;
  334. return nullptr;
  335. }
  336. bool llvm::isSplatValue(const Value *V, int Index, unsigned Depth) {
  337. assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
  338. if (isa<VectorType>(V->getType())) {
  339. if (isa<UndefValue>(V))
  340. return true;
  341. // FIXME: We can allow undefs, but if Index was specified, we may want to
  342. // check that the constant is defined at that index.
  343. if (auto *C = dyn_cast<Constant>(V))
  344. return C->getSplatValue() != nullptr;
  345. }
  346. if (auto *Shuf = dyn_cast<ShuffleVectorInst>(V)) {
  347. // FIXME: We can safely allow undefs here. If Index was specified, we will
  348. // check that the mask elt is defined at the required index.
  349. if (!all_equal(Shuf->getShuffleMask()))
  350. return false;
  351. // Match any index.
  352. if (Index == -1)
  353. return true;
  354. // Match a specific element. The mask should be defined at and match the
  355. // specified index.
  356. return Shuf->getMaskValue(Index) == Index;
  357. }
  358. // The remaining tests are all recursive, so bail out if we hit the limit.
  359. if (Depth++ == MaxAnalysisRecursionDepth)
  360. return false;
  361. // If both operands of a binop are splats, the result is a splat.
  362. Value *X, *Y, *Z;
  363. if (match(V, m_BinOp(m_Value(X), m_Value(Y))))
  364. return isSplatValue(X, Index, Depth) && isSplatValue(Y, Index, Depth);
  365. // If all operands of a select are splats, the result is a splat.
  366. if (match(V, m_Select(m_Value(X), m_Value(Y), m_Value(Z))))
  367. return isSplatValue(X, Index, Depth) && isSplatValue(Y, Index, Depth) &&
  368. isSplatValue(Z, Index, Depth);
  369. // TODO: Add support for unary ops (fneg), casts, intrinsics (overflow ops).
  370. return false;
  371. }
  372. bool llvm::getShuffleDemandedElts(int SrcWidth, ArrayRef<int> Mask,
  373. const APInt &DemandedElts, APInt &DemandedLHS,
  374. APInt &DemandedRHS, bool AllowUndefElts) {
  375. DemandedLHS = DemandedRHS = APInt::getZero(SrcWidth);
  376. // Early out if we don't demand any elements.
  377. if (DemandedElts.isZero())
  378. return true;
  379. // Simple case of a shuffle with zeroinitializer.
  380. if (all_of(Mask, [](int Elt) { return Elt == 0; })) {
  381. DemandedLHS.setBit(0);
  382. return true;
  383. }
  384. for (unsigned I = 0, E = Mask.size(); I != E; ++I) {
  385. int M = Mask[I];
  386. assert((-1 <= M) && (M < (SrcWidth * 2)) &&
  387. "Invalid shuffle mask constant");
  388. if (!DemandedElts[I] || (AllowUndefElts && (M < 0)))
  389. continue;
  390. // For undef elements, we don't know anything about the common state of
  391. // the shuffle result.
  392. if (M < 0)
  393. return false;
  394. if (M < SrcWidth)
  395. DemandedLHS.setBit(M);
  396. else
  397. DemandedRHS.setBit(M - SrcWidth);
  398. }
  399. return true;
  400. }
  401. void llvm::narrowShuffleMaskElts(int Scale, ArrayRef<int> Mask,
  402. SmallVectorImpl<int> &ScaledMask) {
  403. assert(Scale > 0 && "Unexpected scaling factor");
  404. // Fast-path: if no scaling, then it is just a copy.
  405. if (Scale == 1) {
  406. ScaledMask.assign(Mask.begin(), Mask.end());
  407. return;
  408. }
  409. ScaledMask.clear();
  410. for (int MaskElt : Mask) {
  411. if (MaskElt >= 0) {
  412. assert(((uint64_t)Scale * MaskElt + (Scale - 1)) <= INT32_MAX &&
  413. "Overflowed 32-bits");
  414. }
  415. for (int SliceElt = 0; SliceElt != Scale; ++SliceElt)
  416. ScaledMask.push_back(MaskElt < 0 ? MaskElt : Scale * MaskElt + SliceElt);
  417. }
  418. }
  419. bool llvm::widenShuffleMaskElts(int Scale, ArrayRef<int> Mask,
  420. SmallVectorImpl<int> &ScaledMask) {
  421. assert(Scale > 0 && "Unexpected scaling factor");
  422. // Fast-path: if no scaling, then it is just a copy.
  423. if (Scale == 1) {
  424. ScaledMask.assign(Mask.begin(), Mask.end());
  425. return true;
  426. }
  427. // We must map the original elements down evenly to a type with less elements.
  428. int NumElts = Mask.size();
  429. if (NumElts % Scale != 0)
  430. return false;
  431. ScaledMask.clear();
  432. ScaledMask.reserve(NumElts / Scale);
  433. // Step through the input mask by splitting into Scale-sized slices.
  434. do {
  435. ArrayRef<int> MaskSlice = Mask.take_front(Scale);
  436. assert((int)MaskSlice.size() == Scale && "Expected Scale-sized slice.");
  437. // The first element of the slice determines how we evaluate this slice.
  438. int SliceFront = MaskSlice.front();
  439. if (SliceFront < 0) {
  440. // Negative values (undef or other "sentinel" values) must be equal across
  441. // the entire slice.
  442. if (!all_equal(MaskSlice))
  443. return false;
  444. ScaledMask.push_back(SliceFront);
  445. } else {
  446. // A positive mask element must be cleanly divisible.
  447. if (SliceFront % Scale != 0)
  448. return false;
  449. // Elements of the slice must be consecutive.
  450. for (int i = 1; i < Scale; ++i)
  451. if (MaskSlice[i] != SliceFront + i)
  452. return false;
  453. ScaledMask.push_back(SliceFront / Scale);
  454. }
  455. Mask = Mask.drop_front(Scale);
  456. } while (!Mask.empty());
  457. assert((int)ScaledMask.size() * Scale == NumElts && "Unexpected scaled mask");
  458. // All elements of the original mask can be scaled down to map to the elements
  459. // of a mask with wider elements.
  460. return true;
  461. }
  462. void llvm::getShuffleMaskWithWidestElts(ArrayRef<int> Mask,
  463. SmallVectorImpl<int> &ScaledMask) {
  464. std::array<SmallVector<int, 16>, 2> TmpMasks;
  465. SmallVectorImpl<int> *Output = &TmpMasks[0], *Tmp = &TmpMasks[1];
  466. ArrayRef<int> InputMask = Mask;
  467. for (unsigned Scale = 2; Scale <= InputMask.size(); ++Scale) {
  468. while (widenShuffleMaskElts(Scale, InputMask, *Output)) {
  469. InputMask = *Output;
  470. std::swap(Output, Tmp);
  471. }
  472. }
  473. ScaledMask.assign(InputMask.begin(), InputMask.end());
  474. }
  475. void llvm::processShuffleMasks(
  476. ArrayRef<int> Mask, unsigned NumOfSrcRegs, unsigned NumOfDestRegs,
  477. unsigned NumOfUsedRegs, function_ref<void()> NoInputAction,
  478. function_ref<void(ArrayRef<int>, unsigned, unsigned)> SingleInputAction,
  479. function_ref<void(ArrayRef<int>, unsigned, unsigned)> ManyInputsAction) {
  480. SmallVector<SmallVector<SmallVector<int>>> Res(NumOfDestRegs);
  481. // Try to perform better estimation of the permutation.
  482. // 1. Split the source/destination vectors into real registers.
  483. // 2. Do the mask analysis to identify which real registers are
  484. // permuted.
  485. int Sz = Mask.size();
  486. unsigned SzDest = Sz / NumOfDestRegs;
  487. unsigned SzSrc = Sz / NumOfSrcRegs;
  488. for (unsigned I = 0; I < NumOfDestRegs; ++I) {
  489. auto &RegMasks = Res[I];
  490. RegMasks.assign(NumOfSrcRegs, {});
  491. // Check that the values in dest registers are in the one src
  492. // register.
  493. for (unsigned K = 0; K < SzDest; ++K) {
  494. int Idx = I * SzDest + K;
  495. if (Idx == Sz)
  496. break;
  497. if (Mask[Idx] >= Sz || Mask[Idx] == UndefMaskElem)
  498. continue;
  499. int SrcRegIdx = Mask[Idx] / SzSrc;
  500. // Add a cost of PermuteTwoSrc for each new source register permute,
  501. // if we have more than one source registers.
  502. if (RegMasks[SrcRegIdx].empty())
  503. RegMasks[SrcRegIdx].assign(SzDest, UndefMaskElem);
  504. RegMasks[SrcRegIdx][K] = Mask[Idx] % SzSrc;
  505. }
  506. }
  507. // Process split mask.
  508. for (unsigned I = 0; I < NumOfUsedRegs; ++I) {
  509. auto &Dest = Res[I];
  510. int NumSrcRegs =
  511. count_if(Dest, [](ArrayRef<int> Mask) { return !Mask.empty(); });
  512. switch (NumSrcRegs) {
  513. case 0:
  514. // No input vectors were used!
  515. NoInputAction();
  516. break;
  517. case 1: {
  518. // Find the only mask with at least single undef mask elem.
  519. auto *It =
  520. find_if(Dest, [](ArrayRef<int> Mask) { return !Mask.empty(); });
  521. unsigned SrcReg = std::distance(Dest.begin(), It);
  522. SingleInputAction(*It, SrcReg, I);
  523. break;
  524. }
  525. default: {
  526. // The first mask is a permutation of a single register. Since we have >2
  527. // input registers to shuffle, we merge the masks for 2 first registers
  528. // and generate a shuffle of 2 registers rather than the reordering of the
  529. // first register and then shuffle with the second register. Next,
  530. // generate the shuffles of the resulting register + the remaining
  531. // registers from the list.
  532. auto &&CombineMasks = [](MutableArrayRef<int> FirstMask,
  533. ArrayRef<int> SecondMask) {
  534. for (int Idx = 0, VF = FirstMask.size(); Idx < VF; ++Idx) {
  535. if (SecondMask[Idx] != UndefMaskElem) {
  536. assert(FirstMask[Idx] == UndefMaskElem &&
  537. "Expected undefined mask element.");
  538. FirstMask[Idx] = SecondMask[Idx] + VF;
  539. }
  540. }
  541. };
  542. auto &&NormalizeMask = [](MutableArrayRef<int> Mask) {
  543. for (int Idx = 0, VF = Mask.size(); Idx < VF; ++Idx) {
  544. if (Mask[Idx] != UndefMaskElem)
  545. Mask[Idx] = Idx;
  546. }
  547. };
  548. int SecondIdx;
  549. do {
  550. int FirstIdx = -1;
  551. SecondIdx = -1;
  552. MutableArrayRef<int> FirstMask, SecondMask;
  553. for (unsigned I = 0; I < NumOfDestRegs; ++I) {
  554. SmallVectorImpl<int> &RegMask = Dest[I];
  555. if (RegMask.empty())
  556. continue;
  557. if (FirstIdx == SecondIdx) {
  558. FirstIdx = I;
  559. FirstMask = RegMask;
  560. continue;
  561. }
  562. SecondIdx = I;
  563. SecondMask = RegMask;
  564. CombineMasks(FirstMask, SecondMask);
  565. ManyInputsAction(FirstMask, FirstIdx, SecondIdx);
  566. NormalizeMask(FirstMask);
  567. RegMask.clear();
  568. SecondMask = FirstMask;
  569. SecondIdx = FirstIdx;
  570. }
  571. if (FirstIdx != SecondIdx && SecondIdx >= 0) {
  572. CombineMasks(SecondMask, FirstMask);
  573. ManyInputsAction(SecondMask, SecondIdx, FirstIdx);
  574. Dest[FirstIdx].clear();
  575. NormalizeMask(SecondMask);
  576. }
  577. } while (SecondIdx >= 0);
  578. break;
  579. }
  580. }
  581. }
  582. }
  583. MapVector<Instruction *, uint64_t>
  584. llvm::computeMinimumValueSizes(ArrayRef<BasicBlock *> Blocks, DemandedBits &DB,
  585. const TargetTransformInfo *TTI) {
  586. // DemandedBits will give us every value's live-out bits. But we want
  587. // to ensure no extra casts would need to be inserted, so every DAG
  588. // of connected values must have the same minimum bitwidth.
  589. EquivalenceClasses<Value *> ECs;
  590. SmallVector<Value *, 16> Worklist;
  591. SmallPtrSet<Value *, 4> Roots;
  592. SmallPtrSet<Value *, 16> Visited;
  593. DenseMap<Value *, uint64_t> DBits;
  594. SmallPtrSet<Instruction *, 4> InstructionSet;
  595. MapVector<Instruction *, uint64_t> MinBWs;
  596. // Determine the roots. We work bottom-up, from truncs or icmps.
  597. bool SeenExtFromIllegalType = false;
  598. for (auto *BB : Blocks)
  599. for (auto &I : *BB) {
  600. InstructionSet.insert(&I);
  601. if (TTI && (isa<ZExtInst>(&I) || isa<SExtInst>(&I)) &&
  602. !TTI->isTypeLegal(I.getOperand(0)->getType()))
  603. SeenExtFromIllegalType = true;
  604. // Only deal with non-vector integers up to 64-bits wide.
  605. if ((isa<TruncInst>(&I) || isa<ICmpInst>(&I)) &&
  606. !I.getType()->isVectorTy() &&
  607. I.getOperand(0)->getType()->getScalarSizeInBits() <= 64) {
  608. // Don't make work for ourselves. If we know the loaded type is legal,
  609. // don't add it to the worklist.
  610. if (TTI && isa<TruncInst>(&I) && TTI->isTypeLegal(I.getType()))
  611. continue;
  612. Worklist.push_back(&I);
  613. Roots.insert(&I);
  614. }
  615. }
  616. // Early exit.
  617. if (Worklist.empty() || (TTI && !SeenExtFromIllegalType))
  618. return MinBWs;
  619. // Now proceed breadth-first, unioning values together.
  620. while (!Worklist.empty()) {
  621. Value *Val = Worklist.pop_back_val();
  622. Value *Leader = ECs.getOrInsertLeaderValue(Val);
  623. if (!Visited.insert(Val).second)
  624. continue;
  625. // Non-instructions terminate a chain successfully.
  626. if (!isa<Instruction>(Val))
  627. continue;
  628. Instruction *I = cast<Instruction>(Val);
  629. // If we encounter a type that is larger than 64 bits, we can't represent
  630. // it so bail out.
  631. if (DB.getDemandedBits(I).getBitWidth() > 64)
  632. return MapVector<Instruction *, uint64_t>();
  633. uint64_t V = DB.getDemandedBits(I).getZExtValue();
  634. DBits[Leader] |= V;
  635. DBits[I] = V;
  636. // Casts, loads and instructions outside of our range terminate a chain
  637. // successfully.
  638. if (isa<SExtInst>(I) || isa<ZExtInst>(I) || isa<LoadInst>(I) ||
  639. !InstructionSet.count(I))
  640. continue;
  641. // Unsafe casts terminate a chain unsuccessfully. We can't do anything
  642. // useful with bitcasts, ptrtoints or inttoptrs and it'd be unsafe to
  643. // transform anything that relies on them.
  644. if (isa<BitCastInst>(I) || isa<PtrToIntInst>(I) || isa<IntToPtrInst>(I) ||
  645. !I->getType()->isIntegerTy()) {
  646. DBits[Leader] |= ~0ULL;
  647. continue;
  648. }
  649. // We don't modify the types of PHIs. Reductions will already have been
  650. // truncated if possible, and inductions' sizes will have been chosen by
  651. // indvars.
  652. if (isa<PHINode>(I))
  653. continue;
  654. if (DBits[Leader] == ~0ULL)
  655. // All bits demanded, no point continuing.
  656. continue;
  657. for (Value *O : cast<User>(I)->operands()) {
  658. ECs.unionSets(Leader, O);
  659. Worklist.push_back(O);
  660. }
  661. }
  662. // Now we've discovered all values, walk them to see if there are
  663. // any users we didn't see. If there are, we can't optimize that
  664. // chain.
  665. for (auto &I : DBits)
  666. for (auto *U : I.first->users())
  667. if (U->getType()->isIntegerTy() && DBits.count(U) == 0)
  668. DBits[ECs.getOrInsertLeaderValue(I.first)] |= ~0ULL;
  669. for (auto I = ECs.begin(), E = ECs.end(); I != E; ++I) {
  670. uint64_t LeaderDemandedBits = 0;
  671. for (Value *M : llvm::make_range(ECs.member_begin(I), ECs.member_end()))
  672. LeaderDemandedBits |= DBits[M];
  673. uint64_t MinBW = (sizeof(LeaderDemandedBits) * 8) -
  674. llvm::countLeadingZeros(LeaderDemandedBits);
  675. // Round up to a power of 2
  676. if (!isPowerOf2_64((uint64_t)MinBW))
  677. MinBW = NextPowerOf2(MinBW);
  678. // We don't modify the types of PHIs. Reductions will already have been
  679. // truncated if possible, and inductions' sizes will have been chosen by
  680. // indvars.
  681. // If we are required to shrink a PHI, abandon this entire equivalence class.
  682. bool Abort = false;
  683. for (Value *M : llvm::make_range(ECs.member_begin(I), ECs.member_end()))
  684. if (isa<PHINode>(M) && MinBW < M->getType()->getScalarSizeInBits()) {
  685. Abort = true;
  686. break;
  687. }
  688. if (Abort)
  689. continue;
  690. for (Value *M : llvm::make_range(ECs.member_begin(I), ECs.member_end())) {
  691. if (!isa<Instruction>(M))
  692. continue;
  693. Type *Ty = M->getType();
  694. if (Roots.count(M))
  695. Ty = cast<Instruction>(M)->getOperand(0)->getType();
  696. if (MinBW < Ty->getScalarSizeInBits())
  697. MinBWs[cast<Instruction>(M)] = MinBW;
  698. }
  699. }
  700. return MinBWs;
  701. }
  702. /// Add all access groups in @p AccGroups to @p List.
  703. template <typename ListT>
  704. static void addToAccessGroupList(ListT &List, MDNode *AccGroups) {
  705. // Interpret an access group as a list containing itself.
  706. if (AccGroups->getNumOperands() == 0) {
  707. assert(isValidAsAccessGroup(AccGroups) && "Node must be an access group");
  708. List.insert(AccGroups);
  709. return;
  710. }
  711. for (const auto &AccGroupListOp : AccGroups->operands()) {
  712. auto *Item = cast<MDNode>(AccGroupListOp.get());
  713. assert(isValidAsAccessGroup(Item) && "List item must be an access group");
  714. List.insert(Item);
  715. }
  716. }
  717. MDNode *llvm::uniteAccessGroups(MDNode *AccGroups1, MDNode *AccGroups2) {
  718. if (!AccGroups1)
  719. return AccGroups2;
  720. if (!AccGroups2)
  721. return AccGroups1;
  722. if (AccGroups1 == AccGroups2)
  723. return AccGroups1;
  724. SmallSetVector<Metadata *, 4> Union;
  725. addToAccessGroupList(Union, AccGroups1);
  726. addToAccessGroupList(Union, AccGroups2);
  727. if (Union.size() == 0)
  728. return nullptr;
  729. if (Union.size() == 1)
  730. return cast<MDNode>(Union.front());
  731. LLVMContext &Ctx = AccGroups1->getContext();
  732. return MDNode::get(Ctx, Union.getArrayRef());
  733. }
  734. MDNode *llvm::intersectAccessGroups(const Instruction *Inst1,
  735. const Instruction *Inst2) {
  736. bool MayAccessMem1 = Inst1->mayReadOrWriteMemory();
  737. bool MayAccessMem2 = Inst2->mayReadOrWriteMemory();
  738. if (!MayAccessMem1 && !MayAccessMem2)
  739. return nullptr;
  740. if (!MayAccessMem1)
  741. return Inst2->getMetadata(LLVMContext::MD_access_group);
  742. if (!MayAccessMem2)
  743. return Inst1->getMetadata(LLVMContext::MD_access_group);
  744. MDNode *MD1 = Inst1->getMetadata(LLVMContext::MD_access_group);
  745. MDNode *MD2 = Inst2->getMetadata(LLVMContext::MD_access_group);
  746. if (!MD1 || !MD2)
  747. return nullptr;
  748. if (MD1 == MD2)
  749. return MD1;
  750. // Use set for scalable 'contains' check.
  751. SmallPtrSet<Metadata *, 4> AccGroupSet2;
  752. addToAccessGroupList(AccGroupSet2, MD2);
  753. SmallVector<Metadata *, 4> Intersection;
  754. if (MD1->getNumOperands() == 0) {
  755. assert(isValidAsAccessGroup(MD1) && "Node must be an access group");
  756. if (AccGroupSet2.count(MD1))
  757. Intersection.push_back(MD1);
  758. } else {
  759. for (const MDOperand &Node : MD1->operands()) {
  760. auto *Item = cast<MDNode>(Node.get());
  761. assert(isValidAsAccessGroup(Item) && "List item must be an access group");
  762. if (AccGroupSet2.count(Item))
  763. Intersection.push_back(Item);
  764. }
  765. }
  766. if (Intersection.size() == 0)
  767. return nullptr;
  768. if (Intersection.size() == 1)
  769. return cast<MDNode>(Intersection.front());
  770. LLVMContext &Ctx = Inst1->getContext();
  771. return MDNode::get(Ctx, Intersection);
  772. }
  773. /// \returns \p I after propagating metadata from \p VL.
  774. Instruction *llvm::propagateMetadata(Instruction *Inst, ArrayRef<Value *> VL) {
  775. if (VL.empty())
  776. return Inst;
  777. Instruction *I0 = cast<Instruction>(VL[0]);
  778. SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
  779. I0->getAllMetadataOtherThanDebugLoc(Metadata);
  780. for (auto Kind : {LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
  781. LLVMContext::MD_noalias, LLVMContext::MD_fpmath,
  782. LLVMContext::MD_nontemporal, LLVMContext::MD_invariant_load,
  783. LLVMContext::MD_access_group}) {
  784. MDNode *MD = I0->getMetadata(Kind);
  785. for (int J = 1, E = VL.size(); MD && J != E; ++J) {
  786. const Instruction *IJ = cast<Instruction>(VL[J]);
  787. MDNode *IMD = IJ->getMetadata(Kind);
  788. switch (Kind) {
  789. case LLVMContext::MD_tbaa:
  790. MD = MDNode::getMostGenericTBAA(MD, IMD);
  791. break;
  792. case LLVMContext::MD_alias_scope:
  793. MD = MDNode::getMostGenericAliasScope(MD, IMD);
  794. break;
  795. case LLVMContext::MD_fpmath:
  796. MD = MDNode::getMostGenericFPMath(MD, IMD);
  797. break;
  798. case LLVMContext::MD_noalias:
  799. case LLVMContext::MD_nontemporal:
  800. case LLVMContext::MD_invariant_load:
  801. MD = MDNode::intersect(MD, IMD);
  802. break;
  803. case LLVMContext::MD_access_group:
  804. MD = intersectAccessGroups(Inst, IJ);
  805. break;
  806. default:
  807. llvm_unreachable("unhandled metadata");
  808. }
  809. }
  810. Inst->setMetadata(Kind, MD);
  811. }
  812. return Inst;
  813. }
  814. Constant *
  815. llvm::createBitMaskForGaps(IRBuilderBase &Builder, unsigned VF,
  816. const InterleaveGroup<Instruction> &Group) {
  817. // All 1's means mask is not needed.
  818. if (Group.getNumMembers() == Group.getFactor())
  819. return nullptr;
  820. // TODO: support reversed access.
  821. assert(!Group.isReverse() && "Reversed group not supported.");
  822. SmallVector<Constant *, 16> Mask;
  823. for (unsigned i = 0; i < VF; i++)
  824. for (unsigned j = 0; j < Group.getFactor(); ++j) {
  825. unsigned HasMember = Group.getMember(j) ? 1 : 0;
  826. Mask.push_back(Builder.getInt1(HasMember));
  827. }
  828. return ConstantVector::get(Mask);
  829. }
  830. llvm::SmallVector<int, 16>
  831. llvm::createReplicatedMask(unsigned ReplicationFactor, unsigned VF) {
  832. SmallVector<int, 16> MaskVec;
  833. for (unsigned i = 0; i < VF; i++)
  834. for (unsigned j = 0; j < ReplicationFactor; j++)
  835. MaskVec.push_back(i);
  836. return MaskVec;
  837. }
  838. llvm::SmallVector<int, 16> llvm::createInterleaveMask(unsigned VF,
  839. unsigned NumVecs) {
  840. SmallVector<int, 16> Mask;
  841. for (unsigned i = 0; i < VF; i++)
  842. for (unsigned j = 0; j < NumVecs; j++)
  843. Mask.push_back(j * VF + i);
  844. return Mask;
  845. }
  846. llvm::SmallVector<int, 16>
  847. llvm::createStrideMask(unsigned Start, unsigned Stride, unsigned VF) {
  848. SmallVector<int, 16> Mask;
  849. for (unsigned i = 0; i < VF; i++)
  850. Mask.push_back(Start + i * Stride);
  851. return Mask;
  852. }
  853. llvm::SmallVector<int, 16> llvm::createSequentialMask(unsigned Start,
  854. unsigned NumInts,
  855. unsigned NumUndefs) {
  856. SmallVector<int, 16> Mask;
  857. for (unsigned i = 0; i < NumInts; i++)
  858. Mask.push_back(Start + i);
  859. for (unsigned i = 0; i < NumUndefs; i++)
  860. Mask.push_back(-1);
  861. return Mask;
  862. }
  863. llvm::SmallVector<int, 16> llvm::createUnaryMask(ArrayRef<int> Mask,
  864. unsigned NumElts) {
  865. // Avoid casts in the loop and make sure we have a reasonable number.
  866. int NumEltsSigned = NumElts;
  867. assert(NumEltsSigned > 0 && "Expected smaller or non-zero element count");
  868. // If the mask chooses an element from operand 1, reduce it to choose from the
  869. // corresponding element of operand 0. Undef mask elements are unchanged.
  870. SmallVector<int, 16> UnaryMask;
  871. for (int MaskElt : Mask) {
  872. assert((MaskElt < NumEltsSigned * 2) && "Expected valid shuffle mask");
  873. int UnaryElt = MaskElt >= NumEltsSigned ? MaskElt - NumEltsSigned : MaskElt;
  874. UnaryMask.push_back(UnaryElt);
  875. }
  876. return UnaryMask;
  877. }
  878. /// A helper function for concatenating vectors. This function concatenates two
  879. /// vectors having the same element type. If the second vector has fewer
  880. /// elements than the first, it is padded with undefs.
  881. static Value *concatenateTwoVectors(IRBuilderBase &Builder, Value *V1,
  882. Value *V2) {
  883. VectorType *VecTy1 = dyn_cast<VectorType>(V1->getType());
  884. VectorType *VecTy2 = dyn_cast<VectorType>(V2->getType());
  885. assert(VecTy1 && VecTy2 &&
  886. VecTy1->getScalarType() == VecTy2->getScalarType() &&
  887. "Expect two vectors with the same element type");
  888. unsigned NumElts1 = cast<FixedVectorType>(VecTy1)->getNumElements();
  889. unsigned NumElts2 = cast<FixedVectorType>(VecTy2)->getNumElements();
  890. assert(NumElts1 >= NumElts2 && "Unexpect the first vector has less elements");
  891. if (NumElts1 > NumElts2) {
  892. // Extend with UNDEFs.
  893. V2 = Builder.CreateShuffleVector(
  894. V2, createSequentialMask(0, NumElts2, NumElts1 - NumElts2));
  895. }
  896. return Builder.CreateShuffleVector(
  897. V1, V2, createSequentialMask(0, NumElts1 + NumElts2, 0));
  898. }
  899. Value *llvm::concatenateVectors(IRBuilderBase &Builder,
  900. ArrayRef<Value *> Vecs) {
  901. unsigned NumVecs = Vecs.size();
  902. assert(NumVecs > 1 && "Should be at least two vectors");
  903. SmallVector<Value *, 8> ResList;
  904. ResList.append(Vecs.begin(), Vecs.end());
  905. do {
  906. SmallVector<Value *, 8> TmpList;
  907. for (unsigned i = 0; i < NumVecs - 1; i += 2) {
  908. Value *V0 = ResList[i], *V1 = ResList[i + 1];
  909. assert((V0->getType() == V1->getType() || i == NumVecs - 2) &&
  910. "Only the last vector may have a different type");
  911. TmpList.push_back(concatenateTwoVectors(Builder, V0, V1));
  912. }
  913. // Push the last vector if the total number of vectors is odd.
  914. if (NumVecs % 2 != 0)
  915. TmpList.push_back(ResList[NumVecs - 1]);
  916. ResList = TmpList;
  917. NumVecs = ResList.size();
  918. } while (NumVecs > 1);
  919. return ResList[0];
  920. }
  921. bool llvm::maskIsAllZeroOrUndef(Value *Mask) {
  922. assert(isa<VectorType>(Mask->getType()) &&
  923. isa<IntegerType>(Mask->getType()->getScalarType()) &&
  924. cast<IntegerType>(Mask->getType()->getScalarType())->getBitWidth() ==
  925. 1 &&
  926. "Mask must be a vector of i1");
  927. auto *ConstMask = dyn_cast<Constant>(Mask);
  928. if (!ConstMask)
  929. return false;
  930. if (ConstMask->isNullValue() || isa<UndefValue>(ConstMask))
  931. return true;
  932. if (isa<ScalableVectorType>(ConstMask->getType()))
  933. return false;
  934. for (unsigned
  935. I = 0,
  936. E = cast<FixedVectorType>(ConstMask->getType())->getNumElements();
  937. I != E; ++I) {
  938. if (auto *MaskElt = ConstMask->getAggregateElement(I))
  939. if (MaskElt->isNullValue() || isa<UndefValue>(MaskElt))
  940. continue;
  941. return false;
  942. }
  943. return true;
  944. }
  945. bool llvm::maskIsAllOneOrUndef(Value *Mask) {
  946. assert(isa<VectorType>(Mask->getType()) &&
  947. isa<IntegerType>(Mask->getType()->getScalarType()) &&
  948. cast<IntegerType>(Mask->getType()->getScalarType())->getBitWidth() ==
  949. 1 &&
  950. "Mask must be a vector of i1");
  951. auto *ConstMask = dyn_cast<Constant>(Mask);
  952. if (!ConstMask)
  953. return false;
  954. if (ConstMask->isAllOnesValue() || isa<UndefValue>(ConstMask))
  955. return true;
  956. if (isa<ScalableVectorType>(ConstMask->getType()))
  957. return false;
  958. for (unsigned
  959. I = 0,
  960. E = cast<FixedVectorType>(ConstMask->getType())->getNumElements();
  961. I != E; ++I) {
  962. if (auto *MaskElt = ConstMask->getAggregateElement(I))
  963. if (MaskElt->isAllOnesValue() || isa<UndefValue>(MaskElt))
  964. continue;
  965. return false;
  966. }
  967. return true;
  968. }
  969. /// TODO: This is a lot like known bits, but for
  970. /// vectors. Is there something we can common this with?
  971. APInt llvm::possiblyDemandedEltsInMask(Value *Mask) {
  972. assert(isa<FixedVectorType>(Mask->getType()) &&
  973. isa<IntegerType>(Mask->getType()->getScalarType()) &&
  974. cast<IntegerType>(Mask->getType()->getScalarType())->getBitWidth() ==
  975. 1 &&
  976. "Mask must be a fixed width vector of i1");
  977. const unsigned VWidth =
  978. cast<FixedVectorType>(Mask->getType())->getNumElements();
  979. APInt DemandedElts = APInt::getAllOnes(VWidth);
  980. if (auto *CV = dyn_cast<ConstantVector>(Mask))
  981. for (unsigned i = 0; i < VWidth; i++)
  982. if (CV->getAggregateElement(i)->isNullValue())
  983. DemandedElts.clearBit(i);
  984. return DemandedElts;
  985. }
  986. bool InterleavedAccessInfo::isStrided(int Stride) {
  987. unsigned Factor = std::abs(Stride);
  988. return Factor >= 2 && Factor <= MaxInterleaveGroupFactor;
  989. }
  990. void InterleavedAccessInfo::collectConstStrideAccesses(
  991. MapVector<Instruction *, StrideDescriptor> &AccessStrideInfo,
  992. const ValueToValueMap &Strides) {
  993. auto &DL = TheLoop->getHeader()->getModule()->getDataLayout();
  994. // Since it's desired that the load/store instructions be maintained in
  995. // "program order" for the interleaved access analysis, we have to visit the
  996. // blocks in the loop in reverse postorder (i.e., in a topological order).
  997. // Such an ordering will ensure that any load/store that may be executed
  998. // before a second load/store will precede the second load/store in
  999. // AccessStrideInfo.
  1000. LoopBlocksDFS DFS(TheLoop);
  1001. DFS.perform(LI);
  1002. for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO()))
  1003. for (auto &I : *BB) {
  1004. Value *Ptr = getLoadStorePointerOperand(&I);
  1005. if (!Ptr)
  1006. continue;
  1007. Type *ElementTy = getLoadStoreType(&I);
  1008. // Currently, codegen doesn't support cases where the type size doesn't
  1009. // match the alloc size. Skip them for now.
  1010. uint64_t Size = DL.getTypeAllocSize(ElementTy);
  1011. if (Size * 8 != DL.getTypeSizeInBits(ElementTy))
  1012. continue;
  1013. // We don't check wrapping here because we don't know yet if Ptr will be
  1014. // part of a full group or a group with gaps. Checking wrapping for all
  1015. // pointers (even those that end up in groups with no gaps) will be overly
  1016. // conservative. For full groups, wrapping should be ok since if we would
  1017. // wrap around the address space we would do a memory access at nullptr
  1018. // even without the transformation. The wrapping checks are therefore
  1019. // deferred until after we've formed the interleaved groups.
  1020. int64_t Stride =
  1021. getPtrStride(PSE, ElementTy, Ptr, TheLoop, Strides,
  1022. /*Assume=*/true, /*ShouldCheckWrap=*/false).value_or(0);
  1023. const SCEV *Scev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
  1024. AccessStrideInfo[&I] = StrideDescriptor(Stride, Scev, Size,
  1025. getLoadStoreAlignment(&I));
  1026. }
  1027. }
  1028. // Analyze interleaved accesses and collect them into interleaved load and
  1029. // store groups.
  1030. //
  1031. // When generating code for an interleaved load group, we effectively hoist all
  1032. // loads in the group to the location of the first load in program order. When
  1033. // generating code for an interleaved store group, we sink all stores to the
  1034. // location of the last store. This code motion can change the order of load
  1035. // and store instructions and may break dependences.
  1036. //
  1037. // The code generation strategy mentioned above ensures that we won't violate
  1038. // any write-after-read (WAR) dependences.
  1039. //
  1040. // E.g., for the WAR dependence: a = A[i]; // (1)
  1041. // A[i] = b; // (2)
  1042. //
  1043. // The store group of (2) is always inserted at or below (2), and the load
  1044. // group of (1) is always inserted at or above (1). Thus, the instructions will
  1045. // never be reordered. All other dependences are checked to ensure the
  1046. // correctness of the instruction reordering.
  1047. //
  1048. // The algorithm visits all memory accesses in the loop in bottom-up program
  1049. // order. Program order is established by traversing the blocks in the loop in
  1050. // reverse postorder when collecting the accesses.
  1051. //
  1052. // We visit the memory accesses in bottom-up order because it can simplify the
  1053. // construction of store groups in the presence of write-after-write (WAW)
  1054. // dependences.
  1055. //
  1056. // E.g., for the WAW dependence: A[i] = a; // (1)
  1057. // A[i] = b; // (2)
  1058. // A[i + 1] = c; // (3)
  1059. //
  1060. // We will first create a store group with (3) and (2). (1) can't be added to
  1061. // this group because it and (2) are dependent. However, (1) can be grouped
  1062. // with other accesses that may precede it in program order. Note that a
  1063. // bottom-up order does not imply that WAW dependences should not be checked.
  1064. void InterleavedAccessInfo::analyzeInterleaving(
  1065. bool EnablePredicatedInterleavedMemAccesses) {
  1066. LLVM_DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n");
  1067. const ValueToValueMap &Strides = LAI->getSymbolicStrides();
  1068. // Holds all accesses with a constant stride.
  1069. MapVector<Instruction *, StrideDescriptor> AccessStrideInfo;
  1070. collectConstStrideAccesses(AccessStrideInfo, Strides);
  1071. if (AccessStrideInfo.empty())
  1072. return;
  1073. // Collect the dependences in the loop.
  1074. collectDependences();
  1075. // Holds all interleaved store groups temporarily.
  1076. SmallSetVector<InterleaveGroup<Instruction> *, 4> StoreGroups;
  1077. // Holds all interleaved load groups temporarily.
  1078. SmallSetVector<InterleaveGroup<Instruction> *, 4> LoadGroups;
  1079. // Search in bottom-up program order for pairs of accesses (A and B) that can
  1080. // form interleaved load or store groups. In the algorithm below, access A
  1081. // precedes access B in program order. We initialize a group for B in the
  1082. // outer loop of the algorithm, and then in the inner loop, we attempt to
  1083. // insert each A into B's group if:
  1084. //
  1085. // 1. A and B have the same stride,
  1086. // 2. A and B have the same memory object size, and
  1087. // 3. A belongs in B's group according to its distance from B.
  1088. //
  1089. // Special care is taken to ensure group formation will not break any
  1090. // dependences.
  1091. for (auto BI = AccessStrideInfo.rbegin(), E = AccessStrideInfo.rend();
  1092. BI != E; ++BI) {
  1093. Instruction *B = BI->first;
  1094. StrideDescriptor DesB = BI->second;
  1095. // Initialize a group for B if it has an allowable stride. Even if we don't
  1096. // create a group for B, we continue with the bottom-up algorithm to ensure
  1097. // we don't break any of B's dependences.
  1098. InterleaveGroup<Instruction> *Group = nullptr;
  1099. if (isStrided(DesB.Stride) &&
  1100. (!isPredicated(B->getParent()) || EnablePredicatedInterleavedMemAccesses)) {
  1101. Group = getInterleaveGroup(B);
  1102. if (!Group) {
  1103. LLVM_DEBUG(dbgs() << "LV: Creating an interleave group with:" << *B
  1104. << '\n');
  1105. Group = createInterleaveGroup(B, DesB.Stride, DesB.Alignment);
  1106. }
  1107. if (B->mayWriteToMemory())
  1108. StoreGroups.insert(Group);
  1109. else
  1110. LoadGroups.insert(Group);
  1111. }
  1112. for (auto AI = std::next(BI); AI != E; ++AI) {
  1113. Instruction *A = AI->first;
  1114. StrideDescriptor DesA = AI->second;
  1115. // Our code motion strategy implies that we can't have dependences
  1116. // between accesses in an interleaved group and other accesses located
  1117. // between the first and last member of the group. Note that this also
  1118. // means that a group can't have more than one member at a given offset.
  1119. // The accesses in a group can have dependences with other accesses, but
  1120. // we must ensure we don't extend the boundaries of the group such that
  1121. // we encompass those dependent accesses.
  1122. //
  1123. // For example, assume we have the sequence of accesses shown below in a
  1124. // stride-2 loop:
  1125. //
  1126. // (1, 2) is a group | A[i] = a; // (1)
  1127. // | A[i-1] = b; // (2) |
  1128. // A[i-3] = c; // (3)
  1129. // A[i] = d; // (4) | (2, 4) is not a group
  1130. //
  1131. // Because accesses (2) and (3) are dependent, we can group (2) with (1)
  1132. // but not with (4). If we did, the dependent access (3) would be within
  1133. // the boundaries of the (2, 4) group.
  1134. if (!canReorderMemAccessesForInterleavedGroups(&*AI, &*BI)) {
  1135. // If a dependence exists and A is already in a group, we know that A
  1136. // must be a store since A precedes B and WAR dependences are allowed.
  1137. // Thus, A would be sunk below B. We release A's group to prevent this
  1138. // illegal code motion. A will then be free to form another group with
  1139. // instructions that precede it.
  1140. if (isInterleaved(A)) {
  1141. InterleaveGroup<Instruction> *StoreGroup = getInterleaveGroup(A);
  1142. LLVM_DEBUG(dbgs() << "LV: Invalidated store group due to "
  1143. "dependence between " << *A << " and "<< *B << '\n');
  1144. StoreGroups.remove(StoreGroup);
  1145. releaseGroup(StoreGroup);
  1146. }
  1147. // If a dependence exists and A is not already in a group (or it was
  1148. // and we just released it), B might be hoisted above A (if B is a
  1149. // load) or another store might be sunk below A (if B is a store). In
  1150. // either case, we can't add additional instructions to B's group. B
  1151. // will only form a group with instructions that it precedes.
  1152. break;
  1153. }
  1154. // At this point, we've checked for illegal code motion. If either A or B
  1155. // isn't strided, there's nothing left to do.
  1156. if (!isStrided(DesA.Stride) || !isStrided(DesB.Stride))
  1157. continue;
  1158. // Ignore A if it's already in a group or isn't the same kind of memory
  1159. // operation as B.
  1160. // Note that mayReadFromMemory() isn't mutually exclusive to
  1161. // mayWriteToMemory in the case of atomic loads. We shouldn't see those
  1162. // here, canVectorizeMemory() should have returned false - except for the
  1163. // case we asked for optimization remarks.
  1164. if (isInterleaved(A) ||
  1165. (A->mayReadFromMemory() != B->mayReadFromMemory()) ||
  1166. (A->mayWriteToMemory() != B->mayWriteToMemory()))
  1167. continue;
  1168. // Check rules 1 and 2. Ignore A if its stride or size is different from
  1169. // that of B.
  1170. if (DesA.Stride != DesB.Stride || DesA.Size != DesB.Size)
  1171. continue;
  1172. // Ignore A if the memory object of A and B don't belong to the same
  1173. // address space
  1174. if (getLoadStoreAddressSpace(A) != getLoadStoreAddressSpace(B))
  1175. continue;
  1176. // Calculate the distance from A to B.
  1177. const SCEVConstant *DistToB = dyn_cast<SCEVConstant>(
  1178. PSE.getSE()->getMinusSCEV(DesA.Scev, DesB.Scev));
  1179. if (!DistToB)
  1180. continue;
  1181. int64_t DistanceToB = DistToB->getAPInt().getSExtValue();
  1182. // Check rule 3. Ignore A if its distance to B is not a multiple of the
  1183. // size.
  1184. if (DistanceToB % static_cast<int64_t>(DesB.Size))
  1185. continue;
  1186. // All members of a predicated interleave-group must have the same predicate,
  1187. // and currently must reside in the same BB.
  1188. BasicBlock *BlockA = A->getParent();
  1189. BasicBlock *BlockB = B->getParent();
  1190. if ((isPredicated(BlockA) || isPredicated(BlockB)) &&
  1191. (!EnablePredicatedInterleavedMemAccesses || BlockA != BlockB))
  1192. continue;
  1193. // The index of A is the index of B plus A's distance to B in multiples
  1194. // of the size.
  1195. int IndexA =
  1196. Group->getIndex(B) + DistanceToB / static_cast<int64_t>(DesB.Size);
  1197. // Try to insert A into B's group.
  1198. if (Group->insertMember(A, IndexA, DesA.Alignment)) {
  1199. LLVM_DEBUG(dbgs() << "LV: Inserted:" << *A << '\n'
  1200. << " into the interleave group with" << *B
  1201. << '\n');
  1202. InterleaveGroupMap[A] = Group;
  1203. // Set the first load in program order as the insert position.
  1204. if (A->mayReadFromMemory())
  1205. Group->setInsertPos(A);
  1206. }
  1207. } // Iteration over A accesses.
  1208. } // Iteration over B accesses.
  1209. auto InvalidateGroupIfMemberMayWrap = [&](InterleaveGroup<Instruction> *Group,
  1210. int Index,
  1211. std::string FirstOrLast) -> bool {
  1212. Instruction *Member = Group->getMember(Index);
  1213. assert(Member && "Group member does not exist");
  1214. Value *MemberPtr = getLoadStorePointerOperand(Member);
  1215. Type *AccessTy = getLoadStoreType(Member);
  1216. if (getPtrStride(PSE, AccessTy, MemberPtr, TheLoop, Strides,
  1217. /*Assume=*/false, /*ShouldCheckWrap=*/true).value_or(0))
  1218. return false;
  1219. LLVM_DEBUG(dbgs() << "LV: Invalidate candidate interleaved group due to "
  1220. << FirstOrLast
  1221. << " group member potentially pointer-wrapping.\n");
  1222. releaseGroup(Group);
  1223. return true;
  1224. };
  1225. // Remove interleaved groups with gaps whose memory
  1226. // accesses may wrap around. We have to revisit the getPtrStride analysis,
  1227. // this time with ShouldCheckWrap=true, since collectConstStrideAccesses does
  1228. // not check wrapping (see documentation there).
  1229. // FORNOW we use Assume=false;
  1230. // TODO: Change to Assume=true but making sure we don't exceed the threshold
  1231. // of runtime SCEV assumptions checks (thereby potentially failing to
  1232. // vectorize altogether).
  1233. // Additional optional optimizations:
  1234. // TODO: If we are peeling the loop and we know that the first pointer doesn't
  1235. // wrap then we can deduce that all pointers in the group don't wrap.
  1236. // This means that we can forcefully peel the loop in order to only have to
  1237. // check the first pointer for no-wrap. When we'll change to use Assume=true
  1238. // we'll only need at most one runtime check per interleaved group.
  1239. for (auto *Group : LoadGroups) {
  1240. // Case 1: A full group. Can Skip the checks; For full groups, if the wide
  1241. // load would wrap around the address space we would do a memory access at
  1242. // nullptr even without the transformation.
  1243. if (Group->getNumMembers() == Group->getFactor())
  1244. continue;
  1245. // Case 2: If first and last members of the group don't wrap this implies
  1246. // that all the pointers in the group don't wrap.
  1247. // So we check only group member 0 (which is always guaranteed to exist),
  1248. // and group member Factor - 1; If the latter doesn't exist we rely on
  1249. // peeling (if it is a non-reversed accsess -- see Case 3).
  1250. if (InvalidateGroupIfMemberMayWrap(Group, 0, std::string("first")))
  1251. continue;
  1252. if (Group->getMember(Group->getFactor() - 1))
  1253. InvalidateGroupIfMemberMayWrap(Group, Group->getFactor() - 1,
  1254. std::string("last"));
  1255. else {
  1256. // Case 3: A non-reversed interleaved load group with gaps: We need
  1257. // to execute at least one scalar epilogue iteration. This will ensure
  1258. // we don't speculatively access memory out-of-bounds. We only need
  1259. // to look for a member at index factor - 1, since every group must have
  1260. // a member at index zero.
  1261. if (Group->isReverse()) {
  1262. LLVM_DEBUG(
  1263. dbgs() << "LV: Invalidate candidate interleaved group due to "
  1264. "a reverse access with gaps.\n");
  1265. releaseGroup(Group);
  1266. continue;
  1267. }
  1268. LLVM_DEBUG(
  1269. dbgs() << "LV: Interleaved group requires epilogue iteration.\n");
  1270. RequiresScalarEpilogue = true;
  1271. }
  1272. }
  1273. for (auto *Group : StoreGroups) {
  1274. // Case 1: A full group. Can Skip the checks; For full groups, if the wide
  1275. // store would wrap around the address space we would do a memory access at
  1276. // nullptr even without the transformation.
  1277. if (Group->getNumMembers() == Group->getFactor())
  1278. continue;
  1279. // Interleave-store-group with gaps is implemented using masked wide store.
  1280. // Remove interleaved store groups with gaps if
  1281. // masked-interleaved-accesses are not enabled by the target.
  1282. if (!EnablePredicatedInterleavedMemAccesses) {
  1283. LLVM_DEBUG(
  1284. dbgs() << "LV: Invalidate candidate interleaved store group due "
  1285. "to gaps.\n");
  1286. releaseGroup(Group);
  1287. continue;
  1288. }
  1289. // Case 2: If first and last members of the group don't wrap this implies
  1290. // that all the pointers in the group don't wrap.
  1291. // So we check only group member 0 (which is always guaranteed to exist),
  1292. // and the last group member. Case 3 (scalar epilog) is not relevant for
  1293. // stores with gaps, which are implemented with masked-store (rather than
  1294. // speculative access, as in loads).
  1295. if (InvalidateGroupIfMemberMayWrap(Group, 0, std::string("first")))
  1296. continue;
  1297. for (int Index = Group->getFactor() - 1; Index > 0; Index--)
  1298. if (Group->getMember(Index)) {
  1299. InvalidateGroupIfMemberMayWrap(Group, Index, std::string("last"));
  1300. break;
  1301. }
  1302. }
  1303. }
  1304. void InterleavedAccessInfo::invalidateGroupsRequiringScalarEpilogue() {
  1305. // If no group had triggered the requirement to create an epilogue loop,
  1306. // there is nothing to do.
  1307. if (!requiresScalarEpilogue())
  1308. return;
  1309. bool ReleasedGroup = false;
  1310. // Release groups requiring scalar epilogues. Note that this also removes them
  1311. // from InterleaveGroups.
  1312. for (auto *Group : make_early_inc_range(InterleaveGroups)) {
  1313. if (!Group->requiresScalarEpilogue())
  1314. continue;
  1315. LLVM_DEBUG(
  1316. dbgs()
  1317. << "LV: Invalidate candidate interleaved group due to gaps that "
  1318. "require a scalar epilogue (not allowed under optsize) and cannot "
  1319. "be masked (not enabled). \n");
  1320. releaseGroup(Group);
  1321. ReleasedGroup = true;
  1322. }
  1323. assert(ReleasedGroup && "At least one group must be invalidated, as a "
  1324. "scalar epilogue was required");
  1325. (void)ReleasedGroup;
  1326. RequiresScalarEpilogue = false;
  1327. }
  1328. template <typename InstT>
  1329. void InterleaveGroup<InstT>::addMetadata(InstT *NewInst) const {
  1330. llvm_unreachable("addMetadata can only be used for Instruction");
  1331. }
  1332. namespace llvm {
  1333. template <>
  1334. void InterleaveGroup<Instruction>::addMetadata(Instruction *NewInst) const {
  1335. SmallVector<Value *, 4> VL;
  1336. std::transform(Members.begin(), Members.end(), std::back_inserter(VL),
  1337. [](std::pair<int, Instruction *> p) { return p.second; });
  1338. propagateMetadata(NewInst, VL);
  1339. }
  1340. }
  1341. std::string VFABI::mangleTLIVectorName(StringRef VectorName,
  1342. StringRef ScalarName, unsigned numArgs,
  1343. ElementCount VF) {
  1344. SmallString<256> Buffer;
  1345. llvm::raw_svector_ostream Out(Buffer);
  1346. Out << "_ZGV" << VFABI::_LLVM_ << "N";
  1347. if (VF.isScalable())
  1348. Out << 'x';
  1349. else
  1350. Out << VF.getFixedValue();
  1351. for (unsigned I = 0; I < numArgs; ++I)
  1352. Out << "v";
  1353. Out << "_" << ScalarName << "(" << VectorName << ")";
  1354. return std::string(Out.str());
  1355. }
  1356. void VFABI::getVectorVariantNames(
  1357. const CallInst &CI, SmallVectorImpl<std::string> &VariantMappings) {
  1358. const StringRef S = CI.getFnAttr(VFABI::MappingsAttrName).getValueAsString();
  1359. if (S.empty())
  1360. return;
  1361. SmallVector<StringRef, 8> ListAttr;
  1362. S.split(ListAttr, ",");
  1363. for (const auto &S : SetVector<StringRef>(ListAttr.begin(), ListAttr.end())) {
  1364. #ifndef NDEBUG
  1365. LLVM_DEBUG(dbgs() << "VFABI: adding mapping '" << S << "'\n");
  1366. std::optional<VFInfo> Info =
  1367. VFABI::tryDemangleForVFABI(S, *(CI.getModule()));
  1368. assert(Info && "Invalid name for a VFABI variant.");
  1369. assert(CI.getModule()->getFunction(Info->VectorName) &&
  1370. "Vector function is missing.");
  1371. #endif
  1372. VariantMappings.push_back(std::string(S));
  1373. }
  1374. }
  1375. bool VFShape::hasValidParameterList() const {
  1376. for (unsigned Pos = 0, NumParams = Parameters.size(); Pos < NumParams;
  1377. ++Pos) {
  1378. assert(Parameters[Pos].ParamPos == Pos && "Broken parameter list.");
  1379. switch (Parameters[Pos].ParamKind) {
  1380. default: // Nothing to check.
  1381. break;
  1382. case VFParamKind::OMP_Linear:
  1383. case VFParamKind::OMP_LinearRef:
  1384. case VFParamKind::OMP_LinearVal:
  1385. case VFParamKind::OMP_LinearUVal:
  1386. // Compile time linear steps must be non-zero.
  1387. if (Parameters[Pos].LinearStepOrPos == 0)
  1388. return false;
  1389. break;
  1390. case VFParamKind::OMP_LinearPos:
  1391. case VFParamKind::OMP_LinearRefPos:
  1392. case VFParamKind::OMP_LinearValPos:
  1393. case VFParamKind::OMP_LinearUValPos:
  1394. // The runtime linear step must be referring to some other
  1395. // parameters in the signature.
  1396. if (Parameters[Pos].LinearStepOrPos >= int(NumParams))
  1397. return false;
  1398. // The linear step parameter must be marked as uniform.
  1399. if (Parameters[Parameters[Pos].LinearStepOrPos].ParamKind !=
  1400. VFParamKind::OMP_Uniform)
  1401. return false;
  1402. // The linear step parameter can't point at itself.
  1403. if (Parameters[Pos].LinearStepOrPos == int(Pos))
  1404. return false;
  1405. break;
  1406. case VFParamKind::GlobalPredicate:
  1407. // The global predicate must be the unique. Can be placed anywhere in the
  1408. // signature.
  1409. for (unsigned NextPos = Pos + 1; NextPos < NumParams; ++NextPos)
  1410. if (Parameters[NextPos].ParamKind == VFParamKind::GlobalPredicate)
  1411. return false;
  1412. break;
  1413. }
  1414. }
  1415. return true;
  1416. }